tokio-socks-0.5.2/.cargo_vcs_info.json0000644000000001360000000000100133050ustar { "git": { "sha1": "2eeb99ccf290f787e549ffb35b05ad4e3e1a20c2" }, "path_in_vcs": "" }tokio-socks-0.5.2/.github/workflows/main.yml000064400000000000000000000027221046102023000171440ustar 00000000000000name: CI on: push: branches: master pull_request: branches: master jobs: test: strategy: matrix: rust: [stable, beta, nightly] runs-on: [ubuntu-latest] steps: - uses: actions/checkout@v4 - uses: actions-rust-lang/setup-rust-toolchain@v1 with: toolchain: ${{ matrix.rust }} components: clippy - name: Clippy run: | cargo clippy --all-targets --no-default-features --features=tokio -- -D warnings cargo clippy --all-targets --no-default-features --features=tokio,tor -- -D warnings cargo clippy --all-targets --no-default-features --features=futures-io -- -D warnings cargo clippy --all-targets --no-default-features --features=futures-io,tor -- -D warnings cargo clippy --all-targets --all-features -- -D warnings - name: Install 3proxy run: | cd $HOME curl -OL https://github.com/3proxy/3proxy/archive/refs/tags/0.8.13.tar.gz tar xvf 0.8.13.tar.gz cd 3proxy-0.8.13 && ln -s Makefile.Linux Makefile && make -j$(nproc) sudo apt-get update sudo apt-get install socat -y - name: Build run: | cargo build --examples --all-features cargo build --verbose --all --all-features cargo test --lib --verbose --all-features - name: Run tests run: | env PATH=$HOME/3proxy-0.8.13/src:$PATH tests/integration_tests.sh tokio-socks-0.5.2/.gitignore000064400000000000000000000011261046102023000140650ustar 00000000000000# Generated by Cargo # will have compiled files and executables /target/ # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html Cargo.lock # These are backup files generated by rustfmt **/*.rs.bk # OSX leaves these everywhere on SMB shares ._* # OSX trash .DS_Store # Eclipse files .classpath .project .settings/** # Vim swap files *.swp # Files generated by JetBrains IDEs, e.g. IntelliJ IDEA .idea/ *.iml out/ # Vscode files .vscode/** docker-compose.yml Dockerfiletokio-socks-0.5.2/CHANGELOG.md000064400000000000000000000017301046102023000137070ustar 00000000000000# 0.5.2 * Added SOCKS4 support `bind` and `connect`. * `tokio` becomes an optional dependency and [`futures-io`](https://github.com/rust-lang/futures-rs/tree/0.3.30/futures-io) traits are supported through the `futures-io` feature. # 0.5.1 * Reduce dependencies on `futures` crate (#30) # 0.5.0 * Upgrade tokio to 1.0 (#28) # 0.4.0 * Return error if authorization is required but credentials are not present (#24) * Upgrade tokio to 0.3 (#27) # 0.3.0 * Allow to take arbitrary socket instead of address to establish connections to proxy (#20) # 0.2.2 * Replace failure with thiserror (#17) # 0.2.1 * Remove dependency derefable (#16) # 0.2.0 * Support tokio 0.2 (#10) # 0.1.3 * Implement `IntoTargetAddr<'static>` for `String` (#8) # 0.1.2 * Fix ConnectFuture buffer too small (#1) # 0.1.1 * Support SOCKS5 `BIND` command. * Implement `std::net::ToSocketAddrs` for `TargetAddr`. # 0.1.0 * Support SOCKS5 `CONNECT` command. * Support username authentication. tokio-socks-0.5.2/Cargo.lock0000644000000422170000000000100112660ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "addr2line" version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e4503c46a5c0c7844e948c9a4d6acd9f50cccb4de1c48eb9e291ea17470c678" dependencies = [ "gimli", ] [[package]] name = "adler" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" [[package]] name = "async-channel" version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "89b47800b0be77592da0afd425cc03468052844aff33b84e33cc696f64e77b6a" dependencies = [ "concurrent-queue", "event-listener-strategy", "futures-core", "pin-project-lite", ] [[package]] name = "async-executor" version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7ebdfa2ebdab6b1760375fa7d6f382b9f486eac35fc994625a00e89280bdbb7" dependencies = [ "async-task", "concurrent-queue", "fastrand", "futures-lite", "slab", ] [[package]] name = "async-fs" version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebcd09b382f40fcd159c2d695175b2ae620ffa5f3bd6f664131efff4e8b9e04a" dependencies = [ "async-lock", "blocking", "futures-lite", ] [[package]] name = "async-io" version = "2.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d6baa8f0178795da0e71bc42c9e5d13261aac7ee549853162e66a241ba17964" dependencies = [ "async-lock", "cfg-if", "concurrent-queue", "futures-io", "futures-lite", "parking", "polling", "rustix", "slab", "tracing", "windows-sys", ] [[package]] name = "async-lock" version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff6e472cdea888a4bd64f342f09b3f50e1886d32afe8df3d663c01140b811b18" dependencies = [ "event-listener", "event-listener-strategy", "pin-project-lite", ] [[package]] name = "async-net" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b948000fad4873c1c9339d60f2623323a0cfd3816e5181033c6a5cb68b2accf7" dependencies = [ "async-io", "blocking", "futures-lite", ] [[package]] name = "async-process" version = "2.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f7eda79bbd84e29c2b308d1dc099d7de8dcc7035e48f4bf5dc4a531a44ff5e2a" dependencies = [ "async-channel", "async-io", "async-lock", "async-signal", "async-task", "blocking", "cfg-if", "event-listener", "futures-lite", "rustix", "tracing", "windows-sys", ] [[package]] name = "async-signal" version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dfb3634b73397aa844481f814fad23bbf07fdb0eabec10f2eb95e58944b1ec32" dependencies = [ "async-io", "async-lock", "atomic-waker", "cfg-if", "futures-core", "futures-io", "rustix", "signal-hook-registry", "slab", "windows-sys", ] [[package]] name = "async-task" version = "4.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" [[package]] name = "atomic-waker" version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] name = "autocfg" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" [[package]] name = "backtrace" version = "0.3.73" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5cc23269a4f8976d0a4d2e7109211a419fe30e8d88d677cd60b6bc79c5732e0a" dependencies = [ "addr2line", "cc", "cfg-if", "libc", "miniz_oxide", "object", "rustc-demangle", ] [[package]] name = "bitflags" version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" [[package]] name = "blocking" version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "703f41c54fc768e63e091340b424302bb1c29ef4aa0c7f10fe849dfb114d29ea" dependencies = [ "async-channel", "async-task", "futures-io", "futures-lite", "piper", ] [[package]] name = "bytes" version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a12916984aab3fa6e39d655a33e09c0071eb36d6ab3aea5c2d78551f1df6d952" [[package]] name = "cc" version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2aba8f4e9906c7ce3c73463f62a7f0c65183ada1a2d47e397cc8810827f9694f" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "concurrent-queue" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-utils" version = "0.8.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" [[package]] name = "either" version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" [[package]] name = "errno" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" dependencies = [ "libc", "windows-sys", ] [[package]] name = "event-listener" version = "5.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6032be9bd27023a771701cc49f9f053c751055f71efb2e0ae5c15809093675ba" dependencies = [ "concurrent-queue", "parking", "pin-project-lite", ] [[package]] name = "event-listener-strategy" version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f214dc438f977e6d4e3500aaa277f5ad94ca83fbbd9b1a15713ce2344ccc5a1" dependencies = [ "event-listener", "pin-project-lite", ] [[package]] name = "fastrand" version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" [[package]] name = "futures-core" version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d" [[package]] name = "futures-executor" version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a576fc72ae164fca6b9db127eaa9a9dda0d61316034f33a0a0d4eda41f02b01d" dependencies = [ "futures-core", "futures-task", "futures-util", ] [[package]] name = "futures-io" version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" [[package]] name = "futures-lite" version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52527eb5074e35e9339c6b4e8d12600c7128b68fb25dcb9fa9dec18f7c25f3a5" dependencies = [ "fastrand", "futures-core", "futures-io", "parking", "pin-project-lite", ] [[package]] name = "futures-task" version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" [[package]] name = "futures-util" version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" dependencies = [ "futures-core", "futures-io", "futures-task", "memchr", "pin-project-lite", "pin-utils", "slab", ] [[package]] name = "gimli" version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40ecd4077b5ae9fd2e9e169b102c6c330d0605168eb0e8bf79952b256dbefffd" [[package]] name = "hermit-abi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" [[package]] name = "hermit-abi" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" [[package]] name = "libc" version = "0.2.155" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" [[package]] name = "linux-raw-sys" version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" [[package]] name = "memchr" version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "miniz_oxide" version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08" dependencies = [ "adler", ] [[package]] name = "mio" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4569e456d394deccd22ce1c1913e6ea0e54519f577285001215d33557431afe4" dependencies = [ "hermit-abi 0.3.9", "libc", "wasi", "windows-sys", ] [[package]] name = "object" version = "0.36.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f203fa8daa7bb185f760ae12bd8e097f63d17041dcdcaf675ac54cdf863170e" dependencies = [ "memchr", ] [[package]] name = "once_cell" version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" [[package]] name = "parking" version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb813b8af86854136c6922af0598d719255ecb2179515e6e7730d468f05c9cae" [[package]] name = "pin-project-lite" version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02" [[package]] name = "pin-utils" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "piper" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae1d5c74c9876f070d3e8fd503d748c7d974c3e48da8f41350fa5222ef9b4391" dependencies = [ "atomic-waker", "fastrand", "futures-io", ] [[package]] name = "polling" version = "3.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a3ed00ed3fbf728b5816498ecd316d1716eecaced9c0c8d2c5a6740ca214985b" dependencies = [ "cfg-if", "concurrent-queue", "hermit-abi 0.4.0", "pin-project-lite", "rustix", "tracing", "windows-sys", ] [[package]] name = "proc-macro2" version = "1.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.36" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" dependencies = [ "proc-macro2", ] [[package]] name = "rustc-demangle" version = "0.1.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" [[package]] name = "rustix" version = "0.38.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", "windows-sys", ] [[package]] name = "signal-hook-registry" version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" dependencies = [ "libc", ] [[package]] name = "slab" version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" dependencies = [ "autocfg", ] [[package]] name = "smol" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e635339259e51ef85ac7aa29a1cd991b957047507288697a690e80ab97d07cad" dependencies = [ "async-channel", "async-executor", "async-fs", "async-io", "async-lock", "async-net", "async-process", "blocking", "futures-lite", ] [[package]] name = "socket2" version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" dependencies = [ "libc", "windows-sys", ] [[package]] name = "syn" version = "2.0.72" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc4b9b9bf2add8093d3f2c0204471e951b2285580335de42f9d2534f3ae7a8af" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "thiserror" version = "1.0.63" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0342370b38b6a11b6cc11d6a805569958d54cfa061a29969c3b5ce2ea405724" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "1.0.63" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "tokio" version = "1.39.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "daa4fb1bc778bd6f04cbfc4bb2d06a7396a8f299dc33ea1900cedaa316f467b1" dependencies = [ "backtrace", "bytes", "libc", "mio", "pin-project-lite", "socket2", "windows-sys", ] [[package]] name = "tokio-socks" version = "0.5.2" dependencies = [ "either", "futures-executor", "futures-io", "futures-util", "once_cell", "smol", "thiserror", "tokio", ] [[package]] name = "tracing" version = "0.1.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" dependencies = [ "pin-project-lite", "tracing-core", ] [[package]] name = "tracing-core" version = "0.1.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" [[package]] name = "unicode-ident" version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_gnullvm", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" tokio-socks-0.5.2/Cargo.toml0000644000000046100000000000100113040ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "tokio-socks" version = "0.5.2" authors = ["Yilin Chen "] build = false autobins = false autoexamples = false autotests = false autobenches = false description = "Asynchronous SOCKS proxy support for Rust." homepage = "https://github.com/sticnarf/tokio-socks" documentation = "https://docs.rs/tokio-socks" readme = "README.md" keywords = [ "tokio", "async", "proxy", "socks", "socks5", ] categories = [ "asynchronous", "network-programming", ] license = "MIT" repository = "https://github.com/sticnarf/tokio-socks" [lib] name = "tokio_socks" path = "src/lib.rs" [[example]] name = "chainproxy" path = "examples/chainproxy.rs" required-features = ["tokio"] [[example]] name = "socket" path = "examples/socket.rs" required-features = [ "tokio", "tor", ] [[example]] name = "tor" path = "examples/tor.rs" required-features = [ "tokio", "tor", ] [[test]] name = "long_username_password_auth" path = "tests/long_username_password_auth.rs" [[test]] name = "no_auth" path = "tests/no_auth.rs" [[test]] name = "socks4_no_auth" path = "tests/socks4_no_auth.rs" [[test]] name = "socks4_userid" path = "tests/socks4_userid.rs" [[test]] name = "username_auth" path = "tests/username_auth.rs" [dependencies.either] version = "1" [dependencies.futures-io] version = "0.3" optional = true [dependencies.futures-util] version = "0.3" default-features = false [dependencies.thiserror] version = "1.0" [dependencies.tokio] version = "1.0" features = [ "io-util", "net", ] optional = true [dev-dependencies.futures-executor] version = "0.3" [dev-dependencies.futures-util] version = "0.3" features = ["io"] default-features = false [dev-dependencies.once_cell] version = "1.2.0" [dev-dependencies.smol] version = "2.0.0" [dev-dependencies.tokio] version = "1.0" features = [ "io-util", "rt-multi-thread", "net", ] [features] default = ["tokio"] tor = [] tokio-socks-0.5.2/Cargo.toml.orig000064400000000000000000000022321046102023000147630ustar 00000000000000[package] name = "tokio-socks" description = "Asynchronous SOCKS proxy support for Rust." documentation = "https://docs.rs/tokio-socks" homepage = "https://github.com/sticnarf/tokio-socks" repository = "https://github.com/sticnarf/tokio-socks" readme = "README.md" categories = ["asynchronous", "network-programming"] keywords = ["tokio", "async", "proxy", "socks", "socks5"] license = "MIT" version = "0.5.2" authors = ["Yilin Chen "] edition = "2018" [features] default = ["tokio"] tor = [] [[example]] name = "chainproxy" required-features = ["tokio"] [[example]] name = "socket" required-features = ["tokio", "tor"] [[example]] name = "tor" required-features = ["tokio", "tor"] [dependencies] futures-util = { version = "0.3", default-features = false } futures-io = { version = "0.3", optional = true } tokio = { version = "1.0", features = ["io-util", "net"], optional = true } either = "1" thiserror = "1.0" [dev-dependencies] futures-executor = "0.3" futures-util = { version = "0.3", default-features = false, features = ["io"] } tokio = { version = "1.0", features = ["io-util", "rt-multi-thread", "net"] } once_cell = "1.2.0" smol = "2.0.0" tokio-socks-0.5.2/LICENSE000064400000000000000000000020531046102023000131020ustar 00000000000000MIT License Copyright (c) 2018 Yilin Chen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. tokio-socks-0.5.2/README.md000064400000000000000000000023151046102023000133550ustar 00000000000000# tokio-socks [![Build Status](https://github.com/sticnarf/tokio-socks/actions/workflows/main.yml/badge.svg)](https://github.com/sticnarf/tokio-socks/actions) [![Crates Version](https://img.shields.io/crates/v/tokio-socks.svg)](https://crates.io/crates/tokio-socks) [![docs](https://docs.rs/tokio-socks/badge.svg)](https://docs.rs/tokio-socks) Asynchronous SOCKS proxy support for Rust. ## Features - [x] `CONNECT` command - [x] `BIND` command - [ ] `ASSOCIATE` command - [x] Username/password authentication - [ ] GSSAPI authentication - [ ] Asynchronous DNS resolution - [X] Chain proxies ([see example](examples/chainproxy.rs)) - [X] SOCKS4 ## Compatibility with Other Async Runtimes By default, the `tokio` feature is enabled, as the crate name suggests. Users can opt out `tokio` by setting `default-features = false`. The `*_with_socket` functions accept types implementing the `AsyncSocket` trait. The crate provides `io::Compat` that implements `AsyncSocket` for `futures-io` types (requiring the `futures-io` feature). ## License This project is licensed under the MIT License - see the [LICENSE](/LICENSE) file for details. ## Acknowledgments * [sfackler/rust-socks](https://github.com/sfackler/rust-socks) tokio-socks-0.5.2/examples/chainproxy.rs000064400000000000000000000020611046102023000164440ustar 00000000000000//! Test the proxy chaining capabilities //! //! This example make uses of several public proxy. use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, net::TcpStream, runtime::Runtime, }; use tokio_socks::{tcp::socks5::Socks5Stream, Error}; const PROXY_ADDR: [&str; 2] = ["184.176.166.20:4145", "90.89.205.248:1080"]; // public proxies found here : http://spys.one/en/socks-proxy-list/ const DEST_ADDR: &str = "duckduckgo.com:80"; async fn connect_chained_proxy() -> Result<(), Error> { let proxy_stream = TcpStream::connect(PROXY_ADDR[0]).await?; let chained_proxy_stream = Socks5Stream::connect_with_socket(proxy_stream, PROXY_ADDR[1]).await?; let mut stream = Socks5Stream::connect_with_socket(chained_proxy_stream, DEST_ADDR).await?; stream.write_all(b"GET /\n\n").await?; let mut buf = Vec::new(); let n = stream.read_to_end(&mut buf).await?; println!("{} bytes read\n\n{}", n, String::from_utf8_lossy(&buf)); Ok(()) } fn main() { let rt = Runtime::new().unwrap(); rt.block_on(connect_chained_proxy()).unwrap(); } tokio-socks-0.5.2/examples/socket.rs000064400000000000000000000030551046102023000155540ustar 00000000000000//! Test the tor proxy capabilities //! //! This example requires a running tor proxy. use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, net::{TcpStream, UnixStream}, runtime::Runtime, }; use tokio_socks::{tcp::socks5::Socks5Stream, Error}; const UNIX_PROXY_ADDR: &str = "/tmp/tor/socket.s"; const TCP_PROXY_ADDR: &str = "127.0.0.1:9050"; const ONION_ADDR: &str = "3g2upl4pq6kufc4m.onion:80"; // DuckDuckGo async fn connect() -> Result<(), Error> { // This require Tor to listen on and Unix Domain Socket. // You have to create a directory /tmp/tor owned by tor, and for which only tor // has rights, and add the following line to your torrc : // SocksPort unix:/tmp/tor/socket.s let socket = UnixStream::connect(UNIX_PROXY_ADDR).await?; let target = Socks5Stream::tor_resolve_with_socket(socket, "duckduckgo.com:0").await?; eprintln!("duckduckgo.com = {:?}", target); let socket = UnixStream::connect(UNIX_PROXY_ADDR).await?; let target = Socks5Stream::tor_resolve_ptr_with_socket(socket, "176.34.155.23:0").await?; eprintln!("176.34.155.23 = {:?}", target); let socket = TcpStream::connect(TCP_PROXY_ADDR).await?; socket.set_nodelay(true)?; let mut conn = Socks5Stream::connect_with_socket(socket, ONION_ADDR).await?; conn.write_all(b"GET /\n\n").await?; let mut buf = Vec::new(); let n = conn.read_to_end(&mut buf).await?; println!("{} bytes read\n\n{}", n, String::from_utf8_lossy(&buf)); Ok(()) } fn main() { let rt = Runtime::new().unwrap(); rt.block_on(connect()).unwrap(); } tokio-socks-0.5.2/examples/tor.rs000064400000000000000000000017561046102023000150760ustar 00000000000000//! Test the tor proxy capabilities //! //! This example requires a running tor proxy. use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, runtime::Runtime, }; use tokio_socks::{tcp::socks5::Socks5Stream, Error}; const PROXY_ADDR: &str = "127.0.0.1:9050"; const ONION_ADDR: &str = "3g2upl4pq6kufc4m.onion:80"; // DuckDuckGo async fn connect() -> Result<(), Error> { let target = Socks5Stream::tor_resolve(PROXY_ADDR, "duckduckgo.com:0").await?; eprintln!("duckduckgo.com = {:?}", target); let target = Socks5Stream::tor_resolve_ptr(PROXY_ADDR, "176.34.155.23:0").await?; eprintln!("176.34.155.23 = {:?}", target); let mut conn = Socks5Stream::connect(PROXY_ADDR, ONION_ADDR).await?; conn.write_all(b"GET /\n\n").await?; let mut buf = Vec::new(); let n = conn.read_to_end(&mut buf).await?; println!("{} bytes read\n\n{}", n, String::from_utf8_lossy(&buf)); Ok(()) } fn main() { let rt = Runtime::new().unwrap(); rt.block_on(connect()).unwrap(); } tokio-socks-0.5.2/rustfmt.toml000064400000000000000000000011521046102023000144750ustar 00000000000000use_small_heuristics = "Default" hard_tabs = false imports_layout = "HorizontalVertical" imports_granularity = "Crate" group_imports = "StdExternalCrate" match_block_trailing_comma = true max_width = 120 newline_style = "Unix" normalize_comments = true reorder_imports = true reorder_modules = true reorder_impl_items = true space_after_colon = true space_before_colon = false struct_lit_single_line = true use_field_init_shorthand = true use_try_shorthand = true unstable_features = true format_code_in_doc_comments = true where_single_line = true wrap_comments = true overflow_delimited_expr = true edition = "2018" tokio-socks-0.5.2/src/error.rs000064400000000000000000000050101046102023000143570ustar 00000000000000/// Error type of `tokio-socks` #[derive(thiserror::Error, Debug)] pub enum Error { /// Failure caused by an IO error. #[error("{0}")] Io(#[from] std::io::Error), /// Failure when parsing a `String`. #[error("{0}")] ParseError(#[from] std::string::ParseError), /// Failure due to invalid target address. It contains the detailed error /// message. #[error("Target address is invalid: {0}")] InvalidTargetAddress(&'static str), /// Proxy server unreachable. #[error("Proxy server unreachable")] ProxyServerUnreachable, /// Proxy server returns an invalid version number. #[error("Invalid response version")] InvalidResponseVersion, /// No acceptable auth methods #[error("No acceptable auth methods")] NoAcceptableAuthMethods, /// Unknown auth method #[error("Unknown auth method")] UnknownAuthMethod, /// General SOCKS server failure #[error("General SOCKS server failure")] GeneralSocksServerFailure, /// Connection not allowed by ruleset #[error("Connection not allowed by ruleset")] ConnectionNotAllowedByRuleset, /// Network unreachable #[error("Network unreachable")] NetworkUnreachable, /// Host unreachable #[error("Host unreachable")] HostUnreachable, /// Connection refused #[error("Connection refused")] ConnectionRefused, /// TTL expired #[error("TTL expired")] TtlExpired, /// Command not supported #[error("Command not supported")] CommandNotSupported, /// Address type not supported #[error("Address type not supported")] AddressTypeNotSupported, /// Unknown error #[error("Unknown error")] UnknownError, /// Invalid reserved byte #[error("Invalid reserved byte")] InvalidReservedByte, /// Unknown address type #[error("Unknown address type")] UnknownAddressType, /// Invalid authentication values. It contains the detailed error message. #[error("Invalid auth values: {0}")] InvalidAuthValues(&'static str), /// Password auth failure #[error("Password auth failure, code: {0}")] PasswordAuthFailure(u8), #[error("Authorization required")] AuthorizationRequired, #[error("Request rejected because SOCKS server cannot connect to identd on the client")] IdentdAuthFailure, #[error("Request rejected because the client program and identd report different user-ids")] InvalidUserIdAuthFailure, } ///// Result type of `tokio-socks` // pub type Result = std::result::Result; tokio-socks-0.5.2/src/io/compat/futures.rs000064400000000000000000000025571046102023000166320ustar 00000000000000use std::{ io::Result as IoResult, pin::Pin, task::{Context, Poll}, }; use futures_io::{AsyncRead, AsyncWrite}; use super::Compat; use crate::io::AsyncSocket; impl AsyncSocket for Compat where S: AsyncRead + AsyncWrite + Unpin { fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll> { AsyncRead::poll_read(Pin::new(&mut self.0), cx, buf) } fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { AsyncWrite::poll_write(Pin::new(&mut self.0), cx, buf) } } impl AsyncRead for Compat where S: AsyncRead + Unpin { fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll> { AsyncRead::poll_read(Pin::new(&mut self.0), cx, buf) } } impl AsyncWrite for Compat where S: AsyncWrite + Unpin { fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { AsyncWrite::poll_write(Pin::new(&mut self.0), cx, buf) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { AsyncWrite::poll_flush(Pin::new(&mut self.0), cx) } fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { AsyncWrite::poll_close(Pin::new(&mut self.0), cx) } } tokio-socks-0.5.2/src/io/compat.rs000064400000000000000000000020501046102023000151210ustar 00000000000000#[cfg(feature = "futures-io")] mod futures; /// A compatibility layer for using non-tokio types with this crate. /// /// Example: /// ```no_run /// use smol::net::unix::UnixStream; /// use tokio_socks::{io::Compat, tcp::Socks5Stream}; /// let socket = Compat::new(UnixStream::connect(proxy_addr) /// .await /// .map_err(Error::Io)?); // Compat /// let conn = /// Socks5Stream::connect_with_password_and_socket(socket, target, username, password).await?; /// // Socks5Stream has implemented futures-io AsyncRead + AsyncWrite. /// ``` pub struct Compat(S); #[cfg(feature = "futures-io")] impl Compat { pub fn new(inner: S) -> Self { Compat(inner) } /// Consumes the `Compat``, returning the inner value. pub fn into_inner(self) -> S { self.0 } } #[cfg(feature = "futures-io")] impl AsRef for Compat { fn as_ref(&self) -> &S { &self.0 } } #[cfg(feature = "futures-io")] impl AsMut for Compat { fn as_mut(&mut self) -> &mut S { &mut self.0 } } tokio-socks-0.5.2/src/io/mod.rs000064400000000000000000000055401046102023000144240ustar 00000000000000//! Asynchronous I/O abstractions for sockets. #[cfg(feature = "tokio")] mod tokio; use std::{ future::Future, io::{Error, ErrorKind}, mem, pin::Pin, task::{Context, Poll}, }; use futures_util::ready; #[cfg(feature = "futures-io")] mod compat; #[cfg(feature = "futures-io")] pub use compat::Compat; /// A trait for asynchronous socket I/O. /// /// Any type that implements tokio's `AsyncRead` and `AsyncWrite` traits /// has implemented `AsyncSocket` trait. /// /// Use `FuturesIoCompatExt` to wrap `futures-io` types as `AsyncSocket` types. pub trait AsyncSocket { fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll>; fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll>; } pub(crate) trait AsyncSocketExt { fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExact<'a, Self> where Self: Sized; fn write_all<'a>(&'a mut self, buf: &'a [u8]) -> WriteAll<'a, Self> where Self: Sized; } impl AsyncSocketExt for S { fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExact<'a, Self> where Self: Sized { let capacity = buf.len(); ReadExact { reader: self, buf, capacity, } } fn write_all<'a>(&'a mut self, buf: &'a [u8]) -> WriteAll<'a, Self> where Self: Sized { WriteAll { writer: self, buf } } } pub(crate) struct ReadExact<'a, R> { reader: &'a mut R, buf: &'a mut [u8], capacity: usize, } impl Future for ReadExact<'_, R> { type Output = Result; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = &mut *self; while !this.buf.is_empty() { let n = ready!(Pin::new(&mut *this.reader).poll_read(cx, this.buf))?; { let (_, rest) = mem::take(&mut this.buf).split_at_mut(n); this.buf = rest; } if n == 0 { return Poll::Ready(Err(ErrorKind::UnexpectedEof.into())); } } Poll::Ready(Ok(this.capacity)) } } pub(crate) struct WriteAll<'a, W> { writer: &'a mut W, buf: &'a [u8], } impl Future for WriteAll<'_, W> { type Output = Result<(), Error>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = &mut *self; while !this.buf.is_empty() { let n = ready!(Pin::new(&mut *this.writer).poll_write(cx, this.buf))?; { let (_, rest) = mem::take(&mut this.buf).split_at(n); this.buf = rest; } if n == 0 { return Poll::Ready(Err(ErrorKind::WriteZero.into())); } } Poll::Ready(Ok(())) } } tokio-socks-0.5.2/src/io/tokio.rs000064400000000000000000000013421046102023000147660ustar 00000000000000//! AsyncSocket trait implementation for tokio's AsyncRead + AsyncWrite //! traits. use std::{ io::Result as IoResult, pin::Pin, task::{Context, Poll}, }; use futures_util::ready; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use super::AsyncSocket; impl AsyncSocket for S where S: AsyncRead + AsyncWrite { fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll> { let mut buf = ReadBuf::new(buf); ready!(AsyncRead::poll_read(self, cx, &mut buf))?; Poll::Ready(Ok(buf.filled().len())) } fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { AsyncWrite::poll_write(self, cx, buf) } } tokio-socks-0.5.2/src/lib.rs000064400000000000000000000261421046102023000140050ustar 00000000000000use std::{ borrow::Cow, io::Result as IoResult, net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs}, pin::Pin, task::{Context, Poll}, vec, }; use either::Either; pub use error::Error; use futures_util::{ future, stream::{self, Once, Stream}, }; pub type Result = std::result::Result; /// A trait for objects which can be converted or resolved to one or more /// `SocketAddr` values, which are going to be connected as the the proxy /// server. /// /// This trait is similar to `std::net::ToSocketAddrs` but allows asynchronous /// name resolution. pub trait ToProxyAddrs { type Output: Stream> + Unpin; fn to_proxy_addrs(&self) -> Self::Output; } macro_rules! trivial_impl_to_proxy_addrs { ($t: ty) => { impl ToProxyAddrs for $t { type Output = Once>>; fn to_proxy_addrs(&self) -> Self::Output { stream::once(future::ready(Ok(SocketAddr::from(*self)))) } } }; } trivial_impl_to_proxy_addrs!(SocketAddr); trivial_impl_to_proxy_addrs!((IpAddr, u16)); trivial_impl_to_proxy_addrs!((Ipv4Addr, u16)); trivial_impl_to_proxy_addrs!((Ipv6Addr, u16)); trivial_impl_to_proxy_addrs!(SocketAddrV4); trivial_impl_to_proxy_addrs!(SocketAddrV6); impl<'a> ToProxyAddrs for &'a [SocketAddr] { type Output = ProxyAddrsStream; fn to_proxy_addrs(&self) -> Self::Output { let addrs = self.to_vec(); ProxyAddrsStream(Some(IoResult::Ok(addrs.into_iter()))) } } impl ToProxyAddrs for str { type Output = ProxyAddrsStream; fn to_proxy_addrs(&self) -> Self::Output { ProxyAddrsStream(Some(self.to_socket_addrs())) } } impl<'a> ToProxyAddrs for (&'a str, u16) { type Output = ProxyAddrsStream; fn to_proxy_addrs(&self) -> Self::Output { ProxyAddrsStream(Some(self.to_socket_addrs())) } } impl<'a, T: ToProxyAddrs + ?Sized> ToProxyAddrs for &'a T { type Output = T::Output; fn to_proxy_addrs(&self) -> Self::Output { (**self).to_proxy_addrs() } } pub struct ProxyAddrsStream(Option>>); impl Stream for ProxyAddrsStream { type Item = Result; fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { match self.0.as_mut() { Some(Ok(iter)) => Poll::Ready(iter.next().map(Result::Ok)), Some(Err(_)) => { let err = self.0.take().unwrap().unwrap_err(); Poll::Ready(Some(Err(err.into()))) }, None => unreachable!(), } } } /// A SOCKS connection target. #[derive(Debug, PartialEq, Eq)] pub enum TargetAddr<'a> { /// Connect to an IP address. Ip(SocketAddr), /// Connect to a fully-qualified domain name. /// /// The domain name will be passed along to the proxy server and DNS lookup /// will happen there. Domain(Cow<'a, str>, u16), } impl<'a> TargetAddr<'a> { /// Creates owned `TargetAddr` by cloning. It is usually used to eliminate /// the lifetime bound. pub fn to_owned(&self) -> TargetAddr<'static> { match self { TargetAddr::Ip(addr) => TargetAddr::Ip(*addr), TargetAddr::Domain(domain, port) => TargetAddr::Domain(String::from(domain.clone()).into(), *port), } } } impl<'a> ToSocketAddrs for TargetAddr<'a> { type Iter = Either, std::vec::IntoIter>; fn to_socket_addrs(&self) -> IoResult { Ok(match self { TargetAddr::Ip(addr) => Either::Left(addr.to_socket_addrs()?), TargetAddr::Domain(domain, port) => Either::Right((&**domain, *port).to_socket_addrs()?), }) } } /// A trait for objects that can be converted to `TargetAddr`. pub trait IntoTargetAddr<'a> { /// Converts the value of self to a `TargetAddr`. fn into_target_addr(self) -> Result>; } macro_rules! trivial_impl_into_target_addr { ($t: ty) => { impl<'a> IntoTargetAddr<'a> for $t { fn into_target_addr(self) -> Result> { Ok(TargetAddr::Ip(SocketAddr::from(self))) } } }; } trivial_impl_into_target_addr!(SocketAddr); trivial_impl_into_target_addr!((IpAddr, u16)); trivial_impl_into_target_addr!((Ipv4Addr, u16)); trivial_impl_into_target_addr!((Ipv6Addr, u16)); trivial_impl_into_target_addr!(SocketAddrV4); trivial_impl_into_target_addr!(SocketAddrV6); impl<'a> IntoTargetAddr<'a> for TargetAddr<'a> { fn into_target_addr(self) -> Result> { Ok(self) } } impl<'a> IntoTargetAddr<'a> for (&'a str, u16) { fn into_target_addr(self) -> Result> { // Try IP address first if let Ok(addr) = self.0.parse::() { return (addr, self.1).into_target_addr(); } // Treat as domain name if self.0.len() > 255 { return Err(Error::InvalidTargetAddress("overlong domain")); } // TODO: Should we validate the domain format here? Ok(TargetAddr::Domain(self.0.into(), self.1)) } } impl<'a> IntoTargetAddr<'a> for &'a str { fn into_target_addr(self) -> Result> { // Try IP address first if let Ok(addr) = self.parse::() { return addr.into_target_addr(); } let mut parts_iter = self.rsplitn(2, ':'); let port: u16 = parts_iter .next() .and_then(|port_str| port_str.parse().ok()) .ok_or(Error::InvalidTargetAddress("invalid address format"))?; let domain = parts_iter .next() .ok_or(Error::InvalidTargetAddress("invalid address format"))?; if domain.len() > 255 { return Err(Error::InvalidTargetAddress("overlong domain")); } Ok(TargetAddr::Domain(domain.into(), port)) } } impl IntoTargetAddr<'static> for String { fn into_target_addr(mut self) -> Result> { // Try IP address first if let Ok(addr) = self.parse::() { return addr.into_target_addr(); } let mut parts_iter = self.rsplitn(2, ':'); let port: u16 = parts_iter .next() .and_then(|port_str| port_str.parse().ok()) .ok_or(Error::InvalidTargetAddress("invalid address format"))?; let domain_len = parts_iter .next() .ok_or(Error::InvalidTargetAddress("invalid address format"))? .len(); if domain_len > 255 { return Err(Error::InvalidTargetAddress("overlong domain")); } self.truncate(domain_len); Ok(TargetAddr::Domain(self.into(), port)) } } impl IntoTargetAddr<'static> for (String, u16) { fn into_target_addr(self) -> Result> { let addr = (self.0.as_str(), self.1).into_target_addr()?; if let TargetAddr::Ip(addr) = addr { Ok(TargetAddr::Ip(addr)) } else { Ok(TargetAddr::Domain(self.0.into(), self.1)) } } } impl<'a, T> IntoTargetAddr<'a> for &'a T where T: IntoTargetAddr<'a> + Copy { fn into_target_addr(self) -> Result> { (*self).into_target_addr() } } /// Authentication methods #[derive(Debug)] enum Authentication<'a> { Password { username: &'a str, password: &'a str }, None, } impl<'a> Authentication<'a> { fn id(&self) -> u8 { match self { Authentication::Password { .. } => 0x02, Authentication::None => 0x00, } } } mod error; pub mod io; pub mod tcp; #[cfg(test)] mod tests { use futures_executor::block_on; use futures_util::StreamExt; use super::*; fn to_proxy_addrs(t: T) -> Result> { Ok(block_on(t.to_proxy_addrs().map(Result::unwrap).collect())) } #[test] fn converts_socket_addr_to_proxy_addrs() -> Result<()> { let addr = SocketAddr::from(([1, 1, 1, 1], 443)); let res = to_proxy_addrs(addr)?; assert_eq!(&res[..], &[addr]); Ok(()) } #[test] fn converts_socket_addr_ref_to_proxy_addrs() -> Result<()> { let addr = SocketAddr::from(([1, 1, 1, 1], 443)); let res = to_proxy_addrs(addr)?; assert_eq!(&res[..], &[addr]); Ok(()) } #[test] fn converts_socket_addrs_to_proxy_addrs() -> Result<()> { let addrs = [ SocketAddr::from(([1, 1, 1, 1], 443)), SocketAddr::from(([8, 8, 8, 8], 53)), ]; let res = to_proxy_addrs(&addrs[..])?; assert_eq!(&res[..], &addrs); Ok(()) } fn into_target_addr<'a, T>(t: T) -> Result> where T: IntoTargetAddr<'a> { t.into_target_addr() } #[test] fn converts_socket_addr_to_target_addr() -> Result<()> { let addr = SocketAddr::from(([1, 1, 1, 1], 443)); let res = into_target_addr(addr)?; assert_eq!(TargetAddr::Ip(addr), res); Ok(()) } #[test] fn converts_socket_addr_ref_to_target_addr() -> Result<()> { let addr = SocketAddr::from(([1, 1, 1, 1], 443)); let res = into_target_addr(addr)?; assert_eq!(TargetAddr::Ip(addr), res); Ok(()) } #[test] fn converts_socket_addr_str_to_target_addr() -> Result<()> { let addr = SocketAddr::from(([1, 1, 1, 1], 443)); let ip_str = format!("{}", addr); let res = into_target_addr(ip_str.as_str())?; assert_eq!(TargetAddr::Ip(addr), res); Ok(()) } #[test] fn converts_ip_str_and_port_target_addr() -> Result<()> { let addr = SocketAddr::from(([1, 1, 1, 1], 443)); let ip_str = format!("{}", addr.ip()); let res = into_target_addr((ip_str.as_str(), addr.port()))?; assert_eq!(TargetAddr::Ip(addr), res); Ok(()) } #[test] fn converts_domain_to_target_addr() -> Result<()> { let domain = "www.example.com:80"; let res = into_target_addr(domain)?; assert_eq!(TargetAddr::Domain(Cow::Borrowed("www.example.com"), 80), res); let res = into_target_addr(domain.to_owned())?; assert_eq!(TargetAddr::Domain(Cow::Owned("www.example.com".to_owned()), 80), res); Ok(()) } #[test] fn converts_domain_and_port_to_target_addr() -> Result<()> { let domain = "www.example.com"; let res = into_target_addr((domain, 80))?; assert_eq!(TargetAddr::Domain(Cow::Borrowed("www.example.com"), 80), res); Ok(()) } #[test] fn overlong_domain_to_target_addr_should_fail() { let domain = format!("www.{:a<1$}.com:80", 'a', 300); assert!(into_target_addr(domain.as_str()).is_err()); let domain = format!("www.{:a<1$}.com", 'a', 300); assert!(into_target_addr((domain.as_str(), 80)).is_err()); } #[test] fn addr_with_invalid_port_to_target_addr_should_fail() { let addr = "[ffff::1]:65536"; assert!(into_target_addr(addr).is_err()); let addr = "www.example.com:65536"; assert!(into_target_addr(addr).is_err()); } } tokio-socks-0.5.2/src/tcp/mod.rs000064400000000000000000000001071046102023000145750ustar 00000000000000pub mod socks4; pub mod socks5; pub use socks4::*; pub use socks5::*; tokio-socks-0.5.2/src/tcp/socks4.rs000064400000000000000000000412021046102023000152250ustar 00000000000000use std::{ borrow::Borrow, io, net::{Ipv4Addr, SocketAddr}, ops::{Deref, DerefMut}, pin::Pin, task::{Context, Poll}, }; use futures_util::stream::{self, Fuse, Stream, StreamExt}; #[cfg(feature = "tokio")] use tokio::net::TcpStream; #[cfg(feature = "tokio")] use crate::ToProxyAddrs; use crate::{ io::{AsyncSocket, AsyncSocketExt}, Error, IntoTargetAddr, Result, TargetAddr, }; #[repr(u8)] #[derive(Clone, Copy)] enum CommandV4 { Connect = 0x01, Bind = 0x02, } /// A SOCKS4 client. /// /// For convenience, it can be dereferenced to it's inner socket. #[derive(Debug)] pub struct Socks4Stream { socket: S, target: TargetAddr<'static>, } impl Deref for Socks4Stream { type Target = S; fn deref(&self) -> &Self::Target { &self.socket } } impl DerefMut for Socks4Stream { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.socket } } #[cfg(feature = "tokio")] impl Socks4Stream { /// Connects to a target server through a SOCKS4 proxy given the proxy /// address. /// /// # Error /// /// It propagates the error that occurs in the conversion from `T` to /// `TargetAddr`. pub async fn connect<'t, P, T>(proxy: P, target: T) -> Result> where P: ToProxyAddrs, T: IntoTargetAddr<'t>, { Self::execute_command(proxy, target, None, CommandV4::Connect).await } /// Connects to a target server through a SOCKS4 proxy using given username, /// password and the address of the proxy. /// /// # Error /// /// It propagates the error that occurs in the conversion from `T` to /// `TargetAddr`. pub async fn connect_with_userid<'a, 't, P, T>( proxy: P, target: T, user_id: &'a str, ) -> Result> where P: ToProxyAddrs, T: IntoTargetAddr<'t>, { Self::execute_command(proxy, target, Some(user_id), CommandV4::Connect).await } async fn execute_command<'a, 't, P, T>( proxy: P, target: T, user_id: Option<&'a str>, command: CommandV4, ) -> Result> where P: ToProxyAddrs, T: IntoTargetAddr<'t>, { Self::validate_userid(user_id)?; let sock = Socks4Connector::new( user_id, command, proxy.to_proxy_addrs().fuse(), target.into_target_addr()?, ) .execute() .await?; Ok(sock) } } impl Socks4Stream where S: AsyncSocket + Unpin { /// Connects to a target server through a SOCKS4 proxy given a socket to it. /// /// # Error /// /// It propagates the error that occurs in the conversion from `T` to /// `TargetAddr`. pub async fn connect_with_socket<'t, T>(socket: S, target: T) -> Result> where T: IntoTargetAddr<'t> { Self::execute_command_with_socket(socket, target, None, CommandV4::Connect).await } /// Connects to a target server through a SOCKS4 proxy using given username, /// password and a socket to the proxy /// /// # Error /// /// It propagates the error that occurs in the conversion from `T` to /// `TargetAddr`. pub async fn connect_with_userid_and_socket<'a, 't, T>( socket: S, target: T, user_id: &'a str, ) -> Result> where T: IntoTargetAddr<'t>, { Self::execute_command_with_socket(socket, target, Some(user_id), CommandV4::Connect).await } fn validate_userid(user_id: Option<&str>) -> Result<()> { // A hardcode limit for length of userid must be enforced to avoid, buffer // overflow. if let Some(user_id) = user_id { let user_id_len = user_id.len(); if !(1..=255).contains(&user_id_len) { Err(Error::InvalidAuthValues("userid length should between 1 to 255"))? } } Ok(()) } async fn execute_command_with_socket<'a, 't, T>( socket: S, target: T, user_id: Option<&'a str>, command: CommandV4, ) -> Result> where T: IntoTargetAddr<'t>, { Self::validate_userid(user_id)?; let sock = Socks4Connector::new(user_id, command, stream::empty().fuse(), target.into_target_addr()?) .execute_with_socket(socket) .await?; Ok(sock) } /// Consumes the `Socks4Stream`, returning the inner socket. pub fn into_inner(self) -> S { self.socket } /// Returns the target address that the proxy server connects to. pub fn target_addr(&self) -> TargetAddr<'_> { match &self.target { TargetAddr::Ip(addr) => TargetAddr::Ip(*addr), TargetAddr::Domain(domain, port) => { let domain: &str = domain.borrow(); TargetAddr::Domain(domain.into(), *port) }, } } } /// A `Future` which resolves to a socket to the target server through proxy. pub struct Socks4Connector<'a, 't, S> { user_id: Option<&'a str>, command: CommandV4, #[allow(dead_code)] proxy: Fuse, target: TargetAddr<'t>, buf: [u8; 513], ptr: usize, len: usize, } impl<'a, 't, S> Socks4Connector<'a, 't, S> where S: Stream> + Unpin { fn new(user_id: Option<&'a str>, command: CommandV4, proxy: Fuse, target: TargetAddr<'t>) -> Self { Socks4Connector { user_id, command, proxy, target, buf: [0; 513], ptr: 0, len: 0, } } #[cfg(feature = "tokio")] /// Connect to the proxy server, authenticate and issue the SOCKS command pub async fn execute(&mut self) -> Result> { let next_addr = self.proxy.select_next_some().await?; let tcp = TcpStream::connect(next_addr) .await .map_err(|_| Error::ProxyServerUnreachable)?; self.execute_with_socket(tcp).await } pub async fn execute_with_socket(&mut self, mut socket: T) -> Result> { // Send request address that should be proxied self.prepare_send_request()?; socket.write_all(&self.buf[self.ptr..self.len]).await?; let target = self.receive_reply(&mut socket).await?; Ok(Socks4Stream { socket, target }) } fn prepare_send_request(&mut self) -> Result<()> { self.ptr = 0; self.buf[..2].copy_from_slice(&[0x04, self.command as u8]); match &self.target { TargetAddr::Ip(SocketAddr::V4(addr)) => { self.buf[2..4].copy_from_slice(&addr.port().to_be_bytes()); self.buf[4..8].copy_from_slice(&addr.ip().octets()); self.len = 8; if let Some(user_id) = self.user_id { let usr_byts = user_id.as_bytes(); let user_id_len = usr_byts.len(); self.len += user_id_len; self.buf[8..self.len].copy_from_slice(usr_byts); } self.buf[self.len] = 0; // null terminator self.len += 1; }, TargetAddr::Ip(SocketAddr::V6(_)) => { return Err(Error::AddressTypeNotSupported); }, TargetAddr::Domain(domain, port) => { self.buf[2..4].copy_from_slice(&port.to_be_bytes()); self.buf[4..8].copy_from_slice(&[0, 0, 0, 1]); self.len = 8; if let Some(user_id) = self.user_id { let usr_byts = user_id.as_bytes(); let user_id_len = usr_byts.len(); self.len += user_id_len; self.buf[8..self.len].copy_from_slice(usr_byts); } self.buf[self.len] = 0; // null terminator self.len += 1; let domain = domain.as_bytes(); let domain_len = domain.len(); self.buf[self.len..self.len + domain_len].copy_from_slice(domain); self.len += domain_len; self.buf[self.len] = 0; self.len += 1; }, }; Ok(()) } fn prepare_recv_reply(&mut self) { self.ptr = 0; self.len = 8; } async fn receive_reply(&mut self, tcp: &mut T) -> Result> { // https://www.openssh.com/txt/socks4.protocol // +----+----+----+----+----+----+----+----+ // | VN | CD | DSTPORT | DSTIP | // +----+----+----+----+----+----+----+----+ // # of bytes: 1 1 2 4 // // VN is the version of the reply code and should be 0. CD is the result // code with one of the following values: // 90: request granted // 91: request rejected or failed // 92: request rejected becasue SOCKS server cannot connect to // identd on the client // 93: request rejected because the client program and identd // report different user-ids self.prepare_recv_reply(); self.ptr += tcp.read_exact(&mut self.buf[self.ptr..self.len]).await?; if self.buf[0] != 0 { return Err(Error::InvalidResponseVersion); } match self.buf[1] { 0x5A => {}, // request granted 0x5B => return Err(Error::GeneralSocksServerFailure), // connection rejected/failed 0x5C => return Err(Error::IdentdAuthFailure), // cannot connect to identd on the client 0x5D => return Err(Error::InvalidUserIdAuthFailure), // different user-ids _ => return Err(Error::UnknownError), } let port = u16::from_be_bytes([self.buf[2], self.buf[3]]); let target = Ipv4Addr::from([self.buf[4], self.buf[5], self.buf[6], self.buf[7]]); Ok(TargetAddr::Ip(SocketAddr::new(target.into(), port))) } } /// A SOCKS4 BIND client. /// /// Once you get an instance of `Socks4Listener`, you should send the /// `bind_addr` to the remote process via the primary connection. Then, call the /// `accept` function and wait for the other end connecting to the rendezvous /// address. pub struct Socks4Listener { inner: Socks4Stream, } #[cfg(feature = "tokio")] impl Socks4Listener { /// Initiates a BIND request to the specified proxy. /// /// The proxy will filter incoming connections based on the value of /// `target`. /// /// # Error /// /// It propagates the error that occurs in the conversion from `T` to /// `TargetAddr`. pub async fn bind<'t, P, T>(proxy: P, target: T) -> Result> where P: ToProxyAddrs, T: IntoTargetAddr<'t>, { Self::bind_to_target(None, proxy, target).await } /// Initiates a BIND request to the specified proxy using given username /// and password. /// /// The proxy will filter incoming connections based on the value of /// `target`. /// /// # Error /// /// It propagates the error that occurs in the conversion from `T` to /// `TargetAddr`. pub async fn bind_with_userid<'a, 't, P, T>( proxy: P, target: T, user_id: &'a str, ) -> Result> where P: ToProxyAddrs, T: IntoTargetAddr<'t>, { Self::bind_to_target(Some(user_id), proxy, target).await } async fn bind_to_target<'a, 't, P, T>( user_id: Option<&'a str>, proxy: P, target: T, ) -> Result> where P: ToProxyAddrs, T: IntoTargetAddr<'t>, { let socket = Socks4Connector::new( user_id, CommandV4::Bind, proxy.to_proxy_addrs().fuse(), target.into_target_addr()?, ) .execute() .await?; Ok(Socks4Listener { inner: socket }) } } impl Socks4Listener where S: AsyncSocket + Unpin { /// Initiates a BIND request to the specified proxy using the given socket /// to it. /// /// The proxy will filter incoming connections based on the value of /// `target`. /// /// # Error /// /// It propagates the error that occurs in the conversion from `T` to /// `TargetAddr`. pub async fn bind_with_socket<'t, T>(socket: S, target: T) -> Result> where T: IntoTargetAddr<'t> { Self::bind_to_target_with_socket(None, socket, target).await } /// Initiates a BIND request to the specified proxy using given username, /// password and socket to the proxy. /// /// The proxy will filter incoming connections based on the value of /// `target`. /// /// # Error /// /// It propagates the error that occurs in the conversion from `T` to /// `TargetAddr`. pub async fn bind_with_user_and_socket<'a, 't, T>( socket: S, target: T, user_id: &'a str, ) -> Result> where T: IntoTargetAddr<'t>, { Self::bind_to_target_with_socket(Some(user_id), socket, target).await } async fn bind_to_target_with_socket<'a, 't, T>( auth: Option<&'a str>, socket: S, target: T, ) -> Result> where T: IntoTargetAddr<'t>, { let socket = Socks4Connector::new( auth, CommandV4::Bind, stream::empty().fuse(), target.into_target_addr()?, ) .execute_with_socket(socket) .await?; Ok(Socks4Listener { inner: socket }) } /// Returns the address of the proxy-side TCP listener. /// /// This should be forwarded to the remote process, which should open a /// connection to it. pub fn bind_addr(&self) -> TargetAddr { self.inner.target_addr() } /// Consumes this listener, returning a `Future` which resolves to the /// `Socks4Stream` connected to the target server through the proxy. /// /// The value of `bind_addr` should be forwarded to the remote process /// before this method is called. pub async fn accept(mut self) -> Result> { let mut connector = Socks4Connector { user_id: None, command: CommandV4::Bind, proxy: stream::empty().fuse(), target: self.inner.target, buf: [0; 513], ptr: 0, len: 0, }; let target = connector.receive_reply(&mut self.inner.socket).await?; Ok(Socks4Stream { socket: self.inner.socket, target, }) } } #[cfg(feature = "tokio")] impl tokio::io::AsyncRead for Socks4Stream where T: tokio::io::AsyncRead + Unpin { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut tokio::io::ReadBuf<'_>, ) -> Poll> { tokio::io::AsyncRead::poll_read(Pin::new(&mut self.socket), cx, buf) } } #[cfg(feature = "tokio")] impl tokio::io::AsyncWrite for Socks4Stream where T: tokio::io::AsyncWrite + Unpin { fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { tokio::io::AsyncWrite::poll_write(Pin::new(&mut self.socket), cx, buf) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { tokio::io::AsyncWrite::poll_flush(Pin::new(&mut self.socket), cx) } fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { tokio::io::AsyncWrite::poll_shutdown(Pin::new(&mut self.socket), cx) } } #[cfg(feature = "futures-io")] impl futures_io::AsyncRead for Socks4Stream where T: futures_io::AsyncRead + Unpin { fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll> { futures_io::AsyncRead::poll_read(Pin::new(&mut self.socket), cx, buf) } } #[cfg(feature = "futures-io")] impl futures_io::AsyncWrite for Socks4Stream where T: futures_io::AsyncWrite + Unpin { fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { futures_io::AsyncWrite::poll_write(Pin::new(&mut self.socket), cx, buf) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { futures_io::AsyncWrite::poll_flush(Pin::new(&mut self.socket), cx) } fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { futures_io::AsyncWrite::poll_close(Pin::new(&mut self.socket), cx) } } tokio-socks-0.5.2/src/tcp/socks5.rs000064400000000000000000000552601046102023000152370ustar 00000000000000use std::{ borrow::Borrow, io, net::{Ipv4Addr, Ipv6Addr, SocketAddr}, ops::{Deref, DerefMut}, pin::Pin, task::{Context, Poll}, }; use futures_util::stream::{self, Fuse, Stream, StreamExt}; #[cfg(feature = "tokio")] use tokio::net::TcpStream; #[cfg(feature = "tokio")] use crate::ToProxyAddrs; use crate::{ io::{AsyncSocket, AsyncSocketExt}, Authentication, Error, IntoTargetAddr, Result, TargetAddr, }; #[repr(u8)] #[derive(Clone, Copy)] enum Command { Connect = 0x01, Bind = 0x02, #[allow(dead_code)] Associate = 0x03, #[cfg(feature = "tor")] TorResolve = 0xF0, #[cfg(feature = "tor")] TorResolvePtr = 0xF1, } /// A SOCKS5 client. /// /// For convenience, it can be dereferenced to it's inner socket. #[derive(Debug)] pub struct Socks5Stream { socket: S, target: TargetAddr<'static>, } impl Deref for Socks5Stream { type Target = S; fn deref(&self) -> &Self::Target { &self.socket } } impl DerefMut for Socks5Stream { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.socket } } #[cfg(feature = "tokio")] impl Socks5Stream { /// Connects to a target server through a SOCKS5 proxy given the proxy /// address. /// /// # Error /// /// It propagates the error that occurs in the conversion from `T` to /// `TargetAddr`. pub async fn connect<'t, P, T>(proxy: P, target: T) -> Result> where P: ToProxyAddrs, T: IntoTargetAddr<'t>, { Self::execute_command(proxy, target, Authentication::None, Command::Connect).await } /// Connects to a target server through a SOCKS5 proxy using given username, /// password and the address of the proxy. /// /// # Error /// /// It propagates the error that occurs in the conversion from `T` to /// `TargetAddr`. pub async fn connect_with_password<'a, 't, P, T>( proxy: P, target: T, username: &'a str, password: &'a str, ) -> Result> where P: ToProxyAddrs, T: IntoTargetAddr<'t>, { Self::execute_command( proxy, target, Authentication::Password { username, password }, Command::Connect, ) .await } #[cfg(feature = "tor")] /// Resolve the domain name to an ip using special Tor Resolve command, by /// connecting to a Tor compatible proxy given it's address. pub async fn tor_resolve<'t, P, T>(proxy: P, target: T) -> Result> where P: ToProxyAddrs, T: IntoTargetAddr<'t>, { let sock = Self::execute_command(proxy, target, Authentication::None, Command::TorResolve).await?; Ok(sock.target_addr().to_owned()) } #[cfg(feature = "tor")] /// Perform a reverse DNS query on the given ip using special Tor Resolve /// PTR command, by connecting to a Tor compatible proxy given it's /// address. pub async fn tor_resolve_ptr<'t, P, T>(proxy: P, target: T) -> Result> where P: ToProxyAddrs, T: IntoTargetAddr<'t>, { let sock = Self::execute_command(proxy, target, Authentication::None, Command::TorResolvePtr).await?; Ok(sock.target_addr().to_owned()) } async fn execute_command<'a, 't, P, T>( proxy: P, target: T, auth: Authentication<'a>, command: Command, ) -> Result> where P: ToProxyAddrs, T: IntoTargetAddr<'t>, { Self::validate_auth(&auth)?; let sock = SocksConnector::new(auth, command, proxy.to_proxy_addrs().fuse(), target.into_target_addr()?) .execute() .await?; Ok(sock) } } impl Socks5Stream where S: AsyncSocket + Unpin { /// Connects to a target server through a SOCKS5 proxy given a socket to it. /// /// # Error /// /// It propagates the error that occurs in the conversion from `T` to /// `TargetAddr`. pub async fn connect_with_socket<'t, T>(socket: S, target: T) -> Result> where T: IntoTargetAddr<'t> { Self::execute_command_with_socket(socket, target, Authentication::None, Command::Connect).await } /// Connects to a target server through a SOCKS5 proxy using given username, /// password and a socket to the proxy /// /// # Error /// /// It propagates the error that occurs in the conversion from `T` to /// `TargetAddr`. pub async fn connect_with_password_and_socket<'a, 't, T>( socket: S, target: T, username: &'a str, password: &'a str, ) -> Result> where T: IntoTargetAddr<'t>, { Self::execute_command_with_socket( socket, target, Authentication::Password { username, password }, Command::Connect, ) .await } fn validate_auth(auth: &Authentication<'_>) -> Result<()> { match auth { Authentication::Password { username, password } => { let username_len = username.as_bytes().len(); if !(1..=255).contains(&username_len) { Err(Error::InvalidAuthValues("username length should between 1 to 255"))? } let password_len = password.as_bytes().len(); if !(1..=255).contains(&password_len) { Err(Error::InvalidAuthValues("password length should between 1 to 255"))? } }, Authentication::None => {}, } Ok(()) } #[cfg(feature = "tor")] /// Resolve the domain name to an ip using special Tor Resolve command, by /// connecting to a Tor compatible proxy given a socket to it. pub async fn tor_resolve_with_socket<'t, T>(socket: S, target: T) -> Result> where T: IntoTargetAddr<'t> { let sock = Self::execute_command_with_socket(socket, target, Authentication::None, Command::TorResolve).await?; Ok(sock.target_addr().to_owned()) } #[cfg(feature = "tor")] /// Perform a reverse DNS query on the given ip using special Tor Resolve /// PTR command, by connecting to a Tor compatible proxy given a socket /// to it. pub async fn tor_resolve_ptr_with_socket<'t, T>(socket: S, target: T) -> Result> where T: IntoTargetAddr<'t> { let sock = Self::execute_command_with_socket(socket, target, Authentication::None, Command::TorResolvePtr).await?; Ok(sock.target_addr().to_owned()) } async fn execute_command_with_socket<'a, 't, T>( socket: S, target: T, auth: Authentication<'a>, command: Command, ) -> Result> where T: IntoTargetAddr<'t>, { Self::validate_auth(&auth)?; let sock = SocksConnector::new(auth, command, stream::empty().fuse(), target.into_target_addr()?) .execute_with_socket(socket) .await?; Ok(sock) } /// Consumes the `Socks5Stream`, returning the inner socket. pub fn into_inner(self) -> S { self.socket } /// Returns the target address that the proxy server connects to. pub fn target_addr(&self) -> TargetAddr<'_> { match &self.target { TargetAddr::Ip(addr) => TargetAddr::Ip(*addr), TargetAddr::Domain(domain, port) => { let domain: &str = domain.borrow(); TargetAddr::Domain(domain.into(), *port) }, } } } /// A `Future` which resolves to a socket to the target server through proxy. pub struct SocksConnector<'a, 't, S> { auth: Authentication<'a>, command: Command, #[allow(dead_code)] proxy: Fuse, target: TargetAddr<'t>, buf: [u8; 513], ptr: usize, len: usize, } impl<'a, 't, S> SocksConnector<'a, 't, S> where S: Stream> + Unpin { fn new(auth: Authentication<'a>, command: Command, proxy: Fuse, target: TargetAddr<'t>) -> Self { SocksConnector { auth, command, proxy, target, buf: [0; 513], ptr: 0, len: 0, } } #[cfg(feature = "tokio")] /// Connect to the proxy server, authenticate and issue the SOCKS command pub async fn execute(&mut self) -> Result> { let next_addr = self.proxy.select_next_some().await?; let tcp = TcpStream::connect(next_addr) .await .map_err(|_| Error::ProxyServerUnreachable)?; self.execute_with_socket(tcp).await } pub async fn execute_with_socket(&mut self, mut socket: T) -> Result> { self.authenticate(&mut socket).await?; // Send request address that should be proxied self.prepare_send_request(); socket.write_all(&self.buf[self.ptr..self.len]).await?; let target = self.receive_reply(&mut socket).await?; Ok(Socks5Stream { socket, target }) } fn prepare_send_method_selection(&mut self) { self.ptr = 0; self.buf[0] = 0x05; match self.auth { Authentication::None => { self.buf[1..3].copy_from_slice(&[1, 0x00]); self.len = 3; }, Authentication::Password { .. } => { self.buf[1..4].copy_from_slice(&[2, 0x00, 0x02]); self.len = 4; }, } } fn prepare_recv_method_selection(&mut self) { self.ptr = 0; self.len = 2; } fn prepare_send_password_auth(&mut self) { if let Authentication::Password { username, password } = self.auth { self.ptr = 0; self.buf[0] = 0x01; let username_bytes = username.as_bytes(); let username_len = username_bytes.len(); self.buf[1] = username_len as u8; self.buf[2..(2 + username_len)].copy_from_slice(username_bytes); let password_bytes = password.as_bytes(); let password_len = password_bytes.len(); self.len = 3 + username_len + password_len; self.buf[2 + username_len] = password_len as u8; self.buf[(3 + username_len)..self.len].copy_from_slice(password_bytes); } else { unreachable!() } } fn prepare_recv_password_auth(&mut self) { self.ptr = 0; self.len = 2; } fn prepare_send_request(&mut self) { self.ptr = 0; self.buf[..3].copy_from_slice(&[0x05, self.command as u8, 0x00]); match &self.target { TargetAddr::Ip(SocketAddr::V4(addr)) => { self.buf[3] = 0x01; self.buf[4..8].copy_from_slice(&addr.ip().octets()); self.buf[8..10].copy_from_slice(&addr.port().to_be_bytes()); self.len = 10; }, TargetAddr::Ip(SocketAddr::V6(addr)) => { self.buf[3] = 0x04; self.buf[4..20].copy_from_slice(&addr.ip().octets()); self.buf[20..22].copy_from_slice(&addr.port().to_be_bytes()); self.len = 22; }, TargetAddr::Domain(domain, port) => { self.buf[3] = 0x03; let domain = domain.as_bytes(); let len = domain.len(); self.buf[4] = len as u8; self.buf[5..5 + len].copy_from_slice(domain); self.buf[(5 + len)..(7 + len)].copy_from_slice(&port.to_be_bytes()); self.len = 7 + len; }, } } fn prepare_recv_reply(&mut self) { self.ptr = 0; self.len = 4; } async fn password_authentication_protocol(&mut self, tcp: &mut T) -> Result<()> { if let Authentication::None = self.auth { return Err(Error::AuthorizationRequired); } self.prepare_send_password_auth(); tcp.write_all(&self.buf[self.ptr..self.len]).await?; self.prepare_recv_password_auth(); tcp.read_exact(&mut self.buf[self.ptr..self.len]).await?; if self.buf[0] != 0x01 { return Err(Error::InvalidResponseVersion); } if self.buf[1] != 0x00 { return Err(Error::PasswordAuthFailure(self.buf[1])); } Ok(()) } async fn authenticate(&mut self, tcp: &mut T) -> Result<()> { // Write request to connect/authenticate self.prepare_send_method_selection(); tcp.write_all(&self.buf[self.ptr..self.len]).await?; // Receive authentication method self.prepare_recv_method_selection(); tcp.read_exact(&mut self.buf[self.ptr..self.len]).await?; if self.buf[0] != 0x05 { return Err(Error::InvalidResponseVersion); } match self.buf[1] { 0x00 => { // No auth }, 0x02 => { self.password_authentication_protocol(tcp).await?; }, 0xff => { return Err(Error::NoAcceptableAuthMethods); }, m if m != self.auth.id() => return Err(Error::UnknownAuthMethod), _ => unimplemented!(), } Ok(()) } async fn receive_reply(&mut self, tcp: &mut T) -> Result> { self.prepare_recv_reply(); self.ptr += tcp.read_exact(&mut self.buf[self.ptr..self.len]).await?; if self.buf[0] != 0x05 { return Err(Error::InvalidResponseVersion); } if self.buf[2] != 0x00 { return Err(Error::InvalidReservedByte); } match self.buf[1] { 0x00 => {}, // succeeded 0x01 => Err(Error::GeneralSocksServerFailure)?, 0x02 => Err(Error::ConnectionNotAllowedByRuleset)?, 0x03 => Err(Error::NetworkUnreachable)?, 0x04 => Err(Error::HostUnreachable)?, 0x05 => Err(Error::ConnectionRefused)?, 0x06 => Err(Error::TtlExpired)?, 0x07 => Err(Error::CommandNotSupported)?, 0x08 => Err(Error::AddressTypeNotSupported)?, _ => Err(Error::UnknownAuthMethod)?, } match self.buf[3] { // IPv4 0x01 => { self.len = 10; }, // IPv6 0x04 => { self.len = 22; }, // Domain 0x03 => { self.len = 5; self.ptr += tcp.read_exact(&mut self.buf[self.ptr..self.len]).await?; self.len += self.buf[4] as usize + 2; }, _ => Err(Error::UnknownAddressType)?, } self.ptr += tcp.read_exact(&mut self.buf[self.ptr..self.len]).await?; let target: TargetAddr<'static> = match self.buf[3] { // IPv4 0x01 => { let mut ip = [0; 4]; ip[..].copy_from_slice(&self.buf[4..8]); let ip = Ipv4Addr::from(ip); let port = u16::from_be_bytes([self.buf[8], self.buf[9]]); (ip, port).into_target_addr()? }, // IPv6 0x04 => { let mut ip = [0; 16]; ip[..].copy_from_slice(&self.buf[4..20]); let ip = Ipv6Addr::from(ip); let port = u16::from_be_bytes([self.buf[20], self.buf[21]]); (ip, port).into_target_addr()? }, // Domain 0x03 => { let domain_bytes = self.buf[5..(self.len - 2)].to_vec(); let domain = String::from_utf8(domain_bytes) .map_err(|_| Error::InvalidTargetAddress("not a valid UTF-8 string"))?; let port = u16::from_be_bytes([self.buf[self.len - 2], self.buf[self.len - 1]]); TargetAddr::Domain(domain.into(), port) }, _ => unreachable!(), }; Ok(target) } } /// A SOCKS5 BIND client. /// /// Once you get an instance of `Socks5Listener`, you should send the /// `bind_addr` to the remote process via the primary connection. Then, call the /// `accept` function and wait for the other end connecting to the rendezvous /// address. pub struct Socks5Listener { inner: Socks5Stream, } #[cfg(feature = "tokio")] impl Socks5Listener { /// Initiates a BIND request to the specified proxy. /// /// The proxy will filter incoming connections based on the value of /// `target`. /// /// # Error /// /// It propagates the error that occurs in the conversion from `T` to /// `TargetAddr`. pub async fn bind<'t, P, T>(proxy: P, target: T) -> Result> where P: ToProxyAddrs, T: IntoTargetAddr<'t>, { Self::bind_with_auth(Authentication::None, proxy, target).await } /// Initiates a BIND request to the specified proxy using given username /// and password. /// /// The proxy will filter incoming connections based on the value of /// `target`. /// /// # Error /// /// It propagates the error that occurs in the conversion from `T` to /// `TargetAddr`. pub async fn bind_with_password<'a, 't, P, T>( proxy: P, target: T, username: &'a str, password: &'a str, ) -> Result> where P: ToProxyAddrs, T: IntoTargetAddr<'t>, { Self::bind_with_auth(Authentication::Password { username, password }, proxy, target).await } async fn bind_with_auth<'t, P, T>( auth: Authentication<'_>, proxy: P, target: T, ) -> Result> where P: ToProxyAddrs, T: IntoTargetAddr<'t>, { let socket = SocksConnector::new( auth, Command::Bind, proxy.to_proxy_addrs().fuse(), target.into_target_addr()?, ) .execute() .await?; Ok(Socks5Listener { inner: socket }) } } impl Socks5Listener where S: AsyncSocket + Unpin { /// Initiates a BIND request to the specified proxy using the given socket /// to it. /// /// The proxy will filter incoming connections based on the value of /// `target`. /// /// # Error /// /// It propagates the error that occurs in the conversion from `T` to /// `TargetAddr`. pub async fn bind_with_socket<'t, T>(socket: S, target: T) -> Result> where T: IntoTargetAddr<'t> { Self::bind_with_auth_and_socket(Authentication::None, socket, target).await } /// Initiates a BIND request to the specified proxy using given username, /// password and socket to the proxy. /// /// The proxy will filter incoming connections based on the value of /// `target`. /// /// # Error /// /// It propagates the error that occurs in the conversion from `T` to /// `TargetAddr`. pub async fn bind_with_password_and_socket<'a, 't, T>( socket: S, target: T, username: &'a str, password: &'a str, ) -> Result> where T: IntoTargetAddr<'t>, { Self::bind_with_auth_and_socket(Authentication::Password { username, password }, socket, target).await } async fn bind_with_auth_and_socket<'t, T>( auth: Authentication<'_>, socket: S, target: T, ) -> Result> where T: IntoTargetAddr<'t>, { let socket = SocksConnector::new(auth, Command::Bind, stream::empty().fuse(), target.into_target_addr()?) .execute_with_socket(socket) .await?; Ok(Socks5Listener { inner: socket }) } /// Returns the address of the proxy-side TCP listener. /// /// This should be forwarded to the remote process, which should open a /// connection to it. pub fn bind_addr(&self) -> TargetAddr { self.inner.target_addr() } /// Consumes this listener, returning a `Future` which resolves to the /// `Socks5Stream` connected to the target server through the proxy. /// /// The value of `bind_addr` should be forwarded to the remote process /// before this method is called. pub async fn accept(mut self) -> Result> { let mut connector = SocksConnector { auth: Authentication::None, command: Command::Bind, proxy: stream::empty().fuse(), target: self.inner.target, buf: [0; 513], ptr: 0, len: 0, }; let target = connector.receive_reply(&mut self.inner.socket).await?; Ok(Socks5Stream { socket: self.inner.socket, target, }) } } #[cfg(feature = "tokio")] impl tokio::io::AsyncRead for Socks5Stream where T: tokio::io::AsyncRead + Unpin { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut tokio::io::ReadBuf<'_>, ) -> Poll> { tokio::io::AsyncRead::poll_read(Pin::new(&mut self.socket), cx, buf) } } #[cfg(feature = "tokio")] impl tokio::io::AsyncWrite for Socks5Stream where T: tokio::io::AsyncWrite + Unpin { fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { tokio::io::AsyncWrite::poll_write(Pin::new(&mut self.socket), cx, buf) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { tokio::io::AsyncWrite::poll_flush(Pin::new(&mut self.socket), cx) } fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { tokio::io::AsyncWrite::poll_shutdown(Pin::new(&mut self.socket), cx) } } #[cfg(feature = "futures-io")] impl futures_io::AsyncRead for Socks5Stream where T: futures_io::AsyncRead + Unpin { fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll> { futures_io::AsyncRead::poll_read(Pin::new(&mut self.socket), cx, buf) } } #[cfg(feature = "futures-io")] impl futures_io::AsyncWrite for Socks5Stream where T: futures_io::AsyncWrite + Unpin { fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { futures_io::AsyncWrite::poll_write(Pin::new(&mut self.socket), cx, buf) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { futures_io::AsyncWrite::poll_flush(Pin::new(&mut self.socket), cx) } fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { futures_io::AsyncWrite::poll_close(Pin::new(&mut self.socket), cx) } } tokio-socks-0.5.2/tests/common/futures_utils.rs000064400000000000000000000060651046102023000200210ustar 00000000000000use std::{ future::Future, io::{Read, Write}, net::{SocketAddr, TcpStream as StdTcpStream}, sync::Mutex, }; use futures_util::{io::copy, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; use once_cell::sync::OnceCell; use smol::net::{unix::UnixStream, TcpListener}; use tokio_socks::{ io::Compat, tcp::{socks4::Socks4Listener, socks5::Socks5Listener}, Error, Result, }; use super::*; pub async fn echo_server() -> Result<()> { let listener = TcpListener::bind(&SocketAddr::from(([0, 0, 0, 0], 10007))).await?; loop { let (stream, _) = listener.accept().await?; smol::spawn(async move { let (mut reader, mut writer) = stream.split(); copy(&mut reader, &mut writer).await.unwrap(); }) .detach(); } } pub async fn reply_response(mut socket: S) -> Result<[u8; 5]> { socket.write_all(MSG).await?; let mut buf = [0; 5]; socket.read_exact(&mut buf).await?; Ok(buf) } pub async fn test_connect(socket: S) -> Result<()> { let res = reply_response(socket).await?; assert_eq!(&res[..], MSG); Ok(()) } pub fn test_bind( listener: Socks5Listener>, ) -> Result<()> { let bind_addr = listener.bind_addr().to_owned(); runtime().lock().unwrap().spawn(async move { let stream = listener.accept().await.unwrap(); let (mut reader, mut writer) = stream.split(); copy(&mut reader, &mut writer).await.unwrap(); }); let mut tcp = StdTcpStream::connect(bind_addr)?; tcp.write_all(MSG)?; let mut buf = [0; 5]; tcp.read_exact(&mut buf[..])?; assert_eq!(&buf[..], MSG); Ok(()) } pub async fn connect_unix(proxy_addr: &str) -> Result { UnixStream::connect(proxy_addr).await.map_err(Error::Io) } pub struct Runtime; impl Runtime { pub fn spawn(&self, future: F) where F: Future + Send + 'static, T: Send + 'static, { smol::spawn(future).detach(); } pub fn block_on(&self, future: F) -> T where F: Future { smol::block_on(future) } } pub fn runtime() -> &'static Mutex { static RUNTIME: OnceCell> = OnceCell::new(); RUNTIME.get_or_init(|| { smol::spawn(async { echo_server().await.expect("Unable to bind") }).detach(); Mutex::new(Runtime) }) } pub fn test_bind_socks4( listener: Socks4Listener>, ) -> Result<()> { let bind_addr = listener.bind_addr().to_owned(); runtime().lock().unwrap().spawn(async move { let stream = listener.accept().await.unwrap(); let (mut reader, mut writer) = AsyncReadExt::split(stream); copy(&mut reader, &mut writer).await.unwrap(); }); let mut tcp = StdTcpStream::connect(bind_addr)?; tcp.write_all(MSG)?; let mut buf = [0; 5]; tcp.read_exact(&mut buf[..])?; assert_eq!(&buf[..], MSG); Ok(()) } tokio-socks-0.5.2/tests/common/mod.rs000064400000000000000000000007361046102023000156620ustar 00000000000000#![allow(dead_code)] #[cfg(feature = "futures-io")] pub mod futures_utils; #[cfg(feature = "tokio")] pub mod tokio_utils; #[cfg(feature = "tokio")] pub use tokio_utils::*; pub const UNIX_PROXY_ADDR: &str = "/tmp/proxy.s"; pub const PROXY_ADDR: &str = "127.0.0.1:41080"; pub const UNIX_SOCKS4_PROXY_ADDR: &str = "/tmp/socks4_proxy.s"; pub const SOCKS4_PROXY_ADDR: &str = "127.0.0.1:41081"; pub const ECHO_SERVER_ADDR: &str = "localhost:10007"; pub const MSG: &[u8] = b"hello"; tokio-socks-0.5.2/tests/common/tokio_utils.rs000064400000000000000000000053341046102023000174470ustar 00000000000000use std::{ io::{Read, Write}, net::{SocketAddr, TcpStream as StdTcpStream}, sync::Mutex, }; use once_cell::sync::OnceCell; use tokio::{ io::{copy, split, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}, net::{TcpListener, UnixStream}, runtime::Runtime, }; use tokio_socks::{ tcp::{socks4::Socks4Listener, socks5::Socks5Listener}, Error, Result, }; use super::*; pub async fn echo_server() -> Result<()> { let listener = TcpListener::bind(&SocketAddr::from(([0, 0, 0, 0], 10007))).await?; loop { let (mut stream, _) = listener.accept().await?; tokio::spawn(async move { let (mut reader, mut writer) = stream.split(); copy(&mut reader, &mut writer).await.unwrap(); }); } } pub async fn reply_response(mut socket: S) -> Result<[u8; 5]> { socket.write_all(MSG).await?; let mut buf = [0; 5]; socket.read_exact(&mut buf).await?; Ok(buf) } pub async fn test_connect(socket: S) -> Result<()> { let res = reply_response(socket).await?; assert_eq!(&res[..], MSG); Ok(()) } pub fn test_bind(listener: Socks5Listener) -> Result<()> { let bind_addr = listener.bind_addr().to_owned(); runtime().lock().unwrap().spawn(async move { let stream = listener.accept().await.unwrap(); let (mut reader, mut writer) = split(stream); copy(&mut reader, &mut writer).await.unwrap(); }); let mut tcp = StdTcpStream::connect(bind_addr)?; tcp.write_all(MSG)?; let mut buf = [0; 5]; tcp.read_exact(&mut buf[..])?; assert_eq!(&buf[..], MSG); Ok(()) } pub async fn connect_unix(proxy_addr: &str) -> Result { UnixStream::connect(proxy_addr).await.map_err(Error::Io) } pub fn runtime() -> &'static Mutex { static RUNTIME: OnceCell> = OnceCell::new(); RUNTIME.get_or_init(|| { let runtime = Runtime::new().expect("Unable to create runtime"); runtime.spawn(async { echo_server().await.expect("Unable to bind") }); Mutex::new(runtime) }) } pub fn test_bind_socks4(listener: Socks4Listener) -> Result<()> { let bind_addr = listener.bind_addr().to_owned(); runtime().lock().unwrap().spawn(async move { let stream = listener.accept().await.unwrap(); let (mut reader, mut writer) = split(stream); copy(&mut reader, &mut writer).await.unwrap(); }); let mut tcp = StdTcpStream::connect(bind_addr)?; tcp.write_all(MSG)?; let mut buf = [0; 5]; tcp.read_exact(&mut buf[..])?; assert_eq!(&buf[..], MSG); Ok(()) } tokio-socks-0.5.2/tests/integration_tests.sh000075500000000000000000000015171046102023000173470ustar 00000000000000#!/usr/bin/env bash set -x dir="$(dirname "$(which "$0")")" SOCK="/tmp/proxy.s" PROXY_HOST="127.0.0.1:41080" SOCK4="/tmp/socks4_proxy.s" SOCKS4_PROXY_HOST="127.0.0.1:41081" #socat tcp-listen:10007,fork exec:cat & #echo $! > /tmp/socat-test.pid if test -z "$@"; then list="socks4_no_auth socks4_userid no_auth username_auth long_username_password_auth" else list="$@" fi socat UNIX-LISTEN:${SOCK},reuseaddr,fork TCP:${PROXY_HOST} & socat UNIX-LISTEN:${SOCK4},reuseaddr,fork TCP:${SOCKS4_PROXY_HOST} & sleep 2 for test in ${list}; do 3proxy ${dir}/${test}.cfg sleep 1 cargo test --test ${test} --all-features -- --test-threads 1 test_exit_code=$? pkill -F /tmp/3proxy-test.pid sleep 1 if test "$test_exit_code" -ne 0; then break fi done # pkill -F /tmp/socat-test.pid exit ${test_exit_code} tokio-socks-0.5.2/tests/long_username_password_auth.cfg000064400000000000000000000014511046102023000215220ustar 00000000000000daemon users mylonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglogin:CL:longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglongpassword pidfile /tmp/3proxy-test.pid auth strong allow mylonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglogin socks -p41080tokio-socks-0.5.2/tests/long_username_password_auth.rs000064400000000000000000000131171046102023000214110ustar 00000000000000mod common; use common::*; #[cfg(feature = "futures-io")] use tokio_socks::io::Compat; use tokio_socks::{ tcp::socks5::{Socks5Listener, Socks5Stream}, Result, }; #[cfg(feature = "tokio")] #[test] fn connect_long_username_password() -> Result<()> { let runtime = runtime().lock().unwrap(); let conn = runtime.block_on(Socks5Stream::connect_with_password( PROXY_ADDR, ECHO_SERVER_ADDR, "mylonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglogin", "longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglongpassword"))?; runtime.block_on(test_connect(conn)) } #[cfg(feature = "tokio")] #[test] fn bind_long_username_password() -> Result<()> { let bind = { let runtime = runtime().lock().unwrap(); runtime.block_on(Socks5Listener::bind_with_password( PROXY_ADDR, ECHO_SERVER_ADDR, "mylonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglogin", "longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglongpassword" )) }?; test_bind(bind) } #[cfg(feature = "tokio")] #[test] fn connect_with_socket_long_username_password() -> Result<()> { let runtime = runtime().lock().unwrap(); let socket = runtime.block_on(connect_unix(UNIX_PROXY_ADDR))?; let conn = runtime.block_on(Socks5Stream::connect_with_password_and_socket( socket, ECHO_SERVER_ADDR, "mylonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglogin", "longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglongpassword"))?; runtime.block_on(test_connect(conn)) } #[cfg(feature = "tokio")] #[test] fn bind_with_socket_long_username_password() -> Result<()> { let bind = { let runtime = runtime().lock().unwrap(); let socket = runtime.block_on(connect_unix(UNIX_PROXY_ADDR))?; runtime.block_on(Socks5Listener::bind_with_password_and_socket( socket, ECHO_SERVER_ADDR, "mylonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglogin", "longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglongpassword" )) }?; test_bind(bind) } #[cfg(feature = "futures-io")] #[test] fn connect_with_socket_long_username_password_futures_io() -> Result<()> { let runtime = futures_utils::runtime().lock().unwrap(); let socket = Compat::new(runtime.block_on(futures_utils::connect_unix(UNIX_PROXY_ADDR))?); let conn = runtime.block_on(Socks5Stream::connect_with_password_and_socket( socket, ECHO_SERVER_ADDR, "mylonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglogin", "longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglongpassword"))?; runtime.block_on(futures_utils::test_connect(conn)) } #[cfg(feature = "futures-io")] #[test] fn bind_with_socket_long_username_password_futures_io() -> Result<()> { let bind = { let runtime = futures_utils::runtime().lock().unwrap(); let socket = Compat::new(runtime.block_on(futures_utils::connect_unix(UNIX_PROXY_ADDR))?); runtime.block_on(Socks5Listener::bind_with_password_and_socket( socket, ECHO_SERVER_ADDR, "mylonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglogin", "longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglongpassword" )) }?; futures_utils::test_bind(bind) } tokio-socks-0.5.2/tests/no_auth.cfg000064400000000000000000000000731046102023000153550ustar 00000000000000daemon pidfile /tmp/3proxy-test.pid auth none socks -p41080tokio-socks-0.5.2/tests/no_auth.rs000064400000000000000000000041361046102023000152460ustar 00000000000000mod common; use common::*; #[cfg(feature = "futures-io")] use tokio_socks::io::Compat; use tokio_socks::{ tcp::socks5::{Socks5Listener, Socks5Stream}, Result, }; #[cfg(feature = "tokio")] #[test] fn connect_no_auth() -> Result<()> { let runtime = runtime().lock().unwrap(); let conn = runtime.block_on(Socks5Stream::connect(PROXY_ADDR, ECHO_SERVER_ADDR))?; runtime.block_on(test_connect(conn)) } #[cfg(feature = "tokio")] #[test] fn bind_no_auth() -> Result<()> { let bind = { let runtime = runtime().lock().unwrap(); runtime.block_on(Socks5Listener::bind(PROXY_ADDR, ECHO_SERVER_ADDR)) }?; test_bind(bind) } #[cfg(feature = "tokio")] #[test] fn connect_with_socket_no_auth() -> Result<()> { let runtime = runtime().lock().unwrap(); let socket = runtime.block_on(connect_unix(UNIX_PROXY_ADDR))?; let conn = runtime.block_on(Socks5Stream::connect_with_socket(socket, ECHO_SERVER_ADDR))?; runtime.block_on(test_connect(conn)) } #[cfg(feature = "tokio")] #[test] fn bind_with_socket_no_auth() -> Result<()> { let bind = { let runtime = runtime().lock().unwrap(); let socket = runtime.block_on(connect_unix(UNIX_PROXY_ADDR))?; runtime.block_on(Socks5Listener::bind_with_socket(socket, ECHO_SERVER_ADDR)) }?; test_bind(bind) } #[cfg(feature = "futures-io")] #[test] fn connect_with_socket_no_auth_futures_io() -> Result<()> { let runtime = futures_utils::runtime().lock().unwrap(); let socket = Compat::new(runtime.block_on(futures_utils::connect_unix(UNIX_PROXY_ADDR))?); let conn = runtime.block_on(Socks5Stream::connect_with_socket(socket, ECHO_SERVER_ADDR))?; runtime.block_on(futures_utils::test_connect(conn)) } #[cfg(feature = "futures-io")] #[test] fn bind_with_socket_no_auth_futures_io() -> Result<()> { let bind = { let runtime = futures_utils::runtime().lock().unwrap(); let socket = Compat::new(runtime.block_on(futures_utils::connect_unix(UNIX_PROXY_ADDR))?); runtime.block_on(Socks5Listener::bind_with_socket(socket, ECHO_SERVER_ADDR)) }?; futures_utils::test_bind(bind) } tokio-socks-0.5.2/tests/socks4_no_auth.cfg000064400000000000000000000000761046102023000166460ustar 00000000000000daemon pidfile /tmp/3proxy-test.pid auth none socks -p41081 -4tokio-socks-0.5.2/tests/socks4_no_auth.rs000064400000000000000000000043411046102023000165320ustar 00000000000000mod common; use common::*; #[cfg(feature = "futures-io")] use tokio_socks::io::Compat; use tokio_socks::{ tcp::socks4::{Socks4Listener, Socks4Stream}, Result, }; #[cfg(feature = "tokio")] #[test] fn connect_no_auth() -> Result<()> { let runtime = runtime().lock().unwrap(); let conn = runtime.block_on(Socks4Stream::connect(SOCKS4_PROXY_ADDR, ECHO_SERVER_ADDR))?; runtime.block_on(test_connect(conn)) } #[cfg(feature = "tokio")] #[test] fn bind_no_auth() -> Result<()> { let bind = { let runtime = runtime().lock().unwrap(); runtime.block_on(Socks4Listener::bind(SOCKS4_PROXY_ADDR, ECHO_SERVER_ADDR)) }?; test_bind_socks4(bind) } #[cfg(feature = "tokio")] #[test] fn connect_with_socket_no_auth() -> Result<()> { let runtime = runtime().lock().unwrap(); let socket = runtime.block_on(connect_unix(UNIX_SOCKS4_PROXY_ADDR))?; println!("socket connected"); let conn = runtime.block_on(Socks4Stream::connect_with_socket(socket, ECHO_SERVER_ADDR))?; runtime.block_on(test_connect(conn)) } #[cfg(feature = "tokio")] #[test] fn bind_with_socket_no_auth() -> Result<()> { let bind = { let runtime = runtime().lock().unwrap(); let socket = runtime.block_on(connect_unix(UNIX_SOCKS4_PROXY_ADDR))?; runtime.block_on(Socks4Listener::bind_with_socket(socket, ECHO_SERVER_ADDR)) }?; test_bind_socks4(bind) } #[cfg(feature = "futures-io")] #[test] fn connect_with_socket_no_auth_futures_io() -> Result<()> { let runtime = futures_utils::runtime().lock().unwrap(); let socket = Compat::new(runtime.block_on(futures_utils::connect_unix(UNIX_SOCKS4_PROXY_ADDR))?); println!("socket connected"); let conn = runtime.block_on(Socks4Stream::connect_with_socket(socket, ECHO_SERVER_ADDR))?; runtime.block_on(futures_utils::test_connect(conn)) } #[cfg(feature = "futures-io")] #[test] fn bind_with_socket_no_auth_futures_io() -> Result<()> { let bind = { let runtime = futures_utils::runtime().lock().unwrap(); let socket = Compat::new(runtime.block_on(futures_utils::connect_unix(UNIX_SOCKS4_PROXY_ADDR))?); runtime.block_on(Socks4Listener::bind_with_socket(socket, ECHO_SERVER_ADDR)) }?; futures_utils::test_bind_socks4(bind) } tokio-socks-0.5.2/tests/socks4_userid.cfg000064400000000000000000000001401046102023000164740ustar 00000000000000daemon pidfile /tmp/3proxy-test.pid users mylogin:CL: allow mylogin auth strong socks -p41081 -4tokio-socks-0.5.2/tests/socks4_userid.rs000064400000000000000000000047331046102023000163750ustar 00000000000000mod common; use common::*; #[cfg(feature = "futures-io")] use tokio_socks::io::Compat; use tokio_socks::{tcp::socks4::*, Result}; #[cfg(feature = "tokio")] #[test] fn connect_userid() -> Result<()> { let runtime = runtime().lock().unwrap(); let conn = runtime.block_on(Socks4Stream::connect_with_userid( SOCKS4_PROXY_ADDR, ECHO_SERVER_ADDR, "mylogin", ))?; runtime.block_on(test_connect(conn)) } #[cfg(feature = "tokio")] #[test] fn bind_userid() -> Result<()> { let bind = { let runtime = runtime().lock().unwrap(); runtime.block_on(Socks4Listener::bind_with_userid( SOCKS4_PROXY_ADDR, ECHO_SERVER_ADDR, "mylogin", )) }?; test_bind_socks4(bind) } #[cfg(feature = "tokio")] #[test] fn connect_with_socket_userid() -> Result<()> { let runtime = runtime().lock().unwrap(); let socket = runtime.block_on(connect_unix(UNIX_SOCKS4_PROXY_ADDR))?; let conn = runtime.block_on(Socks4Stream::connect_with_userid_and_socket( socket, ECHO_SERVER_ADDR, "mylogin", ))?; runtime.block_on(test_connect(conn)) } #[cfg(feature = "tokio")] #[test] fn bind_with_socket_userid() -> Result<()> { let bind = { let runtime = runtime().lock().unwrap(); let socket = runtime.block_on(connect_unix(UNIX_SOCKS4_PROXY_ADDR))?; runtime.block_on(Socks4Listener::bind_with_user_and_socket( socket, ECHO_SERVER_ADDR, "mylogin", )) }?; test_bind_socks4(bind) } #[cfg(feature = "futures-io")] #[test] fn connect_with_socket_userid_futures_io() -> Result<()> { let runtime = futures_utils::runtime().lock().unwrap(); let socket = Compat::new(runtime.block_on(futures_utils::connect_unix(UNIX_SOCKS4_PROXY_ADDR))?); let conn = runtime.block_on(Socks4Stream::connect_with_userid_and_socket( socket, ECHO_SERVER_ADDR, "mylogin", ))?; runtime.block_on(futures_utils::test_connect(conn)) } #[cfg(feature = "futures-io")] #[test] fn bind_with_socket_userid_futures_io() -> Result<()> { let bind = { let runtime = futures_utils::runtime().lock().unwrap(); let socket = Compat::new(runtime.block_on(futures_utils::connect_unix(UNIX_SOCKS4_PROXY_ADDR))?); runtime.block_on(Socks4Listener::bind_with_user_and_socket( socket, ECHO_SERVER_ADDR, "mylogin", )) }?; futures_utils::test_bind_socks4(bind) } tokio-socks-0.5.2/tests/username_auth.cfg000064400000000000000000000001471046102023000165620ustar 00000000000000daemon users mylogin:CL:mypassword pidfile /tmp/3proxy-test.pid auth strong allow mylogin socks -p41080tokio-socks-0.5.2/tests/username_auth.rs000064400000000000000000000052161046102023000164510ustar 00000000000000mod common; use common::*; #[cfg(feature = "futures-io")] use tokio_socks::io::Compat; use tokio_socks::{ tcp::socks5::{Socks5Listener, Socks5Stream}, Result, }; #[cfg(feature = "tokio")] #[test] fn connect_username_auth() -> Result<()> { let runtime = runtime().lock().unwrap(); let conn = runtime.block_on(Socks5Stream::connect_with_password( PROXY_ADDR, ECHO_SERVER_ADDR, "mylogin", "mypassword", ))?; runtime.block_on(test_connect(conn)) } #[cfg(feature = "tokio")] #[test] fn bind_username_auth() -> Result<()> { let bind = { let runtime = runtime().lock().unwrap(); runtime.block_on(Socks5Listener::bind_with_password( PROXY_ADDR, ECHO_SERVER_ADDR, "mylogin", "mypassword", )) }?; test_bind(bind) } #[cfg(feature = "tokio")] #[test] fn connect_with_socket_username_auth() -> Result<()> { let runtime = runtime().lock().unwrap(); let socket = runtime.block_on(connect_unix(UNIX_PROXY_ADDR))?; let conn = runtime.block_on(Socks5Stream::connect_with_password_and_socket( socket, ECHO_SERVER_ADDR, "mylogin", "mypassword", ))?; runtime.block_on(test_connect(conn)) } #[cfg(feature = "tokio")] #[test] fn bind_with_socket_username_auth() -> Result<()> { let bind = { let runtime = runtime().lock().unwrap(); let socket = runtime.block_on(connect_unix(UNIX_PROXY_ADDR))?; runtime.block_on(Socks5Listener::bind_with_password_and_socket( socket, ECHO_SERVER_ADDR, "mylogin", "mypassword", )) }?; test_bind(bind) } #[cfg(feature = "futures-io")] #[test] fn connect_with_socket_username_auth_futures_io() -> Result<()> { let runtime = futures_utils::runtime().lock().unwrap(); let socket = Compat::new(runtime.block_on(futures_utils::connect_unix(UNIX_PROXY_ADDR))?); let conn = runtime.block_on(Socks5Stream::connect_with_password_and_socket( socket, ECHO_SERVER_ADDR, "mylogin", "mypassword", ))?; runtime.block_on(futures_utils::test_connect(conn)) } #[cfg(feature = "futures-io")] #[test] fn bind_with_socket_username_auth_futures_io() -> Result<()> { let bind = { let runtime = futures_utils::runtime().lock().unwrap(); let socket = Compat::new(runtime.block_on(futures_utils::connect_unix(UNIX_PROXY_ADDR))?); runtime.block_on(Socks5Listener::bind_with_password_and_socket( socket, ECHO_SERVER_ADDR, "mylogin", "mypassword", )) }?; futures_utils::test_bind(bind) }