├── .cargo └── config.toml ├── .github ├── dependabot.yml └── workflows │ ├── auto-merge.yml │ ├── install-cross.sh │ ├── release.yml │ └── rust.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── examples ├── demo-client.rs ├── demo-server.rs ├── dns-query.rs ├── echo-server.rs ├── s5-server.rs ├── udp-client.rs └── util │ ├── dns.rs │ └── mod.rs ├── rustfmt.toml └── src ├── client └── mod.rs ├── error.rs ├── lib.rs ├── protocol ├── address.rs ├── command.rs ├── handshake │ ├── auth_method.rs │ ├── mod.rs │ ├── password_method │ │ ├── mod.rs │ │ ├── request.rs │ │ └── response.rs │ ├── request.rs │ └── response.rs ├── mod.rs ├── reply.rs ├── request.rs ├── response.rs └── udp.rs └── server ├── auth.rs ├── connection ├── associate.rs ├── bind.rs ├── connect.rs └── mod.rs └── mod.rs /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [registries.crates-io] 2 | protocol = "sparse" 3 | 4 | [build] 5 | #target = "aarch64-linux-android" 6 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "cargo" 9 | directory: "/" 10 | schedule: 11 | interval: "weekly" 12 | 13 | - package-ecosystem: "github-actions" 14 | directory: "/" 15 | schedule: 16 | interval: "weekly" 17 | -------------------------------------------------------------------------------- /.github/workflows/auto-merge.yml: -------------------------------------------------------------------------------- 1 | name: Dependabot Auto Merge 2 | 3 | on: 4 | # https://securitylab.github.com/research/github-actions-preventing-pwn-requests 5 | # could and should work, at least for public repos; 6 | # tracking issue for this action's issue: 7 | # https://github.com/ahmadnassri/action-dependabot-auto-merge/issues/60 8 | pull_request_target: 9 | types: [labeled] 10 | 11 | jobs: 12 | auto: 13 | if: github.actor == 'dependabot[bot]' 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v4 17 | with: 18 | token: ${{ secrets.GITHUB_TOKEN }} 19 | - uses: dtolnay/rust-toolchain@stable 20 | - name: Auto approve pull request, then squash and merge 21 | uses: ahmadnassri/action-dependabot-auto-merge@v2 22 | with: 23 | target: minor 24 | # Note: This needs to be a PAT with (public) repo rights, 25 | # PAT-owning user needs to have write access to this repo 26 | # (dependabot needs to recognize the comment as coming from an allowed reviewer) 27 | github-token: ${{ secrets.PAT_REPO_ADMIN }} 28 | -------------------------------------------------------------------------------- /.github/workflows/install-cross.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | curl -s https://api.github.com/repos/cross-rs/cross/releases/latest \ 4 | | grep cross-x86_64-unknown-linux-gnu.tar.gz \ 5 | | cut -d : -f 2,3 \ 6 | | tr -d \" \ 7 | | wget -qi - 8 | 9 | tar -zxvf cross-x86_64-unknown-linux-gnu.tar.gz -C /usr/bin 10 | rm -f cross-x86_64-unknown-linux-gnu.tar.gz 11 | 12 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Deploy Releases 2 | on: 3 | push: 4 | tags: 5 | - "v*.*.*" 6 | env: 7 | CARGO_TERM_COLOR: always 8 | 9 | jobs: 10 | deploy: 11 | strategy: 12 | matrix: 13 | target: 14 | - x86_64-unknown-linux-gnu 15 | - x86_64-unknown-linux-musl 16 | - aarch64-unknown-linux-gnu 17 | - armv7-unknown-linux-gnueabihf 18 | - x86_64-apple-darwin 19 | - aarch64-apple-darwin 20 | - x86_64-pc-windows-msvc 21 | - i686-pc-windows-msvc 22 | 23 | include: 24 | - target: x86_64-unknown-linux-gnu 25 | host_os: ubuntu-latest 26 | - target: x86_64-unknown-linux-musl 27 | host_os: ubuntu-latest 28 | - target: aarch64-unknown-linux-gnu 29 | host_os: ubuntu-latest 30 | - target: armv7-unknown-linux-gnueabihf 31 | host_os: ubuntu-latest 32 | - target: x86_64-apple-darwin 33 | host_os: macos-latest 34 | - target: aarch64-apple-darwin 35 | host_os: macos-latest 36 | - target: x86_64-pc-windows-msvc 37 | host_os: windows-latest 38 | - target: i686-pc-windows-msvc 39 | host_os: windows-latest 40 | 41 | runs-on: ${{ matrix.host_os }} 42 | steps: 43 | - uses: actions/checkout@v4 44 | - uses: dtolnay/rust-toolchain@stable 45 | 46 | - name: Prepare 47 | shell: bash 48 | run: | 49 | mkdir release 50 | rustup target add ${{ matrix.target }} 51 | if [[ "${{ matrix.host_os }}" == "ubuntu-latest" ]]; then 52 | sudo .github/workflows/install-cross.sh 53 | fi 54 | 55 | - name: Build 56 | shell: bash 57 | run: | 58 | if [[ "${{ matrix.host_os }}" == "ubuntu-latest" ]]; then 59 | cross build --all-features --release --examples --target ${{ matrix.target }} 60 | else 61 | cargo build --all-features --release --examples --target ${{ matrix.target }} 62 | fi 63 | if [[ "${{ matrix.host_os }}" == "windows-latest" ]]; then 64 | powershell Compress-Archive -Path target/${{ matrix.target }}/release/examples/s5-server.exe, target/${{ matrix.target }}/release/examples/udp-client.exe, target/${{ matrix.target }}/release/examples/dns-query.exe, target/${{ matrix.target }}/release/examples/echo-server.exe -DestinationPath release/socks5-utilities-${{ matrix.target }}.zip 65 | elif [[ "${{ matrix.host_os }}" == "macos-latest" ]]; then 66 | zip -j release/socks5-utilities-${{ matrix.target }}.zip target/${{ matrix.target }}/release/examples/s5-server target/${{ matrix.target }}/release/examples/udp-client target/${{ matrix.target }}/release/examples/dns-query target/${{ matrix.target }}/release/examples/echo-server 67 | elif [[ "${{ matrix.host_os }}" == "ubuntu-latest" ]]; then 68 | zip -j release/socks5-utilities-${{ matrix.target }}.zip target/${{ matrix.target }}/release/examples/s5-server target/${{ matrix.target }}/release/examples/udp-client target/${{ matrix.target }}/release/examples/dns-query target/${{ matrix.target }}/release/examples/echo-server 69 | fi 70 | 71 | - name: Upload 72 | uses: softprops/action-gh-release@v2 73 | env: 74 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 75 | with: 76 | files: release/* 77 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Push or PR 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | branches: 7 | - '**' 8 | pull_request: 9 | branches: 10 | - '**' 11 | 12 | env: 13 | CARGO_TERM_COLOR: always 14 | 15 | jobs: 16 | build_n_test: 17 | strategy: 18 | fail-fast: false 19 | matrix: 20 | os: [ubuntu-latest, macos-latest, windows-latest] 21 | 22 | runs-on: ${{ matrix.os }} 23 | 24 | steps: 25 | - uses: actions/checkout@v4 26 | - uses: dtolnay/rust-toolchain@stable 27 | - name: rustfmt 28 | run: cargo fmt --all -- --check 29 | - name: check 30 | if: ${{ !cancelled() }} 31 | run: cargo check --verbose 32 | - name: clippy 33 | if: ${{ !cancelled() }} 34 | run: cargo clippy --all-targets --all-features -- -D warnings 35 | - name: Build 36 | if: ${{ !cancelled() }} 37 | run: cargo build --verbose 38 | - name: Run tests 39 | if: ${{ !cancelled() }} 40 | run: cargo test --verbose --all-features 41 | - name: Abort on error 42 | if: ${{ failure() }} 43 | run: echo "build_n_test failed" && false 44 | 45 | semver: 46 | name: Check semver 47 | strategy: 48 | fail-fast: false 49 | matrix: 50 | os: [ubuntu-latest, macos-latest, windows-latest] 51 | runs-on: ${{ matrix.os }} 52 | steps: 53 | - uses: actions/checkout@v4 54 | - uses: dtolnay/rust-toolchain@stable 55 | - name: Check semver 56 | if: ${{ !cancelled() }} 57 | uses: obi1kenobi/cargo-semver-checks-action@v2 58 | - name: Abort on error 59 | if: ${{ failure() }} 60 | run: echo "Semver check failed" && false 61 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .* 2 | examples/ 3 | target/ 4 | Cargo.lock 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "socks5-impl" 3 | version = "0.7.0" 4 | authors = ["ssrlive "] 5 | description = "Fundamental abstractions and async read / write functions for SOCKS5 protocol and Relatively low-level asynchronized SOCKS5 server implementation based on tokio" 6 | categories = ["network-programming", "asynchronous"] 7 | keywords = ["socks5", "socks", "proxy", "async", "network"] 8 | edition = "2024" 9 | readme = "README.md" 10 | license = "GPL-3.0-or-later" 11 | repository = "https://github.com/ssrlive/socks5-impl" 12 | 13 | [features] 14 | # default = ["serde", "client", "server", "tokio"] 15 | client = ["tokio"] 16 | serde = ["dep:serde"] 17 | server = ["tokio"] 18 | tokio = ["dep:tokio"] 19 | 20 | [dependencies] 21 | async-trait = "0.1" 22 | bytes = "1" 23 | percent-encoding = "2" 24 | serde = { version = "1", features = ["derive"], optional = true } 25 | thiserror = "2" 26 | tokio = { version = "1", default-features = false, features = [ 27 | "net", 28 | "io-util", 29 | "time", 30 | "macros", 31 | "rt", 32 | ], optional = true } 33 | 34 | [dev-dependencies] 35 | clap = { version = "4", features = ["derive"] } 36 | ctrlc2 = { version = "3", features = ["tokio", "termination"] } 37 | dotenvy = "0.15" 38 | env_logger = "0.11" 39 | hickory-proto = "0.25" 40 | log = "0.4" 41 | moka = { version = "0.12", features = ["future"] } 42 | rand = "0.9" 43 | tokio = { version = "1", features = ["rt-multi-thread"] } 44 | 45 | [[example]] 46 | name = "demo-client" 47 | path = "examples/demo-client.rs" 48 | required-features = ["client"] 49 | 50 | [[example]] 51 | name = "demo-server" 52 | path = "examples/demo-server.rs" 53 | required-features = ["tokio"] 54 | 55 | [[example]] 56 | name = "dns-query" 57 | path = "examples/dns-query.rs" 58 | required-features = ["client"] 59 | 60 | [[example]] 61 | name = "s5-server" 62 | path = "examples/s5-server.rs" 63 | required-features = ["server"] 64 | 65 | [[example]] 66 | name = "udp-client" 67 | path = "examples/udp-client.rs" 68 | required-features = ["client"] 69 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # socks5-impl 2 | 3 | Fundamental abstractions and async read / write functions for SOCKS5 protocol and Relatively low-level asynchronized SOCKS5 server implementation based on tokio. 4 | 5 | This repo hosts at [socks5-impl](https://github.com/ssrlive/socks5-impl/tree/master/) 6 | 7 | [![Version](https://img.shields.io/crates/v/socks5-impl.svg?style=flat)](https://crates.io/crates/socks5-impl) 8 | [![Documentation](https://img.shields.io/badge/docs-release-brightgreen.svg?style=flat)](https://docs.rs/socks5-impl) 9 | [![License](https://img.shields.io/crates/l/socks5-impl.svg?style=flat)](https://github.com/ssrlive/socks5-impl/blob/master/LICENSE) 10 | 11 | ## Features 12 | 13 | - Fully asynchronized 14 | - Supports all SOCKS5 commands 15 | - CONNECT 16 | - BIND 17 | - ASSOCIATE 18 | - Customizable authentication 19 | - No authentication 20 | - Username / password 21 | - GSSAPI 22 | 23 | ## Usage 24 | 25 | The entry point of this crate is [`socks5_impl::server::Server`](crate::server::Server). 26 | 27 | Check [examples](https://github.com/ssrlive/socks5-impl/tree/master/examples) for usage examples. 28 | 29 | ## Example 30 | 31 | ```rust no_run 32 | use socks5_impl::protocol::{handshake, Address, AuthMethod, Reply, Request, Response, StreamOperation}; 33 | 34 | fn main() -> socks5_impl::Result<()> { 35 | let listener = std::net::TcpListener::bind("127.0.0.1:5000")?; 36 | let (mut stream, _) = listener.accept()?; 37 | 38 | let request = handshake::Request::retrieve_from_stream(&mut stream)?; 39 | 40 | if request.evaluate_method(AuthMethod::NoAuth) { 41 | let response = handshake::Response::new(AuthMethod::NoAuth); 42 | response.write_to_stream(&mut stream)?; 43 | } else { 44 | let response = handshake::Response::new(AuthMethod::NoAcceptableMethods); 45 | response.write_to_stream(&mut stream)?; 46 | let _ = stream.shutdown(std::net::Shutdown::Both); 47 | let err = "No available handshake method provided by client"; 48 | return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err).into()); 49 | } 50 | 51 | let req = match Request::retrieve_from_stream(&mut stream) { 52 | Ok(req) => req, 53 | Err(err) => { 54 | let resp = Response::new(Reply::GeneralFailure, Address::unspecified()); 55 | resp.write_to_stream(&mut stream)?; 56 | let _ = stream.shutdown(std::net::Shutdown::Both); 57 | return Err(err.into()); 58 | } 59 | }; 60 | 61 | match req.command { 62 | _ => {} // process request 63 | } 64 | 65 | Ok(()) 66 | } 67 | ``` 68 | 69 | ## License 70 | GNU General Public License v3.0 71 | -------------------------------------------------------------------------------- /examples/demo-client.rs: -------------------------------------------------------------------------------- 1 | use socks5_impl::{Result, client}; 2 | use tokio::io::{AsyncReadExt, AsyncWriteExt, BufStream}; 3 | use tokio::net::TcpStream; 4 | 5 | #[tokio::main] 6 | async fn main() -> Result<()> { 7 | let s5_proxy = TcpStream::connect("127.0.0.1:1080").await?; 8 | let mut stream = BufStream::new(s5_proxy); 9 | let addr = client::connect(&mut stream, ("google.com", 80), None).await?; 10 | println!("connected {addr}"); 11 | 12 | // write http request 13 | let req = b"GET / HTTP/1.0\r\nHost: google.com\r\n\r\n"; 14 | stream.write_all(req).await?; 15 | stream.flush().await?; 16 | 17 | // read http response 18 | let mut buf = vec![0; 1024]; 19 | let n = stream.read(&mut buf).await?; 20 | println!("read {} bytes", n); 21 | println!("{}", String::from_utf8_lossy(&buf[..n])); 22 | 23 | Ok(()) 24 | } 25 | -------------------------------------------------------------------------------- /examples/demo-server.rs: -------------------------------------------------------------------------------- 1 | use socks5_impl::protocol::{Address, AsyncStreamOperation, AuthMethod, Reply, Request, Response, handshake}; 2 | use std::io; 3 | use tokio::{io::AsyncWriteExt, net::TcpListener}; 4 | 5 | #[tokio::main] 6 | async fn main() -> io::Result<()> { 7 | let listener = TcpListener::bind("127.0.0.1:5000").await?; 8 | let (mut stream, _) = listener.accept().await?; 9 | 10 | let request = handshake::Request::retrieve_from_async_stream(&mut stream).await?; 11 | 12 | if request.evaluate_method(AuthMethod::NoAuth) { 13 | let response = handshake::Response::new(AuthMethod::NoAuth); 14 | response.write_to_async_stream(&mut stream).await?; 15 | } else { 16 | let response = handshake::Response::new(AuthMethod::NoAcceptableMethods); 17 | response.write_to_async_stream(&mut stream).await?; 18 | let _ = stream.shutdown().await; 19 | let err = "No available handshake method provided by client"; 20 | return Err(io::Error::new(io::ErrorKind::Unsupported, err)); 21 | } 22 | 23 | let _req = match Request::retrieve_from_async_stream(&mut stream).await { 24 | Ok(req) => req, 25 | Err(err) => { 26 | let resp = Response::new(Reply::GeneralFailure, Address::unspecified()); 27 | resp.write_to_async_stream(&mut stream).await?; 28 | let _ = stream.shutdown().await; 29 | return Err(err); 30 | } 31 | }; 32 | 33 | // match _req.command { 34 | // _ => {} // process request 35 | // } 36 | 37 | Ok(()) 38 | } 39 | -------------------------------------------------------------------------------- /examples/dns-query.rs: -------------------------------------------------------------------------------- 1 | mod util; 2 | 3 | use hickory_proto::rr::record_type::RecordType; 4 | use socks5_impl::{Result, client, protocol::UserKey}; 5 | use std::{net::SocketAddr, time::Duration}; 6 | use tokio::{ 7 | io::{AsyncReadExt, AsyncWriteExt}, 8 | net::TcpStream, 9 | }; 10 | use util::dns; 11 | 12 | /// DNS query through socks5 proxy. 13 | #[derive(clap::Parser, Debug, Clone, PartialEq, Eq)] 14 | #[command(author, version, about = "DNS query through socks5 proxy or not", long_about = None)] 15 | pub struct CmdOpt { 16 | /// DNS server address. 17 | #[clap(short, long, value_name = "address:port", default_value = "8.8.8.8:53")] 18 | remote_dns_server: SocketAddr, 19 | 20 | /// Domain name for query. 21 | #[clap(short, long, value_name = "domain name")] 22 | domain: String, 23 | 24 | /// Via socks5 proxy. 25 | #[clap(short, long, value_name = "via proxy", default_value = "false")] 26 | via_proxy: bool, 27 | 28 | /// Socks5 proxy server address. 29 | #[clap(short, long, value_name = "address:port")] 30 | proxy_addr: Option, 31 | 32 | /// User name for SOCKS5 authentication. 33 | #[clap(short, long, value_name = "user name")] 34 | username: Option, 35 | 36 | /// Password for SOCKS5 authentication. 37 | #[clap(short = 'w', long, value_name = "password")] 38 | password: Option, 39 | 40 | /// Use TCP protocol. 41 | #[clap(short, long, value_name = "tcp", default_value = "false")] 42 | tcp: bool, 43 | 44 | /// Timeout in seconds. 45 | #[clap(short = 'm', long, value_name = "seconds", default_value = "5")] 46 | timeout: u64, 47 | } 48 | 49 | impl CmdOpt { 50 | pub fn validate(&self) -> Result<(), String> { 51 | if self.via_proxy && self.proxy_addr.is_none() { 52 | return Err("proxy_addr is required when via_proxy is true".into()); 53 | } 54 | Ok(()) 55 | } 56 | } 57 | 58 | #[tokio::main] 59 | async fn main() -> Result<()> { 60 | let opt: CmdOpt = clap::Parser::parse(); 61 | opt.validate()?; 62 | 63 | let is_ipv4 = opt.remote_dns_server.is_ipv4(); 64 | let query_type = if is_ipv4 { RecordType::A } else { RecordType::AAAA }; 65 | let msg_buf = dns::build_dns_query(&opt.domain, query_type, opt.tcp)?; 66 | 67 | let message = dns::parse_data_to_dns_message(&msg_buf, opt.tcp)?; 68 | let domain = dns::extract_domain_from_dns_message(&message)?.trim_end_matches('.').to_string(); 69 | assert_eq!(&domain, &opt.domain); 70 | 71 | let buf = dns_query_from_server(&opt, &msg_buf).await?; 72 | 73 | let message = dns::parse_data_to_dns_message(&buf, opt.tcp)?; 74 | let domain = dns::extract_domain_from_dns_message(&message)?.trim_end_matches('.').to_string(); 75 | assert_eq!(&domain, &opt.domain); 76 | 77 | let addr = dns::extract_ipaddr_from_dns_message(&message)?; 78 | println!("{}", addr); 79 | 80 | Ok(()) 81 | } 82 | 83 | async fn dns_query_from_server(opt: &CmdOpt, msg_buf: &[u8]) -> Result> { 84 | let user_key = match (&opt.username, &opt.password) { 85 | (Some(username), Some(password)) => Some(UserKey::new(username, password)), 86 | _ => None, 87 | }; 88 | let timeout = Duration::from_secs(opt.timeout); 89 | let buf = match (opt.tcp, opt.via_proxy) { 90 | (true, true) => { 91 | let proxy = TcpStream::connect(opt.proxy_addr.as_ref().unwrap()).await?; 92 | let mut stream = tokio::io::BufStream::new(proxy); 93 | let addr = client::connect(&mut stream, &opt.remote_dns_server, user_key).await?; 94 | log::trace!("connected {addr}"); 95 | 96 | // write dns request 97 | stream.write_all(msg_buf).await?; 98 | stream.flush().await?; 99 | 100 | // read dns response 101 | let mut buf = vec![0; 1500]; 102 | let n = tokio::time::timeout(timeout, stream.read(&mut buf)).await??; 103 | log::trace!("read {} bytes", n); 104 | buf.truncate(n); 105 | buf 106 | } 107 | (true, false) => { 108 | let mut stream = TcpStream::connect(&opt.remote_dns_server).await?; 109 | stream.write_all(msg_buf).await?; 110 | stream.flush().await?; 111 | let mut buf = vec![0; 1500]; 112 | let n = tokio::time::timeout(timeout, stream.read(&mut buf)).await??; 113 | buf.truncate(n); 114 | buf 115 | } 116 | (false, true) => { 117 | let proxy_addr = *opt.proxy_addr.as_ref().unwrap(); 118 | let udp_server_addr = opt.remote_dns_server; 119 | client::UdpClientImpl::datagram(proxy_addr, udp_server_addr, user_key) 120 | .await? 121 | .transfer_data(msg_buf, timeout) 122 | .await? 123 | } 124 | (false, false) => { 125 | let client_addr = if opt.remote_dns_server.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" }; 126 | let client = tokio::net::UdpSocket::bind(client_addr).await?; 127 | client.send_to(msg_buf, &opt.remote_dns_server).await?; 128 | let mut buf = vec![0u8; 1500]; 129 | let (len, _) = tokio::time::timeout(timeout, client.recv_from(&mut buf)).await??; 130 | buf.truncate(len); 131 | buf 132 | } 133 | }; 134 | Ok(buf) 135 | } 136 | -------------------------------------------------------------------------------- /examples/echo-server.rs: -------------------------------------------------------------------------------- 1 | use std::{error::Error, net::SocketAddr}; 2 | use tokio::{ 3 | io::{AsyncReadExt, AsyncWriteExt}, 4 | net::{TcpListener, ToSocketAddrs, UdpSocket}, 5 | }; 6 | 7 | /// Simple echo server. 8 | #[derive(clap::Parser, Debug, Clone, PartialEq, Eq)] 9 | #[command(author, version, about = "Simple echo server.", long_about = None)] 10 | pub struct CmdOpt { 11 | /// Echo server listen address. 12 | #[clap(short, long, value_name = "address:port", default_value = "127.0.0.1:8080")] 13 | listen_addr: SocketAddr, 14 | 15 | /// timeout for TCP connection 16 | #[clap(short, long, value_name = "seconds", default_value = "10")] 17 | tcp_timeout: u64, 18 | } 19 | 20 | async fn tcp_main(addr: A, tcp_timeout: u64) -> std::io::Result<()> { 21 | let listener = TcpListener::bind(addr).await?; 22 | log::info!("[TCP] listening on: {}", listener.local_addr()?); 23 | loop { 24 | let (mut socket, peer) = listener.accept().await?; 25 | tokio::spawn(async move { 26 | let block = async move { 27 | let mut buf = vec![0; 1024]; 28 | log::info!("[TCP] incoming peer {}", peer); 29 | loop { 30 | let duration = std::time::Duration::from_secs(tcp_timeout); 31 | let n = tokio::time::timeout(duration, socket.read(&mut buf)).await??; 32 | if n == 0 { 33 | log::info!("[TCP] {} exit", peer); 34 | break; 35 | } 36 | let amt = socket.write(&buf[0..n]).await?; 37 | log::info!("[TCP] Echoed {}/{} bytes to {}", amt, n, peer); 38 | } 39 | Ok::<(), std::io::Error>(()) 40 | }; 41 | if let Err(err) = block.await { 42 | log::info!("[TCP] {}", err); 43 | } 44 | }); 45 | } 46 | } 47 | 48 | async fn udp_main(addr: A) -> std::io::Result<()> { 49 | let socket = UdpSocket::bind(&addr).await?; 50 | log::info!("[UDP] Listening on: {}", socket.local_addr()?); 51 | 52 | let mut buf = vec![0; 1024]; 53 | let mut to_send = None; 54 | 55 | loop { 56 | if let Some((size, peer)) = to_send { 57 | let amt = socket.send_to(&buf[..size], &peer).await?; 58 | log::info!("[UDP] Echoed {}/{} bytes to {}", amt, size, peer); 59 | } 60 | 61 | to_send = Some(socket.recv_from(&mut buf).await?); 62 | } 63 | } 64 | 65 | #[tokio::main] 66 | async fn main() -> Result<(), Box> { 67 | let opt: CmdOpt = clap::Parser::parse(); 68 | 69 | env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("trace")).init(); 70 | 71 | let addr = opt.listen_addr; 72 | let _tcp = tokio::spawn(async move { 73 | tcp_main(&addr, opt.tcp_timeout).await?; 74 | Ok::<(), std::io::Error>(()) 75 | }); 76 | 77 | let _udp = tokio::spawn(async move { 78 | udp_main(&addr).await?; 79 | Ok::<(), std::io::Error>(()) 80 | }); 81 | 82 | let (tx, mut rx) = tokio::sync::mpsc::channel::<()>(1); 83 | 84 | ctrlc2::set_async_handler(async move { 85 | tx.send(()).await.unwrap(); 86 | log::info!("Ctrl-C received, shutting down..."); 87 | }) 88 | .await; 89 | 90 | rx.recv().await.unwrap(); 91 | log::info!("Exiting..."); 92 | 93 | Ok(()) 94 | } 95 | -------------------------------------------------------------------------------- /examples/s5-server.rs: -------------------------------------------------------------------------------- 1 | use socks5_impl::{ 2 | Error, Result, 3 | protocol::{Address, Reply, UdpHeader}, 4 | server::{AssociatedUdpSocket, ClientConnection, IncomingConnection, Server, UdpAssociate, auth, connection::associate}, 5 | }; 6 | use std::{ 7 | net::{SocketAddr, ToSocketAddrs}, 8 | sync::{Arc, atomic::AtomicBool}, 9 | }; 10 | use tokio::{ 11 | io, 12 | net::{TcpStream, UdpSocket}, 13 | sync::Mutex, 14 | }; 15 | 16 | /// Simple socks5 proxy server. 17 | #[derive(clap::Parser, Debug, Clone, PartialEq, Eq)] 18 | #[command(author, version, about = "Simple socks5 proxy server.", long_about = None)] 19 | pub struct CmdOpt { 20 | /// Socks5 server listen address. 21 | #[clap(short, long, value_name = "address:port", default_value = "127.0.0.1:1080")] 22 | listen_addr: SocketAddr, 23 | 24 | /// Username for socks5 authentication. 25 | #[clap(short, long, value_name = "username")] 26 | username: Option, 27 | 28 | /// Password for socks5 authentication. 29 | #[clap(short, long, value_name = "password")] 30 | password: Option, 31 | 32 | /// Verbosity level 33 | #[arg(short, long, value_name = "level", value_enum, default_value = "info")] 34 | verbosity: ArgVerbosity, 35 | } 36 | 37 | #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, clap::ValueEnum)] 38 | enum ArgVerbosity { 39 | Off, 40 | Error, 41 | Warn, 42 | Info, 43 | Debug, 44 | Trace, 45 | } 46 | 47 | pub(crate) static MAX_UDP_RELAY_PACKET_SIZE: usize = 1500; 48 | 49 | #[tokio::main] 50 | async fn main() -> Result<()> { 51 | let opt: CmdOpt = clap::Parser::parse(); 52 | 53 | dotenvy::dotenv().ok(); 54 | 55 | let default = format!("{}={:?}", module_path!(), opt.verbosity); 56 | env_logger::Builder::from_env(env_logger::Env::default().default_filter_or(default)).init(); 57 | 58 | let exiting_flag = Arc::new(AtomicBool::new(false)); 59 | let exiting_flag_clone = exiting_flag.clone(); 60 | 61 | let local_addr = opt.listen_addr; 62 | 63 | ctrlc2::set_async_handler(async move { 64 | exiting_flag_clone.store(true, std::sync::atomic::Ordering::Relaxed); 65 | 66 | let addr = if local_addr.is_ipv6() { 67 | SocketAddr::from((std::net::Ipv6Addr::LOCALHOST, local_addr.port())) 68 | } else { 69 | SocketAddr::from((std::net::Ipv4Addr::LOCALHOST, local_addr.port())) 70 | }; 71 | let _ = std::net::TcpStream::connect(addr); 72 | log::info!(""); 73 | log::info!("Ctrl-C received, shutting down..."); 74 | }) 75 | .await; 76 | 77 | match (opt.username, opt.password) { 78 | (Some(username), password) => { 79 | let password = password.unwrap_or_default(); 80 | let auth = Arc::new(auth::UserKeyAuth::new(&username, &password)); 81 | main_loop(auth, opt.listen_addr, Some(exiting_flag)).await?; 82 | } 83 | _ => { 84 | let auth = Arc::new(auth::NoAuth); 85 | main_loop(auth, opt.listen_addr, Some(exiting_flag)).await?; 86 | } 87 | } 88 | 89 | Ok(()) 90 | } 91 | 92 | async fn main_loop(auth: auth::AuthAdaptor, listen_addr: SocketAddr, exiting_flag: Option>) -> Result<()> 93 | where 94 | S: Send + Sync + 'static, 95 | { 96 | let server = Server::bind(listen_addr, auth).await?; 97 | 98 | while let Ok((conn, _)) = server.accept().await { 99 | if let Some(exiting_flag) = &exiting_flag { 100 | if exiting_flag.load(std::sync::atomic::Ordering::Relaxed) { 101 | break; 102 | } 103 | } 104 | tokio::spawn(async move { 105 | if let Err(err) = handle(conn).await { 106 | log::error!("{err}"); 107 | } 108 | }); 109 | } 110 | Ok(()) 111 | } 112 | 113 | async fn handle(conn: IncomingConnection) -> Result<()> 114 | where 115 | S: Send + Sync + 'static, 116 | { 117 | let (conn, res) = conn.authenticate().await?; 118 | 119 | use std::any::Any; 120 | let res = &res as &dyn Any; 121 | if let Some(res) = res.downcast_ref::>() { 122 | let res = *res.as_ref().map_err(|err| err.to_string())?; 123 | if !res { 124 | log::info!("authentication failed"); 125 | return Ok(()); 126 | } 127 | } 128 | 129 | match conn.wait_request().await? { 130 | ClientConnection::UdpAssociate(associate, _) => { 131 | handle_s5_upd_associate(associate).await?; 132 | } 133 | ClientConnection::Bind(bind, _) => { 134 | let mut conn = bind.reply(Reply::CommandNotSupported, Address::unspecified()).await?; 135 | conn.shutdown().await?; 136 | } 137 | ClientConnection::Connect(connect, addr) => { 138 | let target = match addr { 139 | Address::DomainAddress(domain, port) => TcpStream::connect((domain, port)).await, 140 | Address::SocketAddress(addr) => TcpStream::connect(addr).await, 141 | }; 142 | 143 | if let Ok(mut target) = target { 144 | let mut conn = connect.reply(Reply::Succeeded, Address::unspecified()).await?; 145 | log::trace!("{} -> {}", conn.peer_addr()?, target.peer_addr()?); 146 | io::copy_bidirectional(&mut target, &mut conn).await?; 147 | } else { 148 | let mut conn = connect.reply(Reply::HostUnreachable, Address::unspecified()).await?; 149 | conn.shutdown().await?; 150 | } 151 | } 152 | } 153 | 154 | Ok(()) 155 | } 156 | 157 | pub(crate) async fn handle_s5_upd_associate(associate: UdpAssociate) -> Result<()> { 158 | // listen on a random port 159 | let listen_ip = associate.local_addr()?.ip(); 160 | let udp_listener = UdpSocket::bind(SocketAddr::from((listen_ip, 0))).await; 161 | 162 | match udp_listener.and_then(|socket| socket.local_addr().map(|addr| (socket, addr))) { 163 | Err(err) => { 164 | let mut conn = associate.reply(Reply::GeneralFailure, Address::unspecified()).await?; 165 | conn.shutdown().await?; 166 | Err(err.into()) 167 | } 168 | Ok((listen_udp, listen_addr)) => { 169 | log::info!("[UDP] {listen_addr} listen on"); 170 | 171 | let s5_listen_addr = Address::from(listen_addr); 172 | let mut reply_listener = associate.reply(Reply::Succeeded, s5_listen_addr).await?; 173 | 174 | let buf_size = MAX_UDP_RELAY_PACKET_SIZE - UdpHeader::max_serialized_len(); 175 | let listen_udp = Arc::new(AssociatedUdpSocket::from((listen_udp, buf_size))); 176 | 177 | let zero_addr = SocketAddr::from(([0, 0, 0, 0], 0)); 178 | 179 | let incoming_addr = Arc::new(Mutex::new(zero_addr)); 180 | 181 | let dispatch_socket = UdpSocket::bind(zero_addr).await?; 182 | 183 | let res = loop { 184 | tokio::select! { 185 | res = async { 186 | let buf_size = MAX_UDP_RELAY_PACKET_SIZE - UdpHeader::max_serialized_len(); 187 | listen_udp.set_max_packet_size(buf_size); 188 | 189 | let (pkt, frag, dst_addr, src_addr) = listen_udp.recv_from().await?; 190 | if frag != 0 { 191 | return Err("[UDP] packet fragment is not supported".into()); 192 | } 193 | 194 | *incoming_addr.lock().await = src_addr; 195 | 196 | log::trace!("[UDP] {src_addr} -> {dst_addr} incoming packet size {}", pkt.len()); 197 | let dst_addr = dst_addr.to_socket_addrs()?.next().ok_or("Invalid address")?; 198 | dispatch_socket.send_to(&pkt, dst_addr).await?; 199 | Ok::<_, Error>(()) 200 | } => { 201 | if res.is_err() { 202 | break res; 203 | } 204 | }, 205 | res = async { 206 | let mut buf = vec![0u8; MAX_UDP_RELAY_PACKET_SIZE]; 207 | let (len, remote_addr) = dispatch_socket.recv_from(&mut buf).await?; 208 | let incoming_addr = *incoming_addr.lock().await; 209 | log::trace!("[UDP] {incoming_addr} <- {remote_addr} feedback to incoming"); 210 | listen_udp.send_to(&buf[..len], 0, remote_addr.into(), incoming_addr).await?; 211 | Ok::<_, Error>(()) 212 | } => { 213 | if res.is_err() { 214 | break res; 215 | } 216 | }, 217 | _ = reply_listener.wait_until_closed() => { 218 | log::trace!("[UDP] {} listener closed", listen_addr); 219 | break Ok::<_, Error>(()); 220 | }, 221 | }; 222 | }; 223 | 224 | reply_listener.shutdown().await?; 225 | 226 | res 227 | } 228 | } 229 | } 230 | -------------------------------------------------------------------------------- /examples/udp-client.rs: -------------------------------------------------------------------------------- 1 | use socks5_impl::{Result, client::UdpClientImpl, protocol::UserKey}; 2 | use std::{ 3 | net::{SocketAddr, ToSocketAddrs}, 4 | time::Duration, 5 | }; 6 | use tokio::net::UdpSocket; 7 | 8 | /// Udp client through socks5 proxy. 9 | #[derive(clap::Parser, Debug, Clone, PartialEq, Eq)] 10 | #[command(author, version, about = "Udp client through socks5 proxy", long_about = None)] 11 | pub struct CmdOpt { 12 | /// Udp target server address. 13 | #[clap(short, long, value_name = "addr:port")] 14 | target_addr: SocketAddr, 15 | 16 | /// Data string to send. 17 | #[clap(short, long, value_name = "data")] 18 | data: String, 19 | 20 | /// Via socks5 proxy server. 21 | #[clap(short, long)] 22 | via_proxy: bool, 23 | 24 | /// Socket5 proxy server address. 25 | #[clap(short, long, value_name = "addr:port")] 26 | proxy_addr: Option, 27 | 28 | /// User name for authentication. 29 | #[clap(short, long, value_name = "user name")] 30 | username: Option, 31 | 32 | /// Password for authentication. 33 | #[clap(short = 'w', long, value_name = "password")] 34 | password: Option, 35 | 36 | /// Timeout in seconds. 37 | #[clap(short = 'm', long, value_name = "seconds", default_value = "2")] 38 | timeout: u64, 39 | } 40 | 41 | impl CmdOpt { 42 | pub fn validate(&self) -> Result<(), String> { 43 | if self.via_proxy && self.proxy_addr.is_none() { 44 | return Err("proxy_addr is required when via_proxy is true".into()); 45 | } 46 | Ok(()) 47 | } 48 | } 49 | 50 | #[tokio::main] 51 | async fn main() -> Result<()> { 52 | let opt: CmdOpt = clap::Parser::parse(); 53 | opt.validate()?; 54 | 55 | let user_key = match (opt.username, opt.password) { 56 | (Some(username), password) => Some(UserKey::new(username, password.unwrap_or_default())), 57 | _ => None, 58 | }; 59 | let timeout = Duration::from_secs(opt.timeout); 60 | if !opt.via_proxy { 61 | let target_addr = opt.target_addr.to_socket_addrs()?.next().ok_or("invalid address")?; 62 | let zero_addr = if target_addr.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" }; 63 | let zero_addr = zero_addr.to_socket_addrs()?.next().ok_or("invalid address")?; 64 | let udp = UdpSocket::bind(zero_addr).await?; 65 | udp.send_to(opt.data.as_bytes(), target_addr).await?; 66 | 67 | let mut buf = [0u8; 1024]; 68 | let (len, _) = tokio::time::timeout(timeout, udp.recv_from(&mut buf)).await??; 69 | 70 | println!("{}", std::str::from_utf8(&buf[..len])?); 71 | } else { 72 | let proxy_addr = opt.proxy_addr.ok_or("proxy_addr is required")?; 73 | let data = UdpClientImpl::datagram(proxy_addr, opt.target_addr, user_key) 74 | .await? 75 | .transfer_data(opt.data.as_bytes(), timeout) 76 | .await?; 77 | println!("{}", std::str::from_utf8(data.as_slice())?); 78 | } 79 | Ok(()) 80 | } 81 | -------------------------------------------------------------------------------- /examples/util/dns.rs: -------------------------------------------------------------------------------- 1 | #![allow(dead_code)] 2 | 3 | use hickory_proto::{ 4 | op::{Message, ResponseCode, header::MessageType, op_code::OpCode, query::Query}, 5 | rr::{Name, RData, record_type::RecordType}, 6 | }; 7 | use std::{net::IpAddr, str::FromStr}; 8 | 9 | pub fn build_dns_query(domain: &str, query_type: RecordType, used_by_tcp: bool) -> Result, String> { 10 | let name = Name::from_str(domain).map_err(|e| e.to_string())?; 11 | let query = Query::query(name, query_type); 12 | let mut msg = Message::new(); 13 | msg.add_query(query) 14 | .set_id(rand::Rng::random::(&mut rand::rng())) 15 | .set_op_code(OpCode::Query) 16 | .set_message_type(MessageType::Query) 17 | .set_recursion_desired(true); 18 | let mut msg_buf = msg.to_vec().map_err(|e| e.to_string())?; 19 | if used_by_tcp { 20 | let mut buf = (msg_buf.len() as u16).to_be_bytes().to_vec(); 21 | buf.append(&mut msg_buf); 22 | Ok(buf) 23 | } else { 24 | Ok(msg_buf) 25 | } 26 | } 27 | 28 | pub fn extract_ipaddr_from_dns_message(message: &Message) -> Result { 29 | if message.response_code() != ResponseCode::NoError { 30 | return Err(format!("{:?}", message.response_code())); 31 | } 32 | let mut cname = None; 33 | for answer in message.answers() { 34 | match answer.data() { 35 | RData::A(addr) => { 36 | return Ok(IpAddr::V4((*addr).into())); 37 | } 38 | RData::AAAA(addr) => { 39 | return Ok(IpAddr::V6((*addr).into())); 40 | } 41 | RData::CNAME(name) => { 42 | cname = Some(name.to_utf8()); 43 | } 44 | _ => {} 45 | } 46 | } 47 | if let Some(cname) = cname { 48 | return Err(cname); 49 | } 50 | Err(format!("{:?}", message.answers())) 51 | } 52 | 53 | pub fn extract_domain_from_dns_message(message: &Message) -> Result { 54 | let query = message.queries().first().ok_or("DnsRequest no query body")?; 55 | let name = query.name().to_string(); 56 | Ok(name) 57 | } 58 | 59 | pub fn parse_data_to_dns_message(data: &[u8], used_by_tcp: bool) -> Result { 60 | if used_by_tcp { 61 | if data.len() < 2 { 62 | return Err("invalid dns data".into()); 63 | } 64 | let len = u16::from_be_bytes([data[0], data[1]]) as usize; 65 | let data = data.get(2..len + 2).ok_or("invalid dns data")?; 66 | return parse_data_to_dns_message(data, false); 67 | } 68 | let message = Message::from_vec(data).map_err(|e| e.to_string())?; 69 | Ok(message) 70 | } 71 | -------------------------------------------------------------------------------- /examples/util/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod dns; 2 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | max_width = 140 2 | -------------------------------------------------------------------------------- /src/client/mod.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | error::{Error, Result}, 3 | protocol::{Address, AddressType, AsyncStreamOperation, AuthMethod, Command, Reply, StreamOperation, UserKey, Version}, 4 | }; 5 | use async_trait::async_trait; 6 | use std::{ 7 | fmt::Debug, 8 | io::Cursor, 9 | net::{SocketAddr, ToSocketAddrs}, 10 | time::Duration, 11 | }; 12 | use tokio::{ 13 | io::{AsyncReadExt, AsyncWriteExt, BufStream}, 14 | net::{TcpStream, UdpSocket}, 15 | }; 16 | 17 | #[async_trait] 18 | pub trait Socks5Reader: AsyncReadExt + Unpin { 19 | async fn read_version(&mut self) -> Result<()> { 20 | let value = Version::try_from(self.read_u8().await?)?; 21 | match value { 22 | Version::V4 => Err(Error::WrongVersion), 23 | Version::V5 => Ok(()), 24 | } 25 | } 26 | 27 | async fn read_method(&mut self) -> Result { 28 | let value = AuthMethod::from(self.read_u8().await?); 29 | match value { 30 | AuthMethod::NoAuth | AuthMethod::UserPass => Ok(value), 31 | _ => Err(Error::InvalidAuthMethod(value)), 32 | } 33 | } 34 | 35 | async fn read_command(&mut self) -> Result { 36 | let value = self.read_u8().await?; 37 | Ok(Command::try_from(value)?) 38 | } 39 | 40 | async fn read_atyp(&mut self) -> Result { 41 | let value = self.read_u8().await?; 42 | Ok(AddressType::try_from(value)?) 43 | } 44 | 45 | async fn read_reserved(&mut self) -> Result<()> { 46 | let value = self.read_u8().await?; 47 | match value { 48 | 0x00 => Ok(()), 49 | _ => Err(Error::InvalidReserved(value)), 50 | } 51 | } 52 | 53 | async fn read_fragment_id(&mut self) -> Result<()> { 54 | let value = self.read_u8().await?; 55 | if value == 0x00 { 56 | Ok(()) 57 | } else { 58 | Err(Error::InvalidFragmentId(value)) 59 | } 60 | } 61 | 62 | async fn read_reply(&mut self) -> Result<()> { 63 | let value = self.read_u8().await?; 64 | match Reply::try_from(value)? { 65 | Reply::Succeeded => Ok(()), 66 | reply => Err(format!("{}", reply).into()), 67 | } 68 | } 69 | 70 | async fn read_address(&mut self) -> Result
{ 71 | Ok(Address::retrieve_from_async_stream(self).await?) 72 | } 73 | 74 | async fn read_string(&mut self) -> Result { 75 | let len = self.read_u8().await? as usize; 76 | let mut str = vec![0; len]; 77 | self.read_exact(&mut str).await?; 78 | let str = String::from_utf8(str)?; 79 | Ok(str) 80 | } 81 | 82 | async fn read_auth_version(&mut self) -> Result<()> { 83 | let value = self.read_u8().await?; 84 | if value != 0x01 { 85 | return Err(Error::InvalidAuthSubnegotiation(value)); 86 | } 87 | Ok(()) 88 | } 89 | 90 | async fn read_auth_status(&mut self) -> Result<()> { 91 | let value = self.read_u8().await?; 92 | if value != 0x00 { 93 | return Err(Error::InvalidAuthStatus(value)); 94 | } 95 | Ok(()) 96 | } 97 | 98 | async fn read_selection_msg(&mut self) -> Result { 99 | self.read_version().await?; 100 | self.read_method().await 101 | } 102 | 103 | async fn read_final(&mut self) -> Result
{ 104 | self.read_version().await?; 105 | self.read_reply().await?; 106 | self.read_reserved().await?; 107 | let addr = self.read_address().await?; 108 | Ok(addr) 109 | } 110 | } 111 | 112 | #[async_trait] 113 | impl Socks5Reader for T {} 114 | 115 | #[async_trait] 116 | pub trait Socks5Writer: AsyncWriteExt + Unpin { 117 | async fn write_version(&mut self) -> Result<()> { 118 | self.write_u8(0x05).await?; 119 | Ok(()) 120 | } 121 | 122 | async fn write_method(&mut self, method: AuthMethod) -> Result<()> { 123 | self.write_u8(u8::from(method)).await?; 124 | Ok(()) 125 | } 126 | 127 | async fn write_command(&mut self, command: Command) -> Result<()> { 128 | self.write_u8(u8::from(command)).await?; 129 | Ok(()) 130 | } 131 | 132 | async fn write_atyp(&mut self, atyp: AddressType) -> Result<()> { 133 | self.write_u8(u8::from(atyp)).await?; 134 | Ok(()) 135 | } 136 | 137 | async fn write_reserved(&mut self) -> Result<()> { 138 | self.write_u8(0x00).await?; 139 | Ok(()) 140 | } 141 | 142 | async fn write_fragment_id(&mut self, id: u8) -> Result<()> { 143 | self.write_u8(id).await?; 144 | Ok(()) 145 | } 146 | 147 | async fn write_address(&mut self, address: &Address) -> Result<()> { 148 | address.write_to_async_stream(self).await?; 149 | Ok(()) 150 | } 151 | 152 | async fn write_string(&mut self, string: &str) -> Result<()> { 153 | let bytes = string.as_bytes(); 154 | if bytes.len() > 255 { 155 | return Err("Too long string".into()); 156 | } 157 | self.write_u8(bytes.len() as u8).await?; 158 | self.write_all(bytes).await?; 159 | Ok(()) 160 | } 161 | 162 | async fn write_auth_version(&mut self) -> Result<()> { 163 | self.write_u8(0x01).await?; 164 | Ok(()) 165 | } 166 | 167 | async fn write_methods(&mut self, methods: &[AuthMethod]) -> Result<()> { 168 | self.write_u8(methods.len() as u8).await?; 169 | for method in methods { 170 | self.write_method(*method).await?; 171 | } 172 | Ok(()) 173 | } 174 | 175 | async fn write_selection_msg(&mut self, methods: &[AuthMethod]) -> Result<()> { 176 | self.write_version().await?; 177 | self.write_methods(methods).await?; 178 | self.flush().await?; 179 | Ok(()) 180 | } 181 | 182 | async fn write_final(&mut self, command: Command, addr: &Address) -> Result<()> { 183 | self.write_version().await?; 184 | self.write_command(command).await?; 185 | self.write_reserved().await?; 186 | self.write_address(addr).await?; 187 | self.flush().await?; 188 | Ok(()) 189 | } 190 | } 191 | 192 | #[async_trait] 193 | impl Socks5Writer for T {} 194 | 195 | async fn username_password_auth(stream: &mut S, auth: &UserKey) -> Result<()> 196 | where 197 | S: Socks5Writer + Socks5Reader + Send, 198 | { 199 | stream.write_auth_version().await?; 200 | stream.write_string(&auth.username).await?; 201 | stream.write_string(&auth.password).await?; 202 | stream.flush().await?; 203 | 204 | stream.read_auth_version().await?; 205 | stream.read_auth_status().await 206 | } 207 | 208 | async fn init(stream: &mut S, command: Command, addr: A, auth: Option) -> Result
209 | where 210 | S: Socks5Writer + Socks5Reader + Send, 211 | A: Into
, 212 | { 213 | let addr: Address = addr.into(); 214 | 215 | let mut methods = Vec::with_capacity(2); 216 | methods.push(AuthMethod::NoAuth); 217 | if auth.is_some() { 218 | methods.push(AuthMethod::UserPass); 219 | } 220 | stream.write_selection_msg(&methods).await?; 221 | stream.flush().await?; 222 | 223 | let method: AuthMethod = stream.read_selection_msg().await?; 224 | match method { 225 | AuthMethod::NoAuth => {} 226 | AuthMethod::UserPass if auth.is_some() => { 227 | username_password_auth(stream, auth.as_ref().unwrap()).await?; 228 | } 229 | _ => return Err(Error::InvalidAuthMethod(method)), 230 | } 231 | 232 | stream.write_final(command, &addr).await?; 233 | stream.read_final().await 234 | } 235 | 236 | /// Proxifies a TCP connection. Performs the [`CONNECT`] command under the hood. 237 | /// 238 | /// [`CONNECT`]: https://tools.ietf.org/html/rfc1928#page-6 239 | /// 240 | /// ```no_run 241 | /// # use socks5_impl::Result; 242 | /// # #[tokio::main(flavor = "current_thread")] 243 | /// # async fn main() -> Result<()> { 244 | /// use socks5_impl::client; 245 | /// use tokio::{io::BufStream, net::TcpStream}; 246 | /// 247 | /// let stream = TcpStream::connect("my-proxy-server.com:54321").await?; 248 | /// let mut stream = BufStream::new(stream); 249 | /// client::connect(&mut stream, ("google.com", 80), None).await?; 250 | /// 251 | /// # Ok(()) 252 | /// # } 253 | /// ``` 254 | pub async fn connect(socket: &mut S, addr: A, auth: Option) -> Result
255 | where 256 | S: AsyncWriteExt + AsyncReadExt + Send + Unpin, 257 | A: Into
, 258 | { 259 | init(socket, Command::Connect, addr, auth).await 260 | } 261 | 262 | /// A listener that accepts TCP connections through a proxy. 263 | /// 264 | /// ```no_run 265 | /// # use socks5_impl::Result; 266 | /// # #[tokio::main(flavor = "current_thread")] 267 | /// # async fn main() -> Result<()> { 268 | /// use socks5_impl::client::SocksListener; 269 | /// use tokio::{io::BufStream, net::TcpStream}; 270 | /// 271 | /// let stream = TcpStream::connect("my-proxy-server.com:54321").await?; 272 | /// let mut stream = BufStream::new(stream); 273 | /// let (stream, addr) = SocksListener::bind(stream, ("ftp-server.org", 21), None) 274 | /// .await? 275 | /// .accept() 276 | /// .await?; 277 | /// 278 | /// # Ok(()) 279 | /// # } 280 | /// ``` 281 | #[derive(Debug)] 282 | pub struct SocksListener { 283 | stream: S, 284 | proxy_addr: Address, 285 | } 286 | 287 | impl SocksListener 288 | where 289 | S: AsyncWriteExt + AsyncReadExt + Send + Unpin, 290 | { 291 | /// Creates `SocksListener`. Performs the [`BIND`] command under the hood. 292 | /// 293 | /// [`BIND`]: https://tools.ietf.org/html/rfc1928#page-6 294 | pub async fn bind(mut stream: S, addr: A, auth: Option) -> Result 295 | where 296 | A: Into
, 297 | { 298 | let addr = init(&mut stream, Command::Bind, addr, auth).await?; 299 | Ok(Self { stream, proxy_addr: addr }) 300 | } 301 | 302 | pub fn proxy_addr(&self) -> &Address { 303 | &self.proxy_addr 304 | } 305 | 306 | pub async fn accept(mut self) -> Result<(S, Address)> { 307 | let addr = self.stream.read_final().await?; 308 | Ok((self.stream, addr)) 309 | } 310 | } 311 | 312 | /// A UDP socket that sends packets through a proxy. 313 | #[derive(Debug)] 314 | pub struct SocksDatagram { 315 | socket: UdpSocket, 316 | proxy_addr: Address, 317 | stream: S, 318 | } 319 | 320 | impl SocksDatagram 321 | where 322 | S: AsyncWriteExt + AsyncReadExt + Send + Unpin, 323 | { 324 | /// Creates `SocksDatagram`. Performs [`UDP ASSOCIATE`] under the hood. 325 | /// 326 | /// [`UDP ASSOCIATE`]: https://tools.ietf.org/html/rfc1928#page-7 327 | pub async fn udp_associate(mut stream: S, socket: UdpSocket, auth: Option) -> Result { 328 | let addr = if socket.local_addr()?.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" }; 329 | let addr = addr.parse::()?; 330 | let proxy_addr = init(&mut stream, Command::UdpAssociate, addr, auth).await?; 331 | let addr = proxy_addr.to_socket_addrs()?.next().ok_or("InvalidAddress")?; 332 | socket.connect(addr).await?; 333 | Ok(Self { 334 | socket, 335 | proxy_addr, 336 | stream, 337 | }) 338 | } 339 | 340 | /// Returns the address of the associated udp address. 341 | pub fn proxy_addr(&self) -> &Address { 342 | &self.proxy_addr 343 | } 344 | 345 | /// Returns a reference to the underlying udp socket. 346 | pub fn get_ref(&self) -> &UdpSocket { 347 | &self.socket 348 | } 349 | 350 | /// Returns a mutable reference to the underlying udp socket. 351 | pub fn get_mut(&mut self) -> &mut UdpSocket { 352 | &mut self.socket 353 | } 354 | 355 | /// Returns the associated stream and udp socket. 356 | pub fn into_inner(self) -> (S, UdpSocket) { 357 | (self.stream, self.socket) 358 | } 359 | 360 | // Builds a udp-based client request packet, the format is as follows: 361 | // +----+------+------+----------+----------+----------+ 362 | // |RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA | 363 | // +----+------+------+----------+----------+----------+ 364 | // | 2 | 1 | 1 | Variable | 2 | Variable | 365 | // +----+------+------+----------+----------+----------+ 366 | // The reference link is as follows: 367 | // https://tools.ietf.org/html/rfc1928#page-8 368 | // 369 | pub async fn build_socks5_udp_datagram(buf: &[u8], addr: &Address) -> Result> { 370 | let bytes_size = Self::get_buf_size(addr.len(), buf.len()); 371 | let bytes = Vec::with_capacity(bytes_size); 372 | 373 | let mut cursor = Cursor::new(bytes); 374 | cursor.write_reserved().await?; 375 | cursor.write_reserved().await?; 376 | cursor.write_fragment_id(0x00).await?; 377 | cursor.write_address(addr).await?; 378 | cursor.write_all(buf).await?; 379 | 380 | let bytes = cursor.into_inner(); 381 | Ok(bytes) 382 | } 383 | 384 | /// Sends data via the udp socket to the given address. 385 | pub async fn send_to(&self, buf: &[u8], addr: A) -> Result 386 | where 387 | A: Into
, 388 | { 389 | let addr: Address = addr.into(); 390 | let bytes = Self::build_socks5_udp_datagram(buf, &addr).await?; 391 | Ok(self.socket.send(&bytes).await?) 392 | } 393 | 394 | /// Parses the udp-based server response packet, the format is same as the client request packet. 395 | async fn parse_socks5_udp_response(bytes: &mut [u8], buf: &mut Vec) -> Result<(usize, Address)> { 396 | let len = bytes.len(); 397 | let mut cursor = Cursor::new(bytes); 398 | cursor.read_reserved().await?; 399 | cursor.read_reserved().await?; 400 | cursor.read_fragment_id().await?; 401 | let addr = cursor.read_address().await?; 402 | let header_len = cursor.position() as usize; 403 | buf.resize(len - header_len, 0); 404 | _ = cursor.read_exact(buf).await?; 405 | Ok((len - header_len, addr)) 406 | } 407 | 408 | /// Receives data from the udp socket and returns the number of bytes read and the origin of the data. 409 | pub async fn recv_from(&self, timeout: Duration, buf: &mut Vec) -> Result<(usize, Address)> { 410 | const UDP_MTU: usize = 1500; 411 | // let bytes_size = Self::get_buf_size(Address::max_serialized_len(), buf.len()); 412 | let bytes_size = UDP_MTU; 413 | let mut bytes = vec![0; bytes_size]; 414 | let len = tokio::time::timeout(timeout, self.socket.recv(&mut bytes)).await??; 415 | bytes.truncate(len); 416 | let (read, addr) = Self::parse_socks5_udp_response(&mut bytes, buf).await?; 417 | Ok((read, addr)) 418 | } 419 | 420 | fn get_buf_size(addr_size: usize, buf_len: usize) -> usize { 421 | // reserved + fragment id + addr_size + buf_len 422 | 2 + 1 + addr_size + buf_len 423 | } 424 | } 425 | 426 | pub type GuardTcpStream = BufStream; 427 | pub type SocksUdpClient = SocksDatagram; 428 | 429 | #[async_trait] 430 | pub trait UdpClientTrait { 431 | async fn send_to(&mut self, buf: &[u8], addr: A) -> Result 432 | where 433 | A: Into
+ Send + Unpin; 434 | 435 | async fn recv_from(&mut self, timeout: Duration, buf: &mut Vec) -> Result<(usize, Address)>; 436 | } 437 | 438 | #[async_trait] 439 | impl UdpClientTrait for SocksUdpClient { 440 | async fn send_to(&mut self, buf: &[u8], addr: A) -> Result 441 | where 442 | A: Into
+ Send + Unpin, 443 | { 444 | SocksDatagram::send_to(self, buf, addr).await 445 | } 446 | 447 | async fn recv_from(&mut self, timeout: Duration, buf: &mut Vec) -> Result<(usize, Address), Error> { 448 | SocksDatagram::recv_from(self, timeout, buf).await 449 | } 450 | } 451 | 452 | pub async fn create_udp_client>(proxy_addr: A, auth: Option) -> Result { 453 | let proxy_addr = proxy_addr.into(); 454 | let client_addr = if proxy_addr.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" }; 455 | let proxy = TcpStream::connect(proxy_addr).await?; 456 | let proxy = BufStream::new(proxy); 457 | let client = UdpSocket::bind(client_addr).await?; 458 | SocksDatagram::udp_associate(proxy, client, auth).await 459 | } 460 | 461 | pub struct UdpClientImpl { 462 | client: C, 463 | server_addr: Address, 464 | } 465 | 466 | impl UdpClientImpl { 467 | pub async fn transfer_data(&self, data: &[u8], timeout: Duration) -> Result> { 468 | let len = self.client.send_to(data, &self.server_addr).await?; 469 | let buf = SocksDatagram::::build_socks5_udp_datagram(data, &self.server_addr).await?; 470 | assert_eq!(len, buf.len()); 471 | 472 | let mut buf = Vec::with_capacity(data.len()); 473 | let (_len, _) = self.client.recv_from(timeout, &mut buf).await?; 474 | Ok(buf) 475 | } 476 | 477 | pub async fn datagram(proxy_addr: A1, udp_server_addr: A2, auth: Option) -> Result 478 | where 479 | A1: Into, 480 | A2: Into
, 481 | { 482 | let client = create_udp_client(proxy_addr, auth).await?; 483 | 484 | let server_addr = udp_server_addr.into(); 485 | 486 | Ok(Self { client, server_addr }) 487 | } 488 | } 489 | 490 | #[cfg(test)] 491 | mod tests { 492 | use crate::{ 493 | Error, Result, 494 | client::{self, SocksListener, SocksUdpClient, UdpClientTrait}, 495 | protocol::{Address, UserKey}, 496 | }; 497 | use async_trait::async_trait; 498 | use std::{ 499 | net::{SocketAddr, ToSocketAddrs}, 500 | sync::Arc, 501 | time::Duration, 502 | }; 503 | use tokio::{ 504 | io::{AsyncReadExt, AsyncWriteExt, BufStream}, 505 | net::{TcpStream, UdpSocket}, 506 | }; 507 | 508 | const PROXY_ADDR: &str = "127.0.0.1:1080"; 509 | const PROXY_AUTH_ADDR: &str = "127.0.0.1:1081"; 510 | const DATA: &[u8] = b"Hello, world!"; 511 | 512 | async fn connect(addr: &str, auth: Option) { 513 | let socket = TcpStream::connect(addr).await.unwrap(); 514 | let mut socket = BufStream::new(socket); 515 | client::connect(&mut socket, Address::from(("baidu.com", 80)), auth).await.unwrap(); 516 | } 517 | 518 | #[ignore] 519 | #[tokio::test] 520 | async fn connect_auth() { 521 | connect(PROXY_AUTH_ADDR, Some(UserKey::new("hyper", "proxy"))).await; 522 | } 523 | 524 | #[ignore] 525 | #[tokio::test] 526 | async fn connect_no_auth() { 527 | connect(PROXY_ADDR, None).await; 528 | } 529 | 530 | #[ignore] 531 | #[should_panic = "InvalidAuthMethod(NoAcceptableMethods)"] 532 | #[tokio::test] 533 | async fn connect_no_auth_panic() { 534 | connect(PROXY_AUTH_ADDR, None).await; 535 | } 536 | 537 | #[ignore] 538 | #[tokio::test] 539 | async fn bind() { 540 | let run_block = async { 541 | let server_addr = Address::from(("127.0.0.1", 8000)); 542 | 543 | let client = TcpStream::connect(PROXY_ADDR).await?; 544 | let client = BufStream::new(client); 545 | let client = SocksListener::bind(client, server_addr, None).await?; 546 | 547 | let server_addr = client.proxy_addr.to_socket_addrs()?.next().ok_or("Invalid address")?; 548 | let mut server = TcpStream::connect(&server_addr).await?; 549 | 550 | let (mut client, _) = client.accept().await?; 551 | 552 | server.write_all(DATA).await?; 553 | 554 | let mut buf = [0; DATA.len()]; 555 | client.read_exact(&mut buf).await?; 556 | assert_eq!(buf, DATA); 557 | Ok::<_, Error>(()) 558 | }; 559 | if let Err(e) = run_block.await { 560 | println!("{:?}", e); 561 | } 562 | } 563 | 564 | type TestHalves = (Arc, Arc); 565 | 566 | #[async_trait] 567 | impl UdpClientTrait for TestHalves { 568 | async fn send_to(&mut self, buf: &[u8], addr: A) -> Result 569 | where 570 | A: Into
+ Send, 571 | { 572 | self.1.send_to(buf, addr).await 573 | } 574 | 575 | async fn recv_from(&mut self, timeout: Duration, buf: &mut Vec) -> Result<(usize, Address), Error> { 576 | self.0.recv_from(timeout, buf).await 577 | } 578 | } 579 | 580 | const SERVER_ADDR: &str = "127.0.0.1:23456"; 581 | 582 | struct UdpTest { 583 | client: C, 584 | server: UdpSocket, 585 | server_addr: Address, 586 | } 587 | 588 | impl UdpTest { 589 | async fn test(mut self) { 590 | let mut buf = vec![0; DATA.len()]; 591 | self.client.send_to(DATA, self.server_addr).await.unwrap(); 592 | let (len, addr) = self.server.recv_from(&mut buf).await.unwrap(); 593 | assert_eq!(len, buf.len()); 594 | assert_eq!(buf.as_slice(), DATA); 595 | 596 | let mut buf = vec![0; DATA.len()]; 597 | self.server.send_to(DATA, addr).await.unwrap(); 598 | let timeout = Duration::from_secs(5); 599 | let (len, _) = self.client.recv_from(timeout, &mut buf).await.unwrap(); 600 | assert_eq!(len, buf.len()); 601 | assert_eq!(buf.as_slice(), DATA); 602 | } 603 | } 604 | 605 | impl UdpTest { 606 | async fn datagram() -> Self { 607 | let addr = PROXY_ADDR.parse::().unwrap(); 608 | let client = client::create_udp_client(addr, None).await.unwrap(); 609 | 610 | let server_addr: SocketAddr = SERVER_ADDR.parse().unwrap(); 611 | let server = UdpSocket::bind(server_addr).await.unwrap(); 612 | let server_addr = Address::from(server_addr); 613 | 614 | Self { 615 | client, 616 | server, 617 | server_addr, 618 | } 619 | } 620 | } 621 | 622 | impl UdpTest { 623 | async fn halves() -> Self { 624 | let this = UdpTest::::datagram().await; 625 | let client = Arc::new(this.client); 626 | Self { 627 | client: (client.clone(), client), 628 | server: this.server, 629 | server_addr: this.server_addr, 630 | } 631 | } 632 | } 633 | 634 | #[ignore] 635 | #[tokio::test] 636 | async fn udp_datagram_halves() { 637 | UdpTest::halves().await.test().await 638 | } 639 | } 640 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | /// The library's error type. 2 | #[derive(Debug, thiserror::Error)] 3 | pub enum Error { 4 | #[error("{0}")] 5 | Io(#[from] std::io::Error), 6 | 7 | #[error("{0}")] 8 | FromUtf8(#[from] std::string::FromUtf8Error), 9 | 10 | #[error("Invalid SOCKS version: {0:x}")] 11 | InvalidVersion(u8), 12 | #[error("Invalid command: {0:x}")] 13 | InvalidCommand(u8), 14 | #[error("Invalid address type: {0:x}")] 15 | InvalidAtyp(u8), 16 | #[error("Invalid reserved bytes: {0:x}")] 17 | InvalidReserved(u8), 18 | #[error("Invalid authentication status: {0:x}")] 19 | InvalidAuthStatus(u8), 20 | #[error("Invalid authentication version of subnegotiation: {0:x}")] 21 | InvalidAuthSubnegotiation(u8), 22 | #[error("Invalid fragment id: {0:x}")] 23 | InvalidFragmentId(u8), 24 | 25 | #[error("Invalid authentication method: {0:?}")] 26 | InvalidAuthMethod(crate::protocol::AuthMethod), 27 | 28 | #[error("SOCKS version is 4 when 5 is expected")] 29 | WrongVersion, 30 | 31 | #[error("AddrParseError: {0}")] 32 | AddrParseError(#[from] std::net::AddrParseError), 33 | 34 | #[error("ParseIntError: {0}")] 35 | ParseIntError(#[from] std::num::ParseIntError), 36 | 37 | #[error("Utf8Error: {0}")] 38 | Utf8Error(#[from] std::str::Utf8Error), 39 | 40 | #[error("{0}")] 41 | String(String), 42 | } 43 | 44 | impl From<&str> for Error { 45 | fn from(s: &str) -> Self { 46 | Error::String(s.to_string()) 47 | } 48 | } 49 | 50 | impl From for Error { 51 | fn from(s: String) -> Self { 52 | Error::String(s) 53 | } 54 | } 55 | 56 | impl From<&String> for Error { 57 | fn from(s: &String) -> Self { 58 | Error::String(s.to_string()) 59 | } 60 | } 61 | 62 | impl From for std::io::Error { 63 | fn from(e: Error) -> Self { 64 | match e { 65 | Error::Io(e) => e, 66 | _ => std::io::Error::other(e), 67 | } 68 | } 69 | } 70 | 71 | #[cfg(feature = "tokio")] 72 | impl From for Error { 73 | fn from(e: tokio::time::error::Elapsed) -> Self { 74 | Error::Io(e.into()) 75 | } 76 | } 77 | 78 | /// The library's `Result` type alias. 79 | pub type Result = std::result::Result; 80 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![doc = include_str!("../README.md")] 2 | 3 | #[cfg(feature = "client")] 4 | pub mod client; 5 | pub(crate) mod error; 6 | pub mod protocol; 7 | #[cfg(feature = "server")] 8 | pub mod server; 9 | 10 | pub use crate::error::{Error, Result}; 11 | -------------------------------------------------------------------------------- /src/protocol/address.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "tokio")] 2 | use crate::protocol::AsyncStreamOperation; 3 | use crate::protocol::StreamOperation; 4 | #[cfg(feature = "tokio")] 5 | use async_trait::async_trait; 6 | use bytes::BufMut; 7 | use std::{ 8 | io::Cursor, 9 | net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs}, 10 | }; 11 | #[cfg(feature = "tokio")] 12 | use tokio::io::{AsyncRead, AsyncReadExt}; 13 | 14 | #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Default)] 15 | #[repr(u8)] 16 | pub enum AddressType { 17 | #[default] 18 | IPv4 = 0x01, 19 | Domain = 0x03, 20 | IPv6 = 0x04, 21 | } 22 | 23 | impl TryFrom for AddressType { 24 | type Error = std::io::Error; 25 | fn try_from(code: u8) -> core::result::Result { 26 | let err = format!("Unsupported address type code {0:#x}", code); 27 | match code { 28 | 0x01 => Ok(AddressType::IPv4), 29 | 0x03 => Ok(AddressType::Domain), 30 | 0x04 => Ok(AddressType::IPv6), 31 | _ => Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, err)), 32 | } 33 | } 34 | } 35 | 36 | impl From for u8 { 37 | fn from(addr_type: AddressType) -> Self { 38 | match addr_type { 39 | AddressType::IPv4 => 0x01, 40 | AddressType::Domain => 0x03, 41 | AddressType::IPv6 => 0x04, 42 | } 43 | } 44 | } 45 | 46 | /// SOCKS5 Adderss Format 47 | /// 48 | /// ```plain 49 | /// +------+----------+----------+ 50 | /// | ATYP | DST.ADDR | DST.PORT | 51 | /// +------+----------+----------+ 52 | /// | 1 | Variable | 2 | 53 | /// +------+----------+----------+ 54 | /// ``` 55 | #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] 56 | pub enum Address { 57 | SocketAddress(SocketAddr), 58 | DomainAddress(String, u16), 59 | } 60 | 61 | impl Address { 62 | pub fn unspecified() -> Self { 63 | Address::SocketAddress(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0))) 64 | } 65 | 66 | pub fn get_type(&self) -> AddressType { 67 | match self { 68 | Self::SocketAddress(SocketAddr::V4(_)) => AddressType::IPv4, 69 | Self::SocketAddress(SocketAddr::V6(_)) => AddressType::IPv6, 70 | Self::DomainAddress(_, _) => AddressType::Domain, 71 | } 72 | } 73 | 74 | pub fn port(&self) -> u16 { 75 | match self { 76 | Self::SocketAddress(addr) => addr.port(), 77 | Self::DomainAddress(_, port) => *port, 78 | } 79 | } 80 | 81 | pub fn domain(&self) -> String { 82 | match self { 83 | Self::SocketAddress(addr) => addr.ip().to_string(), 84 | Self::DomainAddress(addr, _) => addr.clone(), 85 | } 86 | } 87 | 88 | pub const fn max_serialized_len() -> usize { 89 | 1 + 1 + u8::MAX as usize + 2 90 | } 91 | } 92 | 93 | impl StreamOperation for Address { 94 | fn retrieve_from_stream(stream: &mut R) -> std::io::Result { 95 | let mut atyp = [0; 1]; 96 | stream.read_exact(&mut atyp)?; 97 | match AddressType::try_from(atyp[0])? { 98 | AddressType::IPv4 => { 99 | let mut buf = [0; 6]; 100 | stream.read_exact(&mut buf)?; 101 | let addr = Ipv4Addr::new(buf[0], buf[1], buf[2], buf[3]); 102 | let port = u16::from_be_bytes([buf[4], buf[5]]); 103 | Ok(Self::SocketAddress(SocketAddr::from((addr, port)))) 104 | } 105 | AddressType::Domain => { 106 | let mut len = [0; 1]; 107 | stream.read_exact(&mut len)?; 108 | let len = len[0] as usize; 109 | let mut buf = vec![0; len + 2]; 110 | stream.read_exact(&mut buf)?; 111 | 112 | let port = u16::from_be_bytes([buf[len], buf[len + 1]]); 113 | buf.truncate(len); 114 | 115 | let addr = match String::from_utf8(buf) { 116 | Ok(addr) => addr, 117 | Err(err) => { 118 | let err = format!("Invalid address encoding: {err}"); 119 | return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, err)); 120 | } 121 | }; 122 | Ok(Self::DomainAddress(addr, port)) 123 | } 124 | AddressType::IPv6 => { 125 | let mut buf = [0; 18]; 126 | stream.read_exact(&mut buf)?; 127 | let port = u16::from_be_bytes([buf[16], buf[17]]); 128 | let mut addr_bytes = [0; 16]; 129 | addr_bytes.copy_from_slice(&buf[..16]); 130 | Ok(Self::SocketAddress(SocketAddr::from((Ipv6Addr::from(addr_bytes), port)))) 131 | } 132 | } 133 | } 134 | 135 | fn write_to_buf(&self, buf: &mut B) { 136 | match self { 137 | Self::SocketAddress(SocketAddr::V4(addr)) => { 138 | buf.put_u8(AddressType::IPv4.into()); 139 | buf.put_slice(&addr.ip().octets()); 140 | buf.put_u16(addr.port()); 141 | } 142 | Self::SocketAddress(SocketAddr::V6(addr)) => { 143 | buf.put_u8(AddressType::IPv6.into()); 144 | buf.put_slice(&addr.ip().octets()); 145 | buf.put_u16(addr.port()); 146 | } 147 | Self::DomainAddress(addr, port) => { 148 | let addr = addr.as_bytes(); 149 | buf.put_u8(AddressType::Domain.into()); 150 | buf.put_u8(addr.len() as u8); 151 | buf.put_slice(addr); 152 | buf.put_u16(*port); 153 | } 154 | } 155 | } 156 | 157 | fn len(&self) -> usize { 158 | match self { 159 | Address::SocketAddress(SocketAddr::V4(_)) => 1 + 4 + 2, 160 | Address::SocketAddress(SocketAddr::V6(_)) => 1 + 16 + 2, 161 | Address::DomainAddress(addr, _) => 1 + 1 + addr.len() + 2, 162 | } 163 | } 164 | } 165 | 166 | #[cfg(feature = "tokio")] 167 | #[async_trait] 168 | impl AsyncStreamOperation for Address { 169 | async fn retrieve_from_async_stream(stream: &mut R) -> std::io::Result 170 | where 171 | R: AsyncRead + Unpin + Send + ?Sized, 172 | { 173 | let atyp = stream.read_u8().await?; 174 | match AddressType::try_from(atyp)? { 175 | AddressType::IPv4 => { 176 | let mut addr_bytes = [0; 4]; 177 | stream.read_exact(&mut addr_bytes).await?; 178 | let mut buf = [0; 2]; 179 | stream.read_exact(&mut buf).await?; 180 | let addr = Ipv4Addr::from(addr_bytes); 181 | let port = u16::from_be_bytes(buf); 182 | Ok(Self::SocketAddress(SocketAddr::from((addr, port)))) 183 | } 184 | AddressType::Domain => { 185 | let len = stream.read_u8().await? as usize; 186 | let mut buf = vec![0; len + 2]; 187 | stream.read_exact(&mut buf).await?; 188 | 189 | let port = u16::from_be_bytes([buf[len], buf[len + 1]]); 190 | buf.truncate(len); 191 | 192 | let addr = match String::from_utf8(buf) { 193 | Ok(addr) => addr, 194 | Err(err) => { 195 | let err = format!("Invalid address encoding: {err}"); 196 | return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, err)); 197 | } 198 | }; 199 | Ok(Self::DomainAddress(addr, port)) 200 | } 201 | AddressType::IPv6 => { 202 | let mut addr_bytes = [0; 16]; 203 | stream.read_exact(&mut addr_bytes).await?; 204 | let mut buf = [0; 2]; 205 | stream.read_exact(&mut buf).await?; 206 | let port = u16::from_be_bytes(buf); 207 | Ok(Self::SocketAddress(SocketAddr::from((Ipv6Addr::from(addr_bytes), port)))) 208 | } 209 | } 210 | } 211 | } 212 | 213 | impl ToSocketAddrs for Address { 214 | type Iter = std::vec::IntoIter; 215 | 216 | fn to_socket_addrs(&self) -> std::io::Result { 217 | match self { 218 | Address::SocketAddress(addr) => Ok(vec![*addr].into_iter()), 219 | Address::DomainAddress(addr, port) => Ok((addr.as_str(), *port).to_socket_addrs()?), 220 | } 221 | } 222 | } 223 | 224 | impl std::fmt::Display for Address { 225 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 226 | match self { 227 | Address::DomainAddress(hostname, port) => write!(f, "{hostname}:{port}"), 228 | Address::SocketAddress(socket_addr) => write!(f, "{socket_addr}"), 229 | } 230 | } 231 | } 232 | 233 | impl TryFrom
for SocketAddr { 234 | type Error = std::io::Error; 235 | 236 | fn try_from(address: Address) -> std::result::Result { 237 | match address { 238 | Address::SocketAddress(addr) => Ok(addr), 239 | Address::DomainAddress(addr, port) => { 240 | if let Ok(addr) = addr.parse::() { 241 | Ok(SocketAddr::from((addr, port))) 242 | } else if let Ok(addr) = addr.parse::() { 243 | Ok(SocketAddr::from((addr, port))) 244 | } else { 245 | let err = format!("domain address {addr} is not supported"); 246 | Err(Self::Error::new(std::io::ErrorKind::Unsupported, err)) 247 | } 248 | } 249 | } 250 | } 251 | } 252 | 253 | impl TryFrom<&Address> for SocketAddr { 254 | type Error = std::io::Error; 255 | 256 | fn try_from(address: &Address) -> std::result::Result { 257 | TryFrom::
::try_from(address.clone()) 258 | } 259 | } 260 | 261 | impl From
for Vec { 262 | fn from(addr: Address) -> Self { 263 | let mut buf = Vec::with_capacity(addr.len()); 264 | addr.write_to_buf(&mut buf); 265 | buf 266 | } 267 | } 268 | 269 | impl TryFrom> for Address { 270 | type Error = std::io::Error; 271 | 272 | fn try_from(data: Vec) -> std::result::Result { 273 | let mut rdr = Cursor::new(data); 274 | Self::retrieve_from_stream(&mut rdr) 275 | } 276 | } 277 | 278 | impl TryFrom<&[u8]> for Address { 279 | type Error = std::io::Error; 280 | 281 | fn try_from(data: &[u8]) -> std::result::Result { 282 | let mut rdr = Cursor::new(data); 283 | Self::retrieve_from_stream(&mut rdr) 284 | } 285 | } 286 | 287 | impl From for Address { 288 | fn from(addr: SocketAddr) -> Self { 289 | Address::SocketAddress(addr) 290 | } 291 | } 292 | 293 | impl From<&SocketAddr> for Address { 294 | fn from(addr: &SocketAddr) -> Self { 295 | Address::SocketAddress(*addr) 296 | } 297 | } 298 | 299 | impl From<(Ipv4Addr, u16)> for Address { 300 | fn from((addr, port): (Ipv4Addr, u16)) -> Self { 301 | Address::SocketAddress(SocketAddr::from((addr, port))) 302 | } 303 | } 304 | 305 | impl From<(Ipv6Addr, u16)> for Address { 306 | fn from((addr, port): (Ipv6Addr, u16)) -> Self { 307 | Address::SocketAddress(SocketAddr::from((addr, port))) 308 | } 309 | } 310 | 311 | impl From<(IpAddr, u16)> for Address { 312 | fn from((addr, port): (IpAddr, u16)) -> Self { 313 | Address::SocketAddress(SocketAddr::from((addr, port))) 314 | } 315 | } 316 | 317 | impl From<(String, u16)> for Address { 318 | fn from((addr, port): (String, u16)) -> Self { 319 | Address::DomainAddress(addr, port) 320 | } 321 | } 322 | 323 | impl From<(&str, u16)> for Address { 324 | fn from((addr, port): (&str, u16)) -> Self { 325 | Address::DomainAddress(addr.to_owned(), port) 326 | } 327 | } 328 | 329 | impl From<&Address> for Address { 330 | fn from(addr: &Address) -> Self { 331 | addr.clone() 332 | } 333 | } 334 | 335 | impl TryFrom<&str> for Address { 336 | type Error = crate::Error; 337 | 338 | fn try_from(addr: &str) -> std::result::Result { 339 | if let Ok(addr) = addr.parse::() { 340 | Ok(Address::SocketAddress(addr)) 341 | } else { 342 | let (addr, port) = if let Some(pos) = addr.rfind(':') { 343 | (&addr[..pos], &addr[pos + 1..]) 344 | } else { 345 | (addr, "0") 346 | }; 347 | let port = port.parse::()?; 348 | Ok(Address::DomainAddress(addr.to_owned(), port)) 349 | } 350 | } 351 | } 352 | 353 | #[test] 354 | fn test_address() { 355 | let addr = Address::from((Ipv4Addr::new(127, 0, 0, 1), 8080)); 356 | let mut buf = Vec::new(); 357 | addr.write_to_buf(&mut buf); 358 | assert_eq!(buf, vec![0x01, 127, 0, 0, 1, 0x1f, 0x90]); 359 | let addr2 = Address::retrieve_from_stream(&mut Cursor::new(&buf)).unwrap(); 360 | assert_eq!(addr, addr2); 361 | 362 | let addr = Address::from((Ipv6Addr::new(0x45, 0xff89, 0, 0, 0, 0, 0, 1), 8080)); 363 | let mut buf = Vec::new(); 364 | addr.write_to_buf(&mut buf); 365 | assert_eq!(buf, vec![0x04, 0, 0x45, 0xff, 0x89, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0x1f, 0x90]); 366 | let addr2 = Address::retrieve_from_stream(&mut Cursor::new(&buf)).unwrap(); 367 | assert_eq!(addr, addr2); 368 | 369 | let addr = Address::from(("sex.com".to_owned(), 8080)); 370 | let mut buf = Vec::new(); 371 | addr.write_to_buf(&mut buf); 372 | assert_eq!(buf, vec![0x03, 0x07, b's', b'e', b'x', b'.', b'c', b'o', b'm', 0x1f, 0x90]); 373 | let addr2 = Address::retrieve_from_stream(&mut Cursor::new(&buf)).unwrap(); 374 | assert_eq!(addr, addr2); 375 | } 376 | 377 | #[cfg(feature = "tokio")] 378 | #[tokio::test] 379 | async fn test_address_async() { 380 | let addr = Address::from((Ipv4Addr::new(127, 0, 0, 1), 8080)); 381 | let mut buf = Vec::new(); 382 | addr.write_to_async_stream(&mut buf).await.unwrap(); 383 | assert_eq!(buf, vec![0x01, 127, 0, 0, 1, 0x1f, 0x90]); 384 | let addr2 = Address::retrieve_from_async_stream(&mut Cursor::new(&buf)).await.unwrap(); 385 | assert_eq!(addr, addr2); 386 | 387 | let addr = Address::from((Ipv6Addr::new(0x45, 0xff89, 0, 0, 0, 0, 0, 1), 8080)); 388 | let mut buf = Vec::new(); 389 | addr.write_to_async_stream(&mut buf).await.unwrap(); 390 | assert_eq!(buf, vec![0x04, 0, 0x45, 0xff, 0x89, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0x1f, 0x90]); 391 | let addr2 = Address::retrieve_from_async_stream(&mut Cursor::new(&buf)).await.unwrap(); 392 | assert_eq!(addr, addr2); 393 | 394 | let addr = Address::from(("sex.com".to_owned(), 8080)); 395 | let mut buf = Vec::new(); 396 | addr.write_to_async_stream(&mut buf).await.unwrap(); 397 | assert_eq!(buf, vec![0x03, 0x07, b's', b'e', b'x', b'.', b'c', b'o', b'm', 0x1f, 0x90]); 398 | let addr2 = Address::retrieve_from_async_stream(&mut Cursor::new(&buf)).await.unwrap(); 399 | assert_eq!(addr, addr2); 400 | } 401 | -------------------------------------------------------------------------------- /src/protocol/command.rs: -------------------------------------------------------------------------------- 1 | #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] 2 | pub enum Command { 3 | Connect = 0x01, 4 | Bind = 0x02, 5 | UdpAssociate = 0x03, 6 | } 7 | 8 | impl TryFrom for Command { 9 | type Error = std::io::Error; 10 | 11 | fn try_from(code: u8) -> std::result::Result { 12 | let err = format!("Unsupported command code {0:#x}", code); 13 | match code { 14 | 0x01 => Ok(Command::Connect), 15 | 0x02 => Ok(Command::Bind), 16 | 0x03 => Ok(Command::UdpAssociate), 17 | _ => Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, err)), 18 | } 19 | } 20 | } 21 | 22 | impl From for u8 { 23 | fn from(cmd: Command) -> Self { 24 | match cmd { 25 | Command::Connect => 0x01, 26 | Command::Bind => 0x02, 27 | Command::UdpAssociate => 0x03, 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/protocol/handshake/auth_method.rs: -------------------------------------------------------------------------------- 1 | /// A proxy authentication method. 2 | #[repr(u8)] 3 | #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Default)] 4 | pub enum AuthMethod { 5 | /// No authentication required. 6 | #[default] 7 | NoAuth = 0x00, 8 | /// GSS API. 9 | GssApi = 0x01, 10 | /// A username + password authentication. 11 | UserPass = 0x02, 12 | /// IANA reserved 0x03..=0x7f. 13 | IanaReserved(u8), 14 | /// A private authentication method 0x80..=0xfe. 15 | Private(u8), 16 | /// X'FF' NO ACCEPTABLE METHODS 17 | NoAcceptableMethods = 0xff, 18 | } 19 | 20 | impl From for AuthMethod { 21 | fn from(value: u8) -> Self { 22 | match value { 23 | 0x00 => AuthMethod::NoAuth, 24 | 0x01 => AuthMethod::GssApi, 25 | 0x02 => AuthMethod::UserPass, 26 | 0x03..=0x7f => AuthMethod::IanaReserved(value), 27 | 0x80..=0xfe => AuthMethod::Private(value), 28 | 0xff => AuthMethod::NoAcceptableMethods, 29 | } 30 | } 31 | } 32 | 33 | impl From for u8 { 34 | fn from(value: AuthMethod) -> Self { 35 | From::<&AuthMethod>::from(&value) 36 | } 37 | } 38 | 39 | impl From<&AuthMethod> for u8 { 40 | fn from(value: &AuthMethod) -> Self { 41 | match value { 42 | AuthMethod::NoAuth => 0x00, 43 | AuthMethod::GssApi => 0x01, 44 | AuthMethod::UserPass => 0x02, 45 | AuthMethod::IanaReserved(value) => *value, 46 | AuthMethod::Private(value) => *value, 47 | AuthMethod::NoAcceptableMethods => 0xff, 48 | } 49 | } 50 | } 51 | 52 | impl std::fmt::Display for AuthMethod { 53 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 54 | match self { 55 | AuthMethod::NoAuth => write!(f, "NoAuth"), 56 | AuthMethod::GssApi => write!(f, "GssApi"), 57 | AuthMethod::UserPass => write!(f, "UserPass"), 58 | AuthMethod::IanaReserved(value) => write!(f, "IanaReserved({0:#x})", value), 59 | AuthMethod::Private(value) => write!(f, "Private({0:#x})", value), 60 | AuthMethod::NoAcceptableMethods => write!(f, "NoAcceptableMethods"), 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/protocol/handshake/mod.rs: -------------------------------------------------------------------------------- 1 | mod auth_method; 2 | pub mod password_method; 3 | mod request; 4 | mod response; 5 | 6 | pub use self::{auth_method::AuthMethod, request::Request, response::Response}; 7 | -------------------------------------------------------------------------------- /src/protocol/handshake/password_method/mod.rs: -------------------------------------------------------------------------------- 1 | mod request; 2 | mod response; 3 | 4 | pub use self::{ 5 | request::Request, 6 | response::{Response, Status}, 7 | }; 8 | 9 | pub const SUBNEGOTIATION_VERSION: u8 = 0x01; 10 | 11 | /// Required for a username + password authentication. 12 | #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] 13 | #[derive(Default, Debug, Eq, PartialEq, Clone, Hash)] 14 | pub struct UserKey { 15 | pub username: String, 16 | pub password: String, 17 | } 18 | 19 | impl std::fmt::Display for UserKey { 20 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 21 | use percent_encoding::{NON_ALPHANUMERIC, percent_encode}; 22 | match (self.username.is_empty(), self.password.is_empty()) { 23 | (true, true) => write!(f, ""), 24 | (true, false) => write!(f, ":{}", percent_encode(self.password.as_bytes(), NON_ALPHANUMERIC)), 25 | (false, true) => write!(f, "{}", percent_encode(self.username.as_bytes(), NON_ALPHANUMERIC)), 26 | (false, false) => { 27 | let username = percent_encode(self.username.as_bytes(), NON_ALPHANUMERIC).to_string(); 28 | let password = percent_encode(self.password.as_bytes(), NON_ALPHANUMERIC).to_string(); 29 | write!(f, "{}:{}", username, password) 30 | } 31 | } 32 | } 33 | } 34 | 35 | impl UserKey { 36 | /// Constructs `UserKey` with the specified username and a password. 37 | pub fn new(username: U, password: P) -> Self 38 | where 39 | U: Into, 40 | P: Into, 41 | { 42 | Self { 43 | username: username.into(), 44 | password: password.into(), 45 | } 46 | } 47 | 48 | pub fn username_arr(&self) -> Vec { 49 | self.username.as_bytes().to_vec() 50 | } 51 | 52 | pub fn password_arr(&self) -> Vec { 53 | self.password.as_bytes().to_vec() 54 | } 55 | } 56 | 57 | #[test] 58 | fn test_user_key() { 59 | let user_key = UserKey::new("username", "pass@word"); 60 | assert_eq!(user_key.to_string(), "username:pass%40word"); 61 | let user_key = UserKey::new("username", ""); 62 | assert_eq!(user_key.to_string(), "username"); 63 | let user_key = UserKey::new("", "password"); 64 | assert_eq!(user_key.to_string(), ":password"); 65 | let user_key = UserKey::new("", ""); 66 | assert_eq!(user_key.to_string(), ""); 67 | } 68 | -------------------------------------------------------------------------------- /src/protocol/handshake/password_method/request.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "tokio")] 2 | use crate::protocol::AsyncStreamOperation; 3 | use crate::protocol::{StreamOperation, UserKey}; 4 | #[cfg(feature = "tokio")] 5 | use async_trait::async_trait; 6 | #[cfg(feature = "tokio")] 7 | use tokio::io::{AsyncRead, AsyncReadExt}; 8 | 9 | /// SOCKS5 password handshake request 10 | /// 11 | /// ```plain 12 | /// +-----+------+----------+------+----------+ 13 | /// | VER | ULEN | UNAME | PLEN | PASSWD | 14 | /// +-----+------+----------+------+----------+ 15 | /// | 1 | 1 | 1 to 255 | 1 | 1 to 255 | 16 | /// +-----+------+----------+------+----------+ 17 | /// ``` 18 | 19 | #[derive(Clone, Debug)] 20 | pub struct Request { 21 | pub user_key: UserKey, 22 | } 23 | 24 | impl Request { 25 | pub fn new(username: &str, password: &str) -> Self { 26 | let user_key = UserKey::new(username, password); 27 | Self { user_key } 28 | } 29 | } 30 | 31 | impl StreamOperation for Request { 32 | fn retrieve_from_stream(r: &mut R) -> std::io::Result { 33 | let mut ver = [0; 1]; 34 | r.read_exact(&mut ver)?; 35 | let ver = ver[0]; 36 | 37 | if ver != super::SUBNEGOTIATION_VERSION { 38 | let err = format!("Unsupported sub-negotiation version {0:#x}", ver); 39 | return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err)); 40 | } 41 | 42 | let mut ulen = [0; 1]; 43 | r.read_exact(&mut ulen)?; 44 | let ulen = ulen[0]; 45 | let mut buf = vec![0; ulen as usize + 1]; 46 | r.read_exact(&mut buf)?; 47 | 48 | let plen = buf[ulen as usize]; 49 | buf.truncate(ulen as usize); 50 | let username = String::from_utf8(buf).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?; 51 | 52 | let mut password = vec![0; plen as usize]; 53 | r.read_exact(&mut password)?; 54 | let pwd = String::from_utf8(password).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?; 55 | 56 | let user_key = UserKey::new(username, pwd); 57 | Ok(Self { user_key }) 58 | } 59 | 60 | fn write_to_buf(&self, buf: &mut B) { 61 | buf.put_u8(super::SUBNEGOTIATION_VERSION); 62 | 63 | let username = self.user_key.username_arr(); 64 | buf.put_u8(username.len() as u8); 65 | buf.put_slice(&username); 66 | 67 | let password = self.user_key.password_arr(); 68 | buf.put_u8(password.len() as u8); 69 | buf.put_slice(&password); 70 | } 71 | 72 | fn len(&self) -> usize { 73 | 3 + self.user_key.username_arr().len() + self.user_key.password_arr().len() 74 | } 75 | } 76 | 77 | #[cfg(feature = "tokio")] 78 | #[async_trait] 79 | impl AsyncStreamOperation for Request { 80 | async fn retrieve_from_async_stream(r: &mut R) -> std::io::Result 81 | where 82 | R: AsyncRead + Unpin + Send + ?Sized, 83 | { 84 | let ver = r.read_u8().await?; 85 | 86 | if ver != super::SUBNEGOTIATION_VERSION { 87 | let err = format!("Unsupported sub-negotiation version {0:#x}", ver); 88 | return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err)); 89 | } 90 | 91 | let ulen = r.read_u8().await?; 92 | let mut buf = vec![0; ulen as usize + 1]; 93 | r.read_exact(&mut buf).await?; 94 | 95 | let plen = buf[ulen as usize]; 96 | buf.truncate(ulen as usize); 97 | let username = String::from_utf8(buf).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?; 98 | 99 | let mut password = vec![0; plen as usize]; 100 | r.read_exact(&mut password).await?; 101 | let pwd = String::from_utf8(password).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?; 102 | 103 | let user_key = UserKey::new(username, pwd); 104 | Ok(Self { user_key }) 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/protocol/handshake/password_method/response.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "tokio")] 2 | use crate::protocol::AsyncStreamOperation; 3 | use crate::protocol::StreamOperation; 4 | #[cfg(feature = "tokio")] 5 | use async_trait::async_trait; 6 | #[cfg(feature = "tokio")] 7 | use tokio::io::{AsyncRead, AsyncReadExt}; 8 | 9 | #[repr(u8)] 10 | #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Default)] 11 | pub enum Status { 12 | #[default] 13 | Succeeded = 0x00, 14 | Failed = 0xff, 15 | } 16 | 17 | impl From for u8 { 18 | fn from(value: Status) -> Self { 19 | value as u8 20 | } 21 | } 22 | 23 | impl TryFrom for Status { 24 | type Error = std::io::Error; 25 | 26 | fn try_from(value: u8) -> Result { 27 | let err = format!("Invalid sub-negotiation status {0:#x}", value); 28 | match value { 29 | 0x00 => Ok(Status::Succeeded), 30 | 0xff => Ok(Status::Failed), 31 | _ => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, err)), 32 | } 33 | } 34 | } 35 | 36 | impl std::fmt::Display for Status { 37 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 38 | match self { 39 | Status::Succeeded => write!(f, "Succeeded"), 40 | Status::Failed => write!(f, "Failed"), 41 | } 42 | } 43 | } 44 | 45 | /// SOCKS5 password handshake response 46 | /// 47 | /// ```plain 48 | /// +-----+--------+ 49 | /// | VER | STATUS | 50 | /// +-----+--------+ 51 | /// | 1 | 1 | 52 | /// +-----+--------+ 53 | /// ``` 54 | #[derive(Clone, Debug)] 55 | pub struct Response { 56 | pub status: Status, 57 | } 58 | 59 | impl Response { 60 | pub fn new(status: Status) -> Self { 61 | Self { status } 62 | } 63 | } 64 | 65 | impl StreamOperation for Response { 66 | fn retrieve_from_stream(r: &mut R) -> std::io::Result { 67 | let mut ver = [0; 1]; 68 | r.read_exact(&mut ver)?; 69 | let ver = ver[0]; 70 | 71 | if ver != super::SUBNEGOTIATION_VERSION { 72 | let err = format!("Unsupported sub-negotiation version {0:#x}", ver); 73 | return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err)); 74 | } 75 | 76 | let mut status = [0; 1]; 77 | r.read_exact(&mut status)?; 78 | let status = Status::try_from(status[0])?; 79 | Ok(Self { status }) 80 | } 81 | 82 | fn write_to_buf(&self, buf: &mut B) { 83 | buf.put_u8(super::SUBNEGOTIATION_VERSION); 84 | buf.put_u8(self.status.into()); 85 | } 86 | 87 | fn len(&self) -> usize { 88 | 2 89 | } 90 | } 91 | 92 | #[cfg(feature = "tokio")] 93 | #[async_trait] 94 | impl AsyncStreamOperation for Response { 95 | async fn retrieve_from_async_stream(r: &mut R) -> std::io::Result 96 | where 97 | R: AsyncRead + Unpin + Send + ?Sized, 98 | { 99 | let ver = r.read_u8().await?; 100 | 101 | if ver != super::SUBNEGOTIATION_VERSION { 102 | let err = format!("Unsupported sub-negotiation version {0:#x}", ver); 103 | return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err)); 104 | } 105 | 106 | let status = Status::try_from(r.read_u8().await?)?; 107 | Ok(Self { status }) 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/protocol/handshake/request.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "tokio")] 2 | use crate::protocol::AsyncStreamOperation; 3 | use crate::protocol::{AuthMethod, StreamOperation, Version}; 4 | #[cfg(feature = "tokio")] 5 | use async_trait::async_trait; 6 | #[cfg(feature = "tokio")] 7 | use tokio::io::{AsyncRead, AsyncReadExt}; 8 | 9 | /// SOCKS5 handshake request 10 | /// 11 | /// ```plain 12 | /// +-----+----------+----------+ 13 | /// | VER | NMETHODS | METHODS | 14 | /// +-----+----------+----------+ 15 | /// | 1 | 1 | 1 to 255 | 16 | /// +-----+----------+----------| 17 | /// ``` 18 | #[derive(Clone, Debug)] 19 | pub struct Request { 20 | methods: Vec, 21 | } 22 | 23 | impl Request { 24 | pub fn new(methods: Vec) -> Self { 25 | Self { methods } 26 | } 27 | 28 | pub fn evaluate_method(&self, server_method: AuthMethod) -> bool { 29 | self.methods.contains(&server_method) 30 | } 31 | } 32 | 33 | impl StreamOperation for Request { 34 | fn retrieve_from_stream(r: &mut R) -> std::io::Result { 35 | let mut ver = [0; 1]; 36 | r.read_exact(&mut ver)?; 37 | let ver = Version::try_from(ver[0])?; 38 | 39 | if ver != Version::V5 { 40 | let err = format!("Unsupported SOCKS version {0:#x}", u8::from(ver)); 41 | return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err)); 42 | } 43 | 44 | let mut mlen = [0; 1]; 45 | r.read_exact(&mut mlen)?; 46 | let mlen = mlen[0]; 47 | 48 | let mut methods = vec![0; mlen as usize]; 49 | r.read_exact(&mut methods)?; 50 | 51 | let methods = methods.into_iter().map(AuthMethod::from).collect(); 52 | 53 | Ok(Self { methods }) 54 | } 55 | 56 | fn write_to_buf(&self, buf: &mut B) { 57 | buf.put_u8(Version::V5.into()); 58 | buf.put_u8(self.methods.len() as u8); 59 | 60 | let methods = self.methods.iter().map(u8::from).collect::>(); 61 | buf.put_slice(&methods); 62 | } 63 | 64 | fn len(&self) -> usize { 65 | 2 + self.methods.len() 66 | } 67 | } 68 | 69 | #[cfg(feature = "tokio")] 70 | #[async_trait] 71 | impl AsyncStreamOperation for Request { 72 | async fn retrieve_from_async_stream(r: &mut R) -> std::io::Result 73 | where 74 | R: AsyncRead + Unpin + Send + ?Sized, 75 | { 76 | let ver = Version::try_from(r.read_u8().await?)?; 77 | 78 | if ver != Version::V5 { 79 | let err = format!("Unsupported SOCKS version {0:#x}", u8::from(ver)); 80 | return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err)); 81 | } 82 | 83 | let mlen = r.read_u8().await?; 84 | let mut methods = vec![0; mlen as usize]; 85 | r.read_exact(&mut methods).await?; 86 | 87 | let methods = methods.into_iter().map(AuthMethod::from).collect(); 88 | 89 | Ok(Self { methods }) 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/protocol/handshake/response.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "tokio")] 2 | use crate::protocol::AsyncStreamOperation; 3 | use crate::protocol::{AuthMethod, StreamOperation, Version}; 4 | #[cfg(feature = "tokio")] 5 | use async_trait::async_trait; 6 | #[cfg(feature = "tokio")] 7 | use tokio::io::{AsyncRead, AsyncReadExt}; 8 | 9 | /// SOCKS5 handshake response 10 | /// 11 | /// ```plain 12 | /// +-----+--------+ 13 | /// | VER | METHOD | 14 | /// +-----+--------+ 15 | /// | 1 | 1 | 16 | /// +-----+--------+ 17 | /// ``` 18 | #[derive(Clone, Debug)] 19 | pub struct Response { 20 | pub method: AuthMethod, 21 | } 22 | 23 | impl Response { 24 | pub fn new(method: AuthMethod) -> Self { 25 | Self { method } 26 | } 27 | } 28 | 29 | impl StreamOperation for Response { 30 | fn retrieve_from_stream(r: &mut R) -> std::io::Result { 31 | let mut ver = [0; 1]; 32 | r.read_exact(&mut ver)?; 33 | let ver = Version::try_from(ver[0])?; 34 | 35 | if ver != Version::V5 { 36 | let err = format!("Unsupported SOCKS version {0:#x}", u8::from(ver)); 37 | return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err)); 38 | } 39 | 40 | let mut method = [0; 1]; 41 | r.read_exact(&mut method)?; 42 | let method = AuthMethod::from(method[0]); 43 | 44 | Ok(Self { method }) 45 | } 46 | 47 | fn write_to_buf(&self, buf: &mut B) { 48 | buf.put_u8(Version::V5.into()); 49 | buf.put_u8(u8::from(self.method)); 50 | } 51 | 52 | fn len(&self) -> usize { 53 | 2 54 | } 55 | } 56 | 57 | #[cfg(feature = "tokio")] 58 | #[async_trait] 59 | impl AsyncStreamOperation for Response { 60 | async fn retrieve_from_async_stream(r: &mut R) -> std::io::Result 61 | where 62 | R: AsyncRead + Unpin + Send + ?Sized, 63 | { 64 | let ver = Version::try_from(r.read_u8().await?)?; 65 | 66 | if ver != Version::V5 { 67 | let err = format!("Unsupported SOCKS version {0:#x}", u8::from(ver)); 68 | return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err)); 69 | } 70 | 71 | let method = AuthMethod::from(r.read_u8().await?); 72 | 73 | Ok(Self { method }) 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/protocol/mod.rs: -------------------------------------------------------------------------------- 1 | mod address; 2 | mod command; 3 | pub mod handshake; 4 | mod reply; 5 | mod request; 6 | mod response; 7 | mod udp; 8 | 9 | pub use self::{ 10 | address::{Address, AddressType}, 11 | command::Command, 12 | handshake::{ 13 | AuthMethod, 14 | password_method::{self, UserKey}, 15 | }, 16 | reply::Reply, 17 | request::Request, 18 | response::Response, 19 | udp::UdpHeader, 20 | }; 21 | pub use bytes::BufMut; 22 | 23 | #[cfg(feature = "tokio")] 24 | use async_trait::async_trait; 25 | #[cfg(feature = "tokio")] 26 | use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt}; 27 | 28 | /// SOCKS protocol version, either 4 or 5 29 | #[repr(u8)] 30 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)] 31 | pub enum Version { 32 | V4 = 4, 33 | #[default] 34 | V5 = 5, 35 | } 36 | 37 | impl TryFrom for Version { 38 | type Error = std::io::Error; 39 | 40 | fn try_from(value: u8) -> std::io::Result { 41 | match value { 42 | 4 => Ok(Version::V4), 43 | 5 => Ok(Version::V5), 44 | _ => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid version")), 45 | } 46 | } 47 | } 48 | 49 | impl From for u8 { 50 | fn from(v: Version) -> Self { 51 | v as u8 52 | } 53 | } 54 | 55 | impl std::fmt::Display for Version { 56 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 57 | let v: u8 = (*self).into(); 58 | write!(f, "{}", v) 59 | } 60 | } 61 | 62 | pub trait StreamOperation { 63 | fn retrieve_from_stream(stream: &mut R) -> std::io::Result 64 | where 65 | R: std::io::Read, 66 | Self: Sized; 67 | 68 | fn write_to_stream(&self, w: &mut W) -> std::io::Result<()> { 69 | let mut buf = Vec::with_capacity(self.len()); 70 | self.write_to_buf(&mut buf); 71 | w.write_all(&buf) 72 | } 73 | 74 | fn write_to_buf(&self, buf: &mut B); 75 | 76 | fn len(&self) -> usize; 77 | 78 | fn is_empty(&self) -> bool { 79 | self.len() == 0 80 | } 81 | } 82 | 83 | #[cfg(feature = "tokio")] 84 | #[async_trait] 85 | pub trait AsyncStreamOperation: StreamOperation { 86 | async fn retrieve_from_async_stream(r: &mut R) -> std::io::Result 87 | where 88 | R: AsyncRead + Unpin + Send + ?Sized, 89 | Self: Sized; 90 | 91 | async fn write_to_async_stream(&self, w: &mut W) -> std::io::Result<()> 92 | where 93 | W: AsyncWrite + Unpin + Send + ?Sized, 94 | { 95 | let mut buf = bytes::BytesMut::with_capacity(self.len()); 96 | self.write_to_buf(&mut buf); 97 | w.write_all(&buf).await 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/protocol/reply.rs: -------------------------------------------------------------------------------- 1 | #[repr(u8)] 2 | #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Default)] 3 | pub enum Reply { 4 | #[default] 5 | Succeeded = 0x00, 6 | GeneralFailure = 0x01, 7 | ConnectionNotAllowed = 0x02, 8 | NetworkUnreachable = 0x03, 9 | HostUnreachable = 0x04, 10 | ConnectionRefused = 0x05, 11 | TtlExpired = 0x06, 12 | CommandNotSupported = 0x07, 13 | AddressTypeNotSupported = 0x08, 14 | } 15 | 16 | impl TryFrom for Reply { 17 | type Error = std::io::Error; 18 | 19 | fn try_from(code: u8) -> Result { 20 | let err = format!("Unsupported reply code {0:#x}", code); 21 | match code { 22 | 0x00 => Ok(Reply::Succeeded), 23 | 0x01 => Ok(Reply::GeneralFailure), 24 | 0x02 => Ok(Reply::ConnectionNotAllowed), 25 | 0x03 => Ok(Reply::NetworkUnreachable), 26 | 0x04 => Ok(Reply::HostUnreachable), 27 | 0x05 => Ok(Reply::ConnectionRefused), 28 | 0x06 => Ok(Reply::TtlExpired), 29 | 0x07 => Ok(Reply::CommandNotSupported), 30 | 0x08 => Ok(Reply::AddressTypeNotSupported), 31 | _ => Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, err)), 32 | } 33 | } 34 | } 35 | 36 | impl From for u8 { 37 | fn from(reply: Reply) -> Self { 38 | match reply { 39 | Reply::Succeeded => 0x00, 40 | Reply::GeneralFailure => 0x01, 41 | Reply::ConnectionNotAllowed => 0x02, 42 | Reply::NetworkUnreachable => 0x03, 43 | Reply::HostUnreachable => 0x04, 44 | Reply::ConnectionRefused => 0x05, 45 | Reply::TtlExpired => 0x06, 46 | Reply::CommandNotSupported => 0x07, 47 | Reply::AddressTypeNotSupported => 0x08, 48 | } 49 | } 50 | } 51 | 52 | impl std::fmt::Display for Reply { 53 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 54 | let s = match self { 55 | Reply::Succeeded => "Reply::Succeeded", 56 | Reply::GeneralFailure => "Reply::GeneralFailure", 57 | Reply::ConnectionNotAllowed => "Reply::ConnectionNotAllowed", 58 | Reply::NetworkUnreachable => "Reply::NetworkUnreachable", 59 | Reply::HostUnreachable => "Reply::HostUnreachable", 60 | Reply::ConnectionRefused => "Reply::ConnectionRefused", 61 | Reply::TtlExpired => "Reply::TtlExpired", 62 | Reply::CommandNotSupported => "Reply::CommandNotSupported", 63 | Reply::AddressTypeNotSupported => "Reply::AddressTypeNotSupported", 64 | }; 65 | write!(f, "{}", s) 66 | } 67 | } 68 | 69 | #[cfg(test)] 70 | mod tests { 71 | use super::*; 72 | 73 | #[test] 74 | fn reply_try_from() { 75 | assert_eq!(Reply::try_from(0x00).unwrap(), Reply::Succeeded); 76 | assert_eq!(Reply::try_from(0x01).unwrap(), Reply::GeneralFailure); 77 | assert_eq!(Reply::try_from(0x02).unwrap(), Reply::ConnectionNotAllowed); 78 | assert_eq!(Reply::try_from(0x03).unwrap(), Reply::NetworkUnreachable); 79 | assert_eq!(Reply::try_from(0x04).unwrap(), Reply::HostUnreachable); 80 | assert_eq!(Reply::try_from(0x05).unwrap(), Reply::ConnectionRefused); 81 | assert_eq!(Reply::try_from(0x06).unwrap(), Reply::TtlExpired); 82 | assert_eq!(Reply::try_from(0x07).unwrap(), Reply::CommandNotSupported); 83 | assert_eq!(Reply::try_from(0x08).unwrap(), Reply::AddressTypeNotSupported); 84 | assert!(Reply::try_from(0x09).is_err()); 85 | } 86 | 87 | #[test] 88 | fn reply_from() { 89 | assert_eq!(u8::from(Reply::Succeeded), 0x00); 90 | assert_eq!(u8::from(Reply::GeneralFailure), 0x01); 91 | assert_eq!(u8::from(Reply::ConnectionNotAllowed), 0x02); 92 | assert_eq!(u8::from(Reply::NetworkUnreachable), 0x03); 93 | assert_eq!(u8::from(Reply::HostUnreachable), 0x04); 94 | assert_eq!(u8::from(Reply::ConnectionRefused), 0x05); 95 | assert_eq!(u8::from(Reply::TtlExpired), 0x06); 96 | assert_eq!(u8::from(Reply::CommandNotSupported), 0x07); 97 | assert_eq!(u8::from(Reply::AddressTypeNotSupported), 0x08); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/protocol/request.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "tokio")] 2 | use crate::protocol::AsyncStreamOperation; 3 | use crate::protocol::{Address, Command, StreamOperation, Version}; 4 | #[cfg(feature = "tokio")] 5 | use async_trait::async_trait; 6 | #[cfg(feature = "tokio")] 7 | use tokio::io::{AsyncRead, AsyncReadExt}; 8 | 9 | /// SOCKS5 request 10 | /// 11 | /// ```plain 12 | /// +-----+-----+-------+------+----------+----------+ 13 | /// | VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT | 14 | /// +-----+-----+-------+------+----------+----------+ 15 | /// | 1 | 1 | X'00' | 1 | Variable | 2 | 16 | /// +-----+-----+-------+------+----------+----------+ 17 | /// ``` 18 | #[derive(Clone, Debug)] 19 | pub struct Request { 20 | pub command: Command, 21 | pub address: Address, 22 | } 23 | 24 | impl Request { 25 | pub fn new(command: Command, address: Address) -> Self { 26 | Self { command, address } 27 | } 28 | } 29 | 30 | impl StreamOperation for Request { 31 | fn retrieve_from_stream(stream: &mut R) -> std::io::Result { 32 | let mut ver = [0u8; 1]; 33 | stream.read_exact(&mut ver)?; 34 | let ver = Version::try_from(ver[0])?; 35 | 36 | if ver != Version::V5 { 37 | let err = format!("Unsupported SOCKS version {0:#x}", u8::from(ver)); 38 | return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err)); 39 | } 40 | 41 | let mut buf = [0; 2]; 42 | stream.read_exact(&mut buf)?; 43 | 44 | let command = Command::try_from(buf[0])?; 45 | let address = Address::retrieve_from_stream(stream)?; 46 | 47 | Ok(Self { command, address }) 48 | } 49 | 50 | fn write_to_buf(&self, buf: &mut B) { 51 | buf.put_u8(Version::V5.into()); 52 | buf.put_u8(u8::from(self.command)); 53 | buf.put_u8(0x00); 54 | self.address.write_to_buf(buf); 55 | } 56 | 57 | fn len(&self) -> usize { 58 | 3 + self.address.len() 59 | } 60 | } 61 | 62 | #[cfg(feature = "tokio")] 63 | #[async_trait] 64 | impl AsyncStreamOperation for Request { 65 | async fn retrieve_from_async_stream(r: &mut R) -> std::io::Result 66 | where 67 | R: AsyncRead + Unpin + Send + ?Sized, 68 | { 69 | let ver = Version::try_from(r.read_u8().await?)?; 70 | 71 | if ver != Version::V5 { 72 | let err = format!("Unsupported SOCKS version {0:#x}", u8::from(ver)); 73 | return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err)); 74 | } 75 | 76 | let mut buf = [0; 2]; 77 | r.read_exact(&mut buf).await?; 78 | 79 | let command = Command::try_from(buf[0])?; 80 | let address = Address::retrieve_from_async_stream(r).await?; 81 | 82 | Ok(Self { command, address }) 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/protocol/response.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "tokio")] 2 | use crate::protocol::AsyncStreamOperation; 3 | use crate::protocol::{Address, Reply, StreamOperation, Version}; 4 | #[cfg(feature = "tokio")] 5 | use async_trait::async_trait; 6 | #[cfg(feature = "tokio")] 7 | use tokio::io::{AsyncRead, AsyncReadExt}; 8 | 9 | /// Response 10 | /// 11 | /// ```plain 12 | /// +-----+-----+-------+------+----------+----------+ 13 | /// | VER | REP | RSV | ATYP | BND.ADDR | BND.PORT | 14 | /// +-----+-----+-------+------+----------+----------+ 15 | /// | 1 | 1 | X'00' | 1 | Variable | 2 | 16 | /// +-----+-----+-------+------+----------+----------+ 17 | /// ``` 18 | #[derive(Clone, Debug)] 19 | pub struct Response { 20 | pub reply: Reply, 21 | pub address: Address, 22 | } 23 | 24 | impl Response { 25 | pub fn new(reply: Reply, address: Address) -> Self { 26 | Self { reply, address } 27 | } 28 | } 29 | 30 | impl StreamOperation for Response { 31 | fn retrieve_from_stream(stream: &mut R) -> std::io::Result { 32 | let mut ver = [0u8; 1]; 33 | stream.read_exact(&mut ver)?; 34 | let ver = Version::try_from(ver[0])?; 35 | 36 | if ver != Version::V5 { 37 | let err = format!("Unsupported SOCKS version {0:#x}", u8::from(ver)); 38 | return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err)); 39 | } 40 | 41 | let mut buf = [0; 2]; 42 | stream.read_exact(&mut buf)?; 43 | 44 | let reply = Reply::try_from(buf[0])?; 45 | let address = Address::retrieve_from_stream(stream)?; 46 | 47 | Ok(Self { reply, address }) 48 | } 49 | 50 | fn write_to_buf(&self, buf: &mut B) { 51 | buf.put_u8(Version::V5.into()); 52 | buf.put_u8(u8::from(self.reply)); 53 | buf.put_u8(0x00); 54 | self.address.write_to_buf(buf); 55 | } 56 | 57 | fn len(&self) -> usize { 58 | 3 + self.address.len() 59 | } 60 | } 61 | 62 | #[cfg(feature = "tokio")] 63 | #[async_trait] 64 | impl AsyncStreamOperation for Response { 65 | async fn retrieve_from_async_stream(r: &mut R) -> std::io::Result 66 | where 67 | R: AsyncRead + Unpin + Send + ?Sized, 68 | { 69 | let ver = Version::try_from(r.read_u8().await?)?; 70 | 71 | if ver != Version::V5 { 72 | let err = format!("Unsupported SOCKS version {0:#x}", u8::from(ver)); 73 | return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err)); 74 | } 75 | 76 | let mut buf = [0; 2]; 77 | r.read_exact(&mut buf).await?; 78 | 79 | let reply = Reply::try_from(buf[0])?; 80 | let address = Address::retrieve_from_async_stream(r).await?; 81 | 82 | Ok(Self { reply, address }) 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/protocol/udp.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "tokio")] 2 | use crate::protocol::AsyncStreamOperation; 3 | use crate::protocol::{Address, StreamOperation}; 4 | #[cfg(feature = "tokio")] 5 | use async_trait::async_trait; 6 | #[cfg(feature = "tokio")] 7 | use tokio::io::{AsyncRead, AsyncReadExt}; 8 | 9 | /// SOCKS5 UDP packet header 10 | /// 11 | /// ```plain 12 | /// +-----+------+------+----------+----------+----------+ 13 | /// | RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA | 14 | /// +-----+------+------+----------+----------+----------+ 15 | /// | 2 | 1 | 1 | Variable | 2 | Variable | 16 | /// +-----+------+------+----------+----------+----------+ 17 | /// ``` 18 | #[derive(Clone, Debug)] 19 | pub struct UdpHeader { 20 | pub frag: u8, 21 | pub address: Address, 22 | } 23 | 24 | impl UdpHeader { 25 | pub fn new(frag: u8, address: Address) -> Self { 26 | Self { frag, address } 27 | } 28 | 29 | pub const fn max_serialized_len() -> usize { 30 | 3 + Address::max_serialized_len() 31 | } 32 | } 33 | 34 | impl StreamOperation for UdpHeader { 35 | fn retrieve_from_stream(stream: &mut R) -> std::io::Result { 36 | let mut buf = [0; 3]; 37 | stream.read_exact(&mut buf)?; 38 | 39 | let frag = buf[2]; 40 | 41 | let address = Address::retrieve_from_stream(stream)?; 42 | Ok(Self { frag, address }) 43 | } 44 | 45 | fn write_to_buf(&self, buf: &mut B) { 46 | buf.put_bytes(0x00, 2); 47 | buf.put_u8(self.frag); 48 | self.address.write_to_buf(buf); 49 | } 50 | 51 | fn len(&self) -> usize { 52 | 3 + self.address.len() 53 | } 54 | } 55 | 56 | #[cfg(feature = "tokio")] 57 | #[async_trait] 58 | impl AsyncStreamOperation for UdpHeader { 59 | async fn retrieve_from_async_stream(r: &mut R) -> std::io::Result 60 | where 61 | R: AsyncRead + Unpin + Send + ?Sized, 62 | { 63 | let mut buf = [0; 3]; 64 | r.read_exact(&mut buf).await?; 65 | 66 | let frag = buf[2]; 67 | 68 | let address = Address::retrieve_from_async_stream(r).await?; 69 | Ok(Self { frag, address }) 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/server/auth.rs: -------------------------------------------------------------------------------- 1 | use crate::protocol::{AsyncStreamOperation, AuthMethod, UserKey, handshake::password_method}; 2 | use async_trait::async_trait; 3 | use std::sync::Arc; 4 | use tokio::net::TcpStream; 5 | 6 | /// This trait is for defining the socks5 authentication method. 7 | /// 8 | /// Pre-defined authentication methods can be found in the [`auth`](crate::server::auth) module. 9 | /// 10 | /// You can create your own authentication method by implementing this trait. Since GAT is not stabled yet, 11 | /// [async_trait](https://docs.rs/async-trait/latest/async_trait/index.html) needs to be used. 12 | /// 13 | /// # Example 14 | /// ```rust 15 | /// use async_trait::async_trait; 16 | /// use socks5_impl::protocol::AuthMethod; 17 | /// use socks5_impl::server::AuthExecutor; 18 | /// use tokio::net::TcpStream; 19 | /// 20 | /// pub struct MyAuth; 21 | /// 22 | /// #[async_trait] 23 | /// impl AuthExecutor for MyAuth { 24 | /// type Output = std::io::Result; 25 | /// 26 | /// fn auth_method(&self) -> AuthMethod { 27 | /// AuthMethod::from(0x80) 28 | /// } 29 | /// 30 | /// async fn execute(&self, stream: &mut TcpStream) -> Self::Output { 31 | /// // do something 32 | /// Ok(1145141919810) 33 | /// } 34 | /// } 35 | /// ``` 36 | #[async_trait] 37 | pub trait AuthExecutor { 38 | type Output; 39 | fn auth_method(&self) -> AuthMethod; 40 | async fn execute(&self, stream: &mut TcpStream) -> Self::Output; 41 | } 42 | 43 | pub type AuthAdaptor = Arc + Send + Sync>; 44 | 45 | /// No authentication as the socks5 handshake method. 46 | #[derive(Debug, Default)] 47 | pub struct NoAuth; 48 | 49 | #[async_trait] 50 | impl AuthExecutor for NoAuth { 51 | type Output = (); 52 | fn auth_method(&self) -> AuthMethod { 53 | AuthMethod::NoAuth 54 | } 55 | 56 | async fn execute(&self, _: &mut TcpStream) -> Self::Output {} 57 | } 58 | 59 | /// Username and password as the socks5 handshake method. 60 | pub struct UserKeyAuth { 61 | user_key: UserKey, 62 | } 63 | 64 | impl UserKeyAuth { 65 | pub fn new(username: &str, password: &str) -> Self { 66 | let user_key = UserKey::new(username, password); 67 | Self { user_key } 68 | } 69 | } 70 | 71 | #[async_trait] 72 | impl AuthExecutor for UserKeyAuth { 73 | type Output = std::io::Result; 74 | 75 | fn auth_method(&self) -> AuthMethod { 76 | AuthMethod::UserPass 77 | } 78 | 79 | async fn execute(&self, stream: &mut TcpStream) -> Self::Output { 80 | use password_method::{Request, Response, Status::*}; 81 | let req = Request::retrieve_from_async_stream(stream).await?; 82 | 83 | let is_equal = req.user_key == self.user_key; 84 | let resp = Response::new(if is_equal { Succeeded } else { Failed }); 85 | resp.write_to_async_stream(stream).await?; 86 | if is_equal { 87 | Ok(true) 88 | } else { 89 | Err(std::io::Error::other("username or password is incorrect")) 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/server/connection/associate.rs: -------------------------------------------------------------------------------- 1 | use crate::protocol::{Address, AsyncStreamOperation, Reply, Response, StreamOperation, UdpHeader}; 2 | use bytes::{Bytes, BytesMut}; 3 | use std::{ 4 | net::SocketAddr, 5 | pin::Pin, 6 | sync::atomic::{AtomicUsize, Ordering}, 7 | task::{Context, Poll}, 8 | time::Duration, 9 | }; 10 | use tokio::{ 11 | io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, ReadBuf}, 12 | net::{TcpStream, ToSocketAddrs, UdpSocket}, 13 | }; 14 | 15 | /// Socks5 connection type `UdpAssociate` 16 | #[derive(Debug)] 17 | pub struct UdpAssociate { 18 | stream: TcpStream, 19 | _state: S, 20 | } 21 | 22 | impl UdpAssociate { 23 | #[inline] 24 | pub(super) fn new(stream: TcpStream) -> Self { 25 | Self { 26 | stream, 27 | _state: S::default(), 28 | } 29 | } 30 | 31 | /// Reply to the SOCKS5 client with the given reply and address. 32 | /// 33 | /// If encountered an error while writing the reply, the error alongside the original `TcpStream` is returned. 34 | pub async fn reply(mut self, reply: Reply, addr: Address) -> std::io::Result> { 35 | let resp = Response::new(reply, addr); 36 | resp.write_to_async_stream(&mut self.stream).await?; 37 | Ok(UdpAssociate::::new(self.stream)) 38 | } 39 | 40 | /// Causes the other peer to receive a read of length 0, indicating that no more data will be sent. This only closes the stream in one direction. 41 | #[inline] 42 | pub async fn shutdown(&mut self) -> std::io::Result<()> { 43 | self.stream.shutdown().await 44 | } 45 | 46 | /// Returns the local address that this stream is bound to. 47 | #[inline] 48 | pub fn local_addr(&self) -> std::io::Result { 49 | self.stream.local_addr() 50 | } 51 | 52 | /// Returns the remote address that this stream is connected to. 53 | #[inline] 54 | pub fn peer_addr(&self) -> std::io::Result { 55 | self.stream.peer_addr() 56 | } 57 | 58 | /// Reads the linger duration for this socket by getting the `SO_LINGER` option. 59 | /// 60 | /// For more information about this option, see [`set_linger`](#method.set_linger). 61 | #[inline] 62 | pub fn linger(&self) -> std::io::Result> { 63 | self.stream.linger() 64 | } 65 | 66 | /// Sets the linger duration of this socket by setting the `SO_LINGER` option. 67 | /// 68 | /// This option controls the action taken when a stream has unsent messages and the stream is closed. If `SO_LINGER` is set, 69 | /// the system shall block the process until it can transmit the data or until the time expires. 70 | /// 71 | /// If `SO_LINGER` is not specified, and the stream is closed, the system handles the call in a way 72 | /// that allows the process to continue as quickly as possible. 73 | #[inline] 74 | pub fn set_linger(&self, dur: Option) -> std::io::Result<()> { 75 | self.stream.set_linger(dur) 76 | } 77 | 78 | /// Gets the value of the `TCP_NODELAY` option on this socket. 79 | /// 80 | /// For more information about this option, see [`set_nodelay`](#method.set_nodelay). 81 | #[inline] 82 | pub fn nodelay(&self) -> std::io::Result { 83 | self.stream.nodelay() 84 | } 85 | 86 | /// Sets the value of the `TCP_NODELAY` option on this socket. 87 | /// 88 | /// If set, this option disables the Nagle algorithm. This means that segments are always sent as soon as possible, 89 | /// even if there is only a small amount of data. When not set, data is buffered until there is a sufficient amount to send out, 90 | /// thereby avoiding the frequent sending of small packets. 91 | pub fn set_nodelay(&self, nodelay: bool) -> std::io::Result<()> { 92 | self.stream.set_nodelay(nodelay) 93 | } 94 | 95 | /// Gets the value of the `IP_TTL` option for this socket. 96 | /// 97 | /// For more information about this option, see [`set_ttl`](#method.set_ttl). 98 | pub fn ttl(&self) -> std::io::Result { 99 | self.stream.ttl() 100 | } 101 | 102 | /// Sets the value for the `IP_TTL` option on this socket. 103 | /// 104 | /// This value sets the time-to-live field that is used in every packet sent from this socket. 105 | pub fn set_ttl(&self, ttl: u32) -> std::io::Result<()> { 106 | self.stream.set_ttl(ttl) 107 | } 108 | } 109 | 110 | #[derive(Debug, Default)] 111 | pub struct NeedReply; 112 | 113 | #[derive(Debug, Default)] 114 | pub struct Ready; 115 | 116 | impl UdpAssociate { 117 | /// Wait until the client closes this TCP connection. 118 | /// 119 | /// Socks5 protocol defines that when the client closes the TCP connection used to send the associate command, 120 | /// the server should release the associated UDP socket. 121 | pub async fn wait_until_closed(&mut self) -> std::io::Result<()> { 122 | loop { 123 | match self.stream.read(&mut [0]).await { 124 | Ok(0) => break Ok(()), 125 | Ok(_) => {} 126 | Err(err) => break Err(err), 127 | } 128 | } 129 | } 130 | } 131 | 132 | impl std::ops::Deref for UdpAssociate { 133 | type Target = TcpStream; 134 | 135 | #[inline] 136 | fn deref(&self) -> &Self::Target { 137 | &self.stream 138 | } 139 | } 140 | 141 | impl std::ops::DerefMut for UdpAssociate { 142 | #[inline] 143 | fn deref_mut(&mut self) -> &mut Self::Target { 144 | &mut self.stream 145 | } 146 | } 147 | 148 | impl AsyncRead for UdpAssociate { 149 | #[inline] 150 | fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll> { 151 | Pin::new(&mut self.stream).poll_read(cx, buf) 152 | } 153 | } 154 | 155 | impl AsyncWrite for UdpAssociate { 156 | #[inline] 157 | fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { 158 | Pin::new(&mut self.stream).poll_write(cx, buf) 159 | } 160 | 161 | #[inline] 162 | fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 163 | Pin::new(&mut self.stream).poll_flush(cx) 164 | } 165 | 166 | #[inline] 167 | fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 168 | Pin::new(&mut self.stream).poll_shutdown(cx) 169 | } 170 | } 171 | 172 | impl From> for TcpStream { 173 | #[inline] 174 | fn from(conn: UdpAssociate) -> Self { 175 | conn.stream 176 | } 177 | } 178 | 179 | /// This is a helper for managing the associated UDP socket. 180 | /// 181 | /// It will add the socks5 UDP header to every UDP packet it sends, also try to parse the socks5 UDP header from any UDP packet received. 182 | /// 183 | /// The receiving buffer size for each UDP packet can be set with [`set_recv_buffer_size()`](#method.set_recv_buffer_size), 184 | /// and be read with [`get_max_packet_size()`](#method.get_recv_buffer_size). 185 | /// 186 | /// You can create this struct by using [`AssociatedUdpSocket::from::<(UdpSocket, usize)>()`](#impl-From), 187 | /// the first element of the tuple is the UDP socket, the second element is the receiving buffer size. 188 | /// 189 | /// This struct can also be revert into a raw tokio UDP socket with [`UdpSocket::from::()`](#impl-From). 190 | /// 191 | /// [`AssociatedUdpSocket`] can be used as the associated UDP socket. 192 | #[derive(Debug)] 193 | pub struct AssociatedUdpSocket { 194 | socket: UdpSocket, 195 | buf_size: AtomicUsize, 196 | } 197 | 198 | impl AssociatedUdpSocket { 199 | /// Connects the UDP socket setting the default destination for send() and limiting packets that are read via recv from the address specified in addr. 200 | #[inline] 201 | pub async fn connect(&self, addr: A) -> std::io::Result<()> { 202 | self.socket.connect(addr).await 203 | } 204 | 205 | /// Get the maximum UDP packet size, with socks5 UDP header included. 206 | pub fn get_max_packet_size(&self) -> usize { 207 | self.buf_size.load(Ordering::Relaxed) 208 | } 209 | 210 | /// Set the maximum UDP packet size, with socks5 UDP header included, for adjusting the receiving buffer size. 211 | pub fn set_max_packet_size(&self, size: usize) { 212 | self.buf_size.store(size, Ordering::Release); 213 | } 214 | 215 | /// Receives a socks5 UDP relay packet on the socket from the remote address to which it is connected. 216 | /// On success, returns the packet itself, the fragment number and the remote target address. 217 | /// 218 | /// The [`connect`](#method.connect) method will connect this socket to a remote address. 219 | /// This method will fail if the socket is not connected. 220 | pub async fn recv(&self) -> std::io::Result<(Bytes, u8, Address)> { 221 | loop { 222 | let max_packet_size = self.buf_size.load(Ordering::Acquire); 223 | let mut buf = vec![0; max_packet_size]; 224 | let len = self.socket.recv(&mut buf).await?; 225 | buf.truncate(len); 226 | let pkt = Bytes::from(buf); 227 | 228 | if let Ok(header) = UdpHeader::retrieve_from_async_stream(&mut pkt.as_ref()).await { 229 | let pkt = pkt.slice(header.len()..); 230 | return Ok((pkt, header.frag, header.address)); 231 | } 232 | } 233 | } 234 | 235 | /// Receives a socks5 UDP relay packet on the socket from the any remote address. 236 | /// On success, returns the packet itself, the fragment number, the remote target address and the source address. 237 | pub async fn recv_from(&self) -> std::io::Result<(Bytes, u8, Address, SocketAddr)> { 238 | loop { 239 | let max_packet_size = self.buf_size.load(Ordering::Acquire); 240 | let mut buf = vec![0; max_packet_size]; 241 | let (len, src_addr) = self.socket.recv_from(&mut buf).await?; 242 | buf.truncate(len); 243 | let pkt = Bytes::from(buf); 244 | 245 | if let Ok(header) = UdpHeader::retrieve_from_async_stream(&mut pkt.as_ref()).await { 246 | let pkt = pkt.slice(header.len()..); 247 | return Ok((pkt, header.frag, header.address, src_addr)); 248 | } 249 | } 250 | } 251 | 252 | /// Sends a UDP relay packet to the remote address to which it is connected. The socks5 UDP header will be added to the packet. 253 | pub async fn send>(&self, pkt: P, frag: u8, from_addr: Address) -> std::io::Result { 254 | let header = UdpHeader::new(frag, from_addr); 255 | let mut buf = BytesMut::with_capacity(header.len() + pkt.as_ref().len()); 256 | header.write_to_buf(&mut buf); 257 | buf.extend_from_slice(pkt.as_ref()); 258 | 259 | self.socket.send(&buf).await.map(|len| len - header.len()) 260 | } 261 | 262 | /// Sends a UDP relay packet to a specified remote address to which it is connected. The socks5 UDP header will be added to the packet. 263 | pub async fn send_to>(&self, pkt: P, frag: u8, from_addr: Address, to_addr: SocketAddr) -> std::io::Result { 264 | let header = UdpHeader::new(frag, from_addr); 265 | let mut buf = BytesMut::with_capacity(header.len() + pkt.as_ref().len()); 266 | header.write_to_buf(&mut buf); 267 | buf.extend_from_slice(pkt.as_ref()); 268 | 269 | self.socket.send_to(&buf, to_addr).await.map(|len| len - header.len()) 270 | } 271 | } 272 | 273 | impl From<(UdpSocket, usize)> for AssociatedUdpSocket { 274 | #[inline] 275 | fn from(from: (UdpSocket, usize)) -> Self { 276 | AssociatedUdpSocket { 277 | socket: from.0, 278 | buf_size: AtomicUsize::new(from.1), 279 | } 280 | } 281 | } 282 | 283 | impl From for UdpSocket { 284 | #[inline] 285 | fn from(from: AssociatedUdpSocket) -> Self { 286 | from.socket 287 | } 288 | } 289 | 290 | impl AsRef for AssociatedUdpSocket { 291 | #[inline] 292 | fn as_ref(&self) -> &UdpSocket { 293 | &self.socket 294 | } 295 | } 296 | 297 | impl AsMut for AssociatedUdpSocket { 298 | #[inline] 299 | fn as_mut(&mut self) -> &mut UdpSocket { 300 | &mut self.socket 301 | } 302 | } 303 | -------------------------------------------------------------------------------- /src/server/connection/bind.rs: -------------------------------------------------------------------------------- 1 | use crate::protocol::{Address, AsyncStreamOperation, Reply, Response}; 2 | use std::{ 3 | marker::PhantomData, 4 | net::SocketAddr, 5 | pin::Pin, 6 | task::{Context, Poll}, 7 | time::Duration, 8 | }; 9 | use tokio::{ 10 | io::{AsyncRead, AsyncWrite, AsyncWriteExt, ReadBuf}, 11 | net::{ 12 | TcpStream, 13 | tcp::{ReadHalf, WriteHalf}, 14 | }, 15 | }; 16 | 17 | /// Socks5 command type `Bind` 18 | /// 19 | /// By [`wait_request`](crate::server::connection::Authenticated::wait_request) 20 | /// on an [`Authenticated`](crate::server::connection::Authenticated) from SOCKS5 client, 21 | /// you may get a `Bind`. After replying the client 2 times 22 | /// using [`reply()`](crate::server::connection::Bind::reply), 23 | /// you will get a `Bind`, which can be used as a regular async TCP stream. 24 | /// 25 | /// A `Bind` can be converted to a regular tokio [`TcpStream`](https://docs.rs/tokio/latest/tokio/net/struct.TcpStream.html) by using the `From` trait. 26 | #[derive(Debug)] 27 | pub struct Bind { 28 | stream: TcpStream, 29 | _state: PhantomData, 30 | } 31 | 32 | /// Marker type indicating that the connection needs its first reply. 33 | #[derive(Debug, Default)] 34 | pub struct NeedFirstReply; 35 | 36 | /// Marker type indicating that the connection needs its second reply. 37 | #[derive(Debug, Default)] 38 | pub struct NeedSecondReply; 39 | 40 | /// Marker type indicating that the connection is ready to use as a regular TCP stream. 41 | #[derive(Debug, Default)] 42 | pub struct Ready; 43 | 44 | impl Bind { 45 | #[inline] 46 | pub(super) fn new(stream: TcpStream) -> Self { 47 | Self { 48 | stream, 49 | _state: PhantomData, 50 | } 51 | } 52 | 53 | /// Reply to the SOCKS5 client with the given reply and address. 54 | /// 55 | /// If encountered an error while writing the reply, the error alongside the original `TcpStream` is returned. 56 | pub async fn reply(mut self, reply: Reply, addr: Address) -> std::io::Result> { 57 | let resp = Response::new(reply, addr); 58 | resp.write_to_async_stream(&mut self.stream).await?; 59 | Ok(Bind::::new(self.stream)) 60 | } 61 | 62 | /// Causes the other peer to receive a read of length 0, indicating that no more data will be sent. This only closes the stream in one direction. 63 | #[inline] 64 | pub async fn shutdown(&mut self) -> std::io::Result<()> { 65 | self.stream.shutdown().await 66 | } 67 | 68 | /// Returns the local address that this stream is bound to. 69 | #[inline] 70 | pub fn local_addr(&self) -> std::io::Result { 71 | self.stream.local_addr() 72 | } 73 | 74 | /// Returns the remote address that this stream is connected to. 75 | #[inline] 76 | pub fn peer_addr(&self) -> std::io::Result { 77 | self.stream.peer_addr() 78 | } 79 | 80 | /// Reads the linger duration for this socket by getting the `SO_LINGER` option. 81 | /// 82 | /// For more information about this option, see [`set_linger`](crate::server::connection::Bind::set_linger). 83 | #[inline] 84 | pub fn linger(&self) -> std::io::Result> { 85 | self.stream.linger() 86 | } 87 | 88 | /// Sets the linger duration of this socket by setting the `SO_LINGER` option. 89 | /// 90 | /// This option controls the action taken when a stream has unsent messages and the stream is closed. 91 | /// If `SO_LINGER` is set, the system shall block the process until it can transmit the data or until the time expires. 92 | /// 93 | /// If `SO_LINGER` is not specified, and the stream is closed, the system handles the call in a way 94 | /// that allows the process to continue as quickly as possible. 95 | #[inline] 96 | pub fn set_linger(&self, dur: Option) -> std::io::Result<()> { 97 | self.stream.set_linger(dur) 98 | } 99 | 100 | /// Gets the value of the `TCP_NODELAY` option on this socket. 101 | /// 102 | /// For more information about this option, see [`set_nodelay`](crate::server::connection::Bind::set_nodelay). 103 | #[inline] 104 | pub fn nodelay(&self) -> std::io::Result { 105 | self.stream.nodelay() 106 | } 107 | 108 | /// Sets the value of the `TCP_NODELAY` option on this socket. 109 | /// 110 | /// If set, this option disables the Nagle algorithm. This means that segments are always sent as soon as possible, 111 | /// even if there is only a small amount of data. When not set, data is buffered until there is a sufficient amount to send out, 112 | /// thereby avoiding the frequent sending of small packets. 113 | pub fn set_nodelay(&self, nodelay: bool) -> std::io::Result<()> { 114 | self.stream.set_nodelay(nodelay) 115 | } 116 | 117 | /// Gets the value of the `IP_TTL` option for this socket. 118 | /// 119 | /// For more information about this option, see [`set_ttl`](crate::server::connection::Bind::set_ttl). 120 | pub fn ttl(&self) -> std::io::Result { 121 | self.stream.ttl() 122 | } 123 | 124 | /// Sets the value for the `IP_TTL` option on this socket. 125 | /// 126 | /// This value sets the time-to-live field that is used in every packet sent from this socket. 127 | pub fn set_ttl(&self, ttl: u32) -> std::io::Result<()> { 128 | self.stream.set_ttl(ttl) 129 | } 130 | } 131 | 132 | impl Bind { 133 | #[inline] 134 | fn new(stream: TcpStream) -> Self { 135 | Self { 136 | stream, 137 | _state: PhantomData, 138 | } 139 | } 140 | 141 | /// Reply to the SOCKS5 client with the given reply and address. 142 | /// 143 | /// If encountered an error while writing the reply, the error alongside the original `TcpStream` is returned. 144 | pub async fn reply(mut self, reply: Reply, addr: Address) -> Result, (std::io::Error, TcpStream)> { 145 | let resp = Response::new(reply, addr); 146 | 147 | if let Err(err) = resp.write_to_async_stream(&mut self.stream).await { 148 | return Err((err, self.stream)); 149 | } 150 | 151 | Ok(Bind::::new(self.stream)) 152 | } 153 | 154 | /// Causes the other peer to receive a read of length 0, indicating that no more data will be sent. This only closes the stream in one direction. 155 | #[inline] 156 | pub async fn shutdown(&mut self) -> std::io::Result<()> { 157 | self.stream.shutdown().await 158 | } 159 | 160 | /// Returns the local address that this stream is bound to. 161 | #[inline] 162 | pub fn local_addr(&self) -> std::io::Result { 163 | self.stream.local_addr() 164 | } 165 | 166 | /// Returns the remote address that this stream is connected to. 167 | #[inline] 168 | pub fn peer_addr(&self) -> std::io::Result { 169 | self.stream.peer_addr() 170 | } 171 | 172 | /// Reads the linger duration for this socket by getting the `SO_LINGER` option. 173 | /// 174 | /// For more information about this option, see [`set_linger`](crate::server::connection::Bind::set_linger). 175 | #[inline] 176 | pub fn linger(&self) -> std::io::Result> { 177 | self.stream.linger() 178 | } 179 | 180 | /// Sets the linger duration of this socket by setting the `SO_LINGER` option. 181 | /// 182 | /// This option controls the action taken when a stream has unsent messages and the stream is closed. 183 | /// If `SO_LINGER` is set, the system shall block the process until it can transmit the data or until the time expires. 184 | /// 185 | /// If `SO_LINGER` is not specified, and the stream is closed, the system handles the call in a way 186 | /// that allows the process to continue as quickly as possible. 187 | #[inline] 188 | pub fn set_linger(&self, dur: Option) -> std::io::Result<()> { 189 | self.stream.set_linger(dur) 190 | } 191 | 192 | /// Gets the value of the `TCP_NODELAY` option on this socket. 193 | /// 194 | /// For more information about this option, see 195 | /// [`set_nodelay`](crate::server::connection::Bind::set_nodelay). 196 | #[inline] 197 | pub fn nodelay(&self) -> std::io::Result { 198 | self.stream.nodelay() 199 | } 200 | 201 | /// Sets the value of the `TCP_NODELAY` option on this socket. 202 | /// 203 | /// If set, this option disables the Nagle algorithm. This means that segments are always sent as soon as possible, 204 | /// even if there is only a small amount of data. When not set, data is buffered until there is a sufficient amount to send out, 205 | /// thereby avoiding the frequent sending of small packets. 206 | pub fn set_nodelay(&self, nodelay: bool) -> std::io::Result<()> { 207 | self.stream.set_nodelay(nodelay) 208 | } 209 | 210 | /// Gets the value of the `IP_TTL` option for this socket. 211 | /// 212 | /// For more information about this option, see [`set_ttl`](crate::server::connection::Bind::set_ttl). 213 | pub fn ttl(&self) -> std::io::Result { 214 | self.stream.ttl() 215 | } 216 | 217 | /// Sets the value for the `IP_TTL` option on this socket. 218 | /// 219 | /// This value sets the time-to-live field that is used in every packet sent from this socket. 220 | pub fn set_ttl(&self, ttl: u32) -> std::io::Result<()> { 221 | self.stream.set_ttl(ttl) 222 | } 223 | } 224 | 225 | impl Bind { 226 | #[inline] 227 | fn new(stream: TcpStream) -> Self { 228 | Self { 229 | stream, 230 | _state: PhantomData, 231 | } 232 | } 233 | 234 | /// Split the connection into a read and a write half. 235 | #[inline] 236 | pub fn split(&mut self) -> (ReadHalf, WriteHalf) { 237 | self.stream.split() 238 | } 239 | } 240 | 241 | impl std::ops::Deref for Bind { 242 | type Target = TcpStream; 243 | 244 | #[inline] 245 | fn deref(&self) -> &Self::Target { 246 | &self.stream 247 | } 248 | } 249 | 250 | impl std::ops::DerefMut for Bind { 251 | #[inline] 252 | fn deref_mut(&mut self) -> &mut Self::Target { 253 | &mut self.stream 254 | } 255 | } 256 | 257 | impl AsyncRead for Bind { 258 | #[inline] 259 | fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll> { 260 | Pin::new(&mut self.stream).poll_read(cx, buf) 261 | } 262 | } 263 | 264 | impl AsyncWrite for Bind { 265 | #[inline] 266 | fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { 267 | Pin::new(&mut self.stream).poll_write(cx, buf) 268 | } 269 | 270 | #[inline] 271 | fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 272 | Pin::new(&mut self.stream).poll_flush(cx) 273 | } 274 | 275 | #[inline] 276 | fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 277 | Pin::new(&mut self.stream).poll_shutdown(cx) 278 | } 279 | } 280 | 281 | impl From> for TcpStream { 282 | #[inline] 283 | fn from(conn: Bind) -> Self { 284 | conn.stream 285 | } 286 | } 287 | -------------------------------------------------------------------------------- /src/server/connection/connect.rs: -------------------------------------------------------------------------------- 1 | use crate::protocol::{Address, AsyncStreamOperation, Reply, Response}; 2 | use std::{ 3 | io::IoSlice, 4 | net::SocketAddr, 5 | pin::Pin, 6 | task::{Context, Poll}, 7 | }; 8 | use tokio::{ 9 | io::{AsyncRead, AsyncWrite, AsyncWriteExt, ReadBuf}, 10 | net::{ 11 | TcpStream, 12 | tcp::{OwnedReadHalf, OwnedWriteHalf, ReadHalf, WriteHalf}, 13 | }, 14 | }; 15 | 16 | /// Socks5 connection type `Connect` 17 | /// 18 | /// This connection can be used as a regular async TCP stream after replying the client. 19 | #[derive(Debug)] 20 | pub struct Connect { 21 | stream: TcpStream, 22 | _state: S, 23 | } 24 | 25 | impl Connect { 26 | #[inline] 27 | pub(super) fn new(stream: TcpStream) -> Self { 28 | Self { 29 | stream, 30 | _state: S::default(), 31 | } 32 | } 33 | 34 | /// Returns the local address that this stream is bound to. 35 | #[inline] 36 | pub fn local_addr(&self) -> std::io::Result { 37 | self.stream.local_addr() 38 | } 39 | 40 | /// Returns the remote address that this stream is connected to. 41 | #[inline] 42 | pub fn peer_addr(&self) -> std::io::Result { 43 | self.stream.peer_addr() 44 | } 45 | 46 | /// Shutdown the TCP stream. 47 | #[inline] 48 | pub async fn shutdown(&mut self) -> std::io::Result<()> { 49 | self.stream.shutdown().await 50 | } 51 | } 52 | 53 | #[derive(Debug, Default)] 54 | pub struct NeedReply; 55 | 56 | #[derive(Debug, Default)] 57 | pub struct Ready; 58 | 59 | impl Connect { 60 | /// Reply to the client. 61 | #[inline] 62 | pub async fn reply(mut self, reply: Reply, addr: Address) -> std::io::Result> { 63 | let resp = Response::new(reply, addr); 64 | resp.write_to_async_stream(&mut self.stream).await?; 65 | Ok(Connect::::new(self.stream)) 66 | } 67 | } 68 | 69 | impl Connect { 70 | /// Returns the read/write half of the stream. 71 | #[inline] 72 | pub fn split(&mut self) -> (ReadHalf, WriteHalf) { 73 | self.stream.split() 74 | } 75 | 76 | /// Returns the owned read/write half of the stream. 77 | #[inline] 78 | pub fn into_split(self) -> (OwnedReadHalf, OwnedWriteHalf) { 79 | self.stream.into_split() 80 | } 81 | } 82 | 83 | impl std::ops::Deref for Connect { 84 | type Target = TcpStream; 85 | 86 | #[inline] 87 | fn deref(&self) -> &Self::Target { 88 | &self.stream 89 | } 90 | } 91 | 92 | impl std::ops::DerefMut for Connect { 93 | #[inline] 94 | fn deref_mut(&mut self) -> &mut Self::Target { 95 | &mut self.stream 96 | } 97 | } 98 | 99 | impl AsyncRead for Connect { 100 | #[inline] 101 | fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll> { 102 | Pin::new(&mut self.stream).poll_read(cx, buf) 103 | } 104 | } 105 | 106 | impl AsyncWrite for Connect { 107 | #[inline] 108 | fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { 109 | Pin::new(&mut self.stream).poll_write(cx, buf) 110 | } 111 | 112 | #[inline] 113 | fn poll_write_vectored(mut self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>]) -> Poll> { 114 | Pin::new(&mut self.stream).poll_write_vectored(cx, bufs) 115 | } 116 | 117 | #[inline] 118 | fn is_write_vectored(&self) -> bool { 119 | self.stream.is_write_vectored() 120 | } 121 | 122 | #[inline] 123 | fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 124 | Pin::new(&mut self.stream).poll_flush(cx) 125 | } 126 | 127 | #[inline] 128 | fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 129 | Pin::new(&mut self.stream).poll_shutdown(cx) 130 | } 131 | } 132 | 133 | impl From> for TcpStream { 134 | #[inline] 135 | fn from(conn: Connect) -> Self { 136 | conn.stream 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /src/server/connection/mod.rs: -------------------------------------------------------------------------------- 1 | use self::{associate::UdpAssociate, bind::Bind, connect::Connect}; 2 | use crate::{ 3 | protocol::{self, Address, AsyncStreamOperation, AuthMethod, Command, handshake}, 4 | server::AuthAdaptor, 5 | }; 6 | use std::{net::SocketAddr, time::Duration}; 7 | use tokio::{io::AsyncWriteExt, net::TcpStream}; 8 | 9 | pub mod associate; 10 | pub mod bind; 11 | pub mod connect; 12 | 13 | /// An incoming connection. This may not be a valid socks5 connection. You need to call [`authenticate()`](#method.authenticate) 14 | /// to perform the socks5 handshake. It will be converted to a proper socks5 connection after the handshake succeeds. 15 | pub struct IncomingConnection { 16 | stream: TcpStream, 17 | auth: AuthAdaptor, 18 | } 19 | 20 | impl IncomingConnection { 21 | #[inline] 22 | pub(crate) fn new(stream: TcpStream, auth: AuthAdaptor) -> Self { 23 | IncomingConnection { stream, auth } 24 | } 25 | 26 | /// Returns the local address that this stream is bound to. 27 | #[inline] 28 | pub fn local_addr(&self) -> std::io::Result { 29 | self.stream.local_addr() 30 | } 31 | 32 | /// Returns the remote address that this stream is connected to. 33 | #[inline] 34 | pub fn peer_addr(&self) -> std::io::Result { 35 | self.stream.peer_addr() 36 | } 37 | 38 | /// Shutdown the TCP stream. 39 | #[inline] 40 | pub async fn shutdown(&mut self) -> std::io::Result<()> { 41 | self.stream.shutdown().await 42 | } 43 | 44 | /// Reads the linger duration for this socket by getting the `SO_LINGER` option. 45 | /// 46 | /// For more information about this option, see [`set_linger`](crate::server::connection::IncomingConnection::set_linger). 47 | #[inline] 48 | pub fn linger(&self) -> std::io::Result> { 49 | self.stream.linger() 50 | } 51 | 52 | /// Sets the linger duration of this socket by setting the `SO_LINGER` option. 53 | /// 54 | /// This option controls the action taken when a stream has unsent messages and the stream is closed. 55 | /// If `SO_LINGER` is set, the system shall block the process until it can transmit the data or until the time expires. 56 | /// 57 | /// If `SO_LINGER` is not specified, and the stream is closed, the system handles the call in a way 58 | /// that allows the process to continue as quickly as possible. 59 | #[inline] 60 | pub fn set_linger(&self, dur: Option) -> std::io::Result<()> { 61 | self.stream.set_linger(dur) 62 | } 63 | 64 | /// Gets the value of the `TCP_NODELAY` option on this socket. 65 | /// 66 | /// For more information about this option, see 67 | /// [`set_nodelay`](#method.set_nodelay). 68 | #[inline] 69 | pub fn nodelay(&self) -> std::io::Result { 70 | self.stream.nodelay() 71 | } 72 | 73 | /// Sets the value of the `TCP_NODELAY` option on this socket. 74 | /// 75 | /// If set, this option disables the Nagle algorithm. This means that segments are always sent as soon as possible, 76 | /// even if there is only a small amount of data. When not set, data is buffered until there is a sufficient amount 77 | /// to send out, thereby avoiding the frequent sending of small packets. 78 | pub fn set_nodelay(&self, nodelay: bool) -> std::io::Result<()> { 79 | self.stream.set_nodelay(nodelay) 80 | } 81 | 82 | /// Gets the value of the `IP_TTL` option for this socket. 83 | /// 84 | /// For more information about this option, see 85 | /// [`set_ttl`](#method.set_ttl). 86 | pub fn ttl(&self) -> std::io::Result { 87 | self.stream.ttl() 88 | } 89 | 90 | /// Sets the value for the `IP_TTL` option on this socket. 91 | /// 92 | /// This value sets the time-to-live field that is used in every packet sent from this socket. 93 | pub fn set_ttl(&self, ttl: u32) -> std::io::Result<()> { 94 | self.stream.set_ttl(ttl) 95 | } 96 | 97 | /// Perform a SOCKS5 authentication handshake using the given 98 | /// [`AuthExecutor`](crate::server::auth::AuthExecutor) adapter. 99 | /// 100 | /// If the handshake succeeds, an [`Authenticated`] 101 | /// alongs with the output of the [`AuthExecutor`](crate::server::auth::AuthExecutor) adapter is returned. 102 | /// Otherwise, the error and the original [`TcpStream`](https://docs.rs/tokio/latest/tokio/net/struct.TcpStream.html) is returned. 103 | /// 104 | /// Note that this method will not implicitly close the connection even if the handshake failed. 105 | pub async fn authenticate(mut self) -> std::io::Result<(Authenticated, O)> { 106 | let request = handshake::Request::retrieve_from_async_stream(&mut self.stream).await?; 107 | if let Some(method) = self.evaluate_request(&request) { 108 | let response = handshake::Response::new(method); 109 | response.write_to_async_stream(&mut self.stream).await?; 110 | let output = self.auth.execute(&mut self.stream).await; 111 | Ok((Authenticated::new(self.stream), output)) 112 | } else { 113 | let response = handshake::Response::new(AuthMethod::NoAcceptableMethods); 114 | response.write_to_async_stream(&mut self.stream).await?; 115 | let err = "No available handshake method provided by client"; 116 | Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err)) 117 | } 118 | } 119 | 120 | fn evaluate_request(&self, req: &handshake::Request) -> Option { 121 | let method = self.auth.auth_method(); 122 | if req.evaluate_method(method) { Some(method) } else { None } 123 | } 124 | } 125 | 126 | impl std::fmt::Debug for IncomingConnection { 127 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 128 | f.debug_struct("IncomingConnection").field("stream", &self.stream).finish() 129 | } 130 | } 131 | 132 | impl From> for TcpStream { 133 | #[inline] 134 | fn from(conn: IncomingConnection) -> Self { 135 | conn.stream 136 | } 137 | } 138 | 139 | /// A TCP stream that has been authenticated. 140 | /// 141 | /// To get the command from the SOCKS5 client, use 142 | /// [`wait_request`](crate::server::connection::Authenticated::wait_request). 143 | /// 144 | /// It can also be converted back into a raw [`tokio::TcpStream`](https://docs.rs/tokio/latest/tokio/net/struct.TcpStream.html) with `From` trait. 145 | pub struct Authenticated(TcpStream); 146 | 147 | impl Authenticated { 148 | #[inline] 149 | fn new(stream: TcpStream) -> Self { 150 | Self(stream) 151 | } 152 | 153 | /// Waits the SOCKS5 client to send a request. 154 | /// 155 | /// This method will return a [`Command`] if the client sends a valid command. 156 | /// 157 | /// When encountering an error, the stream will be returned alongside the error. 158 | /// 159 | /// Note that this method will not implicitly close the connection even if the client sends an invalid request. 160 | pub async fn wait_request(mut self) -> crate::Result { 161 | let req = protocol::Request::retrieve_from_async_stream(&mut self.0).await?; 162 | 163 | match req.command { 164 | Command::UdpAssociate => Ok(ClientConnection::UdpAssociate( 165 | UdpAssociate::::new(self.0), 166 | req.address, 167 | )), 168 | Command::Bind => Ok(ClientConnection::Bind(Bind::::new(self.0), req.address)), 169 | Command::Connect => Ok(ClientConnection::Connect(Connect::::new(self.0), req.address)), 170 | } 171 | } 172 | 173 | /// Causes the other peer to receive a read of length 0, indicating that no more data will be sent. This only closes the stream in one direction. 174 | #[inline] 175 | pub async fn shutdown(&mut self) -> std::io::Result<()> { 176 | self.0.shutdown().await 177 | } 178 | 179 | /// Returns the local address that this stream is bound to. 180 | #[inline] 181 | pub fn local_addr(&self) -> std::io::Result { 182 | self.0.local_addr() 183 | } 184 | 185 | /// Returns the remote address that this stream is connected to. 186 | #[inline] 187 | pub fn peer_addr(&self) -> std::io::Result { 188 | self.0.peer_addr() 189 | } 190 | 191 | /// Reads the linger duration for this socket by getting the `SO_LINGER` option. 192 | /// 193 | /// For more information about this option, see 194 | /// [`set_linger`](crate::server::connection::Authenticated::set_linger). 195 | #[inline] 196 | pub fn linger(&self) -> std::io::Result> { 197 | self.0.linger() 198 | } 199 | 200 | /// Sets the linger duration of this socket by setting the `SO_LINGER` option. 201 | /// 202 | /// This option controls the action taken when a stream has unsent messages and the stream is closed. 203 | /// If `SO_LINGER` is set, the system shall block the process until it can transmit the data or until the time expires. 204 | /// 205 | /// If `SO_LINGER` is not specified, and the stream is closed, the system handles the call in a way 206 | /// that allows the process to continue as quickly as possible. 207 | #[inline] 208 | pub fn set_linger(&self, dur: Option) -> std::io::Result<()> { 209 | self.0.set_linger(dur) 210 | } 211 | 212 | /// Gets the value of the `TCP_NODELAY` option on this socket. 213 | /// 214 | /// For more information about this option, see 215 | /// [`set_nodelay`](crate::server::connection::Authenticated::set_nodelay). 216 | #[inline] 217 | pub fn nodelay(&self) -> std::io::Result { 218 | self.0.nodelay() 219 | } 220 | 221 | /// Sets the value of the `TCP_NODELAY` option on this socket. 222 | /// 223 | /// If set, this option disables the Nagle algorithm. This means that segments are always sent as soon as possible, 224 | /// even if there is only a small amount of data. When not set, data is buffered until there is a sufficient amount to send out, 225 | /// thereby avoiding the frequent sending of small packets. 226 | pub fn set_nodelay(&self, nodelay: bool) -> std::io::Result<()> { 227 | self.0.set_nodelay(nodelay) 228 | } 229 | 230 | /// Gets the value of the `IP_TTL` option for this socket. 231 | /// 232 | /// For more information about this option, see 233 | /// [`set_ttl`](crate::server::connection::Authenticated::set_ttl). 234 | pub fn ttl(&self) -> std::io::Result { 235 | self.0.ttl() 236 | } 237 | 238 | /// Sets the value for the `IP_TTL` option on this socket. 239 | /// 240 | /// This value sets the time-to-live field that is used in every packet sent from this socket. 241 | pub fn set_ttl(&self, ttl: u32) -> std::io::Result<()> { 242 | self.0.set_ttl(ttl) 243 | } 244 | } 245 | 246 | impl From for TcpStream { 247 | #[inline] 248 | fn from(conn: Authenticated) -> Self { 249 | conn.0 250 | } 251 | } 252 | 253 | /// After the socks5 handshake succeeds, the connection may become: 254 | /// 255 | /// - Associate 256 | /// - Bind 257 | /// - Connect 258 | #[derive(Debug)] 259 | pub enum ClientConnection { 260 | UdpAssociate(UdpAssociate, Address), 261 | Bind(Bind, Address), 262 | Connect(Connect, Address), 263 | } 264 | -------------------------------------------------------------------------------- /src/server/mod.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | net::SocketAddr, 3 | task::{Context, Poll}, 4 | }; 5 | use tokio::net::TcpListener; 6 | 7 | pub mod auth; 8 | pub mod connection; 9 | 10 | pub use crate::{ 11 | server::auth::{AuthAdaptor, AuthExecutor}, 12 | server::connection::{ 13 | ClientConnection, IncomingConnection, 14 | associate::{AssociatedUdpSocket, UdpAssociate}, 15 | bind::Bind, 16 | connect::Connect, 17 | }, 18 | }; 19 | 20 | /// The socks5 server itself. 21 | /// 22 | /// The server can be constructed on a given socket address, or be created on an existing TcpListener. 23 | /// 24 | /// The authentication method can be configured with the 25 | /// [`AuthExecutor`] trait. 26 | pub struct Server { 27 | listener: TcpListener, 28 | auth: AuthAdaptor, 29 | } 30 | 31 | impl Server { 32 | /// Create a new socks5 server with the given TCP listener and authentication method. 33 | #[inline] 34 | pub fn new(listener: TcpListener, auth: AuthAdaptor) -> Self { 35 | Self { listener, auth } 36 | } 37 | 38 | /// Create a new socks5 server on the given socket address and authentication method. 39 | #[inline] 40 | pub async fn bind(addr: SocketAddr, auth: AuthAdaptor) -> std::io::Result { 41 | let socket = if addr.is_ipv4() { 42 | tokio::net::TcpSocket::new_v4()? 43 | } else { 44 | tokio::net::TcpSocket::new_v6()? 45 | }; 46 | socket.set_reuseaddr(true)?; 47 | socket.bind(addr)?; 48 | let listener = socket.listen(1024)?; 49 | Ok(Self::new(listener, auth)) 50 | } 51 | 52 | /// Accept an [`IncomingConnection`]. 53 | /// The connection may not be a valid socks5 connection. You need to call 54 | /// [`IncomingConnection::authenticate`](crate::server::connection::IncomingConnection::authenticate) 55 | /// to hand-shake it into a proper socks5 connection. 56 | #[inline] 57 | pub async fn accept(&self) -> std::io::Result<(IncomingConnection, SocketAddr)> { 58 | let (stream, addr) = self.listener.accept().await?; 59 | Ok((IncomingConnection::new(stream, self.auth.clone()), addr)) 60 | } 61 | 62 | /// Polls to accept an [`IncomingConnection`](crate::server::connection::IncomingConnection). 63 | /// 64 | /// The connection is only a freshly created TCP connection and may not be a valid SOCKS5 connection. 65 | /// You should call 66 | /// [`IncomingConnection::authenticate`](crate::server::connection::IncomingConnection::authenticate) 67 | /// to perform a SOCKS5 authentication handshake. 68 | /// 69 | /// If there is no connection to accept, Poll::Pending is returned and the current task will be notified by a waker. 70 | /// Note that on multiple calls to poll_accept, only the Waker from the Context passed to the most recent call is scheduled to receive a wakeup. 71 | #[inline] 72 | pub fn poll_accept(&self, cx: &mut Context<'_>) -> Poll, SocketAddr)>> { 73 | self.listener 74 | .poll_accept(cx) 75 | .map_ok(|(stream, addr)| (IncomingConnection::new(stream, self.auth.clone()), addr)) 76 | } 77 | 78 | /// Get the the local socket address binded to this server 79 | #[inline] 80 | pub fn local_addr(&self) -> std::io::Result { 81 | self.listener.local_addr() 82 | } 83 | } 84 | 85 | impl From<(TcpListener, AuthAdaptor)> for Server { 86 | #[inline] 87 | fn from((listener, auth): (TcpListener, AuthAdaptor)) -> Self { 88 | Self { listener, auth } 89 | } 90 | } 91 | 92 | impl From> for (TcpListener, AuthAdaptor) { 93 | #[inline] 94 | fn from(server: Server) -> Self { 95 | (server.listener, server.auth) 96 | } 97 | } 98 | --------------------------------------------------------------------------------