/usr/share/perl5/IO/Socket/Socks.pm is in libio-socket-socks-perl 0.61-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | ##############################################################################
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
#
# Copyright (C) 2003 Ryan Eatmon
# Copyright (C) 2010-2011 Oleg G
#
##############################################################################
package IO::Socket::Socks;
use strict;
use IO::Socket;
use IO::Select;
use Errno qw(EWOULDBLOCK EAGAIN ENOTCONN ETIMEDOUT);
use Carp;
use vars qw( @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $VERSION $SOCKS_ERROR $SOCKS5_RESOLVE $SOCKS4_RESOLVE $SOCKS_DEBUG %CODES );
require Exporter;
use constant
{
SOCKS_WANT_READ => 20,
SOCKS_WANT_WRITE => 21,
ESOCKSPROTO => exists &Errno::EPROTO ? &Errno::EPROTO : 7000,
};
@ISA = qw(Exporter IO::Socket::INET);
@EXPORT = qw( $SOCKS_ERROR SOCKS_WANT_READ SOCKS_WANT_WRITE ESOCKSPROTO );
@EXPORT_OK = qw(
SOCKS5_VER
SOCKS4_VER
ADDR_IPV4
ADDR_DOMAINNAME
ADDR_IPV6
CMD_CONNECT
CMD_BIND
CMD_UDPASSOC
AUTHMECH_ANON
AUTHMECH_USERPASS
AUTHMECH_INVALID
AUTHREPLY_SUCCESS
AUTHREPLY_FAILURE
ISS_UNKNOWN_ADDRESS
ISS_BAD_VERSION
REPLY_SUCCESS
REPLY_GENERAL_FAILURE
REPLY_CONN_NOT_ALLOWED
REPLY_NETWORK_UNREACHABLE
REPLY_HOST_UNREACHABLE
REPLY_CONN_REFUSED
REPLY_TTL_EXPIRED
REPLY_CMD_NOT_SUPPORTED
REPLY_ADDR_NOT_SUPPORTED
REQUEST_GRANTED
REQUEST_FAILED
REQUEST_REJECTED_IDENTD
REQUEST_REJECTED_USERID
);
%EXPORT_TAGS = (constants => ['SOCKS_WANT_READ', 'SOCKS_WANT_WRITE', @EXPORT_OK]);
$SOCKS_ERROR = new IO::Socket::Socks::Error;
$VERSION = '0.61';
$SOCKS5_RESOLVE = 1;
$SOCKS4_RESOLVE = 0;
$SOCKS_DEBUG = $ENV{SOCKS_DEBUG};
use constant
{
SOCKS5_VER => 5,
SOCKS4_VER => 4,
ADDR_IPV4 => 1,
ADDR_DOMAINNAME => 3,
ADDR_IPV6 => 4,
CMD_CONNECT => 1,
CMD_BIND => 2,
CMD_UDPASSOC => 3,
AUTHMECH_ANON => 0,
#AUTHMECH_GSSAPI => 1,
AUTHMECH_USERPASS => 2,
AUTHMECH_INVALID => 255,
AUTHREPLY_SUCCESS => 0,
AUTHREPLY_FAILURE => 10, # to not intersect with other socks5 constants
ISS_UNKNOWN_ADDRESS => 500,
ISS_BAD_VERSION => 501,
};
$CODES{AUTHMECH}->[AUTHMECH_INVALID] = "No valid auth mechanisms";
$CODES{AUTHREPLY}->[AUTHREPLY_FAILURE] = "Failed to authenticate";
# socks5
use constant
{
REPLY_SUCCESS => 0,
REPLY_GENERAL_FAILURE => 1,
REPLY_CONN_NOT_ALLOWED => 2,
REPLY_NETWORK_UNREACHABLE => 3,
REPLY_HOST_UNREACHABLE => 4,
REPLY_CONN_REFUSED => 5,
REPLY_TTL_EXPIRED => 6,
REPLY_CMD_NOT_SUPPORTED => 7,
REPLY_ADDR_NOT_SUPPORTED => 8,
};
$CODES{REPLY}->{&REPLY_SUCCESS} = "Success";
$CODES{REPLY}->{&REPLY_GENERAL_FAILURE} = "General failure";
$CODES{REPLY}->{&REPLY_CONN_NOT_ALLOWED} = "Not allowed";
$CODES{REPLY}->{&REPLY_NETWORK_UNREACHABLE} = "Network unreachable";
$CODES{REPLY}->{&REPLY_HOST_UNREACHABLE} = "Host unreachable";
$CODES{REPLY}->{&REPLY_CONN_REFUSED} = "Connection refused";
$CODES{REPLY}->{&REPLY_TTL_EXPIRED} = "TTL expired";
$CODES{REPLY}->{&REPLY_CMD_NOT_SUPPORTED} = "Command not supported";
$CODES{REPLY}->{&REPLY_ADDR_NOT_SUPPORTED} = "Address not supported";
# socks4
use constant
{
REQUEST_GRANTED => 90,
REQUEST_FAILED => 91,
REQUEST_REJECTED_IDENTD => 92,
REQUEST_REJECTED_USERID => 93,
};
$CODES{REPLY}->{&REQUEST_GRANTED} = "request granted";
$CODES{REPLY}->{&REQUEST_FAILED} = "request rejected or failed";
$CODES{REPLY}->{&REQUEST_REJECTED_IDENTD} = "request rejected becasue SOCKS server cannot connect to identd on the client";
$CODES{REPLY}->{&REQUEST_REJECTED_USERID} = "request rejected because the client program and identd report different user-ids";
# queue
use constant
{
Q_SUB => 0,
Q_ARGS => 1,
Q_BUF => 2,
Q_READS => 3,
Q_SENDS => 4,
Q_DEBUGS => 5,
};
#------------------------------------------------------------------------------
# sub new is handled by IO::Socket::INET
#------------------------------------------------------------------------------
sub new_from_fd
{
my ($class, $sock, %arg) = @_;
bless $sock, $class;
my $blocking = $sock->blocking;
$sock->autoflush(1);
${*$sock}{'io_socket_timeout'} = delete $arg{Timeout};
scalar(%arg) or return $sock;
if ($sock = $sock->configure(\%arg) and !$blocking) {
$sock->blocking(0);
}
return $sock;
}
*new_from_socket = \&new_from_fd;
###############################################################################
#
# configure - read in the config hash and populate the object.
#
###############################################################################
sub configure
{
my $self = shift;
my $args = shift;
$self->_configure($args)
or return;
${*$self}->{SOCKS}->{ProxyAddr} =
(exists($args->{ProxyAddr}) ?
delete($args->{ProxyAddr}) :
undef
);
${*$self}->{SOCKS}->{ProxyPort} =
(exists($args->{ProxyPort}) ?
delete($args->{ProxyPort}) :
undef
);
${*$self}->{SOCKS}->{COMMAND} = [];
if (exists($args->{Listen}))
{
$args->{LocalAddr} = ${*$self}->{SOCKS}->{ProxyAddr};
$args->{LocalPort} = ${*$self}->{SOCKS}->{ProxyPort};
$args->{Reuse} = 1;
${*$self}->{SOCKS}->{Listen} = 1;
}
elsif(${*$self}->{SOCKS}->{ProxyAddr} && ${*$self}->{SOCKS}->{ProxyPort})
{
$args->{PeerAddr} = ${*$self}->{SOCKS}->{ProxyAddr};
$args->{PeerPort} = ${*$self}->{SOCKS}->{ProxyPort};
}
unless(defined ${*$self}->{SOCKS}->{TCP})
{
$args->{Proto} = "tcp";
$args->{Type} = SOCK_STREAM;
}
elsif(! defined $args->{Proto})
{
$args->{Proto} = "udp";
$args->{Type} = SOCK_DGRAM;
}
$self->SUPER::configure($args);
}
###############################################################################
#
# _configure - reusable configure operations
#
###############################################################################
sub _configure
{
my $self = shift;
my $args = shift;
${*$self}->{SOCKS}->{Version} =
(exists($args->{SocksVersion}) ?
($args->{SocksVersion} == 4 || $args->{SocksVersion} == 5 ?
delete($args->{SocksVersion}) :
croak("Unsupported socks version specified. Should be 4 or 5")
) :
5
);
${*$self}->{SOCKS}->{AuthType} =
(exists($args->{AuthType}) ?
delete($args->{AuthType}) :
"none"
);
${*$self}->{SOCKS}->{RequireAuth} =
(exists($args->{RequireAuth}) ?
delete($args->{RequireAuth}) :
0
);
${*$self}->{SOCKS}->{UserAuth} =
(exists($args->{UserAuth}) ?
delete($args->{UserAuth}) :
undef
);
${*$self}->{SOCKS}->{Username} =
(exists($args->{Username}) ?
delete($args->{Username}) :
((${*$self}->{SOCKS}->{AuthType} eq "none") ?
undef :
croak("If you set AuthType to userpass, then you must provide a username.")
)
);
${*$self}->{SOCKS}->{Password} =
(exists($args->{Password}) ?
delete($args->{Password}) :
((${*$self}->{SOCKS}->{AuthType} eq "none") ?
undef :
croak("If you set AuthType to userpass, then you must provide a password.")
)
);
${*$self}->{SOCKS}->{Debug} =
(exists($args->{SocksDebug}) ?
delete($args->{SocksDebug}) :
$SOCKS_DEBUG
);
${*$self}->{SOCKS}->{Resolve} =
(exists($args->{SocksResolve}) ?
delete($args->{SocksResolve}) :
undef
);
${*$self}->{SOCKS}->{AuthMethods} = [0,0,0];
${*$self}->{SOCKS}->{AuthMethods}->[AUTHMECH_ANON] = 1
unless ${*$self}->{SOCKS}->{RequireAuth};
#${*$self}->{SOCKS}->{AuthMethods}->[AUTHMECH_GSSAPI] = 1
# if (${*$self}->{SOCKS}->{AuthType} eq "gssapi");
${*$self}->{SOCKS}->{AuthMethods}->[AUTHMECH_USERPASS] = 1
if ((!exists($args->{Listen}) &&
(${*$self}->{SOCKS}->{AuthType} eq "userpass")) ||
(exists($args->{Listen}) &&
defined(${*$self}->{SOCKS}->{UserAuth})));
if(exists($args->{BindAddr}) && exists($args->{BindPort}))
{
${*$self}->{SOCKS}->{CmdAddr} = delete($args->{BindAddr});
${*$self}->{SOCKS}->{CmdPort} = delete($args->{BindPort});
${*$self}->{SOCKS}->{Bind} = 1;
}
elsif(exists($args->{UdpAddr}) && exists($args->{UdpPort}))
{
if(${*$self}->{SOCKS}->{Version} == 4) {
croak("Socks v4 doesn't support UDP association");
}
${*$self}->{SOCKS}->{CmdAddr} = delete($args->{UdpAddr});
${*$self}->{SOCKS}->{CmdPort} = delete($args->{UdpPort});
$args->{LocalAddr} = ${*$self}->{SOCKS}->{CmdAddr};
$args->{LocalPort} = ${*$self}->{SOCKS}->{CmdPort};
${*$self}->{SOCKS}->{TCP} = __PACKAGE__->new( # TCP backend for UDP socket
Timeout => $args->{Timeout},
Proto => 'tcp'
) or return;
}
elsif(exists($args->{ConnectAddr}) && exists($args->{ConnectPort}))
{
${*$self}->{SOCKS}->{CmdAddr} = delete($args->{ConnectAddr});
${*$self}->{SOCKS}->{CmdPort} = delete($args->{ConnectPort});
}
return 1;
}
###############################################################################
#+-----------------------------------------------------------------------------
#| Connect Functions
#+-----------------------------------------------------------------------------
###############################################################################
###############################################################################
#
# connect - On a configure, connect is called to open the connection. When
# we do this we have to talk to the SOCKS proxy, log in, and
# connect to the remote host.
#
###############################################################################
sub connect
{
my $self = shift;
croak("Undefined IO::Socket::Socks object passed to connect.")
unless defined($self);
#--------------------------------------------------------------------------
# Establish a connection
#--------------------------------------------------------------------------
my $sock = defined( ${*$self}->{SOCKS}->{TCP} ) ?
${*$self}->{SOCKS}->{TCP}->SUPER::connect(@_)
:
$self->SUPER::connect(@_);
if (!$sock)
{
$SOCKS_ERROR->set($!, $@ = "Connection to proxy failed: $!");
return;
}
$self->_connect();
}
###############################################################################
#
# _connect - reusable connect operations
#
###############################################################################
sub _connect
{
my $self = shift;
${*$self}->{SOCKS}->{ready} = 0;
${*$self}->{SOCKS}->{connected} = 0;
if(${*$self}->{SOCKS}->{Version} == 4)
{
${*$self}->{SOCKS}->{queue} = [
# [sub, [@args], buf, [@reads], sends_cnt]
['_socks4_connect_command', [${*$self}->{SOCKS}->{Bind} ? CMD_BIND : CMD_CONNECT], undef, [], 0],
['_socks4_connect_reply', [], undef, [], 0]
];
}
else
{
${*$self}->{SOCKS}->{queue} = [
['_socks5_connect', [], undef, [], 0],
['_socks5_connect_if_auth', [], undef, [], 0],
['_socks5_connect_command', [
${*$self}->{SOCKS}->{Bind} ?
CMD_BIND :
${*$self}->{SOCKS}->{TCP} ?
CMD_UDPASSOC :
CMD_CONNECT
],
undef, [], 0
],
['_socks5_connect_reply', [], undef, [], 0]
];
}
defined( $self->_run_queue() )
or return;
return $self;
}
###############################################################################
#
# _run_queue - run tasks from queue, return undef on error, -1 if one of the task
# returned not completed because of the possible blocking on network operation
#
###############################################################################
sub _run_queue
{
my $self = shift;
my $retval;
my $sub;
while(my $elt = ${*$self}->{SOCKS}->{queue}[0])
{
$sub = $elt->[Q_SUB];
$retval = $self->$sub(@{$elt->[Q_ARGS]});
unless (defined $retval)
{
${*$self}->{SOCKS}->{queue} = [];
${*$self}->{SOCKS}->{queue_results} = {};
last;
}
last if ($retval == -1);
${*$self}->{SOCKS}->{queue_results}{$elt->[Q_SUB]} = $retval;
shift @{${*$self}->{SOCKS}->{queue}};
}
if(defined($retval) && !@{${*$self}->{SOCKS}->{queue}})
{
${*$self}->{SOCKS}->{queue_results} = {};
${*$self}->{SOCKS}->{ready} = 1;
}
return $retval;
}
###############################################################################
#
# ready - check is non-blocking socket ready to transfer user data
#
###############################################################################
sub ready
{
my $self = shift;
$self->_run_queue();
return ${*$self}->{SOCKS}->{ready};
}
###############################################################################
#
# _socks5_connect - Send the opening handsake, and process the reply.
#
###############################################################################
sub _socks5_connect
{
my $self = shift;
my $debug = IO::Socket::Socks::Debug->new() if ${*$self}->{SOCKS}->{Debug};
my ($reads, $sends, $debugs) = (0, 0, 0);
my $sock = defined( ${*$self}->{SOCKS}->{TCP} ) ?
${*$self}->{SOCKS}->{TCP}
:
$self;
#--------------------------------------------------------------------------
# Send the auth mechanisms
#--------------------------------------------------------------------------
# +----+----------+----------+
# |VER | NMETHODS | METHODS |
# +----+----------+----------+
# | 1 | 1 | 1 to 255 |
# +----+----------+----------+
my $nmethods = 0;
my $methods;
foreach my $method (0..$#{${*$self}->{SOCKS}->{AuthMethods}})
{
if (${*$self}->{SOCKS}->{AuthMethods}->[$method] == 1)
{
$methods .= pack('C', $method);
$nmethods++;
}
}
my $reply;
$reply = $sock->_socks_send(pack('CCa*', SOCKS5_VER, $nmethods, $methods), ++$sends)
or return _fail($reply);
if($debug && !$self->_debugged(++$debugs))
{
$debug->add(
ver => SOCKS5_VER,
nmethods => $nmethods,
methods => join('', unpack("C$nmethods", $methods))
);
$debug->show('Client Send: ');
}
#--------------------------------------------------------------------------
# Read the reply
#--------------------------------------------------------------------------
# +----+--------+
# |VER | METHOD |
# +----+--------+
# | 1 | 1 |
# +----+--------+
$reply = $sock->_socks_read(2, ++$reads)
or return _fail($reply);
my ($version, $auth_method) = unpack('CC', $reply);
if($debug && !$self->_debugged(++$debugs))
{
$debug->add(
ver => $version,
method => $auth_method
);
$debug->show('Client Recv: ');
}
if ($auth_method == AUTHMECH_INVALID)
{
$! = ESOCKSPROTO;
$SOCKS_ERROR->set(AUTHMECH_INVALID, $@ = $CODES{AUTHMECH}->[$auth_method]);
return;
}
return $auth_method;
}
sub _socks5_connect_if_auth
{
my $self = shift;
if(${*$self}->{SOCKS}->{queue_results}{'_socks5_connect'} != AUTHMECH_ANON)
{
unshift @{${*$self}->{SOCKS}->{queue}}, ['_socks5_connect_auth', [], undef, [], 0];
(${*$self}->{SOCKS}->{queue}[0], ${*$self}->{SOCKS}->{queue}[1])
=
(${*$self}->{SOCKS}->{queue}[1], ${*$self}->{SOCKS}->{queue}[0]);
}
1;
}
###############################################################################
#
# _socks5_connect_auth - Send and receive a SOCKS5 auth handshake (rfc1929)
#
###############################################################################
sub _socks5_connect_auth
{
my $self = shift;
my $debug = IO::Socket::Socks::Debug->new() if ${*$self}->{SOCKS}->{Debug};
my ($reads, $sends, $debugs) = (0, 0, 0);
my $sock = defined( ${*$self}->{SOCKS}->{TCP} ) ?
${*$self}->{SOCKS}->{TCP}
:
$self;
#--------------------------------------------------------------------------
# Send the auth
#--------------------------------------------------------------------------
# +----+------+----------+------+----------+
# |VER | ULEN | UNAME | PLEN | PASSWD |
# +----+------+----------+------+----------+
# | 1 | 1 | 1 to 255 | 1 | 1 to 255 |
# +----+------+----------+------+----------+
my $uname = ${*$self}->{SOCKS}->{Username};
my $passwd = ${*$self}->{SOCKS}->{Password};
my $ulen = length($uname);
my $plen = length($passwd);
my $reply;
$reply = $sock->_socks_send(pack("CCa${ulen}Ca*", 1, $ulen, $uname, $plen, $passwd), ++$sends)
or return _fail($reply);
if($debug && !$self->_debugged(++$debugs))
{
$debug->add(
ver => 1,
ulen => $ulen,
uname => $uname,
plen => $plen,
passwd => $passwd
);
$debug->show('Client Send: ');
}
#--------------------------------------------------------------------------
# Read the reply
#--------------------------------------------------------------------------
# +----+--------+
# |VER | STATUS |
# +----+--------+
# | 1 | 1 |
# +----+--------+
$reply = $sock->_socks_read(2, ++$reads)
or return _fail($reply);
my ($ver, $status) = unpack('CC', $reply);
if($debug && !$self->_debugged(++$debugs))
{
$debug->add(
ver => $ver,
status => $status
);
$debug->show('Client Recv: ');
}
if ($status != AUTHREPLY_SUCCESS)
{
$! = ESOCKSPROTO;
$SOCKS_ERROR->set(AUTHREPLY_FAILURE, $@ = "Authentication failed with SOCKS5 proxy");
return;
}
return 1;
}
###############################################################################
#
# _socks_connect_command - Process a SOCKS5 command request
#
###############################################################################
sub _socks5_connect_command
{
my $self = shift;
my $command = shift;
my $debug = IO::Socket::Socks::Debug->new() if ${*$self}->{SOCKS}->{Debug};
my ($reads, $sends, $debugs) = (0, 0, 0);
my $resolve = defined(${*$self}->{SOCKS}->{Resolve}) ? ${*$self}->{SOCKS}->{Resolve} : $SOCKS5_RESOLVE;
my $sock = defined( ${*$self}->{SOCKS}->{TCP} ) ?
${*$self}->{SOCKS}->{TCP}
:
$self;
#--------------------------------------------------------------------------
# Send the command
#--------------------------------------------------------------------------
# +----+-----+-------+------+----------+----------+
# |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
# +----+-----+-------+------+----------+----------+
# | 1 | 1 | X'00' | 1 | Variable | 2 |
# +----+-----+-------+------+----------+----------+
my $atyp = $resolve ? ADDR_DOMAINNAME : ADDR_IPV4;
my $dstaddr = $resolve ? ${*$self}->{SOCKS}->{CmdAddr} : inet_aton(${*$self}->{SOCKS}->{CmdAddr});
my $hlen = length($dstaddr) if $resolve;
my $dstport = pack('n', ${*$self}->{SOCKS}->{CmdPort});
my $reply;
$reply = $sock->_socks_send(pack('C4', SOCKS5_VER, $command, 0, $atyp) . (defined($hlen) ? pack('C', $hlen) : '') . $dstaddr . $dstport, ++$sends)
or return _fail($reply);
if($debug && !$self->_debugged(++$debugs))
{
$debug->add(
ver => SOCKS5_VER,
cmd => $command,
rsv => 0,
atyp => $atyp
);
$debug->add(hlen => $hlen) if defined $hlen;
$debug->add(
dstaddr => $resolve ? $dstaddr : (length($dstaddr) == 4 ? inet_ntoa($dstaddr) : undef),
dstport => ${*$self}->{SOCKS}->{CmdPort}
);
$debug->show('Client Send: ');
}
return 1;
}
sub _socks5_connect_reply
{
my $self = shift;
my $debug = IO::Socket::Socks::Debug->new() if ${*$self}->{SOCKS}->{Debug};
my ($reads, $sends, $debugs) = (0, 0, 0);
my $sock = defined( ${*$self}->{SOCKS}->{TCP} ) ?
${*$self}->{SOCKS}->{TCP}
:
$self;
#--------------------------------------------------------------------------
# Read the reply
#--------------------------------------------------------------------------
# +----+-----+-------+------+----------+----------+
# |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
# +----+-----+-------+------+----------+----------+
# | 1 | 1 | X'00' | 1 | Variable | 2 |
# +----+-----+-------+------+----------+----------+
my $reply;
$reply = $sock->_socks_read(4, ++$reads)
or return _fail($reply);
my ($ver, $rep, $rsv, $atyp) = unpack('C4', $reply);
if($debug)
{
$debug->add(
ver => $ver,
rep => $rep,
rsv => $rsv,
atyp => $atyp
);
}
my ($bndaddr, $bndport);
if ($atyp == ADDR_DOMAINNAME)
{
length( $reply = $sock->_socks_read(1, ++$reads) )
or return _fail($reply);
my $hlen = unpack('C', $reply);
$bndaddr = $sock->_socks_read($hlen, ++$reads)
or return _fail($bndaddr);
if($debug)
{
$debug->add(
hlen => $hlen,
bndaddr => $bndaddr
);
}
}
elsif ($atyp == ADDR_IPV4)
{
$reply = $sock->_socks_read(4, ++$reads)
or return _fail($reply);
$bndaddr = length($reply) == 4 ? inet_ntoa($reply) : undef;
if($debug)
{
$debug->add(bndaddr => $bndaddr);
}
}
else
{
$! = ESOCKSPROTO;
$SOCKS_ERROR->set(ISS_UNKNOWN_ADDRESS, $@ = "Unsupported address type returned by socks server: $atyp");
return;
}
$reply = $sock->_socks_read(2, ++$reads)
or return _fail($reply);
$bndport = unpack('n', $reply);
${*$self}->{SOCKS}->{DstAddr} = $bndaddr;
${*$self}->{SOCKS}->{DstPort} = $bndport;
if($debug && !$self->_debugged(++$debugs))
{
$debug->add(bndport => $bndport);
$debug->show('Client Recv: ');
}
if($rep != REPLY_SUCCESS)
{
$! = ESOCKSPROTO;
unless(exists $CODES{REPLY}->{$rep})
{
$rep = REPLY_GENERAL_FAILURE;
}
$SOCKS_ERROR->set($rep, $@ = $CODES{REPLY}->{$rep});
return;
}
return 1;
}
###############################################################################
#
# _socks4_connect_command - Send the opening handsake, and process the reply.
#
###############################################################################
sub _socks4_connect_command
{
# http://ss5.sourceforge.net/socks4.protocol.txt
# http://ss5.sourceforge.net/socks4A.protocol.txt
my $self = shift;
my $command = shift;
my $debug = IO::Socket::Socks::Debug->new() if ${*$self}->{SOCKS}->{Debug};
my ($reads, $sends, $debugs) = (0, 0, 0);
my $resolve = defined(${*$self}->{SOCKS}->{Resolve}) ? ${*$self}->{SOCKS}->{Resolve} : $SOCKS4_RESOLVE;
#--------------------------------------------------------------------------
# Send the command
#--------------------------------------------------------------------------
# +-----+-----+----------+---------------+----------+------+
# | VER | CMD | DST.PORT | DST.ADDR | USERID | NULL |
# +-----+-----+----------+---------------+----------+------+
# | 1 | 1 | 2 | 4 | variable | 1 |
# +-----+-----+----------+---------------+----------+------+
my $dstaddr = $resolve ? inet_aton('0.0.0.1') : inet_aton(${*$self}->{SOCKS}->{CmdAddr});
my $dstport = pack('n', ${*$self}->{SOCKS}->{CmdPort});
my $userid = ${*$self}->{SOCKS}->{Username} || '';
my $dsthost = '';
if($resolve)
{ # socks4a
$dsthost = ${*$self}->{SOCKS}->{CmdAddr} . pack('C', 0);
}
my $reply;
$reply = $self->_socks_send(pack('CC', SOCKS4_VER, $command) . $dstport . $dstaddr . $userid . pack('C', 0) . $dsthost, ++$sends)
or return _fail($reply);
if($debug && !$self->_debugged(++$debugs))
{
$debug->add(
ver => SOCKS4_VER,
cmd => $command,
dstport => ${*$self}->{SOCKS}->{CmdPort},
dstaddr => length($dstaddr) == 4 ? inet_ntoa($dstaddr) : undef,
userid => $userid,
null => 0
);
if($dsthost)
{
$debug->add(
dsthost => ${*$self}->{SOCKS}->{CmdAddr},
null => 0
);
}
$debug->show('Client Send: ');
}
return 1;
}
sub _socks4_connect_reply
{
my $self = shift;
my $debug = IO::Socket::Socks::Debug->new() if ${*$self}->{SOCKS}->{Debug};
my ($reads, $sends, $debugs) = (0, 0, 0);
#--------------------------------------------------------------------------
# Read the reply
#--------------------------------------------------------------------------
# +-----+-----+----------+---------------+
# | VER | REP | BND.PORT | BND.ADDR |
# +-----+-----+----------+---------------+
# | 1 | 1 | 2 | 4 |
# +-----+-----+----------+---------------+
my $reply;
$reply = $self->_socks_read(8, ++$reads)
or return _fail($reply);
my ($ver, $rep, $bndport) = unpack('CCn', $reply);
substr($reply, 0, 4) = '';
my $bndaddr = length($reply) == 4 ? inet_ntoa($reply) : undef;
${*$self}->{SOCKS}->{DstAddr} = $bndaddr;
${*$self}->{SOCKS}->{DstPort} = $bndport;
if($debug && !$self->_debugged(++$debugs))
{
$debug->add(
ver => $ver,
rep => $rep,
bndport => $bndport,
bndaddr => $bndaddr
);
$debug->show('Client Recv: ');
}
if($rep != REQUEST_GRANTED)
{
$! = ESOCKSPROTO;
unless(exists $CODES{REPLY}->{$rep})
{
$rep = REQUEST_FAILED;
}
$SOCKS_ERROR->set($rep, $@ = $CODES{REPLY}->{$rep});
return;
}
return 1;
}
###############################################################################
#+-----------------------------------------------------------------------------
#| Accept Functions
#+-----------------------------------------------------------------------------
###############################################################################
###############################################################################
#
# accept - When we are accepting new connections, we need to do the SOCKS
# handshaking before we return a usable socket.
#
###############################################################################
sub accept
{
my $self = shift;
croak("Undefined IO::Socket::Socks object passed to accept.")
unless defined($self);
if(${*$self}->{SOCKS}->{Listen})
{
my $client = $self->SUPER::accept(@_);
if(!$client)
{
if($! == EAGAIN || $! == EWOULDBLOCK)
{
$SOCKS_ERROR->set(SOCKS_WANT_READ, "Socks want read");
}
else
{
$SOCKS_ERROR->set($!, $@ = "Proxy accept new client failed: $!");
}
return;
}
# inherit some socket parameters
${*$client}->{SOCKS}->{Debug} = ${*$self}->{SOCKS}->{Debug};
${*$client}->{SOCKS}->{Version} = ${*$self}->{SOCKS}->{Version};
${*$client}->{SOCKS}->{AuthMethods} = ${*$self}->{SOCKS}->{AuthMethods};
${*$client}->{SOCKS}->{UserAuth} = ${*$self}->{SOCKS}->{UserAuth};
${*$client}->{SOCKS}->{ready} = 0;
$client->blocking($self->blocking); # temporarily
if(${*$self}->{SOCKS}->{Version} == 4)
{
${*$client}->{SOCKS}->{queue} = [
['_socks4_accept_command', [], undef, [], 0]
];
}
else
{
${*$client}->{SOCKS}->{queue} = [
['_socks5_accept', [], undef, [], 0],
['_socks5_accept_if_auth', [], undef, [], 0],
['_socks5_accept_command', [], undef, [], 0]
];
}
defined( $client->_run_queue() )
or return;
$client->blocking(1); # new socket should be in blocking mode
return $client;
}
else
{
${*$self}->{SOCKS}->{ready} = 0;
if({*$self}->{SOCKS}->{Version} == 4)
{
push @{${*$self}->{SOCKS}->{queue}}, ['_socks4_connect_reply', [], undef, [], 0];
}
else
{
push @{${*$self}->{SOCKS}->{queue}}, ['_socks5_connect_reply', [], undef, [], 0];
}
defined( $self->_run_queue() )
or return;
return $self;
}
}
###############################################################################
#
# _socks5_accept - Wait for an opening handsake, and reply.
#
###############################################################################
sub _socks5_accept
{
my $self = shift;
my $debug = IO::Socket::Socks::Debug->new() if ${*$self}->{SOCKS}->{Debug};
my ($reads, $sends, $debugs) = (0, 0, 0);
#--------------------------------------------------------------------------
# Read the auth mechanisms
#--------------------------------------------------------------------------
# +----+----------+----------+
# |VER | NMETHODS | METHODS |
# +----+----------+----------+
# | 1 | 1 | 1 to 255 |
# +----+----------+----------+
my $request;
$request = $self->_socks_read(2, ++$reads)
or return _fail($request);
my ($ver, $nmethods) = unpack('CC', $request);
$request = $self->_socks_read($nmethods, ++$reads)
or return _fail($request);
my @methods = unpack('C'x$nmethods, $request);
if($debug && !$self->_debugged(++$debugs))
{
$debug->add(
ver => $ver,
nmethods => $nmethods,
methods => join('', @methods)
);
$debug->show('Server Recv: ');
}
if($ver != SOCKS5_VER)
{
$! = ESOCKSPROTO;
$SOCKS_ERROR->set(ISS_BAD_VERSION, $@ = "Socks version should be 5, $ver recieved");
return;
}
if ($nmethods == 0)
{
$! = ESOCKSPROTO;
$SOCKS_ERROR->set(AUTHMECH_INVALID, $@ = "No auth methods sent");
return;
}
my $authmech;
foreach my $method (@methods)
{
if (${*$self}->{SOCKS}->{AuthMethods}->[$method] == 1)
{
$authmech = $method;
last;
}
}
if (!defined($authmech))
{
$authmech = AUTHMECH_INVALID;
}
#--------------------------------------------------------------------------
# Send the reply
#--------------------------------------------------------------------------
# +----+--------+
# |VER | METHOD |
# +----+--------+
# | 1 | 1 |
# +----+--------+
$request = $self->_socks_send(pack('CC', SOCKS5_VER, $authmech), ++$sends)
or return _fail($request);
if($debug && !$self->_debugged(++$debugs))
{
$debug->add(
ver => SOCKS5_VER,
method => $authmech
);
$debug->show('Server Send: ');
}
if ($authmech == AUTHMECH_INVALID)
{
$! = ESOCKSPROTO;
$SOCKS_ERROR->set(AUTHMECH_INVALID, $@ = "No available auth methods");
return;
}
return $authmech;
}
sub _socks5_accept_if_auth
{
my $self = shift;
if(${*$self}->{SOCKS}->{queue_results}{'_socks5_accept'} == AUTHMECH_USERPASS)
{
unshift @{${*$self}->{SOCKS}->{queue}}, ['_socks5_accept_auth', [], undef, [], 0];
(${*$self}->{SOCKS}->{queue}[0], ${*$self}->{SOCKS}->{queue}[1])
=
(${*$self}->{SOCKS}->{queue}[1], ${*$self}->{SOCKS}->{queue}[0]);
}
1;
}
###############################################################################
#
# _socks5_accept_auth - Send and receive a SOCKS5 auth handshake (rfc1929)
#
###############################################################################
sub _socks5_accept_auth
{
my $self = shift;
my $debug = IO::Socket::Socks::Debug->new() if ${*$self}->{SOCKS}->{Debug};
my ($reads, $sends, $debugs) = (0, 0, 0);
#--------------------------------------------------------------------------
# Read the auth
#--------------------------------------------------------------------------
# +----+------+----------+------+----------+
# |VER | ULEN | UNAME | PLEN | PASSWD |
# +----+------+----------+------+----------+
# | 1 | 1 | 1 to 255 | 1 | 1 to 255 |
# +----+------+----------+------+----------+
my $request;
$request = $self->_socks_read(2, ++$reads)
or return _fail($request);
my ($ver, $ulen) = unpack('CC', $request);
$request = $self->_socks_read($ulen+1, ++$reads)
or return _fail($request);
my $uname = substr($request, 0, $ulen);
my $plen = unpack('C', substr($request, $ulen));
my $passwd; $passwd = $self->_socks_read($plen, ++$reads)
or return _fail($passwd);
if($debug && !$self->_debugged(++$debugs))
{
$debug->add(
ver => $ver,
ulen => $ulen,
uname => $uname,
plen => $plen,
passwd => $passwd
);
$debug->show('Server Recv: ');
}
my $status = 1;
if (defined(${*$self}->{SOCKS}->{UserAuth}))
{
$status = &{${*$self}->{SOCKS}->{UserAuth}}($uname, $passwd);
}
#--------------------------------------------------------------------------
# Send the reply
#--------------------------------------------------------------------------
# +----+--------+
# |VER | STATUS |
# +----+--------+
# | 1 | 1 |
# +----+--------+
$status = $status ? AUTHREPLY_SUCCESS : 1; #XXX AUTHREPLY_FAILURE broken
$request = $self->_socks_send(pack('CC', 1, $status), ++$sends)
or return _fail($request);
if($debug && !$self->_debugged(++$debugs))
{
$debug->add(
ver => 1,
status => $status
);
$debug->show('Server Send: ');
}
if ($status != AUTHREPLY_SUCCESS)
{
$! = ESOCKSPROTO;
$SOCKS_ERROR->set(AUTHREPLY_FAILURE, $@ = "Authentication failed with SOCKS5 proxy");
return;
}
return 1;
}
###############################################################################
#
# _socks5_acccept_command - Process a SOCKS5 command request. Since this is
# a library and not a server, we cannot process the
# command. Let the parent program handle that.
#
###############################################################################
sub _socks5_accept_command
{
my $self = shift;
my $debug = IO::Socket::Socks::Debug->new() if ${*$self}->{SOCKS}->{Debug};
my ($reads, $sends, $debugs) = (0, 0, 0);
@{${*$self}->{SOCKS}->{COMMAND}} = ();
#--------------------------------------------------------------------------
# Read the command
#--------------------------------------------------------------------------
# +----+-----+-------+------+----------+----------+
# |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
# +----+-----+-------+------+----------+----------+
# | 1 | 1 | X'00' | 1 | Variable | 2 |
# +----+-----+-------+------+----------+----------+
my $request;
$request = $self->_socks_read(4, ++$reads)
or return _fail($request);
my ($ver, $cmd, $rsv, $atyp) = unpack('CCCC', $request);
if($debug && !$self->_debugged(++$debugs))
{
$debug->add(
ver => $ver,
cmd => $cmd,
rsv => $rsv,
atyp => $atyp
);
}
my $dstaddr;
if ($atyp == ADDR_DOMAINNAME)
{
length( $request = $self->_socks_read(1, ++$reads) )
or return _fail($request);
my $hlen = unpack('C', $request);
$dstaddr = $self->_socks_read($hlen, ++$reads)
or return _fail($dstaddr);
if($debug && !$self->_debugged(++$debugs))
{
$debug->add(hlen => $hlen);
}
}
elsif ($atyp == ADDR_IPV4)
{
$request = $self->_socks_read(4, ++$reads)
or return _fail($request);
$dstaddr = length($request) == 4 ? inet_ntoa($request) : undef;
}
else
{ # unknown address type - how many bytes to read?
${*$self}->{SOCKS}->{queue} = [
['_socks5_accept_command_reply', [REPLY_ADDR_NOT_SUPPORTED, '0.0.0.0', 0], undef, [], 0]
];
$! = ESOCKSPROTO;
$SOCKS_ERROR->set(REPLY_ADDR_NOT_SUPPORTED, $@ = $CODES{REPLY}->{REPLY_ADDR_NOT_SUPPORTED});
return 1;
}
$request = $self->_socks_read(2, ++$reads)
or return _fail($request);
my $dstport = unpack('n', $request);
if($debug && !$self->_debugged(++$debugs))
{
$debug->add(
dstaddr => $dstaddr,
dstport => $dstport
);
$debug->show('Server Recv: ');
}
@{${*$self}->{SOCKS}->{COMMAND}} = ($cmd, $dstaddr, $dstport);
return 1;
}
###############################################################################
#
# _socks5_acccept_command_reply - Answer a SOCKS5 command request. Since this
# is a library and not a server, we cannot
# process the command. Let the parent program
# handle that.
#
###############################################################################
sub _socks5_accept_command_reply
{
my $self = shift;
my $reply = shift;
my $host = shift;
my $port = shift;
my $debug = IO::Socket::Socks::Debug->new() if ${*$self}->{SOCKS}->{Debug};
my $resolve = defined(${*$self}->{SOCKS}->{Resolve}) ? ${*$self}->{SOCKS}->{Resolve} : $SOCKS5_RESOLVE;
my ($reads, $sends, $debugs) = (0, 0, 0);
if (!defined($reply) || !defined($host) || !defined($port))
{
croak("You must provide a reply, host, and port on the command reply.");
}
#--------------------------------------------------------------------------
# Send the reply
#--------------------------------------------------------------------------
# +----+-----+-------+------+----------+----------+
# |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
# +----+-----+-------+------+----------+----------+
# | 1 | 1 | X'00' | 1 | Variable | 2 |
# +----+-----+-------+------+----------+----------+
my $atyp = $resolve ? ADDR_IPV4 : ADDR_DOMAINNAME;
my $bndaddr = $resolve ? inet_aton($host) : $host;
my $hlen = length($bndaddr) unless $resolve;
my $rc; $rc = $self->_socks_send(pack('CCCC', SOCKS5_VER, $reply, 0, $atyp) . ($resolve ? '' : pack('C', $hlen)) . $bndaddr . pack('n', $port), ++$sends)
or return _fail($rc);
if($debug && !$self->_debugged(++$debugs))
{
$debug->add(
ver => SOCKS5_VER,
rep => $reply,
rsv => 0,
atyp => $atyp
);
$debug->add(hlen => $hlen) unless $resolve;
$debug->add(
bndaddr => $resolve ? (length($bndaddr) == 4 ? inet_ntoa($bndaddr) : undef) : $bndaddr,
bndport => $port
);
$debug->show('Server Send: ');
}
1;
}
###############################################################################
#
# _socks4_accept_command - Wait for an opening handsake and process a SOCKS4
# command request. Since this is a library and not
# a server, we cannot process the command. Let the
# parent program handle that.
#
###############################################################################
sub _socks4_accept_command
{
my $self = shift;
my $debug = IO::Socket::Socks::Debug->new() if ${*$self}->{SOCKS}->{Debug};
my $resolve = defined(${*$self}->{SOCKS}->{Resolve}) ? ${*$self}->{SOCKS}->{Resolve} : $SOCKS4_RESOLVE;
my ($reads, $sends, $debugs) = (0, 0, 0);
@{${*$self}->{SOCKS}->{COMMAND}} = ();
#--------------------------------------------------------------------------
# Read the auth mechanisms
#--------------------------------------------------------------------------
# +-----+-----+----------+---------------+----------+------+
# | VER | CMD | DST.PORT | DST.ADDR | USERID | NULL |
# +-----+-----+----------+---------------+----------+------+
# | 1 | 1 | 2 | 4 | variable | 1 |
# +-----+-----+----------+---------------+----------+------+
my $request;
$request = $self->_socks_read(8, ++$reads)
or return _fail($request);
my ($ver, $cmd, $dstport) = unpack('CCn', $request);
substr($request, 0, 4) = '';
my $dstaddr = length($request) == 4 ? inet_ntoa($request) : undef;
my $userid = '';
my $c;
while(1)
{
length( $c = $self->_socks_read(1, ++$reads) )
or return _fail($c);
if($c ne "\0")
{
$userid .= $c;
}
else
{
last;
}
}
if($debug && !$self->_debugged(++$debugs))
{
$debug->add(
ver => $ver,
cmd => $cmd,
dstport => $dstport,
dstaddr => $dstaddr,
userid => $userid,
null => 0
);
}
if($resolve && $dstaddr =~ /^0\.0\.0\.[1-9]/)
{ # socks4a
my $dsthost = '';
while(1)
{
length( $c = $self->_socks_read(1, ++$reads) )
or return _fail($c);
if($c ne "\0")
{
$dsthost .= $c;
}
else
{
last;
}
}
if($debug && !$self->_debugged(++$debugs))
{
$debug->add(
dsthost => $dsthost,
null => 0
);
}
$dstaddr = join('.', unpack('C4', (gethostbyname($dsthost))[4]));
}
if($debug && !$self->_debugged(++$debugs))
{
$debug->show('Server Recv: ');
}
if(defined(${*$self}->{SOCKS}->{UserAuth}))
{
unless( &{${*$self}->{SOCKS}->{UserAuth}}($userid) )
{
${*$self}->{SOCKS}->{queue} = [
['_socks4_accept_command_reply', [REQUEST_REJECTED_USERID, '0.0.0.0', 0], undef, [], 0]
];
$! = ESOCKSPROTO;
$SOCKS_ERROR->set(REQUEST_REJECTED_USERID, $@ = 'Authentication failed with SOCKS4 proxy');
return 1;
}
}
if($ver != SOCKS4_VER)
{
$! = ESOCKSPROTO;
$SOCKS_ERROR->set(ISS_BAD_VERSION, $@ = "Socks version should be 4, $ver recieved");
return;
}
@{${*$self}->{SOCKS}->{COMMAND}} = ($cmd, $dstaddr, $dstport);
return 1;
}
###############################################################################
#
# _socks4_acccept_command_reply - Answer a SOCKS4 command request. Since this
# is a library and not a server, we cannot
# process the command. Let the parent program
# handle that.
#
###############################################################################
sub _socks4_accept_command_reply
{
my $self = shift;
my $reply = shift;
my $host = shift;
my $port = shift;
my $debug = IO::Socket::Socks::Debug->new() if ${*$self}->{SOCKS}->{Debug};
my ($reads, $sends, $debugs) = (0, 0, 0);
if (!defined($reply) || !defined($host) || !defined($port))
{
croak("You must provide a reply, host, and port on the command reply.");
}
#--------------------------------------------------------------------------
# Send the reply
#--------------------------------------------------------------------------
# +-----+-----+----------+---------------+
# | VER | REP | BND.PORT | BND.ADDR |
# +-----+-----+----------+---------------+
# | 1 | 1 | 2 | 4 |
# +-----+-----+----------+---------------+
my $bndaddr = inet_aton($host);
my $rc; $rc = $self->_socks_send(pack('CCna*', 0, $reply, $port, $bndaddr), ++$sends)
or return _fail($rc);
if($debug && !$self->_debugged(++$debugs))
{
$debug->add(
ver => 0,
rep => $reply,
bndport => $port,
bndaddr => length($bndaddr) == 4 ? inet_ntoa($bndaddr) : undef
);
$debug->show('Server Send: ');
}
1;
}
###############################################################################
#
# command - return the command the user request along with the host and
# port to operate on.
#
###############################################################################
sub command
{
my $self = shift;
unless(exists ${*$self}->{SOCKS}->{RequireAuth}) # TODO: find more correct way
{
return ${*$self}->{SOCKS}->{COMMAND};
}
else
{
my @keys = qw(Version AuthType RequireAuth UserAuth Username Password
Debug Resolve AuthMethods CmdAddr CmdPort Bind TCP);
my %tmp;
$tmp{$_} = ${*$self}->{SOCKS}->{$_} for @keys;
my %args = @_;
$self->_configure(\%args);
if( $self->_connect() )
{
return 1;
}
${*$self}->{SOCKS}->{$_} = $tmp{$_} for @keys;
return 0;
}
}
###############################################################################
#
# command_reply - public reply wrapper to the client.
#
###############################################################################
sub command_reply
{
my $self = shift;
${*$self}->{SOCKS}->{ready} = 0;
if(${*$self}->{SOCKS}->{Version} == 4)
{
${*$self}->{SOCKS}->{queue} = [
['_socks4_accept_command_reply', [@_], undef, [], 0]
];
}
else
{
${*$self}->{SOCKS}->{queue} = [
['_socks5_accept_command_reply', [@_], undef, [], 0]
];
}
$self->_run_queue();
}
###############################################################################
#
# dst - access to the address and port selected by socks server when connect/bind/udpassoc
#
###############################################################################
sub dst
{
my $self = shift;
return (${*$self}->{SOCKS}->{DstAddr}, ${*$self}->{SOCKS}->{DstPort});
}
###############################################################################
#
# send - send UDP datagram
#
###############################################################################
sub send
{
my $self = shift;
unless(defined ${*$self}->{SOCKS}->{TCP})
{
return $self->SUPER::send(@_);
}
my ($msg, $flags, $peer) = @_;
my $debug = IO::Socket::Socks::Debug->new() if ${*$self}->{SOCKS}->{Debug};
my $resolve = defined(${*$self}->{SOCKS}->{Resolve}) ? ${*$self}->{SOCKS}->{Resolve} : $SOCKS5_RESOLVE;
croak "send: Cannot determine peer address"
unless defined $peer;
my ($dstport, $dstaddr) = sockaddr_in($peer);
my ($sndaddr, $sndport) = $self->dst;
if($sndaddr eq '0.0.0.0')
{
$sndaddr = ${*$self}->{SOCKS}->{ProxyAddr};
}
$sndaddr = inet_aton($sndaddr);
$peer = sockaddr_in($sndport, $sndaddr);
my ($atyp, $hlen);
if($resolve)
{
$atyp = ADDR_DOMAINNAME;
$dstaddr = inet_ntoa($dstaddr);
$hlen = length($dstaddr);
}
else
{
$atyp = ADDR_IPV4;
}
my $msglen = length($msg) if $debug;
# we need to add socks header to the message
# +----+------+------+----------+----------+----------+
# |RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA |
# +----+------+------+----------+----------+----------+
# | 2 | 1 | 1 | Variable | 2 | Variable |
# +----+------+------+----------+----------+----------+
$msg = pack('C4', 0, 0, 0, $atyp) . ($resolve ? pack('C', $hlen) : '') . $dstaddr . pack('n', $dstport) . $msg;
if($debug)
{
$debug->add(
rsv => '00',
frag => '0',
atyp => $atyp
);
$debug->add(hlen => $hlen) if $resolve;
$debug->add(
dstaddr => $resolve ? $dstaddr : (length($dstaddr) == 4 ? inet_ntoa($dstaddr) : undef),
dstport => $dstport,
data => "...($msglen)"
);
$debug->show('Client Send: ');
}
$self->SUPER::send($msg, $flags, $peer);
}
###############################################################################
#
# recv - receive UDP datagram
#
###############################################################################
sub recv
{
my $self = shift;
unless(defined ${*$self}->{SOCKS}->{TCP})
{
return $self->SUPER::recv(@_);
}
my $debug = IO::Socket::Socks::Debug->new() if ${*$self}->{SOCKS}->{Debug};
defined(my $peer = $self->SUPER::recv($_[0], $_[1]+262, $_[2]) )
or return;
# we need to remove socks header from the message
# +----+------+------+----------+----------+----------+
# |RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA |
# +----+------+------+----------+----------+----------+
# | 2 | 1 | 1 | Variable | 2 | Variable |
# +----+------+------+----------+----------+----------+
my $rsv = join('', unpack('C2', $_[0]));
substr($_[0], 0, 2) = '';
my ($frag, $atyp) = unpack('C2', $_[0]);
substr($_[0], 0, 2) = '';
if($debug)
{
$debug->add(
rsv => $rsv,
frag => $frag,
atyp => $atyp
);
}
my $dstaddr;
if($atyp == ADDR_DOMAINNAME)
{
my $hlen = unpack('C', $_[0]);
$dstaddr = substr($_[0], 1, $hlen);
substr($_[0], 0, $hlen+1) = '';
if($debug)
{
$debug->add(
hlen => $hlen
);
}
}
elsif($atyp == ADDR_IPV4)
{
$dstaddr = substr($_[0], 0, 4);
$dstaddr = length($dstaddr) == 4 ? inet_ntoa($dstaddr) : undef;
substr($_[0], 0, 4) = '';
}
else
{
$! = ESOCKSPROTO;
$SOCKS_ERROR->set(ISS_UNKNOWN_ADDRESS, $@ = "Unsupported address type returned by socks server: $atyp");
return;
}
my $dstport = unpack('n', $_[0]);
substr($_[0], 0, 2) = '';
if($debug)
{
$debug->add(
dstaddr => $dstaddr,
dstport => $dstport,
data => "...(" . length($_[0]) . ")"
);
$debug->show('Client Recv: ');
}
return $peer;
}
###############################################################################
#+-----------------------------------------------------------------------------
#| Helper Functions
#+-----------------------------------------------------------------------------
###############################################################################
sub _socks_send
{ # this sub may cause SIGPIPE if you'll not alternate it call with _socks_read()
my $self = shift;
my $data = shift;
my $numb = shift;
$SOCKS_ERROR->set();
my $rc;
my $writed = 0;
my $blocking = ${*$self}{io_socket_timeout} ? $self->blocking(0) : $self->blocking;
unless($blocking || ${*$self}{io_socket_timeout})
{
if(${*$self}->{SOCKS}->{queue}[0][Q_SENDS] >= $numb)
{ # already sent
return 1;
}
if(defined ${*$self}->{SOCKS}->{queue}[0][Q_BUF])
{ # some chunk already sent
substr($data, 0, ${*$self}->{SOCKS}->{queue}[0][Q_BUF]) = '';
}
while(length $data)
{
$rc = $self->syswrite($data);
if(defined $rc)
{
${*$self}->{SOCKS}->{connected} = 1 unless ${*$self}->{SOCKS}->{connected};
if($rc > 0)
{
${*$self}->{SOCKS}->{queue}[0][Q_BUF] += $rc;
substr($data, 0, $rc) = '';
}
else
{ # XXX: socket closed? if smth writed, but not all?
last;
}
}
elsif($! == EWOULDBLOCK || $! == EAGAIN ||
($! == ENOTCONN && !${*$self}->{SOCKS}->{connected}))
{
$SOCKS_ERROR->set(SOCKS_WANT_WRITE, 'Socks want write');
return undef;
}
else
{
$SOCKS_ERROR->set($!, $@ = "send: $!");
last;
}
}
$writed = int(${*$self}->{SOCKS}->{queue}[0][Q_BUF]);
${*$self}->{SOCKS}->{queue}[0][Q_BUF] = undef;
${*$self}->{SOCKS}->{queue}[0][Q_SENDS]++;
return $writed;
}
my $selector = IO::Select->new($self);
my $start = time();
while(1)
{
if(${*$self}{io_socket_timeout} && time() - $start >= ${*$self}{io_socket_timeout})
{
$! = ETIMEDOUT;
last;
}
unless($selector->can_write(1))
{ # socket couldn't accept data for now, check if timeout expired and try again
next;
}
$rc = $self->syswrite($data);
if($rc > 0)
{ # reduce our message
$writed += $rc;
substr($data, 0, $rc) = '';
if(length($data) == 0)
{ # all data successfully writed
last;
}
}
else
{ # some error in the socket; will return false
$SOCKS_ERROR->set($!, $@ = "send: $!") unless defined $rc;
last;
}
}
$self->blocking(1) if $blocking;
return $writed;
}
sub _socks_read
{
my $self = shift;
my $length = shift || 1;
my $numb = shift;
$SOCKS_ERROR->set();
my $data = '';
my ($buf, $rc);
my $blocking = $self->blocking;
# non-blocking read
unless ($blocking || ${*$self}{io_socket_timeout})
{ # no timeout should be specified for non-blocking connect
if(defined ${*$self}->{SOCKS}->{queue}[0][Q_READS][$numb])
{ # already readed
return ${*$self}->{SOCKS}->{queue}[0][Q_READS][$numb];
}
if(defined ${*$self}->{SOCKS}->{queue}[0][Q_BUF])
{ # some chunk already readed
$data = ${*$self}->{SOCKS}->{queue}[0][Q_BUF];
$length -= length $data;
}
while($length > 0)
{
$rc = $self->sysread($buf, $length);
if(defined $rc)
{
if($rc > 0)
{
$length -= $rc;
$data .= $buf;
}
else
{ # XXX: socket closed, if smth readed but not all?
last
}
}
elsif($! == EWOULDBLOCK || $! == EAGAIN)
{ # no data to read
if (length $data)
{ # save already readed data in the queue buffer
${*$self}->{SOCKS}->{queue}[0][Q_BUF] = $data;
}
$SOCKS_ERROR->set(SOCKS_WANT_READ, 'Socks want read');
return undef;
}
else
{
$SOCKS_ERROR->set($!, $@ = "read: $!");
last;
}
}
${*$self}->{SOCKS}->{queue}[0][Q_BUF] = undef;
${*$self}->{SOCKS}->{queue}[0][Q_READS][$numb] = $data;
return $data;
}
# blocking read
my $selector = IO::Select->new($self);
my $start = time();
while($length > 0)
{
if(${*$self}{io_socket_timeout} && time() - $start >= ${*$self}{io_socket_timeout})
{
$! = ETIMEDOUT;
last;
}
unless($selector->can_read(1))
{ # no data in socket for now, check if timeout expired and try again
next;
}
$rc = $self->sysread($buf, $length);
if(defined $rc && $rc > 0)
{ # reduce limit and modify buffer
$length -= $rc;
$data .= $buf;
}
else
{ # EOF or error in the socket
$SOCKS_ERROR->set($!, $@ = "read: $!") unless defined $rc;
last; # TODO handle unexpected EOF more correct
}
}
# XXX it may return incomplete $data if timed out. Could it break smth?
return $data;
}
sub _debugged
{
my ($self, $debugs) = @_;
if(${*$self}->{SOCKS}->{queue}[0][Q_DEBUGS] >= $debugs)
{
return 1;
}
${*$self}->{SOCKS}->{queue}[0][Q_DEBUGS] = $debugs;
return 0;
}
sub _fail
{
if(!@_ || defined($_[0]))
{
$SOCKS_ERROR->set(ETIMEDOUT, $@ = 'Timeout') if $SOCKS_ERROR == undef;
return;
}
return -1;
}
###############################################################################
#+-----------------------------------------------------------------------------
#| Helper Package to bring some magic in $SOCKS_ERROR
#+-----------------------------------------------------------------------------
###############################################################################
package IO::Socket::Socks::Error;
use strict;
use overload
'==' => \&num_eq,
'!=' => sub { !num_eq(@_) },
'""' => \&as_str,
'0+' => \&as_num;
sub new
{
my ($class, $num, $str) = @_;
my $self = {
num => $num,
str => $str,
};
bless $self, $class;
}
sub set
{
my ($self, $num, $str) = @_;
$self->{num} = defined $num ? int($num) : $num;
$self->{str} = $str;
}
sub as_str
{
my $self = shift;
return $self->{str};
}
sub as_num
{
my $self = shift;
return $self->{num};
}
sub num_eq
{
my ($self, $num) = @_;
unless(defined $num)
{
return !defined($self->{num});
}
return $self->{num} == int($num);
}
###############################################################################
#+-----------------------------------------------------------------------------
#| Helper Package to display pretty debug messages
#+-----------------------------------------------------------------------------
###############################################################################
package IO::Socket::Socks::Debug;
sub new
{
my ($class) = @_;
my $self = [];
bless $self, $class;
}
sub add
{
my $self = shift;
push @{$self}, @_;
}
sub show
{
my ($self, $tag) = @_;
$self->_separator($tag);
$self->_row(0, $tag);
$self->_separator($tag);
$self->_row(1, $tag);
$self->_separator($tag);
print STDERR "\n";
@{$self} = ();
}
sub _separator
{
my $self = shift;
my $tag = shift;
my ($row1_len, $row2_len, $len);
print STDERR $tag, '+';
for(my $i=0; $i<@$self; $i+=2)
{
$row1_len = length($self->[$i]);
$row2_len = length($self->[$i+1]);
$len = ($row1_len > $row2_len ? $row1_len : $row2_len)+2;
print STDERR '-' x $len, '+';
}
print STDERR "\n";
}
sub _row
{
my $self = shift;
my $row = shift;
my $tag = shift;
my ($row1_len, $row2_len, $len);
print STDERR $tag, '|';
for(my $i=0; $i<@$self; $i+=2)
{
$row1_len = length($self->[$i]);
$row2_len = length($self->[$i+1]);
$len = ($row1_len > $row2_len ? $row1_len : $row2_len);
printf STDERR ' %-'.$len.'s |', $self->[$i+$row];
}
print STDERR "\n";
}
1;
__END__
=head1 NAME
IO::Socket::Socks - Provides a way to create socks client or server both 4 and 5 version.
=head1 SYNOPSIS
=head2 Client
use IO::Socket::Socks;
my $socks = new IO::Socket::Socks(ProxyAddr=>"proxy host",
ProxyPort=>"proxy port",
ConnectAddr=>"remote host",
ConnectPort=>"remote port",
);
print $socks "foo\n";
$socks->close();
=head2 Server
use IO::Socket::Socks;
my $socks_server = new IO::Socket::Socks(ProxyAddr=>"localhost",
ProxyPort=>"8000",
Listen=>1,
UserAuth=>\&auth,
RequireAuth=>1
);
my $select = new IO::Select($socks_server);
while(1)
{
if ($select->can_read())
{
my $client = $socks_server->accept();
if (!defined($client))
{
print "ERROR: $SOCKS_ERROR\n";
next;
}
my $command = $client->command();
if ($command->[0] == 1) # CONNECT
{
# Handle the CONNECT
$client->command_reply(0, addr, port);
}
...
#read from the client and send to the CONNECT address
...
$client->close();
}
}
sub auth
{
my $user = shift;
my $pass = shift;
return 1 if (($user eq "foo") && ($pass eq "bar"));
return 0;
}
=head1 DESCRIPTION
IO::Socket::Socks connects to a SOCKS proxy, tells it to open a
connection to a remote host/port when the object is created. The
object you receive can be used directly as a socket for sending and
receiving data from the remote host. In addition to create socks client
this module could be used to create socks server. See examples below.
=head1 EXAMPLES
For complete examples of socks 4/5 client and server see `examples'
subdirectory in the distribution.
=head1 METHODS
=head2 Socks Client
=head3 new( %cfg )
=head3 new_from_socket($socket, %cfg)
=head3 new_from_fd($socket, %cfg)
Creates a new IO::Socket::Socks client object. new_from_socket() is the same as
new(), but allows one to create object from an existing socket (new_from_fd is new_from_socket alias).
Both takes the following config hash:
SocksVersion => 4 or 5. Default is 5
Timeout => connect/accept timeout
Blocking => Since IO::Socket::Socks version 0.5 you can perform non-blocking connect/bind by
passing false value for this option. Default is true - blocking. See ready()
below for more details.
SocksResolve => resolve host name to ip by proxy server or
not (will resolve by client). This
overrides value of $SOCKS4_RESOLVE or $SOCKS5_RESOLVE
variable. Boolean.
SocksDebug => This will cause all of the SOCKS traffic to
be presented on the command line in a form
similar to the tables in the RFCs. This overrides value
of $SOCKS_DEBUG variable. Boolean.
ProxyAddr => Hostname of the proxy
ProxyPort => Port of the proxy
ConnectAddr => Hostname of the remote machine
ConnectPort => Port of the remote machine
BindAddr => Hostname of the remote machine which will
connect to the proxy server after bind request
BindPort => Port of the remote machine which will
connect to the proxy server after bind request
UdpAddr => Associate UDP socket on the server with this client
hostname
UdpPort => Associate UDP socket on the server with this client
port
AuthType => What kind of authentication to support:
none - no authentication (default)
userpass - Username/Password. For socks5
proxy only.
RequireAuth => Do not send ANON as a valid auth mechanism.
For socks5 proxy only
Username => For socks5 if AuthType is set to userpass, then
you must provide a username. For socks4 proxy with
this option you can specify userid.
Password => If AuthType is set to userpass, then you must
provide a password. For socks5 proxy only.
The following options should be specified:
ProxyAddr and ProxyPort
ConnectAddr and ConnectPort or BindAddr and BindPort or UdpAddr and UdpPort
Other options are facultative.
=head3
ready( )
Returns true when socket becomes ready to transfer data (socks handshake done),
false otherwise. This is useful for non-blocking connect/bind. When this method
returns false value you can determine what socks handshake need for with $SOCKS_ERROR
variable. It may need for read, then $SOCKS_ERROR will be SOCKS_WANT_READ or need for
write, then it will be SOCKS_WANT_WRITE.
Example:
use IO::Socket::Socks;
use IO::Select;
my $sock = IO::Socket::Socks->new(
ProxyAddr => 'localhost', ProxyPort => 1080, ConnectAddr => 'mail.com', ConnectPort => 80, Blocking => 0
) or die $SOCKS_ERROR;
my $sel = IO::Select->new($sock);
until ($sock->ready) {
if ($SOCKS_ERROR == SOCKS_WANT_READ) {
$sel->can_read();
}
elsif ($SOCKS_ERROR == SOCKS_WANT_WRITE) {
$sel->can_write();
}
else {
die $SOCKS_ERROR;
}
}
# you may want to return socket to blocking state by $sock->blocking(1)
$sock->syswrite("I am ready");
=head3
accept( )
Accept an incoming connection after bind request. On failed returns undef.
On success returns socket. No new socket created, returned socket is same
on which this method was called. Because accept(2) is not invoked on the
client side, socks server calls accept(2) and proxify all traffic via socket
opened by client bind request. You can call accept only once on IO::Socket::Socks
client socket.
=head3
command( %cfg )
Allows one to execute socks command on already opened socket. Thus you
can create socks chain. For example see L</EXAMPLES> section.
%cfg is like hash in the constructor. Only options listed below makes sence:
ConnectAddr
ConnectPort
BindAddr
BindPort
UdpAddr
UdpPort
SocksVersion
SocksDebug
SocksResolve
AuthType
RequireAuth
Username
Password
AuthMethods
Values of the other options (Timeout for example) inherited from the constructor.
Options like ProxyAddr and ProxyPort are not included.
=head3
dst( )
Return (host, port) of the remote host after connect/accept or socks server (host, port)
after bind/udpassoc.
=head2 Socks Server
=head3 new( %cfg )
=head3 new_from_socket($socket, %cfg)
=head3 new_from_fd($socket, %cfg)
Creates a new IO::Socket::Socks server object. new_from_socket() is the same as
new(), but allows one to create object from an existing socket (new_from_fd is new_from_socket alias).
Both takes the following config hash:
SocksVersion => 4 for socks v4, 5 for socks v5. Default is 5
Timeout => Timeout value for various operations
Blocking => Since IO::Socket::Socks version 0.6 you can perform non-blocking accept by
passing false value for this option. Default is true - blocking. See ready()
below for more details.
SocksResolve => For socks v5: return destination address to the client
in form of 4 bytes if true, otherwise in form of host
length and host name.
For socks v4: allow use socks4a protocol extension if
true and not otherwise.
This overrides value of $SOCKS4_RESOLVE or $SOCKS5_RESOLVE.
SocksDebug => This will cause all of the SOCKS traffic to
be presented on the command line in a form
similar to the tables in the RFCs. This overrides value
of $SOCKS_DEBUG variable. Boolean.
ProxyAddr => Local host bind address
ProxyPort => Local host bind port
UserAuth => Reference to a function that returns 1 if client
allowed to use socks server, 0 otherwise. For
socks5 proxy it takes login and password as
arguments. For socks4 argument is userid.
RequireAuth => Not allow anonymous access for socks5 proxy.
Listen => Same as IO::Socket::INET listen option. Should be
specified as number > 0.
The following options should be specified:
Listen
ProxyAddr
ProxyPort
Other options are facultative.
=head3 accept( )
Accept an incoming connection and return a new IO::Socket::Socks
object that represents that connection. You must call command()
on this to find out what the incoming connection wants you to do,
and then call command_reply() to send back the reply.
=head3 ready( )
After non-blocking accept you will get new client socket object, which may be
not ready to transfer data (if socks handshake is not done yet). ready() will return
true value when handshake will be done successfully and false otherwise. Note, socket
returned by accept() call will be always in blocking mode. So if your program can't
block you should set non-blocking mode for this socket before ready() call: $socket->blocking(0).
When ready() returns false value you can determine what socks handshake needs for with $SOCKS_ERROR
variable. It may need for read, then $SOCKS_ERROR will be SOCKS_WANT_READ or need for
write, then it will be SOCKS_WANT_WRITE.
Example:
use IO::Socket::Socks;
use IO::Select;
my $server = IO::Socket::Socks->new(ProxyAddr => 'localhost', ProxyPort => 1080, Blocking => 0)
or die $@;
my $select = IO::Select->new($server);
$select->can_read(); # wait for client
my $client = $server->accept()
or die "accept(): $! ($SOCKS_ERROR)";
$client->blocking(0); # !!!
$select->add($client);
$select->remove($server); # no more connections
while (1) {
if ($client->ready) {
my $command = $client->command;
... # do client command
$client->command_reply(IO::Socket::Socks::REPLY_SUCCESS, $command->[1], $command->[2]);
... # transfer traffic
last;
}
elsif ($SOCKS_ERROR == SOCKS_WANT_READ) {
$select->can_read();
}
elsif ($SOCKS_ERROR == SOCKS_WANT_WRITE) {
$select->can_write();
}
else {
die "Unexpected error: $SOCKS_ERROR";
}
}
=head3 command( )
After you call accept() the client has sent the command they want
you to process. This function should be called on the socket returned
by accept(). It returns a reference to an array with the following format:
[ COMMAND, HOST, PORT ]
=head3 command_reply( REPLY CODE, HOST, PORT )
After you call command() the client needs to be told what the result
is. The REPLY CODE is as follows (integer value):
For socks v4
REQUEST_GRANTED(90): request granted
REQUEST_FAILED(91): request rejected or failed
REQUEST_REJECTED_IDENTD(92): request rejected becasue SOCKS server cannot connect to identd on the client
REQUEST_REJECTED_USERID(93): request rejected because the client program and identd report different user-ids
For socks v5
REPLY_SUCCESS(0): Success
REPLY_GENERAL_FAILURE(1): General Failure
REPLY_CONN_NOT_ALLOWED(2): Connection Not Allowed
REPLY_NETWORK_UNREACHABLE(3): Network Unreachable
REPLY_HOST_UNREACHABLE(4): Host Unreachable
REPLY_CONN_REFUSED(5): Connection Refused
REPLY_TTL_EXPIRED(6): TTL Expired
REPLY_CMD_NOT_SUPPORTED(7): Command Not Supported
REPLY_ADDR_NOT_SUPPORTED(8): Address Not Supported
HOST and PORT are the resulting host and port that you use for the
command.
=head1 VARIABLES
=head2 $SOCKS_ERROR
This scalar behaves like $! in that if undef is returned. C<$SOCKS_ERROR> is IO::Socket::Socks::ERROR
object with some overloaded operators. In string context this variable should contain a string reason for
the error. In numeric context it contains error code.
=head2 $SOCKS4_RESOLVE
If this variable has true value resolving of host names will be done
by proxy server, otherwise resolving will be done locally. Resolving
host by socks proxy version 4 is extension to the protocol also known
as socks4a. So, only socks4a proxy supports resolving of hostnames.
Default value of this variable is false. This variable is not importable.
See also `SocksResolve' parameter in the constructor.
=head2 $SOCKS5_RESOLVE
If this variable has true value resolving of host names will be done
by proxy server, otherwise resolving will be done locally. Note: some
bugous socks5 servers doesn't support resolving of host names. Default
value is true. This variable is not importable.
See also `SocksResolve' parameter in the constructor.
=head2 $SOCKS_DEBUG
Default value is $ENV{SOCKS_DEBUG}. If this variable has true value and
no SocksDebug option in the constructor specified, then SocksDebug will
has true value. This variable is not importable.
=head1 CONSTANTS
The following constants could be imported manually or using `:constants' tag:
SOCKS5_VER
SOCKS4_VER
ADDR_IPV4
ADDR_DOMAINNAME
ADDR_IPV6
CMD_CONNECT
CMD_BIND
CMD_UDPASSOC
AUTHMECH_ANON
AUTHMECH_USERPASS
AUTHMECH_INVALID
AUTHREPLY_SUCCESS
AUTHREPLY_FAILURE
ISS_UNKNOWN_ADDRESS
ISS_BAD_VERSION
REPLY_SUCCESS
REPLY_GENERAL_FAILURE
REPLY_CONN_NOT_ALLOWED
REPLY_NETWORK_UNREACHABLE
REPLY_HOST_UNREACHABLE
REPLY_CONN_REFUSED
REPLY_TTL_EXPIRED
REPLY_CMD_NOT_SUPPORTED
REPLY_ADDR_NOT_SUPPORTED
REQUEST_GRANTED
REQUEST_FAILED
REQUEST_REJECTED_IDENTD
REQUEST_REJECTED_USERID
SOCKS_WANT_READ
SOCKS_WANT_WRITE
ESOCKSPROTO
SOCKS_WANT_READ, SOCKS_WANT_WRITE and ESOCKSPROTO are imported by default.
=head1 FAQ
=over
=item How to determine is connection to socks server (client accept) failed or some protocol error
occurred?
You can check $! variable. If $! == ESOCKSPROTO constant, then it was error in the protocol. Error
description could be found in $SOCKS_ERROR.
=item How to determine which error in the protocol occurred?
You should compare C<$SOCKS_ERROR> with constants below:
AUTHMECH_INVALID
AUTHREPLY_FAILURE
ISS_UNKNOWN_ADDRESS # address type sent by client/server not supported by I::S::S
ISS_BAD_VERSION # socks version sent by client/server != specified version
REPLY_GENERAL_FAILURE
REPLY_CONN_NOT_ALLOWED
REPLY_NETWORK_UNREACHABLE
REPLY_HOST_UNREACHABLE
REPLY_CONN_REFUSED
REPLY_TTL_EXPIRED
REPLY_CMD_NOT_SUPPORTED
REPLY_ADDR_NOT_SUPPORTED
REQUEST_FAILED
REQUEST_REJECTED_IDENTD
REQUEST_REJECTED_USERID
=back
=head1 BUGS
The following options are not implemented:
=over
=item GSSAPI authentication
=item UDP server side support
=item IPV6 support
=back
Patches are welcome.
=head1 SEE ALSO
L<IO::Socket::Socks::Wrapper>
=head1 AUTHOR
Original author is Ryan Eatmon
Now maintained by Oleg G <oleg@cpan.org>
=head1 COPYRIGHT
This module is free software, you can redistribute it and/or modify
it under the terms of LGPL.
=cut
|