├── .github └── workflows │ └── nightly.yaml ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── Makefile ├── README.md ├── config ├── client.toml ├── forward.toml └── server.toml └── src ├── error └── mod.rs ├── main.rs ├── protocol ├── direct │ ├── connector.rs │ └── mod.rs ├── dokodemo │ ├── acceptor.rs │ └── mod.rs ├── mod.rs ├── mux │ ├── acceptor.rs │ ├── connector.rs │ └── mod.rs ├── plaintext │ ├── acceptor.rs │ └── mod.rs ├── socks5 │ ├── acceptor.rs │ └── mod.rs ├── tls │ ├── acceptor.rs │ ├── connector.rs │ └── mod.rs ├── trojan │ ├── acceptor.rs │ ├── connector.rs │ └── mod.rs └── websocket │ ├── acceptor.rs │ ├── connector.rs │ └── mod.rs └── proxy └── mod.rs /.github/workflows/nightly.yaml: -------------------------------------------------------------------------------- 1 | on: [push] 2 | 3 | name: nightly 4 | 5 | jobs: 6 | build-windows: 7 | runs-on: windows-latest 8 | steps: 9 | - uses: actions/checkout@v2 10 | - uses: actions-rs/toolchain@v1 11 | with: 12 | toolchain: stable 13 | - uses: actions-rs/cargo@v1 14 | with: 15 | command: build 16 | args: --release 17 | - uses: actions/upload-artifact@v2 18 | with: 19 | name: build-windows 20 | path: target\release\trojan-r 21 | 22 | build-linux: 23 | strategy: 24 | matrix: 25 | target: [x86_64-unknown-linux-musl, armv7-unknown-linux-musleabihf, arm-unknown-linux-musleabihf, aarch64-unknown-linux-musl] 26 | runs-on: ubuntu-latest 27 | steps: 28 | - uses: actions/checkout@v2 29 | - uses: actions-rs/toolchain@v1 30 | with: 31 | toolchain: stable 32 | target: ${{ matrix.target }} 33 | override: true 34 | - uses: actions-rs/cargo@v1 35 | with: 36 | use-cross: true 37 | command: build 38 | args: --release --target ${{ matrix.target }} 39 | - uses: actions/upload-artifact@v2 40 | with: 41 | name: build-${{ matrix.target }} 42 | path: target/${{ matrix.target }}/release/trojan-r 43 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "aho-corasick" 5 | version = "0.7.18" 6 | source = "registry+https://github.com/rust-lang/crates.io-index" 7 | checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" 8 | dependencies = [ 9 | "memchr", 10 | ] 11 | 12 | [[package]] 13 | name = "ansi_term" 14 | version = "0.11.0" 15 | source = "registry+https://github.com/rust-lang/crates.io-index" 16 | checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" 17 | dependencies = [ 18 | "winapi", 19 | ] 20 | 21 | [[package]] 22 | name = "async-trait" 23 | version = "0.1.50" 24 | source = "registry+https://github.com/rust-lang/crates.io-index" 25 | checksum = "0b98e84bbb4cbcdd97da190ba0c58a1bb0de2c1fdf67d159e192ed766aeca722" 26 | dependencies = [ 27 | "proc-macro2", 28 | "quote", 29 | "syn", 30 | ] 31 | 32 | [[package]] 33 | name = "atty" 34 | version = "0.2.14" 35 | source = "registry+https://github.com/rust-lang/crates.io-index" 36 | checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" 37 | dependencies = [ 38 | "hermit-abi", 39 | "libc", 40 | "winapi", 41 | ] 42 | 43 | [[package]] 44 | name = "autocfg" 45 | version = "1.0.1" 46 | source = "registry+https://github.com/rust-lang/crates.io-index" 47 | checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" 48 | 49 | [[package]] 50 | name = "base64" 51 | version = "0.13.0" 52 | source = "registry+https://github.com/rust-lang/crates.io-index" 53 | checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" 54 | 55 | [[package]] 56 | name = "bitflags" 57 | version = "1.2.1" 58 | source = "registry+https://github.com/rust-lang/crates.io-index" 59 | checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" 60 | 61 | [[package]] 62 | name = "block-buffer" 63 | version = "0.9.0" 64 | source = "registry+https://github.com/rust-lang/crates.io-index" 65 | checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" 66 | dependencies = [ 67 | "generic-array", 68 | ] 69 | 70 | [[package]] 71 | name = "bumpalo" 72 | version = "3.7.0" 73 | source = "registry+https://github.com/rust-lang/crates.io-index" 74 | checksum = "9c59e7af012c713f529e7a3ee57ce9b31ddd858d4b512923602f74608b009631" 75 | 76 | [[package]] 77 | name = "byteorder" 78 | version = "1.4.3" 79 | source = "registry+https://github.com/rust-lang/crates.io-index" 80 | checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" 81 | 82 | [[package]] 83 | name = "bytes" 84 | version = "1.0.1" 85 | source = "registry+https://github.com/rust-lang/crates.io-index" 86 | checksum = "b700ce4376041dcd0a327fd0097c41095743c4c8af8887265942faf1100bd040" 87 | 88 | [[package]] 89 | name = "cc" 90 | version = "1.0.68" 91 | source = "registry+https://github.com/rust-lang/crates.io-index" 92 | checksum = "4a72c244c1ff497a746a7e1fb3d14bd08420ecda70c8f25c7112f2781652d787" 93 | 94 | [[package]] 95 | name = "cfg-if" 96 | version = "1.0.0" 97 | source = "registry+https://github.com/rust-lang/crates.io-index" 98 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 99 | 100 | [[package]] 101 | name = "clap" 102 | version = "2.33.3" 103 | source = "registry+https://github.com/rust-lang/crates.io-index" 104 | checksum = "37e58ac78573c40708d45522f0d80fa2f01cc4f9b4e2bf749807255454312002" 105 | dependencies = [ 106 | "ansi_term", 107 | "atty", 108 | "bitflags", 109 | "strsim", 110 | "textwrap", 111 | "unicode-width", 112 | "vec_map", 113 | ] 114 | 115 | [[package]] 116 | name = "cpufeatures" 117 | version = "0.1.4" 118 | source = "registry+https://github.com/rust-lang/crates.io-index" 119 | checksum = "ed00c67cb5d0a7d64a44f6ad2668db7e7530311dd53ea79bcd4fb022c64911c8" 120 | dependencies = [ 121 | "libc", 122 | ] 123 | 124 | [[package]] 125 | name = "digest" 126 | version = "0.9.0" 127 | source = "registry+https://github.com/rust-lang/crates.io-index" 128 | checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" 129 | dependencies = [ 130 | "generic-array", 131 | ] 132 | 133 | [[package]] 134 | name = "env_logger" 135 | version = "0.8.3" 136 | source = "registry+https://github.com/rust-lang/crates.io-index" 137 | checksum = "17392a012ea30ef05a610aa97dfb49496e71c9f676b27879922ea5bdf60d9d3f" 138 | dependencies = [ 139 | "atty", 140 | "humantime", 141 | "log", 142 | "regex", 143 | "termcolor", 144 | ] 145 | 146 | [[package]] 147 | name = "fnv" 148 | version = "1.0.7" 149 | source = "registry+https://github.com/rust-lang/crates.io-index" 150 | checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" 151 | 152 | [[package]] 153 | name = "form_urlencoded" 154 | version = "1.0.1" 155 | source = "registry+https://github.com/rust-lang/crates.io-index" 156 | checksum = "5fc25a87fa4fd2094bffb06925852034d90a17f0d1e05197d4956d3555752191" 157 | dependencies = [ 158 | "matches", 159 | "percent-encoding", 160 | ] 161 | 162 | [[package]] 163 | name = "futures-core" 164 | version = "0.3.15" 165 | source = "registry+https://github.com/rust-lang/crates.io-index" 166 | checksum = "0402f765d8a89a26043b889b26ce3c4679d268fa6bb22cd7c6aad98340e179d1" 167 | 168 | [[package]] 169 | name = "futures-macro" 170 | version = "0.3.15" 171 | source = "registry+https://github.com/rust-lang/crates.io-index" 172 | checksum = "a4c40298486cdf52cc00cd6d6987892ba502c7656a16a4192a9992b1ccedd121" 173 | dependencies = [ 174 | "autocfg", 175 | "proc-macro-hack", 176 | "proc-macro2", 177 | "quote", 178 | "syn", 179 | ] 180 | 181 | [[package]] 182 | name = "futures-sink" 183 | version = "0.3.15" 184 | source = "registry+https://github.com/rust-lang/crates.io-index" 185 | checksum = "a57bead0ceff0d6dde8f465ecd96c9338121bb7717d3e7b108059531870c4282" 186 | 187 | [[package]] 188 | name = "futures-task" 189 | version = "0.3.15" 190 | source = "registry+https://github.com/rust-lang/crates.io-index" 191 | checksum = "8a16bef9fc1a4dddb5bee51c989e3fbba26569cbb0e31f5b303c184e3dd33dae" 192 | 193 | [[package]] 194 | name = "futures-util" 195 | version = "0.3.15" 196 | source = "registry+https://github.com/rust-lang/crates.io-index" 197 | checksum = "feb5c238d27e2bf94ffdfd27b2c29e3df4a68c4193bb6427384259e2bf191967" 198 | dependencies = [ 199 | "autocfg", 200 | "futures-core", 201 | "futures-macro", 202 | "futures-sink", 203 | "futures-task", 204 | "pin-project-lite", 205 | "pin-utils", 206 | "proc-macro-hack", 207 | "proc-macro-nested", 208 | "slab", 209 | ] 210 | 211 | [[package]] 212 | name = "generic-array" 213 | version = "0.14.4" 214 | source = "registry+https://github.com/rust-lang/crates.io-index" 215 | checksum = "501466ecc8a30d1d3b7fc9229b122b2ce8ed6e9d9223f1138d4babb253e51817" 216 | dependencies = [ 217 | "typenum", 218 | "version_check", 219 | ] 220 | 221 | [[package]] 222 | name = "getrandom" 223 | version = "0.2.3" 224 | source = "registry+https://github.com/rust-lang/crates.io-index" 225 | checksum = "7fcd999463524c52659517fe2cea98493cfe485d10565e7b0fb07dbba7ad2753" 226 | dependencies = [ 227 | "cfg-if", 228 | "libc", 229 | "wasi", 230 | ] 231 | 232 | [[package]] 233 | name = "hermit-abi" 234 | version = "0.1.18" 235 | source = "registry+https://github.com/rust-lang/crates.io-index" 236 | checksum = "322f4de77956e22ed0e5032c359a0f1273f1f7f0d79bfa3b8ffbc730d7fbcc5c" 237 | dependencies = [ 238 | "libc", 239 | ] 240 | 241 | [[package]] 242 | name = "http" 243 | version = "0.2.4" 244 | source = "registry+https://github.com/rust-lang/crates.io-index" 245 | checksum = "527e8c9ac747e28542699a951517aa9a6945af506cd1f2e1b53a576c17b6cc11" 246 | dependencies = [ 247 | "bytes", 248 | "fnv", 249 | "itoa", 250 | ] 251 | 252 | [[package]] 253 | name = "httparse" 254 | version = "1.4.1" 255 | source = "registry+https://github.com/rust-lang/crates.io-index" 256 | checksum = "f3a87b616e37e93c22fb19bcd386f02f3af5ea98a25670ad0fce773de23c5e68" 257 | 258 | [[package]] 259 | name = "humantime" 260 | version = "2.1.0" 261 | source = "registry+https://github.com/rust-lang/crates.io-index" 262 | checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" 263 | 264 | [[package]] 265 | name = "idna" 266 | version = "0.2.3" 267 | source = "registry+https://github.com/rust-lang/crates.io-index" 268 | checksum = "418a0a6fab821475f634efe3ccc45c013f742efe03d853e8d3355d5cb850ecf8" 269 | dependencies = [ 270 | "matches", 271 | "unicode-bidi", 272 | "unicode-normalization", 273 | ] 274 | 275 | [[package]] 276 | name = "input_buffer" 277 | version = "0.4.0" 278 | source = "registry+https://github.com/rust-lang/crates.io-index" 279 | checksum = "f97967975f448f1a7ddb12b0bc41069d09ed6a1c161a92687e057325db35d413" 280 | dependencies = [ 281 | "bytes", 282 | ] 283 | 284 | [[package]] 285 | name = "itoa" 286 | version = "0.4.7" 287 | source = "registry+https://github.com/rust-lang/crates.io-index" 288 | checksum = "dd25036021b0de88a0aff6b850051563c6516d0bf53f8638938edbb9de732736" 289 | 290 | [[package]] 291 | name = "js-sys" 292 | version = "0.3.51" 293 | source = "registry+https://github.com/rust-lang/crates.io-index" 294 | checksum = "83bdfbace3a0e81a4253f73b49e960b053e396a11012cbd49b9b74d6a2b67062" 295 | dependencies = [ 296 | "wasm-bindgen", 297 | ] 298 | 299 | [[package]] 300 | name = "lazy_static" 301 | version = "1.4.0" 302 | source = "registry+https://github.com/rust-lang/crates.io-index" 303 | checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" 304 | 305 | [[package]] 306 | name = "libc" 307 | version = "0.2.95" 308 | source = "registry+https://github.com/rust-lang/crates.io-index" 309 | checksum = "789da6d93f1b866ffe175afc5322a4d76c038605a1c3319bb57b06967ca98a36" 310 | 311 | [[package]] 312 | name = "log" 313 | version = "0.4.14" 314 | source = "registry+https://github.com/rust-lang/crates.io-index" 315 | checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710" 316 | dependencies = [ 317 | "cfg-if", 318 | ] 319 | 320 | [[package]] 321 | name = "matches" 322 | version = "0.1.8" 323 | source = "registry+https://github.com/rust-lang/crates.io-index" 324 | checksum = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08" 325 | 326 | [[package]] 327 | name = "memchr" 328 | version = "2.4.0" 329 | source = "registry+https://github.com/rust-lang/crates.io-index" 330 | checksum = "b16bd47d9e329435e309c58469fe0791c2d0d1ba96ec0954152a5ae2b04387dc" 331 | 332 | [[package]] 333 | name = "mio" 334 | version = "0.7.11" 335 | source = "registry+https://github.com/rust-lang/crates.io-index" 336 | checksum = "cf80d3e903b34e0bd7282b218398aec54e082c840d9baf8339e0080a0c542956" 337 | dependencies = [ 338 | "libc", 339 | "log", 340 | "miow", 341 | "ntapi", 342 | "winapi", 343 | ] 344 | 345 | [[package]] 346 | name = "miow" 347 | version = "0.3.7" 348 | source = "registry+https://github.com/rust-lang/crates.io-index" 349 | checksum = "b9f1c5b025cda876f66ef43a113f91ebc9f4ccef34843000e0adf6ebbab84e21" 350 | dependencies = [ 351 | "winapi", 352 | ] 353 | 354 | [[package]] 355 | name = "ntapi" 356 | version = "0.3.6" 357 | source = "registry+https://github.com/rust-lang/crates.io-index" 358 | checksum = "3f6bb902e437b6d86e03cce10a7e2af662292c5dfef23b65899ea3ac9354ad44" 359 | dependencies = [ 360 | "winapi", 361 | ] 362 | 363 | [[package]] 364 | name = "num_cpus" 365 | version = "1.13.0" 366 | source = "registry+https://github.com/rust-lang/crates.io-index" 367 | checksum = "05499f3756671c15885fee9034446956fff3f243d6077b91e5767df161f766b3" 368 | dependencies = [ 369 | "hermit-abi", 370 | "libc", 371 | ] 372 | 373 | [[package]] 374 | name = "once_cell" 375 | version = "1.7.2" 376 | source = "registry+https://github.com/rust-lang/crates.io-index" 377 | checksum = "af8b08b04175473088b46763e51ee54da5f9a164bc162f615b91bc179dbf15a3" 378 | 379 | [[package]] 380 | name = "opaque-debug" 381 | version = "0.3.0" 382 | source = "registry+https://github.com/rust-lang/crates.io-index" 383 | checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" 384 | 385 | [[package]] 386 | name = "percent-encoding" 387 | version = "2.1.0" 388 | source = "registry+https://github.com/rust-lang/crates.io-index" 389 | checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" 390 | 391 | [[package]] 392 | name = "pin-project" 393 | version = "1.0.7" 394 | source = "registry+https://github.com/rust-lang/crates.io-index" 395 | checksum = "c7509cc106041c40a4518d2af7a61530e1eed0e6285296a3d8c5472806ccc4a4" 396 | dependencies = [ 397 | "pin-project-internal", 398 | ] 399 | 400 | [[package]] 401 | name = "pin-project-internal" 402 | version = "1.0.7" 403 | source = "registry+https://github.com/rust-lang/crates.io-index" 404 | checksum = "48c950132583b500556b1efd71d45b319029f2b71518d979fcc208e16b42426f" 405 | dependencies = [ 406 | "proc-macro2", 407 | "quote", 408 | "syn", 409 | ] 410 | 411 | [[package]] 412 | name = "pin-project-lite" 413 | version = "0.2.6" 414 | source = "registry+https://github.com/rust-lang/crates.io-index" 415 | checksum = "dc0e1f259c92177c30a4c9d177246edd0a3568b25756a977d0632cf8fa37e905" 416 | 417 | [[package]] 418 | name = "pin-utils" 419 | version = "0.1.0" 420 | source = "registry+https://github.com/rust-lang/crates.io-index" 421 | checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" 422 | 423 | [[package]] 424 | name = "ppv-lite86" 425 | version = "0.2.10" 426 | source = "registry+https://github.com/rust-lang/crates.io-index" 427 | checksum = "ac74c624d6b2d21f425f752262f42188365d7b8ff1aff74c82e45136510a4857" 428 | 429 | [[package]] 430 | name = "proc-macro-hack" 431 | version = "0.5.19" 432 | source = "registry+https://github.com/rust-lang/crates.io-index" 433 | checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" 434 | 435 | [[package]] 436 | name = "proc-macro-nested" 437 | version = "0.1.7" 438 | source = "registry+https://github.com/rust-lang/crates.io-index" 439 | checksum = "bc881b2c22681370c6a780e47af9840ef841837bc98118431d4e1868bd0c1086" 440 | 441 | [[package]] 442 | name = "proc-macro2" 443 | version = "1.0.27" 444 | source = "registry+https://github.com/rust-lang/crates.io-index" 445 | checksum = "f0d8caf72986c1a598726adc988bb5984792ef84f5ee5aa50209145ee8077038" 446 | dependencies = [ 447 | "unicode-xid", 448 | ] 449 | 450 | [[package]] 451 | name = "quote" 452 | version = "1.0.9" 453 | source = "registry+https://github.com/rust-lang/crates.io-index" 454 | checksum = "c3d0b9745dc2debf507c8422de05d7226cc1f0644216dfdfead988f9b1ab32a7" 455 | dependencies = [ 456 | "proc-macro2", 457 | ] 458 | 459 | [[package]] 460 | name = "rand" 461 | version = "0.8.3" 462 | source = "registry+https://github.com/rust-lang/crates.io-index" 463 | checksum = "0ef9e7e66b4468674bfcb0c81af8b7fa0bb154fa9f28eb840da5c447baeb8d7e" 464 | dependencies = [ 465 | "libc", 466 | "rand_chacha", 467 | "rand_core", 468 | "rand_hc", 469 | ] 470 | 471 | [[package]] 472 | name = "rand_chacha" 473 | version = "0.3.0" 474 | source = "registry+https://github.com/rust-lang/crates.io-index" 475 | checksum = "e12735cf05c9e10bf21534da50a147b924d555dc7a547c42e6bb2d5b6017ae0d" 476 | dependencies = [ 477 | "ppv-lite86", 478 | "rand_core", 479 | ] 480 | 481 | [[package]] 482 | name = "rand_core" 483 | version = "0.6.2" 484 | source = "registry+https://github.com/rust-lang/crates.io-index" 485 | checksum = "34cf66eb183df1c5876e2dcf6b13d57340741e8dc255b48e40a26de954d06ae7" 486 | dependencies = [ 487 | "getrandom", 488 | ] 489 | 490 | [[package]] 491 | name = "rand_hc" 492 | version = "0.3.0" 493 | source = "registry+https://github.com/rust-lang/crates.io-index" 494 | checksum = "3190ef7066a446f2e7f42e239d161e905420ccab01eb967c9eb27d21b2322a73" 495 | dependencies = [ 496 | "rand_core", 497 | ] 498 | 499 | [[package]] 500 | name = "regex" 501 | version = "1.5.4" 502 | source = "registry+https://github.com/rust-lang/crates.io-index" 503 | checksum = "d07a8629359eb56f1e2fb1652bb04212c072a87ba68546a04065d525673ac461" 504 | dependencies = [ 505 | "aho-corasick", 506 | "memchr", 507 | "regex-syntax", 508 | ] 509 | 510 | [[package]] 511 | name = "regex-syntax" 512 | version = "0.6.25" 513 | source = "registry+https://github.com/rust-lang/crates.io-index" 514 | checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" 515 | 516 | [[package]] 517 | name = "ring" 518 | version = "0.16.20" 519 | source = "registry+https://github.com/rust-lang/crates.io-index" 520 | checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" 521 | dependencies = [ 522 | "cc", 523 | "libc", 524 | "once_cell", 525 | "spin", 526 | "untrusted", 527 | "web-sys", 528 | "winapi", 529 | ] 530 | 531 | [[package]] 532 | name = "rustls" 533 | version = "0.19.1" 534 | source = "registry+https://github.com/rust-lang/crates.io-index" 535 | checksum = "35edb675feee39aec9c99fa5ff985081995a06d594114ae14cbe797ad7b7a6d7" 536 | dependencies = [ 537 | "base64", 538 | "log", 539 | "ring", 540 | "sct", 541 | "webpki", 542 | ] 543 | 544 | [[package]] 545 | name = "sct" 546 | version = "0.6.1" 547 | source = "registry+https://github.com/rust-lang/crates.io-index" 548 | checksum = "b362b83898e0e69f38515b82ee15aa80636befe47c3b6d3d89a911e78fc228ce" 549 | dependencies = [ 550 | "ring", 551 | "untrusted", 552 | ] 553 | 554 | [[package]] 555 | name = "serde" 556 | version = "1.0.126" 557 | source = "registry+https://github.com/rust-lang/crates.io-index" 558 | checksum = "ec7505abeacaec74ae4778d9d9328fe5a5d04253220a85c4ee022239fc996d03" 559 | dependencies = [ 560 | "serde_derive", 561 | ] 562 | 563 | [[package]] 564 | name = "serde_derive" 565 | version = "1.0.126" 566 | source = "registry+https://github.com/rust-lang/crates.io-index" 567 | checksum = "963a7dbc9895aeac7ac90e74f34a5d5261828f79df35cbed41e10189d3804d43" 568 | dependencies = [ 569 | "proc-macro2", 570 | "quote", 571 | "syn", 572 | ] 573 | 574 | [[package]] 575 | name = "sha-1" 576 | version = "0.9.6" 577 | source = "registry+https://github.com/rust-lang/crates.io-index" 578 | checksum = "8c4cfa741c5832d0ef7fab46cabed29c2aae926db0b11bb2069edd8db5e64e16" 579 | dependencies = [ 580 | "block-buffer", 581 | "cfg-if", 582 | "cpufeatures", 583 | "digest", 584 | "opaque-debug", 585 | ] 586 | 587 | [[package]] 588 | name = "sha2" 589 | version = "0.9.5" 590 | source = "registry+https://github.com/rust-lang/crates.io-index" 591 | checksum = "b362ae5752fd2137731f9fa25fd4d9058af34666ca1966fb969119cc35719f12" 592 | dependencies = [ 593 | "block-buffer", 594 | "cfg-if", 595 | "cpufeatures", 596 | "digest", 597 | "opaque-debug", 598 | ] 599 | 600 | [[package]] 601 | name = "slab" 602 | version = "0.4.3" 603 | source = "registry+https://github.com/rust-lang/crates.io-index" 604 | checksum = "f173ac3d1a7e3b28003f40de0b5ce7fe2710f9b9dc3fc38664cebee46b3b6527" 605 | 606 | [[package]] 607 | name = "spin" 608 | version = "0.5.2" 609 | source = "registry+https://github.com/rust-lang/crates.io-index" 610 | checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" 611 | 612 | [[package]] 613 | name = "strsim" 614 | version = "0.8.0" 615 | source = "registry+https://github.com/rust-lang/crates.io-index" 616 | checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" 617 | 618 | [[package]] 619 | name = "syn" 620 | version = "1.0.72" 621 | source = "registry+https://github.com/rust-lang/crates.io-index" 622 | checksum = "a1e8cdbefb79a9a5a65e0db8b47b723ee907b7c7f8496c76a1770b5c310bab82" 623 | dependencies = [ 624 | "proc-macro2", 625 | "quote", 626 | "unicode-xid", 627 | ] 628 | 629 | [[package]] 630 | name = "termcolor" 631 | version = "1.1.2" 632 | source = "registry+https://github.com/rust-lang/crates.io-index" 633 | checksum = "2dfed899f0eb03f32ee8c6a0aabdb8a7949659e3466561fc0adf54e26d88c5f4" 634 | dependencies = [ 635 | "winapi-util", 636 | ] 637 | 638 | [[package]] 639 | name = "textwrap" 640 | version = "0.11.0" 641 | source = "registry+https://github.com/rust-lang/crates.io-index" 642 | checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" 643 | dependencies = [ 644 | "unicode-width", 645 | ] 646 | 647 | [[package]] 648 | name = "thiserror" 649 | version = "1.0.25" 650 | source = "registry+https://github.com/rust-lang/crates.io-index" 651 | checksum = "fa6f76457f59514c7eeb4e59d891395fab0b2fd1d40723ae737d64153392e9c6" 652 | dependencies = [ 653 | "thiserror-impl", 654 | ] 655 | 656 | [[package]] 657 | name = "thiserror-impl" 658 | version = "1.0.25" 659 | source = "registry+https://github.com/rust-lang/crates.io-index" 660 | checksum = "8a36768c0fbf1bb15eca10defa29526bda730a2376c2ab4393ccfa16fb1a318d" 661 | dependencies = [ 662 | "proc-macro2", 663 | "quote", 664 | "syn", 665 | ] 666 | 667 | [[package]] 668 | name = "tinyvec" 669 | version = "1.2.0" 670 | source = "registry+https://github.com/rust-lang/crates.io-index" 671 | checksum = "5b5220f05bb7de7f3f53c7c065e1199b3172696fe2db9f9c4d8ad9b4ee74c342" 672 | dependencies = [ 673 | "tinyvec_macros", 674 | ] 675 | 676 | [[package]] 677 | name = "tinyvec_macros" 678 | version = "0.1.0" 679 | source = "registry+https://github.com/rust-lang/crates.io-index" 680 | checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" 681 | 682 | [[package]] 683 | name = "tokio" 684 | version = "1.6.1" 685 | source = "registry+https://github.com/rust-lang/crates.io-index" 686 | checksum = "0a38d31d7831c6ed7aad00aa4c12d9375fd225a6dd77da1d25b707346319a975" 687 | dependencies = [ 688 | "autocfg", 689 | "bytes", 690 | "libc", 691 | "memchr", 692 | "mio", 693 | "num_cpus", 694 | "pin-project-lite", 695 | "tokio-macros", 696 | ] 697 | 698 | [[package]] 699 | name = "tokio-macros" 700 | version = "1.2.0" 701 | source = "registry+https://github.com/rust-lang/crates.io-index" 702 | checksum = "c49e3df43841dafb86046472506755d8501c5615673955f6aa17181125d13c37" 703 | dependencies = [ 704 | "proc-macro2", 705 | "quote", 706 | "syn", 707 | ] 708 | 709 | [[package]] 710 | name = "tokio-rustls" 711 | version = "0.22.0" 712 | source = "registry+https://github.com/rust-lang/crates.io-index" 713 | checksum = "bc6844de72e57df1980054b38be3a9f4702aba4858be64dd700181a8a6d0e1b6" 714 | dependencies = [ 715 | "rustls", 716 | "tokio", 717 | "webpki", 718 | ] 719 | 720 | [[package]] 721 | name = "tokio-tungstenite" 722 | version = "0.14.0" 723 | source = "registry+https://github.com/rust-lang/crates.io-index" 724 | checksum = "1e96bb520beab540ab664bd5a9cfeaa1fcd846fa68c830b42e2c8963071251d2" 725 | dependencies = [ 726 | "futures-util", 727 | "log", 728 | "pin-project", 729 | "tokio", 730 | "tungstenite", 731 | ] 732 | 733 | [[package]] 734 | name = "toml" 735 | version = "0.5.8" 736 | source = "registry+https://github.com/rust-lang/crates.io-index" 737 | checksum = "a31142970826733df8241ef35dc040ef98c679ab14d7c3e54d827099b3acecaa" 738 | dependencies = [ 739 | "serde", 740 | ] 741 | 742 | [[package]] 743 | name = "trojan-r" 744 | version = "0.1.0" 745 | dependencies = [ 746 | "async-trait", 747 | "bytes", 748 | "clap", 749 | "env_logger", 750 | "futures-core", 751 | "futures-util", 752 | "log", 753 | "serde", 754 | "sha2", 755 | "tokio", 756 | "tokio-rustls", 757 | "tokio-tungstenite", 758 | "toml", 759 | "webpki", 760 | "webpki-roots", 761 | ] 762 | 763 | [[package]] 764 | name = "tungstenite" 765 | version = "0.13.0" 766 | source = "registry+https://github.com/rust-lang/crates.io-index" 767 | checksum = "5fe8dada8c1a3aeca77d6b51a4f1314e0f4b8e438b7b1b71e3ddaca8080e4093" 768 | dependencies = [ 769 | "base64", 770 | "byteorder", 771 | "bytes", 772 | "http", 773 | "httparse", 774 | "input_buffer", 775 | "log", 776 | "rand", 777 | "sha-1", 778 | "thiserror", 779 | "url", 780 | "utf-8", 781 | ] 782 | 783 | [[package]] 784 | name = "typenum" 785 | version = "1.13.0" 786 | source = "registry+https://github.com/rust-lang/crates.io-index" 787 | checksum = "879f6906492a7cd215bfa4cf595b600146ccfac0c79bcbd1f3000162af5e8b06" 788 | 789 | [[package]] 790 | name = "unicode-bidi" 791 | version = "0.3.5" 792 | source = "registry+https://github.com/rust-lang/crates.io-index" 793 | checksum = "eeb8be209bb1c96b7c177c7420d26e04eccacb0eeae6b980e35fcb74678107e0" 794 | dependencies = [ 795 | "matches", 796 | ] 797 | 798 | [[package]] 799 | name = "unicode-normalization" 800 | version = "0.1.18" 801 | source = "registry+https://github.com/rust-lang/crates.io-index" 802 | checksum = "33717dca7ac877f497014e10d73f3acf948c342bee31b5ca7892faf94ccc6b49" 803 | dependencies = [ 804 | "tinyvec", 805 | ] 806 | 807 | [[package]] 808 | name = "unicode-width" 809 | version = "0.1.8" 810 | source = "registry+https://github.com/rust-lang/crates.io-index" 811 | checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3" 812 | 813 | [[package]] 814 | name = "unicode-xid" 815 | version = "0.2.2" 816 | source = "registry+https://github.com/rust-lang/crates.io-index" 817 | checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" 818 | 819 | [[package]] 820 | name = "untrusted" 821 | version = "0.7.1" 822 | source = "registry+https://github.com/rust-lang/crates.io-index" 823 | checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" 824 | 825 | [[package]] 826 | name = "url" 827 | version = "2.2.2" 828 | source = "registry+https://github.com/rust-lang/crates.io-index" 829 | checksum = "a507c383b2d33b5fc35d1861e77e6b383d158b2da5e14fe51b83dfedf6fd578c" 830 | dependencies = [ 831 | "form_urlencoded", 832 | "idna", 833 | "matches", 834 | "percent-encoding", 835 | ] 836 | 837 | [[package]] 838 | name = "utf-8" 839 | version = "0.7.6" 840 | source = "registry+https://github.com/rust-lang/crates.io-index" 841 | checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" 842 | 843 | [[package]] 844 | name = "vec_map" 845 | version = "0.8.2" 846 | source = "registry+https://github.com/rust-lang/crates.io-index" 847 | checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" 848 | 849 | [[package]] 850 | name = "version_check" 851 | version = "0.9.3" 852 | source = "registry+https://github.com/rust-lang/crates.io-index" 853 | checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe" 854 | 855 | [[package]] 856 | name = "wasi" 857 | version = "0.10.2+wasi-snapshot-preview1" 858 | source = "registry+https://github.com/rust-lang/crates.io-index" 859 | checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6" 860 | 861 | [[package]] 862 | name = "wasm-bindgen" 863 | version = "0.2.74" 864 | source = "registry+https://github.com/rust-lang/crates.io-index" 865 | checksum = "d54ee1d4ed486f78874278e63e4069fc1ab9f6a18ca492076ffb90c5eb2997fd" 866 | dependencies = [ 867 | "cfg-if", 868 | "wasm-bindgen-macro", 869 | ] 870 | 871 | [[package]] 872 | name = "wasm-bindgen-backend" 873 | version = "0.2.74" 874 | source = "registry+https://github.com/rust-lang/crates.io-index" 875 | checksum = "3b33f6a0694ccfea53d94db8b2ed1c3a8a4c86dd936b13b9f0a15ec4a451b900" 876 | dependencies = [ 877 | "bumpalo", 878 | "lazy_static", 879 | "log", 880 | "proc-macro2", 881 | "quote", 882 | "syn", 883 | "wasm-bindgen-shared", 884 | ] 885 | 886 | [[package]] 887 | name = "wasm-bindgen-macro" 888 | version = "0.2.74" 889 | source = "registry+https://github.com/rust-lang/crates.io-index" 890 | checksum = "088169ca61430fe1e58b8096c24975251700e7b1f6fd91cc9d59b04fb9b18bd4" 891 | dependencies = [ 892 | "quote", 893 | "wasm-bindgen-macro-support", 894 | ] 895 | 896 | [[package]] 897 | name = "wasm-bindgen-macro-support" 898 | version = "0.2.74" 899 | source = "registry+https://github.com/rust-lang/crates.io-index" 900 | checksum = "be2241542ff3d9f241f5e2cb6dd09b37efe786df8851c54957683a49f0987a97" 901 | dependencies = [ 902 | "proc-macro2", 903 | "quote", 904 | "syn", 905 | "wasm-bindgen-backend", 906 | "wasm-bindgen-shared", 907 | ] 908 | 909 | [[package]] 910 | name = "wasm-bindgen-shared" 911 | version = "0.2.74" 912 | source = "registry+https://github.com/rust-lang/crates.io-index" 913 | checksum = "d7cff876b8f18eed75a66cf49b65e7f967cb354a7aa16003fb55dbfd25b44b4f" 914 | 915 | [[package]] 916 | name = "web-sys" 917 | version = "0.3.51" 918 | source = "registry+https://github.com/rust-lang/crates.io-index" 919 | checksum = "e828417b379f3df7111d3a2a9e5753706cae29c41f7c4029ee9fd77f3e09e582" 920 | dependencies = [ 921 | "js-sys", 922 | "wasm-bindgen", 923 | ] 924 | 925 | [[package]] 926 | name = "webpki" 927 | version = "0.21.4" 928 | source = "registry+https://github.com/rust-lang/crates.io-index" 929 | checksum = "b8e38c0608262c46d4a56202ebabdeb094cef7e560ca7a226c6bf055188aa4ea" 930 | dependencies = [ 931 | "ring", 932 | "untrusted", 933 | ] 934 | 935 | [[package]] 936 | name = "webpki-roots" 937 | version = "0.21.1" 938 | source = "registry+https://github.com/rust-lang/crates.io-index" 939 | checksum = "aabe153544e473b775453675851ecc86863d2a81d786d741f6b76778f2a48940" 940 | dependencies = [ 941 | "webpki", 942 | ] 943 | 944 | [[package]] 945 | name = "winapi" 946 | version = "0.3.9" 947 | source = "registry+https://github.com/rust-lang/crates.io-index" 948 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 949 | dependencies = [ 950 | "winapi-i686-pc-windows-gnu", 951 | "winapi-x86_64-pc-windows-gnu", 952 | ] 953 | 954 | [[package]] 955 | name = "winapi-i686-pc-windows-gnu" 956 | version = "0.4.0" 957 | source = "registry+https://github.com/rust-lang/crates.io-index" 958 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 959 | 960 | [[package]] 961 | name = "winapi-util" 962 | version = "0.1.5" 963 | source = "registry+https://github.com/rust-lang/crates.io-index" 964 | checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" 965 | dependencies = [ 966 | "winapi", 967 | ] 968 | 969 | [[package]] 970 | name = "winapi-x86_64-pc-windows-gnu" 971 | version = "0.4.0" 972 | source = "registry+https://github.com/rust-lang/crates.io-index" 973 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 974 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "trojan-r" 3 | version = "0.1.0" 4 | authors = ["Page Fault "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | bytes = "1.0" 9 | tokio = {version = "1.6", features = ["rt", "net", "io-util", "rt-multi-thread", "sync", "macros"]} 10 | tokio-rustls = "0.22" 11 | log = "0.4" 12 | async-trait = "0.1" 13 | sha2 = "0.9" 14 | serde = { version = "1.0", features = ["derive"] } 15 | env_logger = "0.8" 16 | toml = "0.5" 17 | clap = "2.33" 18 | webpki = "0.21" 19 | webpki-roots = "0.21" 20 | tokio-tungstenite = "0.14" 21 | futures-core = "0.3" 22 | futures-util = "0.3" 23 | 24 | [profile.release] 25 | lto = true 26 | 27 | [features] 28 | default = ["full"] 29 | client = [] 30 | server = [] 31 | forward = [] 32 | full = ["client", "server", "forward"] -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | default: 2 | cargo build --release 3 | 4 | x86_64-unknown-linux-musl: 5 | cargo build --target $@ --release 6 | 7 | armv7-unknown-linux-musleabihf: 8 | cross build --target $@ --release 9 | 10 | arm-unknown-linux-musleabihf: 11 | cross build --target $@ --release 12 | 13 | aarch64-unknown-linux-musl: 14 | cross build --target $@ --release 15 | 16 | aarch64-linux-android: 17 | cross build --target $@ --release 18 | 19 | armv7-linux-androideabi: 20 | cross build --target $@ --release 21 | 22 | i686-linux-android: 23 | cross build --target $@ --release 24 | 25 | x86_64-linux-android: 26 | cross build --target $@ --release -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Trojan-R 2 | 3 | 高性能的 Trojan 代理,使用 Rust 实现。为嵌入式设备或低性能机器设计。R 意为 **R**ust / **R**apid。 4 | 5 | **Trojan-R 目前为实验性项目,仍处于重度开发中,协议、接口和配置文件格式均可能改变,请勿用于任何生产环境。** 6 | 7 | ## 特性 8 | 9 | - 极致性能 10 | 11 | 牺牲部分灵活性,采用激进的性能优化策略以极力减少不必要的开销。采用[更高效](https://jbp.io/2019/07/01/rustls-vs-openssl-performance.html)的 `rustls` (相较 openssl)建立 TLS 隧道以提升加解密的性能表现。 12 | 13 | 使用 tokio 异步运行时,允许 `Trojan-R` 同时使用所有 CPU 核心,保证低时延和高效的吞吐能力。 14 | 15 | > 需要更多 benchmark 数据和更多优化 16 | 17 | - 低内存占用 18 | 19 | Rust 无 GC 机制,内存占用可被预计。简化的握手和连接流程,仅使用极少的堆内存和复制。 20 | 21 | > 需要更多 benchmark 数据和更多优化 22 | 23 | - 简易配置 24 | 25 | 使用 toml 格式配置,仅需数行配置即可启动完整客户端或服务器。 26 | 27 | - 内存安全 28 | 29 | 使用 Rust 语言实现,可证明的内存安全性。在语法层面保证所有内存操作安全可靠。无竞争条件,无悬挂指针,无 UAF,无 Double Free。 30 | 31 | - 密码学安全 32 | 33 | 使用 `rustls` 建立 TLS 加密安全信道,过时的或不安全的密码学套件[均被禁用](https://docs.rs/rustls/0.18.1/rustls/#non-features)。`Trojan-R` 强制开启服务器证书校验以防止中间人攻击。 34 | 35 | - 隐蔽传输 36 | 37 | `Trojan-R` 使用 TLS 建立代理隧道,难以从正常 TLS 流量中被区分。支持协议回落,在遭到主动探测时将与普通 TLS 服务器表现一致。 38 | 39 | - 跨平台支持 40 | 41 | `Trojan-R` 可被交叉编译,支持 Android, Linux,Windows 和 MacOS 等操作系统,以及 x86,x86_64,armv7,aarch64 等硬件平台。 42 | 43 | ## 非特性 44 | 45 | 由于与项目的设计原则冲突,下列特性不计划实现 46 | 47 | - 统计功能,包括 API 和数据库对接等 48 | 49 | - 路由功能 50 | 51 | - 用户自定义协议栈 52 | 53 | - 透明代理 54 | 55 | 如果需要实现上述功能,请使用其他类似工具与 `Trojan-R` 组合实现。 56 | 57 | ## 设计原则 58 | 59 | - 安全性 60 | 61 | `Trojan-R` 不涉及底层操作,且目前的性能瓶颈与其无关,无使用 unsafe rust 的必要。协议回落和 TLS 配置等安全敏感代码经过仔细考虑和审计,同时也欢迎更多来自开源社区的安全审计。 62 | 63 | 目前 `Trojan-R` 使用 `#![forbid(unsafe_code)]` 禁用 unsafe rust。如未来有必要使用 unsafe rust 时,必须经过严格审计和测试。 64 | 65 | - 使用静态分发而非动态分发 66 | 67 | 协议实现使用统一的 trait。协议嵌套使用静态分发,以保证嵌套协议栈的函数调用关系在编译时被确定,使编译器可以进行内联和更好的优化。 68 | 69 | - 低内存分配 70 | 71 | 减少热点代码的内存分配,用引用替换复制,以实现更高的性能和更低的内存开销。 72 | 73 | - 简洁 74 | 75 | 保持最简洁干净的实现,以保证最低的代码复杂度,尽可能少的性能开销,并增加可靠性和减少攻击面。 76 | 77 | ## 部署和使用 78 | 79 | `Trojan-R` 使用 toml 进行配置,参考 `config` 文件夹下配置文件。 80 | 81 | ## 编译 82 | 83 | ```shell 84 | cargo build --release 85 | ``` 86 | 87 | 交叉编译基于 `cross` 完成,编译前请确认已经安装 `cross` (`cargo install cross`) 88 | 89 | ```shell 90 | make armv7-unknown-linux-musleabihf 91 | ``` 92 | 93 | 编译默认开启链接时优化,以提升性能并减小可执行文件体积,因此编译耗时可能较其他项目更长。 94 | 95 | 编译完成后可以使用 `strip` 去除调试符号表以减少文件体积。 96 | 97 | ## TODOs 98 | 99 | - [ ] 更完善的交互接口和文档 100 | 101 | - [ ] 更多的单元测试和集成测试 102 | 103 | - [ ] 性能调优 104 | 105 | - [ ] 可复现的 benchmark 环境 106 | 107 | - [ ] 实现 lib.rs 和导出函数 108 | 109 | - [x] 分离客户端和服务端 features 110 | 111 | - [ ] Github Actions 112 | 113 | ## 致谢 114 | 115 | - [trojan](https://github.com/trojan-gfw/trojan) 116 | 117 | - [shadowsocks-rust](https://github.com/shadowsocks/shadowsocks-rust) 118 | -------------------------------------------------------------------------------- /config/client.toml: -------------------------------------------------------------------------------- 1 | mode = "client" 2 | log_level = "debug" # optional 3 | 4 | [trojan] 5 | password = "password" 6 | 7 | [socks5] 8 | addr = "127.0.0.1:1080" 9 | 10 | [tls] 11 | addr = "example.com:443" 12 | sni = "example.com" 13 | cert = "cert.pem" # optional 14 | cipher = ["TLS13_AES_128_GCM_SHA256"] # optional 15 | #cipher = ["TLS13_CHACHA20_POLY1305_SHA256","TLS13_AES_256_GCM_SHA384","TLS13_AES_128_GCM_SHA256","TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256","TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256","TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384","TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256","TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384","TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA25"] 16 | 17 | # optional 18 | #[websocket] 19 | #uri = "wss://example.com/trojanpath" 20 | 21 | # optional 22 | #[mux] 23 | #concurrent = 8 24 | #timeout = 30 25 | -------------------------------------------------------------------------------- /config/forward.toml: -------------------------------------------------------------------------------- 1 | mode = "forward" 2 | log_level = "debug" # optional 3 | 4 | [dokodemo] 5 | target_addr = "8.8.8.8:53" 6 | listen_addr = "127.0.0.1:53" 7 | 8 | [trojan] 9 | password = "password" 10 | 11 | [tls] 12 | addr = "example.com:443" 13 | sni = "example.com" 14 | cert = "cert.pem" # optional 15 | cipher = ["TLS13_AES_128_GCM_SHA256"] # optional 16 | # cipher = ["TLS13_CHACHA20_POLY1305_SHA256","TLS13_AES_256_GCM_SHA384","TLS13_AES_128_GCM_SHA256","TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256","TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256","TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384","TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256","TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384","TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA25"] 17 | 18 | # optional 19 | # [websocket] 20 | # uri = "wss://example.com/trojanpath" 21 | -------------------------------------------------------------------------------- /config/server.toml: -------------------------------------------------------------------------------- 1 | mode = "server" 2 | log_level = "debug" # optional 3 | 4 | [trojan] 5 | password = "password" 6 | fallback_addr = "127.0.0.1:80" 7 | 8 | [tls] 9 | addr = "0.0.0.0:443" 10 | sni = "example.com" 11 | cert = "cert.pem" 12 | key = "key.pem" 13 | 14 | # optional 15 | # [plaintext] 16 | # addr = "127.0.0.1:12345" 17 | 18 | # optional 19 | # [websocket] 20 | # path = "/trojanpath" 21 | 22 | # optional 23 | # [mux] 24 | -------------------------------------------------------------------------------- /src/error/mod.rs: -------------------------------------------------------------------------------- 1 | use std::error; 2 | use std::fmt::{self, Debug, Formatter}; 3 | use std::io; 4 | 5 | #[derive(Clone)] 6 | pub struct Error { 7 | pub message: String, 8 | } 9 | 10 | impl Error { 11 | pub fn new(message: S) -> Error 12 | where 13 | S: Into, 14 | { 15 | Error { 16 | message: message.into(), 17 | } 18 | } 19 | } 20 | 21 | impl Debug for Error { 22 | #[inline] 23 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 24 | write!(f, "{}", self.message) 25 | } 26 | } 27 | 28 | impl fmt::Display for Error { 29 | #[inline] 30 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 31 | write!(f, "{}", self.message) 32 | } 33 | } 34 | 35 | impl error::Error for Error {} 36 | 37 | impl From for Error { 38 | fn from(err: io::Error) -> Error { 39 | Error::new(err.to_string()) 40 | } 41 | } 42 | 43 | impl From for io::Error { 44 | fn from(err: Error) -> io::Error { 45 | io::Error::new(io::ErrorKind::Other, err.message) 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | #![forbid(unsafe_code)] 2 | 3 | use clap::{App, Arg}; 4 | 5 | mod error; 6 | mod protocol; 7 | mod proxy; 8 | 9 | #[tokio::main] 10 | async fn main() { 11 | let matches = App::new("trojan-r") 12 | .version("v0.1.0") 13 | .arg( 14 | Arg::with_name("config") 15 | .short("c") 16 | .long("config") 17 | .required(true) 18 | .takes_value(true) 19 | .help(".toml config file name"), 20 | ) 21 | .author("Developed by @p4gefau1t (Page Fault)") 22 | .about("An unidentifiable mechanism that helps you bypass GFW") 23 | .get_matches(); 24 | let filename = matches.value_of("config").unwrap().to_string(); 25 | if let Err(e) = proxy::launch_from_config_filename(filename).await { 26 | println!("failed to launch proxy: {}", e); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/protocol/direct/connector.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | 3 | use async_trait::async_trait; 4 | use tokio::net::{TcpStream, UdpSocket}; 5 | 6 | use crate::protocol::{Address, ProxyConnector}; 7 | 8 | use super::{DirectTcpStream, DirectUdpStream}; 9 | 10 | pub struct DirectConnector {} 11 | 12 | #[async_trait] 13 | impl ProxyConnector for DirectConnector { 14 | type TS = DirectTcpStream; 15 | type US = DirectUdpStream; 16 | 17 | async fn connect_tcp(&self, addr: &Address) -> std::io::Result { 18 | log::debug!("direct: connecting to {}", addr); 19 | let stream = TcpStream::connect(addr.to_string()).await?; 20 | Ok(DirectTcpStream { inner: stream }) 21 | } 22 | 23 | async fn connect_udp(&self) -> std::io::Result { 24 | let socket = Arc::new(UdpSocket::bind(":::0").await?); 25 | Ok(DirectUdpStream { inner: socket }) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/protocol/direct/mod.rs: -------------------------------------------------------------------------------- 1 | use std::{io, pin::Pin, sync::Arc, task::Context, task::Poll}; 2 | 3 | use async_trait::async_trait; 4 | use tokio::{ 5 | io::{AsyncRead, AsyncWrite}, 6 | net::{TcpStream, UdpSocket}, 7 | }; 8 | 9 | use super::ProxyTcpStream; 10 | use crate::protocol::{Address, ProxyUdpStream, UdpRead, UdpWrite}; 11 | 12 | pub mod connector; 13 | 14 | pub struct DirectTcpStream { 15 | inner: TcpStream, 16 | } 17 | 18 | impl DirectTcpStream { 19 | pub fn new(inner: TcpStream) -> Self { 20 | Self { inner } 21 | } 22 | } 23 | 24 | impl AsyncRead for DirectTcpStream { 25 | fn poll_read( 26 | mut self: Pin<&mut Self>, 27 | cx: &mut Context<'_>, 28 | buf: &mut tokio::io::ReadBuf<'_>, 29 | ) -> Poll> { 30 | Pin::new(&mut self.inner).poll_read(cx, buf) 31 | } 32 | } 33 | 34 | impl AsyncWrite for DirectTcpStream { 35 | fn poll_write( 36 | mut self: Pin<&mut Self>, 37 | cx: &mut Context<'_>, 38 | buf: &[u8], 39 | ) -> Poll> { 40 | Pin::new(&mut self.inner).poll_write(cx, buf) 41 | } 42 | 43 | fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 44 | Pin::new(&mut self.inner).poll_flush(cx) 45 | } 46 | 47 | fn poll_shutdown( 48 | mut self: Pin<&mut Self>, 49 | cx: &mut Context<'_>, 50 | ) -> Poll> { 51 | Pin::new(&mut self.inner).poll_shutdown(cx) 52 | } 53 | } 54 | 55 | impl ProxyTcpStream for DirectTcpStream {} 56 | 57 | #[derive(Clone)] 58 | pub struct DirectUdpStream { 59 | inner: Arc, 60 | } 61 | 62 | #[async_trait] 63 | impl UdpRead for DirectUdpStream { 64 | async fn read_from(&mut self, buf: &mut [u8]) -> io::Result<(usize, Address)> { 65 | let (len, addr) = self.inner.recv_from(buf).await?; 66 | Ok((len, Address::SocketAddress(addr))) 67 | } 68 | } 69 | 70 | #[async_trait] 71 | impl UdpWrite for DirectUdpStream { 72 | async fn write_to(&mut self, buf: &[u8], addr: &Address) -> io::Result<()> { 73 | let _ = self.inner.send_to(buf, addr.to_string()).await?; 74 | Ok(()) 75 | } 76 | } 77 | 78 | #[async_trait] 79 | impl ProxyUdpStream for DirectUdpStream { 80 | type R = Self; 81 | type W = Self; 82 | 83 | fn split(self) -> (Self::R, Self::W) { 84 | (self.clone(), self) 85 | } 86 | 87 | fn reunite(r: Self::R, _: Self::W) -> Self { 88 | r 89 | } 90 | 91 | async fn close(self) -> io::Result<()> { 92 | Ok(()) 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/protocol/dokodemo/acceptor.rs: -------------------------------------------------------------------------------- 1 | use crate::protocol::{AcceptResult, Address, ProxyAcceptor, ProxyUdpStream, UdpRead, UdpWrite}; 2 | use async_trait::async_trait; 3 | use serde::Deserialize; 4 | use std::{ 5 | io::Result, 6 | str::FromStr, 7 | sync::{ 8 | atomic::{AtomicBool, Ordering}, 9 | Arc, 10 | }, 11 | }; 12 | use tokio::net::{TcpListener, TcpStream, UdpSocket}; 13 | 14 | #[derive(Deserialize)] 15 | pub struct DokodemoAcceptorConfig { 16 | listen_addr: String, 17 | target_addr: String, 18 | } 19 | 20 | #[derive(Clone)] 21 | pub struct DokodemoUdpStream { 22 | inner: Arc, 23 | addr: Address, 24 | } 25 | 26 | #[async_trait] 27 | impl UdpRead for DokodemoUdpStream { 28 | async fn read_from(&mut self, buf: &mut [u8]) -> Result<(usize, Address)> { 29 | let (len, _) = self.inner.recv_from(buf).await?; 30 | Ok((len, self.addr.clone())) 31 | } 32 | } 33 | 34 | #[async_trait] 35 | impl UdpWrite for DokodemoUdpStream { 36 | async fn write_to(&mut self, buf: &[u8], _: &Address) -> Result<()> { 37 | self.inner.send_to(buf, self.addr.to_string()).await?; 38 | Ok(()) 39 | } 40 | } 41 | 42 | #[async_trait] 43 | impl ProxyUdpStream for DokodemoUdpStream { 44 | type R = Self; 45 | type W = Self; 46 | 47 | fn split(self) -> (Self::R, Self::W) { 48 | (self.clone(), self) 49 | } 50 | 51 | fn reunite(r: Self::R, _: Self::W) -> Self { 52 | r 53 | } 54 | 55 | async fn close(self) -> Result<()> { 56 | Ok(()) 57 | } 58 | } 59 | 60 | pub struct DokodemoAcceptor { 61 | target_addr: Address, 62 | udp_spawned: AtomicBool, 63 | tcp_listener: TcpListener, 64 | } 65 | 66 | #[async_trait] 67 | impl ProxyAcceptor for DokodemoAcceptor { 68 | type TS = TcpStream; 69 | type US = DokodemoUdpStream; 70 | 71 | async fn accept(&self) -> Result> { 72 | if !self.udp_spawned.load(Ordering::Relaxed) { 73 | self.udp_spawned.store(true, Ordering::Relaxed); 74 | let socket = Arc::new(UdpSocket::bind(self.tcp_listener.local_addr().unwrap()).await?); 75 | let udp_stream = DokodemoUdpStream { 76 | inner: socket, 77 | addr: self.target_addr.clone(), 78 | }; 79 | log::info!( 80 | "udp socket listening on {}", 81 | self.tcp_listener.local_addr().unwrap() 82 | ); 83 | return Ok(AcceptResult::Udp(udp_stream)); 84 | } 85 | let (stream, addr) = self.tcp_listener.accept().await?; 86 | log::info!("tcp connection from {}", addr.to_string()); 87 | Ok(AcceptResult::Tcp((stream, self.target_addr.clone()))) 88 | } 89 | } 90 | 91 | impl DokodemoAcceptor { 92 | pub async fn new(config: &DokodemoAcceptorConfig) -> Result { 93 | let tcp_listener = TcpListener::bind(config.listen_addr.clone()).await?; 94 | Ok(DokodemoAcceptor { 95 | target_addr: Address::from_str(&config.target_addr)?, 96 | udp_spawned: AtomicBool::new(false), 97 | tcp_listener, 98 | }) 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/protocol/dokodemo/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod acceptor; 2 | -------------------------------------------------------------------------------- /src/protocol/mod.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use bytes::{Buf, BufMut}; 3 | use fmt::Debug; 4 | use std::{ 5 | fmt::{self, Formatter}, 6 | io::{self, Cursor}, 7 | net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs}, 8 | str::FromStr, 9 | vec, 10 | }; 11 | use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite}; 12 | 13 | use crate::error::Error; 14 | 15 | pub mod direct; 16 | pub mod dokodemo; 17 | pub mod mux; 18 | pub mod plaintext; 19 | pub mod socks5; 20 | pub mod tls; 21 | pub mod trojan; 22 | pub mod websocket; 23 | 24 | fn new_error(message: T) -> io::Error { 25 | return Error::new(format!("protocol: {}", message.to_string())).into(); 26 | } 27 | 28 | pub trait ProxyTcpStream: AsyncRead + AsyncWrite + Send + Sync + Unpin {} 29 | #[derive(Clone, PartialEq, Eq, Hash)] 30 | pub enum Address { 31 | /// Socket address (IP Address) 32 | SocketAddress(SocketAddr), 33 | /// Domain name address 34 | DomainNameAddress(String, u16), 35 | } 36 | 37 | /// Parse `Address` error 38 | #[derive(Debug)] 39 | pub struct AddressError { 40 | message: String, 41 | } 42 | 43 | impl From for io::Error { 44 | fn from(e: AddressError) -> Self { 45 | io::Error::new( 46 | io::ErrorKind::Other, 47 | format!("address error: {}", e.message), 48 | ) 49 | } 50 | } 51 | 52 | impl FromStr for Address { 53 | type Err = AddressError; 54 | 55 | fn from_str(s: &str) -> Result { 56 | match s.parse::() { 57 | Ok(addr) => Ok(Address::SocketAddress(addr)), 58 | Err(..) => { 59 | let mut sp = s.split(':'); 60 | match (sp.next(), sp.next()) { 61 | (Some(dn), Some(port)) => match port.parse::() { 62 | Ok(port) => Ok(Address::DomainNameAddress(dn.to_owned(), port)), 63 | Err(..) => Err(AddressError { 64 | message: s.to_owned(), 65 | }), 66 | }, 67 | (Some(dn), None) => { 68 | // Assume it is 80 (http's default port) 69 | Ok(Address::DomainNameAddress(dn.to_owned(), 80)) 70 | } 71 | _ => Err(AddressError { 72 | message: s.to_owned(), 73 | }), 74 | } 75 | } 76 | } 77 | } 78 | } 79 | impl Address { 80 | const ADDR_TYPE_IPV4: u8 = 1; 81 | const ADDR_TYPE_DOMAIN_NAME: u8 = 3; 82 | const ADDR_TYPE_IPV6: u8 = 4; 83 | 84 | #[inline] 85 | fn new_dummy_address() -> Address { 86 | Address::SocketAddress(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0)) 87 | } 88 | 89 | #[inline] 90 | fn serialized_len(&self) -> usize { 91 | match self { 92 | Address::SocketAddress(SocketAddr::V4(..)) => 1 + 4 + 2, 93 | Address::SocketAddress(SocketAddr::V6(..)) => 1 + 8 * 2 + 2, 94 | Address::DomainNameAddress(ref dmname, _) => 1 + 1 + dmname.len() + 2, 95 | } 96 | } 97 | 98 | async fn read_from_stream(stream: &mut R) -> Result 99 | where 100 | R: AsyncRead + Unpin, 101 | { 102 | let mut addr_type_buf = [0u8; 1]; 103 | let _ = stream.read_exact(&mut addr_type_buf).await?; 104 | 105 | let addr_type = addr_type_buf[0]; 106 | match addr_type { 107 | Self::ADDR_TYPE_IPV4 => { 108 | let mut buf = [0u8; 6]; 109 | stream.read_exact(&mut buf).await?; 110 | let mut cursor = Cursor::new(buf); 111 | 112 | let v4addr = Ipv4Addr::new( 113 | cursor.get_u8(), 114 | cursor.get_u8(), 115 | cursor.get_u8(), 116 | cursor.get_u8(), 117 | ); 118 | let port = cursor.get_u16(); 119 | Ok(Address::SocketAddress(SocketAddr::V4(SocketAddrV4::new( 120 | v4addr, port, 121 | )))) 122 | } 123 | Self::ADDR_TYPE_IPV6 => { 124 | let mut buf = [0u8; 18]; 125 | stream.read_exact(&mut buf).await?; 126 | 127 | let mut cursor = Cursor::new(&buf); 128 | let v6addr = Ipv6Addr::new( 129 | cursor.get_u16(), 130 | cursor.get_u16(), 131 | cursor.get_u16(), 132 | cursor.get_u16(), 133 | cursor.get_u16(), 134 | cursor.get_u16(), 135 | cursor.get_u16(), 136 | cursor.get_u16(), 137 | ); 138 | let port = cursor.get_u16(); 139 | 140 | Ok(Address::SocketAddress(SocketAddr::V6(SocketAddrV6::new( 141 | v6addr, port, 0, 0, 142 | )))) 143 | } 144 | Self::ADDR_TYPE_DOMAIN_NAME => { 145 | let mut length_buf = [0u8; 1]; 146 | let mut addr_buf = [0u8; 255 + 2]; 147 | stream.read_exact(&mut length_buf).await?; 148 | let length = length_buf[0] as usize; 149 | 150 | // Len(Domain) + Len(Port) 151 | stream.read_exact(&mut addr_buf[..length + 2]).await?; 152 | 153 | let domain_buf = &addr_buf[..length]; 154 | let addr = match String::from_utf8(domain_buf.to_vec()) { 155 | Ok(addr) => addr, 156 | Err(..) => return Err(Error::new("invalid address encoding")), 157 | }; 158 | let mut port_buf = &addr_buf[length..length + 2]; 159 | let port = port_buf.get_u16(); 160 | 161 | Ok(Address::DomainNameAddress(addr, port)) 162 | } 163 | _ => { 164 | // Wrong Address Type . Socks5 only supports ipv4, ipv6 and domain name 165 | Err(Error::new(format!( 166 | "not supported address type {:#x}", 167 | addr_type 168 | ))) 169 | } 170 | } 171 | } 172 | 173 | fn read_from_buf(buf: &[u8]) -> io::Result { 174 | let mut cur = Cursor::new(buf); 175 | if cur.remaining() < 1 + 1 { 176 | return Err(new_error("invalid address buffer")); 177 | } 178 | let addr_type = cur.get_u8(); 179 | match addr_type { 180 | Self::ADDR_TYPE_IPV4 => { 181 | if cur.remaining() < 4 + 2 { 182 | return Err(new_error("IPv4 address too short")); 183 | } 184 | let addr = Ipv4Addr::new(cur.get_u8(), cur.get_u8(), cur.get_u8(), cur.get_u8()); 185 | let port = cur.get_u16(); 186 | Ok(Address::SocketAddress(SocketAddr::V4(SocketAddrV4::new( 187 | addr, port, 188 | )))) 189 | } 190 | Self::ADDR_TYPE_DOMAIN_NAME => { 191 | let domain_len = cur.get_u8() as usize; 192 | if cur.remaining() < domain_len { 193 | return Err(new_error("Domain name too short")); 194 | } 195 | let mut domain_name = vec![0u8; domain_len]; 196 | cur.copy_to_slice(&mut domain_name); 197 | let port = cur.get_u16(); 198 | let domain_name = String::from_utf8(domain_name).map_err(|e| { 199 | new_error(format!("invalid utf8 domain name {}", e.to_string())) 200 | })?; 201 | Ok(Address::DomainNameAddress(domain_name, port)) 202 | } 203 | Self::ADDR_TYPE_IPV6 => { 204 | if cur.remaining() < 8 * 2 + 2 { 205 | return Err(new_error("IPv4 address too short")); 206 | } 207 | let addr = Ipv6Addr::new( 208 | cur.get_u16(), 209 | cur.get_u16(), 210 | cur.get_u16(), 211 | cur.get_u16(), 212 | cur.get_u16(), 213 | cur.get_u16(), 214 | cur.get_u16(), 215 | cur.get_u16(), 216 | ); 217 | let port = cur.get_u16(); 218 | Ok(Address::SocketAddress(SocketAddr::V6(SocketAddrV6::new( 219 | addr, port, 0, 0, 220 | )))) 221 | } 222 | _ => Err(new_error(format!("unknown address type {}", addr_type))), 223 | } 224 | } 225 | 226 | fn write_to_buf(&self, buf: &mut B) { 227 | match self { 228 | Self::SocketAddress(SocketAddr::V4(addr)) => { 229 | buf.put_u8(Self::ADDR_TYPE_IPV4); 230 | buf.put_slice(&addr.ip().octets()); 231 | buf.put_u16(addr.port()); 232 | } 233 | Self::SocketAddress(SocketAddr::V6(addr)) => { 234 | buf.put_u8(Self::ADDR_TYPE_IPV6); 235 | for seg in &addr.ip().segments() { 236 | buf.put_u16(*seg); 237 | } 238 | buf.put_u16(addr.port()); 239 | } 240 | Self::DomainNameAddress(domain_name, port) => { 241 | buf.put_u8(Self::ADDR_TYPE_DOMAIN_NAME); 242 | buf.put_u8(domain_name.len() as u8); 243 | buf.put_slice(&domain_name.as_bytes()[..]); 244 | buf.put_u16(*port); 245 | } 246 | } 247 | } 248 | } 249 | 250 | impl Debug for Address { 251 | #[inline] 252 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 253 | match *self { 254 | Address::SocketAddress(ref addr) => write!(f, "{}", addr), 255 | Address::DomainNameAddress(ref addr, ref port) => write!(f, "{}:{}", addr, port), 256 | } 257 | } 258 | } 259 | 260 | impl fmt::Display for Address { 261 | #[inline] 262 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 263 | match *self { 264 | Address::SocketAddress(ref addr) => write!(f, "{}", addr), 265 | Address::DomainNameAddress(ref addr, ref port) => write!(f, "{}:{}", addr, port), 266 | } 267 | } 268 | } 269 | 270 | impl ToSocketAddrs for Address { 271 | type Iter = vec::IntoIter; 272 | 273 | fn to_socket_addrs(&self) -> io::Result> { 274 | match self.clone() { 275 | Address::SocketAddress(addr) => Ok(vec![addr].into_iter()), 276 | Address::DomainNameAddress(addr, port) => (&addr[..], port).to_socket_addrs(), 277 | } 278 | } 279 | } 280 | 281 | impl From for Address { 282 | fn from(s: SocketAddr) -> Address { 283 | Address::SocketAddress(s) 284 | } 285 | } 286 | 287 | impl From<(String, u16)> for Address { 288 | fn from((dn, port): (String, u16)) -> Address { 289 | Address::DomainNameAddress(dn, port) 290 | } 291 | } 292 | 293 | impl From<&Address> for Address { 294 | fn from(addr: &Address) -> Address { 295 | addr.clone() 296 | } 297 | } 298 | 299 | #[async_trait] 300 | pub trait UdpRead: Send + Sync + Unpin { 301 | async fn read_from(&mut self, buf: &mut [u8]) -> io::Result<(usize, Address)>; 302 | } 303 | #[async_trait] 304 | pub trait UdpWrite: Send + Sync + Unpin { 305 | async fn write_to(&mut self, buf: &[u8], addr: &Address) -> io::Result<()>; 306 | } 307 | 308 | #[async_trait] 309 | pub trait ProxyUdpStream: Send + Unpin { 310 | type R: UdpRead; 311 | type W: UdpWrite; 312 | fn split(self) -> (Self::R, Self::W); 313 | fn reunite(r: Self::R, w: Self::W) -> Self; 314 | async fn close(self) -> io::Result<()>; 315 | } 316 | 317 | #[async_trait] 318 | pub trait ProxyConnector: Send + Sync { 319 | type TS: ProxyTcpStream + 'static; 320 | type US: ProxyUdpStream + 'static; 321 | async fn connect_tcp(&self, addr: &Address) -> io::Result; 322 | async fn connect_udp(&self) -> io::Result; 323 | } 324 | 325 | pub enum AcceptResult { 326 | Tcp((T, Address)), 327 | Udp(U), 328 | } 329 | 330 | impl AcceptResult { 331 | pub fn unwrap_tcp_with_addr(self) -> (T, Address) { 332 | match self { 333 | Self::Tcp(t) => t, 334 | _ => unreachable!(), 335 | } 336 | } 337 | } 338 | 339 | #[async_trait] 340 | pub trait ProxyAcceptor: Send + Sync { 341 | type TS: ProxyTcpStream + 'static; 342 | type US: ProxyUdpStream + 'static; 343 | async fn accept(&self) -> io::Result>; 344 | } 345 | 346 | pub struct DummyUdpRead {} 347 | 348 | #[async_trait] 349 | impl UdpRead for DummyUdpRead { 350 | async fn read_from(&mut self, _: &mut [u8]) -> io::Result<(usize, Address)> { 351 | unimplemented!() 352 | } 353 | } 354 | 355 | pub struct DummyUdpWrite {} 356 | 357 | #[async_trait] 358 | impl UdpWrite for DummyUdpWrite { 359 | async fn write_to(&mut self, _: &[u8], _: &Address) -> io::Result<()> { 360 | unimplemented!() 361 | } 362 | } 363 | 364 | pub struct DummyUdpStream {} 365 | 366 | #[async_trait] 367 | impl UdpRead for DummyUdpStream { 368 | async fn read_from(&mut self, _: &mut [u8]) -> io::Result<(usize, Address)> { 369 | unimplemented!() 370 | } 371 | } 372 | 373 | #[async_trait] 374 | impl UdpWrite for DummyUdpStream { 375 | async fn write_to(&mut self, _: &[u8], _: &Address) -> io::Result<()> { 376 | unimplemented!() 377 | } 378 | } 379 | 380 | #[async_trait] 381 | impl ProxyUdpStream for DummyUdpStream { 382 | type R = DummyUdpRead; 383 | type W = DummyUdpWrite; 384 | fn split(self) -> (Self::R, Self::W) { 385 | unimplemented!() 386 | } 387 | fn reunite(_: Self::R, _: Self::W) -> Self { 388 | unimplemented!() 389 | } 390 | async fn close(self) -> io::Result<()> { 391 | unimplemented!() 392 | } 393 | } 394 | -------------------------------------------------------------------------------- /src/protocol/mux/acceptor.rs: -------------------------------------------------------------------------------- 1 | use std::{io, sync::Arc}; 2 | 3 | use async_trait::async_trait; 4 | use io::ErrorKind; 5 | use serde::Deserialize; 6 | use tokio::{ 7 | sync::{ 8 | mpsc::{channel, Receiver}, 9 | Mutex, 10 | }, 11 | task::JoinHandle, 12 | }; 13 | 14 | use super::{MuxHandle, MuxStream, MuxUdpStream, RequestHeader, STREAM_CHANNEL_LEN}; 15 | use crate::protocol::{AcceptResult, Address, ProxyAcceptor}; 16 | 17 | #[derive(Deserialize)] 18 | pub struct MuxAcceptorConfig {} 19 | 20 | pub struct MuxAcceptor { 21 | accept_stream_rx: Arc>>>, 22 | handle: JoinHandle>, 23 | } 24 | 25 | impl Drop for MuxAcceptor { 26 | fn drop(&mut self) { 27 | self.handle.abort(); 28 | } 29 | } 30 | 31 | #[async_trait] 32 | impl ProxyAcceptor for MuxAcceptor { 33 | type TS = MuxStream; 34 | type US = MuxUdpStream; 35 | 36 | async fn accept(&self) -> io::Result> { 37 | if let Some(result) = self.accept_stream_rx.lock().await.recv().await { 38 | Ok(result) 39 | } else { 40 | Err(io::ErrorKind::ConnectionReset.into()) 41 | } 42 | } 43 | } 44 | 45 | impl MuxAcceptor { 46 | pub fn new( 47 | inner: T, 48 | _config: &MuxAcceptorConfig, 49 | ) -> io::Result { 50 | let (accept_stream_tx, accept_stream_rx) = channel(STREAM_CHANNEL_LEN); 51 | let handle: JoinHandle> = tokio::spawn(async move { 52 | loop { 53 | let result = match inner.accept().await { 54 | Ok(r) => r, 55 | Err(e) => { 56 | log::error!("mux accept err: {}", e); 57 | continue; 58 | } 59 | }; 60 | match result { 61 | AcceptResult::Tcp((stream, addr)) => { 62 | let accept_stream_tx = accept_stream_tx.clone(); 63 | let _: JoinHandle> = tokio::spawn(async move { 64 | let valid_magic_addr = { 65 | match &addr { 66 | Address::DomainNameAddress(domain, port) => { 67 | domain == "MUX_CONN" && *port == 0 68 | } 69 | _ => false, 70 | } 71 | }; 72 | if !valid_magic_addr { 73 | log::error!("invalid mux magic address {}", addr.to_string()); 74 | return Err(ErrorKind::InvalidData.into()); 75 | } 76 | log::debug!("new inbound stream for mux"); 77 | let mux_handle = MuxHandle::new(stream); 78 | loop { 79 | let mut stream = mux_handle.accept().await?; 80 | log::debug!("new mux stream {:x} accepted", stream.stream_id); 81 | let header = RequestHeader::read_from(&mut stream).await?; 82 | let result = match header { 83 | RequestHeader::TcpConnect(addr) => { 84 | AcceptResult::Tcp((stream, addr)) 85 | } 86 | RequestHeader::UdpAssociate => { 87 | AcceptResult::Udp(MuxUdpStream { inner: stream }) 88 | } 89 | }; 90 | accept_stream_tx 91 | .send(result) 92 | .await 93 | .map_err(|_| io::ErrorKind::ConnectionAborted)?; 94 | } 95 | }); 96 | } 97 | AcceptResult::Udp(_) => { 98 | log::error!("mux: invalid udp stream"); 99 | } 100 | } 101 | } 102 | }); 103 | Ok(Self { 104 | accept_stream_rx: Arc::new(Mutex::new(accept_stream_rx)), 105 | handle, 106 | }) 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/protocol/mux/connector.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | collections::HashMap, 3 | io, 4 | sync::{atomic::AtomicU32, Arc}, 5 | }; 6 | 7 | use async_trait::async_trait; 8 | use serde::Deserialize; 9 | use tokio::sync::Mutex; 10 | 11 | use super::{new_key, MuxHandle, MuxStream, MuxUdpStream, RequestHeader}; 12 | use crate::protocol::{Address, ProxyConnector}; 13 | 14 | #[derive(Deserialize)] 15 | pub struct MuxConnectorConfig { 16 | concurrent: usize, 17 | } 18 | 19 | pub struct MuxConnector { 20 | handlers: Mutex>, 21 | concurrent: usize, 22 | inner: T, 23 | handle_id_hint: Arc, 24 | } 25 | 26 | impl MuxConnector { 27 | pub fn new(config: &MuxConnectorConfig, inner: T) -> io::Result { 28 | let handlers = Mutex::new(HashMap::new()); 29 | if config.concurrent < 2 { 30 | return Err(io::Error::new( 31 | io::ErrorKind::InvalidData, 32 | "invalid parameters for mux", 33 | )); 34 | } 35 | Ok(Self { 36 | concurrent: config.concurrent, 37 | handlers, 38 | inner, 39 | handle_id_hint: Arc::new(AtomicU32::new(0)), 40 | }) 41 | } 42 | } 43 | 44 | impl MuxConnector { 45 | async fn clean_mux_streams(&self) { 46 | let mut inactive_handle_id = Vec::new(); 47 | let mut handlers = self.handlers.lock().await; 48 | for (handle_id, handle) in handlers.iter() { 49 | let num_streams = handle.established_streams().await; 50 | if num_streams == 0 || handle.is_closed() { 51 | inactive_handle_id.push(*handle_id); 52 | } 53 | log::debug!( 54 | "mux handle {:x}: {}/{}", 55 | *handle_id, 56 | num_streams, 57 | self.concurrent 58 | ); 59 | } 60 | for handle_id in inactive_handle_id.iter() { 61 | let handle = handlers.remove(handle_id).unwrap(); 62 | handle.close().await; // TODO dead lock? 63 | } 64 | } 65 | 66 | async fn spawn_mux_stream(&self) -> io::Result { 67 | let mut handlers = self.handlers.lock().await; 68 | loop { 69 | for (handle_id, handle) in handlers.iter() { 70 | if handle.established_streams().await < self.concurrent { 71 | let stream = match handle.connect().await { 72 | Ok(stream) => stream, 73 | Err(e) => { 74 | log::error!( 75 | "fail to spawn new mux stream from handle {:x}: {}", 76 | *handle_id, 77 | e 78 | ); 79 | handle.close().await; // TODO dead lock? 80 | continue; 81 | } 82 | }; 83 | log::debug!( 84 | "mux stream {:x} spawned from handle {:x}", 85 | stream.stream_id, 86 | handle_id 87 | ); 88 | return Ok(stream); 89 | } 90 | } 91 | let stream = self 92 | .inner 93 | .connect_tcp(&Address::DomainNameAddress("MUX_CONN".to_string(), 0)) 94 | .await?; 95 | let handle = MuxHandle::new(stream); 96 | let handle_id = new_key(&handlers, &self.handle_id_hint); 97 | handlers.insert(handle_id, handle); 98 | log::debug!("new stream spawned for mux"); 99 | } 100 | } 101 | } 102 | 103 | #[async_trait] 104 | impl ProxyConnector for MuxConnector { 105 | type TS = MuxStream; 106 | type US = MuxUdpStream; 107 | 108 | async fn connect_tcp(&self, addr: &Address) -> io::Result { 109 | let mut stream = self.spawn_mux_stream().await?; 110 | self.clean_mux_streams().await; 111 | let header = RequestHeader::TcpConnect(addr.clone()); 112 | header.write_to(&mut stream).await?; 113 | return Ok(stream); 114 | } 115 | 116 | async fn connect_udp(&self) -> io::Result { 117 | let mut stream = self.spawn_mux_stream().await?; 118 | self.clean_mux_streams().await; 119 | let header = RequestHeader::UdpAssociate; 120 | header.write_to(&mut stream).await?; 121 | Ok(MuxUdpStream { inner: stream }) 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/protocol/mux/mod.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use bytes::{Buf, BufMut, Bytes}; 3 | use futures_core::{ready, Future}; 4 | use futures_util::FutureExt; 5 | use tokio::{ 6 | io::{split, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, ReadHalf, WriteHalf}, 7 | sync::{ 8 | mpsc::{ 9 | channel, 10 | error::{SendError, TrySendError}, 11 | Receiver, Sender, 12 | }, 13 | Mutex, 14 | }, 15 | task::JoinHandle, 16 | }; 17 | 18 | use std::{ 19 | cmp::min, 20 | collections::HashMap, 21 | io::{self, Cursor}, 22 | num::Wrapping, 23 | pin::Pin, 24 | sync::{ 25 | atomic::{AtomicBool, AtomicU32, Ordering}, 26 | Arc, 27 | }, 28 | task::{Context, Poll}, 29 | }; 30 | 31 | use super::{trojan::UdpHeader, Address, ProxyTcpStream, ProxyUdpStream, UdpRead, UdpWrite}; 32 | use crate::error::Error; 33 | 34 | pub mod acceptor; 35 | pub mod connector; 36 | 37 | fn new_error(message: T) -> io::Error { 38 | return Error::new(format!("mux: {}", message.to_string())).into(); 39 | } 40 | 41 | const SMUX_VERSION: u8 = 1; 42 | const HEADER_LEN: usize = 8; 43 | const MAX_DATA_LEN: usize = 0xffff; 44 | 45 | const CMD_SYNC: u8 = 0; 46 | const CMD_FINISH: u8 = 1; 47 | const CMD_PUSH: u8 = 2; 48 | const CMD_NOP: u8 = 3; 49 | 50 | const SHARED_CHANNEL_LEN: usize = 0x200; 51 | const PRIVATE_CHANNEL_LEN: usize = 0x50; 52 | const STREAM_CHANNEL_LEN: usize = 0x20; 53 | 54 | const CMD_TCP_CONNECT: u8 = 0x01; 55 | const CMD_UDP_ASSOCIATE: u8 = 0x03; 56 | 57 | enum RequestHeader { 58 | TcpConnect(Address), 59 | UdpAssociate, 60 | } 61 | 62 | impl RequestHeader { 63 | async fn read_from(stream: &mut R) -> io::Result 64 | where 65 | R: AsyncRead + Unpin, 66 | { 67 | let mut cmd = [0u8; 1]; 68 | stream.read_exact(&mut cmd).await?; 69 | let addr = Address::read_from_stream(stream).await?; 70 | match cmd[0] { 71 | CMD_TCP_CONNECT => Ok(Self::TcpConnect(addr)), 72 | CMD_UDP_ASSOCIATE => Ok(Self::UdpAssociate), 73 | _ => Err(new_error("invalid cmd")), 74 | } 75 | } 76 | 77 | async fn write_to(&self, w: &mut W) -> io::Result<()> 78 | where 79 | W: AsyncWrite + Unpin, 80 | { 81 | let dummy_addr = Address::new_dummy_address(); 82 | let (cmd, addr) = match self { 83 | RequestHeader::TcpConnect(addr) => (CMD_TCP_CONNECT, addr), 84 | RequestHeader::UdpAssociate => (CMD_UDP_ASSOCIATE, &dummy_addr), 85 | }; 86 | let mut buf = Vec::with_capacity(1 + addr.serialized_len()); 87 | let cursor = &mut buf; 88 | 89 | cursor.put_u8(cmd); 90 | addr.write_to_buf(cursor); 91 | 92 | w.write(&buf).await?; 93 | Ok(()) 94 | } 95 | } 96 | 97 | struct SyncFrame { 98 | stream_id: u32, 99 | } 100 | 101 | struct PushFrame { 102 | stream_id: u32, 103 | data: Bytes, 104 | } 105 | 106 | struct FinishFrame { 107 | stream_id: u32, 108 | } 109 | 110 | struct NopFrame { 111 | stream_id: u32, 112 | } 113 | 114 | enum MuxFrame { 115 | Sync(SyncFrame), 116 | Push(PushFrame), 117 | Finish(FinishFrame), 118 | Nop(NopFrame), 119 | } 120 | 121 | impl MuxFrame { 122 | async fn write_to(&self, writer: &mut W) -> io::Result<()> { 123 | let (stream_id, command) = match self { 124 | MuxFrame::Sync(f) => (f.stream_id, CMD_SYNC), 125 | MuxFrame::Finish(f) => (f.stream_id, CMD_FINISH), 126 | MuxFrame::Nop(f) => (f.stream_id, CMD_NOP), 127 | MuxFrame::Push(f) => (f.stream_id, CMD_PUSH), 128 | }; 129 | let mut buf = [0u8; HEADER_LEN]; 130 | let mut cursor = &mut buf[..]; 131 | let data_length = if let MuxFrame::Push(f) = self { 132 | f.data.len() 133 | } else { 134 | 0 135 | }; 136 | assert!(data_length <= MAX_DATA_LEN); 137 | cursor.put_u8(SMUX_VERSION); 138 | cursor.put_u8(command); 139 | cursor.put_u16_le(data_length as u16); 140 | cursor.put_u32_le(stream_id); 141 | writer.write(&buf).await?; 142 | if let MuxFrame::Push(f) = self { 143 | writer.write(&f.data).await?; 144 | } 145 | writer.flush().await?; 146 | Ok(()) 147 | } 148 | 149 | async fn read_from(reader: &mut R) -> io::Result { 150 | let mut buf = [0u8; HEADER_LEN]; 151 | reader.read_exact(&mut buf).await?; 152 | 153 | let mut cursor = Cursor::new(buf); 154 | let version = cursor.get_u8(); 155 | if version != SMUX_VERSION { 156 | return Err(new_error("invalid mux version")); 157 | } 158 | let command = cursor.get_u8(); 159 | let length = cursor.get_u16_le(); 160 | let stream_id = cursor.get_u32_le(); 161 | 162 | let frame = match command { 163 | CMD_FINISH => MuxFrame::Finish(FinishFrame { stream_id }), 164 | CMD_NOP => MuxFrame::Nop(NopFrame { stream_id }), 165 | CMD_SYNC => MuxFrame::Sync(SyncFrame { stream_id }), 166 | CMD_PUSH => { 167 | let mut buf = Vec::with_capacity(length as usize); 168 | buf.resize(length as usize, 0); 169 | reader.read_exact(&mut buf).await?; 170 | MuxFrame::Push(PushFrame { 171 | stream_id, 172 | data: Bytes::from(buf), 173 | }) 174 | } 175 | _ => return Err(new_error("invalid mux command")), 176 | }; 177 | 178 | Ok(frame) 179 | } 180 | } 181 | 182 | fn new_key(map: &HashMap, hint: &AtomicU32) -> u32 { 183 | let init_hint = hint.load(Ordering::Relaxed); 184 | let mut key = Wrapping(init_hint + 1); 185 | loop { 186 | if !map.contains_key(&key.0) { 187 | hint.store(key.0, Ordering::Relaxed); 188 | return key.0; 189 | } 190 | key.0 += 1; 191 | if key.0 == init_hint { 192 | panic!(); 193 | } 194 | } 195 | } 196 | 197 | pub struct MuxStream { 198 | tx: Sender, 199 | stream_id: u32, 200 | rx: Receiver, 201 | read_buffer: Option, 202 | write_buffer: Option, 203 | write_future: 204 | Option>> + Send + Sync>>>, 205 | closed: Arc, 206 | } 207 | 208 | impl MuxStream { 209 | #[inline] 210 | fn is_closed(&self) -> bool { 211 | self.closed.load(Ordering::Relaxed) 212 | } 213 | } 214 | 215 | impl AsyncRead for MuxStream { 216 | fn poll_read( 217 | mut self: Pin<&mut Self>, 218 | cx: &mut Context<'_>, 219 | buf: &mut tokio::io::ReadBuf<'_>, 220 | ) -> Poll> { 221 | loop { 222 | if let Some(read_buffer) = &mut self.read_buffer { 223 | if read_buffer.len() <= buf.remaining() { 224 | buf.put_slice(read_buffer); 225 | self.read_buffer = None; 226 | } else { 227 | let len = buf.remaining(); 228 | buf.put_slice(&read_buffer[..len]); 229 | read_buffer.advance(len); 230 | } 231 | return Poll::Ready(Ok(())); 232 | } 233 | if let Some(f) = ready!(self.rx.poll_recv(cx)) { 234 | self.read_buffer = Some(f.data); 235 | } else { 236 | return Poll::Ready(Err(io::ErrorKind::ConnectionReset.into())); 237 | } 238 | } 239 | } 240 | } 241 | 242 | impl MuxStream { 243 | fn try_send_frame(&mut self, frame: MuxFrame) -> io::Result { 244 | if self.is_closed() { 245 | return Err(io::ErrorKind::ConnectionReset.into()); 246 | } 247 | // FIXME horrible workaround 248 | if let Err(e) = self.tx.try_send(frame) { 249 | match e { 250 | TrySendError::Full(f) => { 251 | let tx = self.tx.clone(); 252 | let fut = Box::pin(async move { 253 | tx.send(f).await?; 254 | Ok(()) 255 | }); 256 | self.write_future = Some(fut); 257 | Ok(false) 258 | } 259 | TrySendError::Closed(_) => Err(io::ErrorKind::ConnectionReset.into()), 260 | } 261 | } else { 262 | Ok(true) 263 | } 264 | } 265 | } 266 | 267 | impl AsyncWrite for MuxStream { 268 | fn poll_write( 269 | mut self: Pin<&mut Self>, 270 | cx: &mut Context<'_>, 271 | buf: &[u8], 272 | ) -> Poll> { 273 | if self.is_closed() { 274 | return Poll::Ready(Err(io::ErrorKind::ConnectionReset.into())); 275 | } 276 | loop { 277 | if let Some(fut) = &mut self.write_future { 278 | if ready!(fut.poll_unpin(cx)).is_err() { 279 | return Poll::Ready(Err(io::ErrorKind::ConnectionReset.into())); 280 | } 281 | self.write_future = None; 282 | if self.write_buffer.is_none() { 283 | return Poll::Ready(Ok(buf.len())); 284 | } 285 | } 286 | 287 | let stream_id = self.stream_id; 288 | if let Some(mut data) = self.write_buffer.take() { 289 | let mut all_sent = true; 290 | while data.len() > MAX_DATA_LEN { 291 | let fragment = data.split_off(MAX_DATA_LEN); 292 | let frame = MuxFrame::Push(PushFrame { 293 | stream_id, 294 | data: fragment, 295 | }); 296 | if !self.try_send_frame(frame)? { 297 | // pending 298 | all_sent = false; 299 | break; 300 | } 301 | } 302 | if !all_sent { 303 | self.write_buffer = Some(data); 304 | // poll write_future 305 | continue; 306 | } 307 | // the last frame 308 | let frame = MuxFrame::Push(PushFrame { stream_id, data }); 309 | if !self.try_send_frame(frame)? { 310 | // poll write_future, return Ready once the future is done 311 | self.write_buffer = None; 312 | continue; 313 | } else { 314 | return Poll::Ready(Ok(buf.len())); 315 | } 316 | } 317 | 318 | // self.write_buffer == None, first polling 319 | let data = Bytes::copy_from_slice(buf); 320 | self.write_buffer = Some(data); 321 | } 322 | } 323 | 324 | fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { 325 | return Poll::Ready(Ok(())); 326 | } 327 | 328 | fn poll_shutdown( 329 | mut self: Pin<&mut Self>, 330 | cx: &mut Context<'_>, 331 | ) -> Poll> { 332 | loop { 333 | if let Some(fut) = &mut self.write_future { 334 | if ready!(fut.poll_unpin(cx)).is_err() { 335 | return Poll::Ready(Err(io::ErrorKind::ConnectionReset.into())); 336 | } 337 | self.write_future = None; 338 | if self.write_buffer.is_none() { 339 | break; 340 | } 341 | } 342 | let stream_id = self.stream_id; 343 | if let Some(mut data) = self.write_buffer.take() { 344 | let mut all_sent = true; 345 | while data.len() > MAX_DATA_LEN { 346 | let fragment = data.split_off(MAX_DATA_LEN); 347 | let frame = MuxFrame::Push(PushFrame { 348 | stream_id, 349 | data: fragment, 350 | }); 351 | if !self.try_send_frame(frame)? { 352 | all_sent = false; 353 | break; 354 | } 355 | } 356 | if !all_sent { 357 | self.write_buffer = Some(data); 358 | // poll write_future 359 | continue; 360 | } 361 | // the last frame 362 | let frame = MuxFrame::Push(PushFrame { stream_id, data }); 363 | if !self.try_send_frame(frame)? { 364 | self.write_buffer = None; 365 | continue; 366 | } else { 367 | break; 368 | } 369 | } 370 | break; 371 | } 372 | 373 | self.closed.store(true, Ordering::Relaxed); 374 | let frame = MuxFrame::Finish(FinishFrame { 375 | stream_id: self.stream_id, 376 | }); 377 | 378 | // FIXME horrible workaround 379 | if let Err(e) = self.tx.try_send(frame) { 380 | let tx = self.tx.clone(); 381 | match e { 382 | TrySendError::Full(frame) => { 383 | tokio::spawn(async move { 384 | let _ = tx.send(frame).await; 385 | }); 386 | } 387 | TrySendError::Closed(_) => {} 388 | } 389 | } 390 | return Poll::Ready(Ok(())); 391 | } 392 | } 393 | 394 | impl Drop for MuxStream { 395 | fn drop(&mut self) { 396 | if !self.closed.load(Ordering::Relaxed) { 397 | log::debug!("MuxStream was dropped without calling shutdown"); 398 | self.closed.store(true, Ordering::Relaxed); 399 | let frame = MuxFrame::Finish(FinishFrame { 400 | stream_id: self.stream_id, 401 | }); 402 | if let Err(e) = self.tx.try_send(frame) { 403 | match e { 404 | TrySendError::Full(f) => { 405 | let tx = self.tx.clone(); 406 | tokio::spawn(async move { 407 | let _ = tx.send(f).await; 408 | }); 409 | } 410 | TrySendError::Closed(_) => {} 411 | } 412 | } 413 | } 414 | } 415 | } 416 | 417 | impl MuxStream { 418 | fn new( 419 | stream_id: u32, 420 | tx: Sender, 421 | rx: Receiver, 422 | ) -> (Self, Arc) { 423 | let closed = Arc::new(AtomicBool::new(false)); 424 | ( 425 | MuxStream { 426 | rx, 427 | read_buffer: None, 428 | write_buffer: None, 429 | closed: closed.clone(), 430 | tx, 431 | stream_id, 432 | write_future: None, 433 | }, 434 | closed, 435 | ) 436 | } 437 | } 438 | 439 | impl ProxyTcpStream for MuxStream {} 440 | 441 | #[async_trait] 442 | impl UdpRead for ReadHalf { 443 | async fn read_from(&mut self, buf: &mut [u8]) -> io::Result<(usize, Address)> { 444 | let udp_header = UdpHeader::read_from(self).await?; 445 | let len = min(udp_header.payload_len as usize, buf.len()); 446 | self.read_exact(&mut buf[..len]).await?; 447 | Ok((len, udp_header.address)) 448 | } 449 | } 450 | 451 | #[async_trait] 452 | impl UdpWrite for WriteHalf { 453 | async fn write_to(&mut self, buf: &[u8], addr: &Address) -> io::Result<()> { 454 | let len = min(buf.len(), MAX_DATA_LEN); 455 | let udp_header = UdpHeader::new(addr, len); 456 | udp_header.write_to(self).await?; 457 | self.write(buf).await?; 458 | Ok(()) 459 | } 460 | } 461 | 462 | pub struct MuxUdpStream { 463 | inner: MuxStream, 464 | } 465 | 466 | #[async_trait] 467 | impl ProxyUdpStream for MuxUdpStream { 468 | type R = ReadHalf; 469 | type W = WriteHalf; 470 | 471 | fn split(self) -> (Self::R, Self::W) { 472 | split(self.inner) 473 | } 474 | 475 | fn reunite(r: Self::R, w: Self::W) -> Self { 476 | MuxUdpStream { 477 | inner: r.unsplit(w), 478 | } 479 | } 480 | 481 | async fn close(mut self) -> io::Result<()> { 482 | self.inner.shutdown().await 483 | } 484 | } 485 | 486 | struct MuxStreamHandle { 487 | closed: Arc, 488 | tx: Sender, 489 | } 490 | 491 | impl MuxStreamHandle { 492 | #[inline] 493 | fn close(&self) { 494 | self.closed.store(true, Ordering::Relaxed); 495 | } 496 | } 497 | 498 | struct MuxHandle { 499 | read_handle: JoinHandle>, 500 | write_handle: JoinHandle>, 501 | write_tx: Sender, 502 | accept_stream_rx: Arc>>, 503 | mux_map: Arc>>, 504 | closed: Arc, 505 | stream_id_hint: Arc, 506 | } 507 | 508 | impl Drop for MuxHandle { 509 | fn drop(&mut self) { 510 | self.read_handle.abort(); 511 | self.write_handle.abort(); 512 | } 513 | } 514 | 515 | impl MuxHandle { 516 | fn new(inner: T) -> Self { 517 | let (mut r, mut w) = split(inner); 518 | let mux_map = Arc::new(Mutex::new(HashMap::new())); 519 | let (write_tx, mut write_rx) = channel(SHARED_CHANNEL_LEN); 520 | let (accept_stream_tx, accept_stream_rx) = channel(STREAM_CHANNEL_LEN); 521 | let closed = Arc::new(AtomicBool::new(false)); 522 | let read_handle: JoinHandle> = { 523 | let write_tx = write_tx.clone(); 524 | let mux_map = mux_map.clone(); 525 | let closed = closed.clone(); 526 | tokio::spawn(async move { 527 | async fn echo_finish_frame( 528 | stream_id: u32, 529 | write_tx: &Sender, 530 | ) -> io::Result<()> { 531 | let new_frame = MuxFrame::Finish(FinishFrame { stream_id }); 532 | write_tx 533 | .send(new_frame) 534 | .await 535 | .map_err(|_| io::ErrorKind::ConnectionReset)?; 536 | log::debug!("echo finish frame {:x}", stream_id); 537 | Ok(()) 538 | } 539 | let fut = { 540 | let mux_map = mux_map.clone(); 541 | // stupid workaround 542 | async move { 543 | if false { 544 | return Err(io::Error::new(io::ErrorKind::ConnectionReset, "")); 545 | } 546 | if false { 547 | return Ok(()); 548 | } 549 | loop { 550 | let frame = MuxFrame::read_from(&mut r).await?; 551 | match frame { 552 | MuxFrame::Sync(f) => { 553 | let stream_id = f.stream_id; 554 | let (tx, rx) = channel(PRIVATE_CHANNEL_LEN); 555 | let (stream, closed) = 556 | MuxStream::new(stream_id, write_tx.clone(), rx); 557 | mux_map 558 | .lock() 559 | .await 560 | .insert(f.stream_id, MuxStreamHandle { tx, closed }); 561 | accept_stream_tx 562 | .send(stream) 563 | .await 564 | .map_err(|_| io::ErrorKind::ConnectionReset)?; 565 | } 566 | MuxFrame::Push(f) => { 567 | let stream_id = f.stream_id; 568 | let tx = { 569 | let m = mux_map.lock().await; 570 | if let Some(handle) = m.get(&stream_id) { 571 | handle.tx.clone() 572 | } else { 573 | log::debug!( 574 | "invalid frame recvd, stream_id = {:x}", 575 | stream_id 576 | ); 577 | continue; 578 | } 579 | }; 580 | if let Err(_) = tx.send(f).await { 581 | log::debug!( 582 | "frame recvd but the stream {:x} is closed", 583 | stream_id 584 | ); 585 | if let Some(_) = mux_map.lock().await.remove(&stream_id) { 586 | echo_finish_frame(stream_id, &write_tx).await?; 587 | } 588 | } 589 | } 590 | MuxFrame::Finish(f) => { 591 | let stream_id = f.stream_id; 592 | if let Some(stream_handle) = 593 | mux_map.lock().await.remove(&stream_id) 594 | { 595 | stream_handle.close(); 596 | echo_finish_frame(stream_id, &write_tx).await?; 597 | } 598 | 599 | log::debug!("remote shutdown stream {:x}", stream_id); 600 | } 601 | MuxFrame::Nop(_) => {} 602 | } 603 | } 604 | } 605 | }; 606 | let _ = fut.await; 607 | closed.store(true, Ordering::Relaxed); 608 | mux_map.lock().await.clear(); 609 | log::debug!("mux read err"); 610 | Ok(()) 611 | }) 612 | }; 613 | let write_handle: JoinHandle> = { 614 | let mux_map = mux_map.clone(); 615 | let closed = closed.clone(); 616 | tokio::spawn(async move { 617 | let fut = { 618 | let mux_map = mux_map.clone(); 619 | async move { 620 | // Stupid workaround 621 | if false { 622 | return Err(io::Error::new(io::ErrorKind::ConnectionReset, "")); 623 | } 624 | loop { 625 | if let Some(mut frame) = write_rx.recv().await { 626 | match &mut frame { 627 | MuxFrame::Push(p) => { 628 | assert!(p.data.len() < MAX_DATA_LEN); 629 | } 630 | MuxFrame::Finish(f) => { 631 | log::debug!("local shutdown stream {:x}", f.stream_id); 632 | if let None = mux_map.lock().await.remove(&f.stream_id) { 633 | continue; 634 | } 635 | } 636 | _ => {} 637 | } 638 | frame.write_to(&mut w).await?; 639 | } else { 640 | log::debug!("all write_tx are closed",); 641 | return Ok(()); 642 | } 643 | } 644 | } 645 | }; 646 | if let Err(e) = fut.await { 647 | log::error!("mux write err {}", e); 648 | closed.store(true, Ordering::Relaxed); 649 | } 650 | mux_map.lock().await.clear(); 651 | Ok(()) 652 | }) 653 | }; 654 | Self { 655 | read_handle, 656 | write_handle, 657 | write_tx, 658 | accept_stream_rx: Arc::new(Mutex::new(accept_stream_rx)), 659 | mux_map, 660 | closed, 661 | stream_id_hint: Arc::new(AtomicU32::new(0)), 662 | } 663 | } 664 | 665 | async fn generate_stream_id(&self) -> u32 { 666 | let mux_map = self.mux_map.lock().await; 667 | let stream_id = new_key(&mux_map, &self.stream_id_hint); 668 | stream_id 669 | } 670 | 671 | async fn connect(&self) -> io::Result { 672 | let stream_id = self.generate_stream_id().await; 673 | let (tx, rx) = channel(PRIVATE_CHANNEL_LEN); 674 | let frame = MuxFrame::Sync(SyncFrame { stream_id }); 675 | self.write_tx 676 | .send(frame) 677 | .await 678 | .map_err(|_| io::ErrorKind::ConnectionReset)?; 679 | let (stream, closed) = MuxStream::new(stream_id, self.write_tx.clone(), rx); 680 | self.mux_map 681 | .lock() 682 | .await 683 | .insert(stream_id, MuxStreamHandle { closed, tx }); 684 | Ok(stream) 685 | } 686 | 687 | async fn accept(&self) -> io::Result { 688 | if let Some(stream) = self.accept_stream_rx.lock().await.recv().await { 689 | Ok(stream) 690 | } else { 691 | Err(io::ErrorKind::ConnectionReset.into()) 692 | } 693 | } 694 | 695 | #[inline] 696 | async fn established_streams(&self) -> usize { 697 | self.mux_map.lock().await.len() 698 | } 699 | 700 | #[inline] 701 | fn is_closed(&self) -> bool { 702 | self.closed.load(Ordering::Relaxed) 703 | } 704 | 705 | #[inline] 706 | async fn close(&self) { 707 | self.closed.store(true, Ordering::Relaxed); 708 | 709 | // drop inner 710 | self.read_handle.abort(); 711 | self.write_handle.abort(); 712 | 713 | let mut mux_map = self.mux_map.lock().await; 714 | for (_, stream_handle) in mux_map.iter() { 715 | stream_handle.close(); 716 | } 717 | mux_map.clear(); 718 | } 719 | } 720 | -------------------------------------------------------------------------------- /src/protocol/plaintext/acceptor.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | use async_trait::async_trait; 4 | use serde::Deserialize; 5 | use tokio::net::TcpListener; 6 | 7 | use crate::protocol::{ 8 | direct::DirectTcpStream, AcceptResult, Address, DummyUdpStream, ProxyAcceptor, 9 | }; 10 | 11 | #[derive(Deserialize)] 12 | pub struct PlaintextAcceptorConfig { 13 | addr: String, 14 | } 15 | 16 | pub struct PlaintextAcceptor { 17 | inner: TcpListener, 18 | } 19 | 20 | #[async_trait] 21 | impl ProxyAcceptor for PlaintextAcceptor { 22 | type TS = DirectTcpStream; 23 | type US = DummyUdpStream; 24 | 25 | async fn accept(&self) -> io::Result> { 26 | let (stream, addr) = self.inner.accept().await?; 27 | let addr = Address::from(addr); 28 | Ok(AcceptResult::Tcp((DirectTcpStream::new(stream), addr))) 29 | } 30 | } 31 | 32 | impl PlaintextAcceptor { 33 | pub async fn new(config: &PlaintextAcceptorConfig) -> io::Result { 34 | let listener = TcpListener::bind(&config.addr).await?; 35 | Ok(Self { inner: listener }) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/protocol/plaintext/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod acceptor; 2 | -------------------------------------------------------------------------------- /src/protocol/socks5/acceptor.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use bytes::{BufMut, BytesMut}; 3 | use serde::Deserialize; 4 | use std::{io, net::SocketAddr, sync::Arc}; 5 | use tokio::{ 6 | io::AsyncReadExt, 7 | net::{TcpListener, TcpStream, UdpSocket}, 8 | sync::{ 9 | broadcast::{channel, Receiver, Sender}, 10 | RwLock, 11 | }, 12 | }; 13 | 14 | use super::{ 15 | new_error, Command, HandshakeRequest, HandshakeResponse, TcpRequestHeader, TcpResponseHeader, 16 | UdpAssociateHeader, AUTH_METHOD_NONE, 17 | }; 18 | use crate::protocol::{ 19 | AcceptResult, Address, ProxyAcceptor, ProxyTcpStream, ProxyUdpStream, UdpRead, UdpWrite, 20 | }; 21 | 22 | #[derive(Deserialize)] 23 | pub struct Socks5AcceptorConfig { 24 | addr: String, 25 | } 26 | 27 | pub struct Socks5UdpStream { 28 | src_addr: Arc>>, 29 | inner: Arc, 30 | shutdown_tx: Sender<()>, 31 | shutdown_rx: Receiver<()>, 32 | } 33 | 34 | const UDP_BUFFER_SIZE: usize = 0x2000; 35 | 36 | #[async_trait] 37 | impl UdpRead for Socks5UdpStream { 38 | async fn read_from(&mut self, buf: &mut [u8]) -> io::Result<(usize, Address)> { 39 | let mut recv_buf = [0u8; UDP_BUFFER_SIZE]; 40 | let (recv_len, addr) = tokio::select! { 41 | result = self.inner.recv_from(&mut recv_buf) => { 42 | result? 43 | } 44 | _ = self.shutdown_rx.recv() => { 45 | return Err(io::ErrorKind::ConnectionReset.into()); 46 | } 47 | }; 48 | 49 | let src_address = self.src_addr.read().await.clone(); 50 | if src_address.is_none() { 51 | // first packet 52 | self.src_addr.write().await.replace(addr); 53 | } else if src_address.unwrap() != addr { 54 | return Err(new_error("udp packet from unknown source")); 55 | } 56 | log::debug!("recv_len={}", recv_len); 57 | let header = UdpAssociateHeader::read_from_buf(&recv_buf[..recv_len])?; 58 | let header_len = header.serialized_len(); 59 | let payload_len = recv_len - header_len; 60 | buf[..payload_len].copy_from_slice(&recv_buf[header_len..recv_len]); 61 | log::debug!("payload={}, addr={}", payload_len, header.address); 62 | Ok((payload_len, header.address)) 63 | } 64 | } 65 | 66 | #[async_trait] 67 | impl UdpWrite for Socks5UdpStream { 68 | async fn write_to(&mut self, buf: &[u8], addr: &Address) -> io::Result<()> { 69 | let header = UdpAssociateHeader::new(0, addr.clone()); 70 | let mut send_buf = BytesMut::with_capacity(header.serialized_len() + buf.len()); 71 | header.write_to_buf(&mut send_buf); 72 | send_buf.put_slice(buf); 73 | let address = self.src_addr.read().await; 74 | if address.is_none() { 75 | return Err(new_error("uninitialized udp socket")); 76 | } 77 | let address = address.unwrap(); 78 | self.inner.send_to(&send_buf, address).await?; 79 | Ok(()) 80 | } 81 | } 82 | 83 | #[async_trait] 84 | impl ProxyUdpStream for Socks5UdpStream { 85 | type R = Self; 86 | type W = Self; 87 | 88 | fn split(self) -> (Self::R, Self::W) { 89 | let a = self; 90 | let b = Self { 91 | src_addr: a.src_addr.clone(), 92 | inner: a.inner.clone(), 93 | shutdown_rx: a.shutdown_tx.subscribe(), 94 | shutdown_tx: a.shutdown_tx.clone(), 95 | }; 96 | (a, b) 97 | } 98 | 99 | fn reunite(r: Self::R, _: Self::W) -> Self { 100 | r 101 | } 102 | 103 | async fn close(self) -> io::Result<()> { 104 | Ok(()) 105 | } 106 | } 107 | 108 | pub struct Socks5Acceptor { 109 | tcp_listener: TcpListener, 110 | } 111 | 112 | impl Socks5Acceptor { 113 | pub async fn new(config: &Socks5AcceptorConfig) -> io::Result { 114 | let tcp_listener = TcpListener::bind(config.addr.to_owned()).await?; 115 | Ok(Self { tcp_listener }) 116 | } 117 | } 118 | 119 | impl ProxyTcpStream for TcpStream {} 120 | 121 | #[async_trait] 122 | impl ProxyAcceptor for Socks5Acceptor { 123 | type TS = TcpStream; 124 | type US = Socks5UdpStream; 125 | 126 | async fn accept(&self) -> io::Result> { 127 | let (mut stream, addr) = self.tcp_listener.accept().await?; 128 | log::info!("socks5 stream from address {}", addr); 129 | 130 | // 1. handshake 131 | let req = HandshakeRequest::read_from(&mut stream).await?; 132 | if !req.methods.contains(&AUTH_METHOD_NONE) { 133 | return Err(new_error("invalid handshake method")); 134 | } 135 | let resp = HandshakeResponse::new(AUTH_METHOD_NONE); 136 | resp.write_to(&mut stream).await?; 137 | 138 | // 2. parse 139 | let req = TcpRequestHeader::read_from(&mut stream).await?; 140 | 141 | // 3. respond 142 | return match req.command { 143 | Command::TcpConnect => { 144 | let resp = 145 | TcpResponseHeader::new(Address::SocketAddress(self.tcp_listener.local_addr()?)); 146 | resp.write_to(&mut stream).await?; 147 | Ok(AcceptResult::Tcp((stream, req.address))) 148 | } 149 | Command::UdpAssociate => { 150 | log::debug!("udp associate"); 151 | let ip = self.tcp_listener.local_addr().unwrap().ip(); 152 | let socket_addr = SocketAddr::new(ip, 0); 153 | let udp_socket = Arc::new(UdpSocket::bind(socket_addr).await?); 154 | let resp = TcpResponseHeader::new(Address::SocketAddress(udp_socket.local_addr()?)); 155 | log::debug!( 156 | "udp socket listening on {}", 157 | udp_socket.local_addr().unwrap() 158 | ); 159 | let (shutdown_tx, shutdown_rx) = channel(16); 160 | resp.write_to(&mut stream).await?; 161 | { 162 | let shutdown_tx = shutdown_tx.clone(); 163 | // keep tcp connection alive 164 | tokio::spawn(async move { 165 | let mut buf = [0u8; 0x10]; 166 | let _ = stream.read(&mut buf).await; 167 | log::debug!("shutting down udp session.."); 168 | let _ = shutdown_tx.send(()); 169 | }); 170 | } 171 | Ok(AcceptResult::Udp(Socks5UdpStream { 172 | inner: udp_socket, 173 | src_addr: Arc::new(RwLock::new(None)), 174 | shutdown_rx, 175 | shutdown_tx, 176 | })) 177 | } 178 | }; 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /src/protocol/socks5/mod.rs: -------------------------------------------------------------------------------- 1 | use crate::error::Error; 2 | use std::io; 3 | 4 | pub mod acceptor; 5 | 6 | use std::{fmt::Debug, u8, vec}; 7 | 8 | use bytes::{BufMut, BytesMut}; 9 | use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; 10 | 11 | use super::Address; 12 | 13 | const VERSION: u8 = 0x05; 14 | 15 | const AUTH_METHOD_NONE: u8 = 0x00; 16 | 17 | const CMD_TCP_CONNECT: u8 = 0x01; 18 | const CMD_UDP_ASSOCIATE: u8 = 0x03; 19 | 20 | const REPLY_SUCCEEDED: u8 = 0x00; 21 | 22 | fn new_error(message: T) -> io::Error { 23 | return Error::new(format!("socks: {}", message.to_string())).into(); 24 | } 25 | 26 | #[derive(Clone, Debug, Copy)] 27 | enum Command { 28 | /// CONNECT command (TCP tunnel) 29 | TcpConnect, 30 | /// UDP ASSOCIATE command 31 | UdpAssociate, 32 | } 33 | 34 | impl Command { 35 | #[inline] 36 | fn from_u8(code: u8) -> Option { 37 | match code { 38 | CMD_TCP_CONNECT => Some(Command::TcpConnect), 39 | CMD_UDP_ASSOCIATE => Some(Command::UdpAssociate), 40 | _ => None, 41 | } 42 | } 43 | } 44 | 45 | /// TCP request header after handshake 46 | /// 47 | /// ```plain 48 | /// +----+-----+-------+------+----------+----------+ 49 | /// |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT | 50 | /// +----+-----+-------+------+----------+----------+ 51 | /// | 1 | 1 | X'00' | 1 | Variable | 2 | 52 | /// +----+-----+-------+------+----------+----------+ 53 | /// ``` 54 | #[derive(Clone, Debug)] 55 | struct TcpRequestHeader { 56 | /// SOCKS5 command 57 | command: Command, 58 | /// Remote address 59 | address: Address, 60 | } 61 | 62 | impl TcpRequestHeader { 63 | /// Read from a reader 64 | async fn read_from(r: &mut R) -> io::Result 65 | where 66 | R: AsyncRead + Unpin, 67 | { 68 | let mut buf = [0u8; 3]; 69 | let _ = r.read_exact(&mut buf).await?; 70 | 71 | let ver = buf[0]; 72 | if ver != VERSION { 73 | return Err(new_error(format!("unsupported socks version {:#x}", ver))); 74 | } 75 | 76 | let cmd = buf[1]; 77 | let command = match Command::from_u8(cmd) { 78 | Some(c) => c, 79 | None => { 80 | return Err(new_error(format!("unsupported command {:#x}", cmd))); 81 | } 82 | }; 83 | 84 | let address = Address::read_from_stream(r).await?; 85 | Ok(TcpRequestHeader { command, address }) 86 | } 87 | } 88 | 89 | /// TCP response header 90 | /// 91 | /// ```plain 92 | /// +----+-----+-------+------+----------+----------+ 93 | /// |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT | 94 | /// +----+-----+-------+------+----------+----------+ 95 | /// | 1 | 1 | X'00' | 1 | Variable | 2 | 96 | /// +----+-----+-------+------+----------+----------+ 97 | /// ``` 98 | #[derive(Clone, Debug)] 99 | struct TcpResponseHeader { 100 | /// Reply address 101 | address: Address, 102 | } 103 | 104 | impl TcpResponseHeader { 105 | /// Creates a response header 106 | fn new(address: Address) -> TcpResponseHeader { 107 | TcpResponseHeader { address } 108 | } 109 | 110 | /// Write to a writer 111 | async fn write_to(&self, w: &mut W) -> io::Result<()> 112 | where 113 | W: AsyncWrite + Unpin, 114 | { 115 | let mut buf = BytesMut::with_capacity(self.serialized_len()); 116 | self.write_to_buf(&mut buf); 117 | w.write(&buf).await?; 118 | Ok(()) 119 | } 120 | 121 | /// Writes to buffer 122 | fn write_to_buf(&self, buf: &mut B) { 123 | let TcpResponseHeader { ref address } = *self; 124 | buf.put_slice(&[VERSION, REPLY_SUCCEEDED, 0x00]); 125 | address.write_to_buf(buf); 126 | } 127 | 128 | /// Length in bytes 129 | #[inline] 130 | fn serialized_len(&self) -> usize { 131 | self.address.serialized_len() + 3 132 | } 133 | } 134 | 135 | /// SOCKS5 handshake request packet 136 | /// 137 | /// ```plain 138 | /// +----+----------+----------+ 139 | /// |VER | NMETHODS | METHODS | 140 | /// +----+----------+----------+ 141 | /// | 5 | 1 | 1 to 255 | 142 | /// +----+----------+----------| 143 | /// ``` 144 | #[derive(Clone, Debug)] 145 | struct HandshakeRequest { 146 | methods: Vec, 147 | } 148 | 149 | impl HandshakeRequest { 150 | /// Read from a reader 151 | async fn read_from(r: &mut R) -> io::Result 152 | where 153 | R: AsyncRead + Unpin, 154 | { 155 | let mut buf = [0u8; 2]; 156 | let _ = r.read_exact(&mut buf).await?; 157 | 158 | let ver = buf[0]; 159 | let nmet = buf[1]; 160 | 161 | if ver != VERSION { 162 | use std::io::{Error, ErrorKind}; 163 | let err = Error::new( 164 | ErrorKind::InvalidData, 165 | format!("unsupported socks version {:#x}", ver), 166 | ); 167 | return Err(err); 168 | } 169 | 170 | let mut methods = vec![0u8; nmet as usize]; 171 | let _ = r.read_exact(&mut methods).await?; 172 | 173 | Ok(HandshakeRequest { methods }) 174 | } 175 | } 176 | 177 | /// SOCKS5 handshake response packet 178 | /// 179 | /// ```plain 180 | /// +----+--------+ 181 | /// |VER | METHOD | 182 | /// +----+--------+ 183 | /// | 1 | 1 | 184 | /// +----+--------+ 185 | /// ``` 186 | #[derive(Clone, Debug, Copy)] 187 | struct HandshakeResponse { 188 | chosen_method: u8, 189 | } 190 | 191 | impl HandshakeResponse { 192 | /// Creates a handshake response 193 | fn new(cm: u8) -> HandshakeResponse { 194 | HandshakeResponse { chosen_method: cm } 195 | } 196 | 197 | /// Write to a writer 198 | async fn write_to(self, w: &mut W) -> io::Result<()> 199 | where 200 | W: AsyncWrite + Unpin, 201 | { 202 | let mut buf = BytesMut::with_capacity(self.serialized_len()); 203 | self.write_to_buf(&mut buf); 204 | w.write_all(&buf).await 205 | } 206 | 207 | /// Write to buffer 208 | fn write_to_buf(self, buf: &mut B) { 209 | buf.put_slice(&[VERSION, self.chosen_method]); 210 | } 211 | 212 | /// Length in bytes 213 | fn serialized_len(self) -> usize { 214 | 2 215 | } 216 | } 217 | 218 | /// UDP ASSOCIATE request header 219 | /// 220 | /// ```plain 221 | /// +----+------+------+----------+----------+----------+ 222 | /// |RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA | 223 | /// +----+------+------+----------+----------+----------+ 224 | /// | 2 | 1 | 1 | Variable | 2 | Variable | 225 | /// +----+------+------+----------+----------+----------+ 226 | /// ``` 227 | #[derive(Clone, Debug)] 228 | struct UdpAssociateHeader { 229 | /// Fragment 230 | frag: u8, 231 | /// Remote address 232 | address: Address, 233 | } 234 | 235 | impl UdpAssociateHeader { 236 | /// Creates a header 237 | fn new(frag: u8, address: Address) -> UdpAssociateHeader { 238 | UdpAssociateHeader { frag, address } 239 | } 240 | 241 | fn read_from_buf(buf: &[u8]) -> io::Result { 242 | if buf.len() <= 3 { 243 | return Err(new_error("packet too short")); 244 | } 245 | let addr = Address::read_from_buf(&buf[3..])?; 246 | Ok(UdpAssociateHeader::new(0, addr)) 247 | } 248 | 249 | fn write_to_buf(&self, buf: &mut B) { 250 | buf.put_slice(&[0x00, 0x00, 0x00]); 251 | self.address.write_to_buf(buf); 252 | } 253 | 254 | /// Length in bytes 255 | #[inline] 256 | fn serialized_len(&self) -> usize { 257 | 3 + self.address.serialized_len() 258 | } 259 | } 260 | -------------------------------------------------------------------------------- /src/protocol/tls/acceptor.rs: -------------------------------------------------------------------------------- 1 | use crate::protocol::{ 2 | tls::{get_cipher_suite, load_cert, load_key, new_error}, 3 | AcceptResult, Address, DummyUdpStream, ProxyAcceptor, ProxyTcpStream, 4 | }; 5 | use async_trait::async_trait; 6 | use serde::Deserialize; 7 | use std::{io, path::Path, sync::Arc}; 8 | use tokio::net::{TcpListener, TcpStream}; 9 | use tokio_rustls::{ 10 | rustls::{NoClientAuth, ServerConfig}, 11 | server::TlsStream, 12 | TlsAcceptor, 13 | }; 14 | 15 | #[derive(Deserialize)] 16 | pub struct TrojanTlsAcceptorConfig { 17 | addr: String, 18 | cert: String, 19 | key: String, 20 | cipher: Option>, 21 | } 22 | 23 | pub struct TrojanTlsAcceptor { 24 | tls_acceptor: TlsAcceptor, 25 | tcp_listener: TcpListener, 26 | } 27 | 28 | impl ProxyTcpStream for TlsStream {} 29 | 30 | #[async_trait] 31 | impl ProxyAcceptor for TrojanTlsAcceptor { 32 | type TS = TlsStream; 33 | type US = DummyUdpStream; 34 | 35 | async fn accept(&self) -> io::Result> { 36 | let (stream, addr) = self.tcp_listener.accept().await?; 37 | log::info!("tcp connection from {}", addr); 38 | let stream = self.tls_acceptor.accept(stream).await?; 39 | Ok(AcceptResult::Tcp((stream, Address::SocketAddress(addr)))) 40 | } 41 | } 42 | 43 | impl TrojanTlsAcceptor { 44 | pub async fn new(config: &TrojanTlsAcceptorConfig) -> io::Result { 45 | let tcp_listener = TcpListener::bind(config.addr.to_owned()).await?; 46 | log::debug!("tls listen addr = {}", config.addr); 47 | 48 | let cert_path = Path::new(&config.cert); 49 | let key_path = Path::new(&config.key); 50 | let certs = load_cert(&cert_path)?; 51 | let mut keys = load_key(&key_path)?; 52 | 53 | let mut tls_config = ServerConfig::new(NoClientAuth::new()); 54 | tls_config 55 | .set_single_cert(certs, keys.remove(0)) 56 | .map_err(|e| new_error(format!("invalid cert {}", e.to_string())))?; 57 | 58 | tls_config.ciphersuites = get_cipher_suite(config.cipher.clone())?; 59 | 60 | let tls_acceptor = TlsAcceptor::from(Arc::new(tls_config)); 61 | Ok(Self { 62 | tcp_listener, 63 | tls_acceptor, 64 | }) 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/protocol/tls/connector.rs: -------------------------------------------------------------------------------- 1 | use crate::protocol::{Address, DummyUdpStream, ProxyConnector, ProxyTcpStream}; 2 | use async_trait::async_trait; 3 | use serde::Deserialize; 4 | use std::{ 5 | fs::File, 6 | io::{self, BufReader}, 7 | path::Path, 8 | sync::Arc, 9 | }; 10 | use tokio::net::TcpStream; 11 | use tokio_rustls::{client::TlsStream, rustls::ClientConfig, TlsConnector}; 12 | use webpki::DNSNameRef; 13 | 14 | use super::get_cipher_suite; 15 | 16 | #[derive(Deserialize)] 17 | pub struct TrojanTlsConnectorConfig { 18 | addr: String, 19 | sni: String, 20 | cipher: Option>, 21 | cert: Option, 22 | } 23 | 24 | pub struct TrojanTlsConnector { 25 | sni: String, 26 | server_addr: String, 27 | tls_config: Arc, 28 | } 29 | 30 | impl ProxyTcpStream for TlsStream {} 31 | 32 | impl TrojanTlsConnector { 33 | pub fn new(config: &TrojanTlsConnectorConfig) -> io::Result { 34 | let mut tls_config = ClientConfig::new(); 35 | 36 | tls_config.ciphersuites = get_cipher_suite(config.cipher.clone())?; 37 | 38 | if let Some(ref cert_path) = config.cert { 39 | let cert_path = Path::new(cert_path); 40 | tls_config 41 | .root_store 42 | .add_pem_file(&mut BufReader::new(File::open(cert_path)?)) 43 | .unwrap(); 44 | } else { 45 | tls_config 46 | .root_store 47 | .add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS); 48 | } 49 | 50 | Ok(Self { 51 | sni: config.sni.clone(), 52 | server_addr: config.addr.clone(), 53 | tls_config: Arc::new(tls_config), 54 | }) 55 | } 56 | } 57 | 58 | #[async_trait] 59 | impl ProxyConnector for TrojanTlsConnector { 60 | type TS = TlsStream; 61 | type US = DummyUdpStream; 62 | 63 | async fn connect_tcp(&self, _: &Address) -> io::Result { 64 | let stream = TcpStream::connect(&self.server_addr).await?; 65 | stream.set_nodelay(true)?; 66 | 67 | let dns_name = DNSNameRef::try_from_ascii_str(&self.sni) 68 | .map_err(|e| io::Error::new(io::ErrorKind::NotFound, e.to_string()))?; 69 | let stream = TlsConnector::from(self.tls_config.clone()) 70 | .connect(dns_name, stream) 71 | .await?; 72 | 73 | log::info!("connected to {}", self.server_addr); 74 | Ok(stream) 75 | } 76 | 77 | async fn connect_udp(&self) -> io::Result { 78 | unimplemented!() 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/protocol/tls/mod.rs: -------------------------------------------------------------------------------- 1 | use tokio_rustls::rustls::{ 2 | internal::pemfile, Certificate, CipherSuite, PrivateKey, SupportedCipherSuite, ALL_CIPHERSUITES, 3 | }; 4 | 5 | use crate::error::Error; 6 | use std::{ 7 | fs::File, 8 | io::{self, BufReader}, 9 | path::Path, 10 | }; 11 | 12 | pub mod acceptor; 13 | pub mod connector; 14 | 15 | fn new_error(message: T) -> io::Error { 16 | return Error::new(format!("tls: {}", message.to_string())).into(); 17 | } 18 | 19 | fn load_cert(path: &Path) -> io::Result> { 20 | pemfile::certs(&mut BufReader::new(File::open(path)?)) 21 | .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid tls cert")) 22 | } 23 | 24 | fn load_key(path: &Path) -> io::Result> { 25 | let pkcs8_key = pemfile::pkcs8_private_keys(&mut BufReader::new(File::open(path)?)) 26 | .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid tls pkcs8 key"))?; 27 | if pkcs8_key.len() != 0 { 28 | return Ok(pkcs8_key); 29 | } 30 | let rsa_key = pemfile::rsa_private_keys(&mut BufReader::new(File::open(path)?)) 31 | .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid tls rsa key"))?; 32 | if rsa_key.len() != 0 { 33 | return Ok(rsa_key); 34 | } 35 | return Err(new_error("no valid key found")); 36 | } 37 | 38 | fn get_cipher_name(cipher: &SupportedCipherSuite) -> &'static str { 39 | /* 40 | /// A list of all the cipher suites supported by rustls. 41 | pub static ALL_CIPHERSUITES: [&SupportedCipherSuite; 9] = [ 42 | // TLS1.3 suites 43 | &TLS13_CHACHA20_POLY1305_SHA256, 44 | &TLS13_AES_256_GCM_SHA384, 45 | &TLS13_AES_128_GCM_SHA256, 46 | 47 | // TLS1.2 suites 48 | &TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 49 | &TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 50 | &TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 51 | &TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 52 | &TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 53 | &TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 54 | ]; 55 | */ 56 | match cipher.suite { 57 | CipherSuite::TLS13_CHACHA20_POLY1305_SHA256 => "TLS13_CHACHA20_POLY1305_SHA256", 58 | CipherSuite::TLS13_AES_256_GCM_SHA384 => "TLS13_AES_256_GCM_SHA384", 59 | CipherSuite::TLS13_AES_128_GCM_SHA256 => "TLS13_AES_128_GCM_SHA256", 60 | CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 => { 61 | "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256" 62 | } 63 | CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 => { 64 | "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256" 65 | } 66 | CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 => { 67 | "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384" 68 | } 69 | CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 => { 70 | "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" 71 | } 72 | CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 => { 73 | "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384" 74 | } 75 | CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 => { 76 | "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" 77 | } 78 | _ => "???", 79 | } 80 | } 81 | 82 | fn get_cipher_suite(cipher: Option>) -> io::Result> { 83 | if cipher.is_none() { 84 | return Ok(ALL_CIPHERSUITES.to_vec()); 85 | } 86 | let cipher = cipher.unwrap(); 87 | let mut result = Vec::new(); 88 | 89 | for name in cipher { 90 | let mut found = false; 91 | for i in ALL_CIPHERSUITES.to_vec() { 92 | if name == get_cipher_name(i) { 93 | result.push(i); 94 | found = true; 95 | log::debug!("cipher: {} applied", name); 96 | break; 97 | } 98 | } 99 | if !found { 100 | return Err(new_error(format!("bad cipher: {}", name))); 101 | } 102 | } 103 | Ok(result) 104 | } 105 | -------------------------------------------------------------------------------- /src/protocol/trojan/acceptor.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use bytes::Buf; 3 | use serde::Deserialize; 4 | use std::{io, str::FromStr}; 5 | use tokio::{io::AsyncWriteExt, net::TcpStream}; 6 | 7 | use crate::protocol::{trojan::RequestHeader, AcceptResult, Address, ProxyAcceptor}; 8 | use crate::proxy::relay_tcp; 9 | 10 | use super::{new_error, password_to_hash, TrojanUdpStream, HASH_STR_LEN}; 11 | 12 | #[derive(Deserialize)] 13 | pub struct TrojanAcceptorConfig { 14 | password: String, 15 | fallback_addr: String, 16 | } 17 | 18 | pub struct TrojanAcceptor { 19 | valid_hash: [u8; HASH_STR_LEN], 20 | fallback_addr: Address, 21 | inner: T, 22 | } 23 | 24 | #[async_trait] 25 | impl ProxyAcceptor for TrojanAcceptor { 26 | type TS = T::TS; 27 | type US = TrojanUdpStream; 28 | async fn accept(&self) -> io::Result> { 29 | let (mut stream, addr) = self.inner.accept().await?.unwrap_tcp_with_addr(); 30 | let mut first_packet = Vec::new(); 31 | match RequestHeader::read_from(&mut stream, &self.valid_hash, &mut first_packet).await { 32 | Ok(header) => match header { 33 | RequestHeader::TcpConnect(_, addr) => { 34 | log::info!("trojan tcp stream {}", addr); 35 | Ok(AcceptResult::Tcp((stream, addr))) 36 | } 37 | RequestHeader::UdpAssociate(_) => { 38 | log::info!("trojan udp stream {}", addr); 39 | Ok(AcceptResult::Udp(TrojanUdpStream::new(stream))) 40 | } 41 | }, 42 | Err(e) => { 43 | log::debug!("first packet {:x?}", first_packet); 44 | let fallback_addr = self.fallback_addr.clone(); 45 | log::warn!("invalid trojan request, falling back to {}", fallback_addr); 46 | tokio::spawn(async move { 47 | let inbound = stream; 48 | let mut outbound = TcpStream::connect(fallback_addr.to_string()).await.unwrap(); 49 | let _ = outbound.write(&first_packet).await; 50 | relay_tcp(inbound, outbound).await; 51 | }); 52 | Err(new_error(format!("invalid packet: {}", e.to_string()))) 53 | } 54 | } 55 | } 56 | } 57 | 58 | impl TrojanAcceptor { 59 | pub fn new(config: &TrojanAcceptorConfig, inner: T) -> io::Result { 60 | let fallback_addr = Address::from_str(&config.fallback_addr)?; 61 | let mut valid_hash = [0u8; HASH_STR_LEN]; 62 | password_to_hash(&config.password) 63 | .as_bytes() 64 | .copy_to_slice(&mut valid_hash); 65 | Ok(Self { 66 | fallback_addr, 67 | valid_hash, 68 | inner, 69 | }) 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/protocol/trojan/connector.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use bytes::Buf; 3 | use serde::Deserialize; 4 | use std::io; 5 | 6 | use crate::protocol::{Address, ProxyConnector}; 7 | 8 | use super::{new_error, password_to_hash, RequestHeader, TrojanUdpStream, HASH_STR_LEN}; 9 | 10 | #[derive(Deserialize)] 11 | pub struct TrojanConnectorConfig { 12 | password: String, 13 | } 14 | 15 | pub struct TrojanConnector { 16 | inner: T, 17 | hash: [u8; HASH_STR_LEN], 18 | } 19 | 20 | impl TrojanConnector { 21 | pub fn new(config: &TrojanConnectorConfig, inner: T) -> io::Result { 22 | if config.password.len() < 1 { 23 | return Err(new_error("no valid password found")); 24 | } 25 | let mut hash = [0u8; HASH_STR_LEN]; 26 | password_to_hash(&config.password) 27 | .as_bytes() 28 | .copy_to_slice(&mut hash); 29 | Ok(Self { inner, hash }) 30 | } 31 | } 32 | 33 | #[async_trait] 34 | impl ProxyConnector for TrojanConnector { 35 | type TS = T::TS; 36 | type US = TrojanUdpStream; 37 | 38 | async fn connect_tcp(&self, addr: &Address) -> io::Result { 39 | let mut stream = self.inner.connect_tcp(addr).await?; 40 | let header = RequestHeader::TcpConnect(self.hash.clone(), addr.clone()); 41 | header.write_to(&mut stream).await?; 42 | Ok(stream) 43 | } 44 | 45 | async fn connect_udp(&self) -> io::Result { 46 | let udp_dummy_addr = Address::new_dummy_address(); 47 | let mut stream = self.inner.connect_tcp(&udp_dummy_addr).await?; 48 | let header = RequestHeader::UdpAssociate(self.hash.clone()); 49 | header.write_to(&mut stream).await?; 50 | Ok(TrojanUdpStream::new(stream)) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/protocol/trojan/mod.rs: -------------------------------------------------------------------------------- 1 | use crate::error::Error; 2 | use async_trait::async_trait; 3 | use bytes::BufMut; 4 | use sha2::{Digest, Sha224}; 5 | use std::{fmt::Write, io}; 6 | use tokio::io::{split, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, ReadHalf, WriteHalf}; 7 | 8 | use super::{Address, ProxyTcpStream, ProxyUdpStream, UdpRead, UdpWrite}; 9 | 10 | pub mod acceptor; 11 | pub mod connector; 12 | 13 | const HASH_STR_LEN: usize = 56; 14 | 15 | fn new_error(message: T) -> io::Error { 16 | return Error::new(format!("trojan: {}", message.to_string())).into(); 17 | } 18 | 19 | fn password_to_hash(s: T) -> String { 20 | let mut hasher = Sha224::new(); 21 | hasher.update(&s.to_string().into_bytes()); 22 | let h = hasher.finalize(); 23 | let mut s = String::with_capacity(HASH_STR_LEN); 24 | for i in h { 25 | write!(s, "{:02x}", i).unwrap(); 26 | } 27 | s 28 | } 29 | 30 | const CMD_TCP_CONNECT: u8 = 0x01; 31 | const CMD_UDP_ASSOCIATE: u8 = 0x03; 32 | 33 | /// ```plain 34 | /// +-----------------------+---------+----------------+---------+----------+ 35 | /// | hex(SHA224(password)) | CRLF | Trojan Request | CRLF | Payload | 36 | /// +-----------------------+---------+----------------+---------+----------+ 37 | /// | 56 | X'0D0A' | Variable | X'0D0A' | Variable | 38 | /// +-----------------------+---------+----------------+---------+----------+ 39 | /// 40 | /// where Trojan Request is a SOCKS5-like request: 41 | /// 42 | /// +-----+------+----------+----------+ 43 | /// | CMD | ATYP | DST.ADDR | DST.PORT | 44 | /// +-----+------+----------+----------+ 45 | /// | 1 | 1 | Variable | 2 | 46 | /// +-----+------+----------+----------+ 47 | /// 48 | /// where: 49 | /// 50 | /// o CMD 51 | /// o CONNECT X'01' 52 | /// o UDP ASSOCIATE X'03' 53 | /// o ATYP address type of following address 54 | /// o IP V4 address: X'01' 55 | /// o DOMAINNAME: X'03' 56 | /// o IP V6 address: X'04' 57 | /// o DST.ADDR desired destination address 58 | /// o DST.PORT desired destination port in network octet order 59 | /// ``` 60 | enum RequestHeader { 61 | TcpConnect([u8; HASH_STR_LEN], Address), 62 | UdpAssociate([u8; HASH_STR_LEN]), 63 | } 64 | 65 | impl RequestHeader { 66 | async fn read_from( 67 | stream: &mut R, 68 | valid_hash: &[u8], 69 | first_packet: &mut Vec, 70 | ) -> io::Result 71 | where 72 | R: AsyncRead + Unpin, 73 | { 74 | let mut hash_buf = [0u8; HASH_STR_LEN]; 75 | let len = stream.read(&mut hash_buf).await?; 76 | if len != HASH_STR_LEN { 77 | first_packet.extend_from_slice(&hash_buf[..len]); 78 | return Err(new_error("first packet too short")); 79 | } 80 | 81 | if valid_hash != hash_buf { 82 | first_packet.extend_from_slice(&hash_buf); 83 | return Err(new_error(format!( 84 | "invalid password hash: {}", 85 | String::from_utf8_lossy(&hash_buf) 86 | ))); 87 | } 88 | 89 | let mut crlf_buf = [0u8; 2]; 90 | let mut cmd_buf = [0u8; 1]; 91 | 92 | stream.read_exact(&mut crlf_buf).await?; 93 | stream.read_exact(&mut cmd_buf).await?; 94 | let addr = Address::read_from_stream(stream).await?; 95 | stream.read_exact(&mut crlf_buf).await?; 96 | 97 | match cmd_buf[0] { 98 | CMD_TCP_CONNECT => Ok(Self::TcpConnect(hash_buf, addr)), 99 | CMD_UDP_ASSOCIATE => Ok(Self::UdpAssociate(hash_buf)), 100 | _ => Err(new_error("invalid command")), 101 | } 102 | } 103 | 104 | async fn write_to(&self, w: &mut W) -> io::Result<()> 105 | where 106 | W: AsyncWrite + Unpin, 107 | { 108 | let udp_dummy_addr = Address::new_dummy_address(); 109 | let (hash, addr, cmd) = match self { 110 | RequestHeader::TcpConnect(hash, addr) => (hash, addr, CMD_TCP_CONNECT), 111 | RequestHeader::UdpAssociate(hash) => (hash, &udp_dummy_addr, CMD_UDP_ASSOCIATE), 112 | }; 113 | 114 | let header_len = HASH_STR_LEN + 2 + 1 + addr.serialized_len() + 2; 115 | let mut buf = Vec::with_capacity(header_len); 116 | 117 | let cursor = &mut buf; 118 | let crlf = b"\r\n"; 119 | cursor.put_slice(hash); 120 | cursor.put_slice(crlf); 121 | cursor.put_u8(cmd); 122 | addr.write_to_buf(cursor); 123 | cursor.put_slice(crlf); 124 | 125 | w.write(&buf).await?; 126 | Ok(()) 127 | } 128 | } 129 | 130 | /// ```plain 131 | /// +------+----------+----------+--------+---------+----------+ 132 | /// | ATYP | DST.ADDR | DST.PORT | Length | CRLF | Payload | 133 | /// +------+----------+----------+--------+---------+----------+ 134 | /// | 1 | Variable | 2 | 2 | X'0D0A' | Variable | 135 | /// +------+----------+----------+--------+---------+----------+ 136 | /// ``` 137 | pub struct UdpHeader { 138 | pub address: Address, 139 | pub payload_len: u16, 140 | } 141 | 142 | impl UdpHeader { 143 | #[inline] 144 | pub fn new(addr: &Address, payload_len: usize) -> Self { 145 | Self { 146 | address: addr.clone(), 147 | payload_len: payload_len as u16, 148 | } 149 | } 150 | 151 | pub async fn read_from(stream: &mut R) -> io::Result 152 | where 153 | R: AsyncRead + Unpin, 154 | { 155 | let addr = Address::read_from_stream(stream).await?; 156 | let mut buf = [0u8; 2]; 157 | stream.read_exact(&mut buf).await?; 158 | let len = ((buf[0] as u16) << 8) | (buf[1] as u16); 159 | stream.read_exact(&mut buf).await?; 160 | log::debug!("udp addr={} len={}", addr, len); 161 | Ok(Self { 162 | address: addr, 163 | payload_len: len, 164 | }) 165 | } 166 | 167 | pub async fn write_to(&self, w: &mut W) -> io::Result<()> 168 | where 169 | W: AsyncWrite + Unpin, 170 | { 171 | let mut buf = Vec::with_capacity(self.address.serialized_len() + 2 + 1); 172 | let cursor = &mut buf; 173 | self.address.write_to_buf(cursor); 174 | cursor.put_u16(self.payload_len); 175 | cursor.put_slice(b"\r\n"); 176 | w.write(&buf).await?; 177 | Ok(()) 178 | } 179 | } 180 | 181 | pub struct TrojanUdpReader { 182 | inner: T, 183 | } 184 | 185 | #[async_trait] 186 | impl UdpRead for TrojanUdpReader { 187 | async fn read_from(&mut self, buf: &mut [u8]) -> io::Result<(usize, Address)> { 188 | let header = UdpHeader::read_from(&mut self.inner).await?; 189 | self.inner 190 | .read_exact(&mut buf[..header.payload_len as usize]) 191 | .await?; 192 | Ok((header.payload_len as usize, header.address)) 193 | } 194 | } 195 | 196 | pub struct TrojanUdpWriter { 197 | inner: T, 198 | } 199 | 200 | #[async_trait] 201 | impl UdpWrite for TrojanUdpWriter { 202 | async fn write_to(&mut self, buf: &[u8], addr: &Address) -> io::Result<()> { 203 | let header = UdpHeader::new(addr, buf.len()); 204 | header.write_to(&mut self.inner).await?; 205 | self.inner.write(buf).await?; 206 | Ok(()) 207 | } 208 | } 209 | 210 | pub struct TrojanUdpStream { 211 | reader: TrojanUdpReader>, 212 | writer: TrojanUdpWriter>, 213 | } 214 | 215 | impl TrojanUdpStream { 216 | pub fn new(inner: T) -> Self { 217 | let (reader, writer) = split(inner); 218 | let reader = TrojanUdpReader { inner: reader }; 219 | let writer = TrojanUdpWriter { inner: writer }; 220 | Self { reader, writer } 221 | } 222 | } 223 | 224 | #[async_trait] 225 | impl ProxyUdpStream for TrojanUdpStream { 226 | type R = TrojanUdpReader>; 227 | type W = TrojanUdpWriter>; 228 | 229 | fn split(self) -> (Self::R, Self::W) { 230 | (self.reader, self.writer) 231 | } 232 | 233 | fn reunite(r: Self::R, w: Self::W) -> Self { 234 | Self { 235 | reader: r, 236 | writer: w, 237 | } 238 | } 239 | 240 | async fn close(self) -> io::Result<()> { 241 | let mut inner = self.reader.inner.unsplit(self.writer.inner); 242 | inner.shutdown().await?; 243 | Ok(()) 244 | } 245 | } 246 | -------------------------------------------------------------------------------- /src/protocol/websocket/acceptor.rs: -------------------------------------------------------------------------------- 1 | use super::{new_error, BinaryWsStream}; 2 | use crate::protocol::{AcceptResult, DummyUdpStream, ProxyAcceptor}; 3 | use async_trait::async_trait; 4 | use log::error; 5 | use serde::Deserialize; 6 | use std::io; 7 | use tokio_tungstenite::{ 8 | accept_hdr_async_with_config, 9 | tungstenite::{ 10 | handshake::server::{Callback, ErrorResponse, Request, Response}, 11 | http::StatusCode, 12 | }, 13 | }; 14 | 15 | #[derive(Deserialize)] 16 | pub struct WebSocketAcceptorConfig { 17 | path: String, 18 | } 19 | 20 | struct WebSocketCallback { 21 | path: String, 22 | } 23 | 24 | impl Callback for WebSocketCallback { 25 | fn on_request(self, request: &Request, response: Response) -> Result { 26 | if request.uri().to_string() != self.path { 27 | let mut resp = ErrorResponse::new(None); 28 | *resp.status_mut() = StatusCode::NOT_FOUND; 29 | error!( 30 | "invalid websocket path: {}, expected: {}", 31 | request.uri(), 32 | self.path 33 | ); 34 | Err(resp) 35 | } else { 36 | Ok(response) 37 | } 38 | } 39 | } 40 | 41 | pub struct WebSocketAcceptor { 42 | path: String, 43 | inner: T, 44 | } 45 | 46 | #[async_trait] 47 | impl ProxyAcceptor for WebSocketAcceptor { 48 | type TS = BinaryWsStream; 49 | type US = DummyUdpStream; 50 | 51 | async fn accept(&self) -> io::Result> { 52 | let (stream, addr) = self.inner.accept().await?.unwrap_tcp_with_addr(); 53 | let stream = accept_hdr_async_with_config( 54 | stream, 55 | WebSocketCallback { 56 | path: self.path.clone(), 57 | }, 58 | None, 59 | ) 60 | .await 61 | .map_err(|e| new_error(e))?; 62 | let stream = BinaryWsStream::new(stream); 63 | Ok(AcceptResult::Tcp((stream, addr))) 64 | } 65 | } 66 | 67 | impl WebSocketAcceptor { 68 | pub fn new(config: &WebSocketAcceptorConfig, inner: T) -> io::Result { 69 | Ok(Self { 70 | inner, 71 | path: config.path.clone(), 72 | }) 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/protocol/websocket/connector.rs: -------------------------------------------------------------------------------- 1 | use super::{new_error, BinaryWsStream}; 2 | use crate::protocol::{DummyUdpStream, ProxyConnector}; 3 | use async_trait::async_trait; 4 | use serde::Deserialize; 5 | use std::io; 6 | use tokio_tungstenite::{ 7 | client_async, 8 | tungstenite::http::{StatusCode, Uri}, 9 | }; 10 | 11 | #[derive(Deserialize)] 12 | pub struct WebSocketConnectorConfig { 13 | uri: String, 14 | } 15 | 16 | pub struct WebSocketConnector { 17 | uri: Uri, 18 | inner: T, 19 | } 20 | 21 | #[async_trait] 22 | impl ProxyConnector for WebSocketConnector { 23 | type TS = BinaryWsStream; 24 | type US = DummyUdpStream; 25 | 26 | async fn connect_tcp(&self, addr: &crate::protocol::Address) -> io::Result { 27 | let stream = self.inner.connect_tcp(addr).await?; 28 | let (stream, resp) = client_async(&self.uri, stream) 29 | .await 30 | .map_err(|e| new_error(e))?; 31 | if resp.status() != StatusCode::SWITCHING_PROTOCOLS { 32 | return Err(new_error(format!("bad status: {}", resp.status()))); 33 | } 34 | let stream = BinaryWsStream::new(stream); 35 | Ok(stream) 36 | } 37 | 38 | async fn connect_udp(&self) -> io::Result { 39 | unimplemented!() 40 | } 41 | } 42 | 43 | impl WebSocketConnector { 44 | pub fn new(config: &WebSocketConnectorConfig, inner: T) -> io::Result { 45 | let uri = config.uri.parse().map_err(|e| new_error(e))?; 46 | Ok(Self { inner, uri }) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/protocol/websocket/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod acceptor; 2 | pub mod connector; 3 | 4 | use bytes::{Buf, Bytes}; 5 | use tokio::io::{AsyncRead, AsyncWrite}; 6 | use tokio_tungstenite::{tungstenite::Message, WebSocketStream}; 7 | 8 | use crate::error::Error; 9 | use futures_core::{ready, Stream}; 10 | use futures_util::sink::Sink; 11 | use std::{ 12 | io, 13 | pin::Pin, 14 | task::{Context, Poll}, 15 | }; 16 | 17 | use super::ProxyTcpStream; 18 | 19 | fn new_error(message: T) -> io::Error { 20 | return Error::new(format!("websocket: {}", message.to_string())).into(); 21 | } 22 | 23 | pub struct BinaryWsStream { 24 | inner: WebSocketStream, 25 | read_buffer: Option, 26 | } 27 | 28 | impl ProxyTcpStream for BinaryWsStream {} 29 | 30 | impl AsyncRead for BinaryWsStream { 31 | fn poll_read( 32 | mut self: Pin<&mut Self>, 33 | cx: &mut Context<'_>, 34 | buf: &mut tokio::io::ReadBuf<'_>, 35 | ) -> Poll> { 36 | loop { 37 | if let Some(read_buffer) = &mut self.read_buffer { 38 | if read_buffer.len() <= buf.remaining() { 39 | buf.put_slice(read_buffer); 40 | self.read_buffer = None; 41 | } else { 42 | let len = buf.remaining(); 43 | buf.put_slice(&read_buffer[..len]); 44 | read_buffer.advance(len); 45 | } 46 | return Poll::Ready(Ok(())); 47 | } 48 | let message = ready!(Pin::new(&mut self.inner).poll_next(cx)); 49 | if message.is_none() { 50 | return Poll::Ready(Err(new_error("websocket stream drained"))); 51 | } 52 | let message = message.unwrap().map_err(|e| new_error(e))?; 53 | // binary only 54 | match message { 55 | Message::Binary(binary) => { 56 | if binary.len() < buf.remaining() { 57 | buf.put_slice(&binary); 58 | return Poll::Ready(Ok(())); 59 | } else { 60 | self.read_buffer = Some(Bytes::from(binary)); 61 | continue; 62 | } 63 | } 64 | Message::Close(_) => { 65 | return Poll::Ready(Err(io::ErrorKind::ConnectionAborted.into())); 66 | } 67 | _ => { 68 | return Poll::Ready(Err(new_error(format!( 69 | "invalid message type {:?}", 70 | message 71 | )))) 72 | } 73 | } 74 | } 75 | } 76 | } 77 | 78 | impl AsyncWrite for BinaryWsStream { 79 | fn poll_write( 80 | mut self: Pin<&mut Self>, 81 | cx: &mut Context<'_>, 82 | buf: &[u8], 83 | ) -> Poll> { 84 | ready!(Pin::new(&mut self.inner).poll_ready(cx)) 85 | .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{:?}", e)))?; 86 | let message = Message::Binary(buf.into()); 87 | Pin::new(&mut self.inner) 88 | .start_send(message) 89 | .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{:?}", e)))?; 90 | Poll::Ready(Ok(buf.len())) 91 | } 92 | 93 | fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 94 | let inner = Pin::new(&mut self.inner); 95 | inner 96 | .poll_flush(cx) 97 | .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{:?}", e))) 98 | } 99 | 100 | fn poll_shutdown( 101 | mut self: Pin<&mut Self>, 102 | cx: &mut Context<'_>, 103 | ) -> Poll> { 104 | ready!(Pin::new(&mut self.inner).poll_ready(cx)) 105 | .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{:?}", e)))?; 106 | let message = Message::Close(None); 107 | let _ = Pin::new(&mut self.inner).start_send(message); 108 | 109 | let inner = Pin::new(&mut self.inner); 110 | inner 111 | .poll_close(cx) 112 | .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{:?}", e))) 113 | } 114 | } 115 | 116 | impl BinaryWsStream { 117 | pub fn new(inner: WebSocketStream) -> Self { 118 | return Self { 119 | inner, 120 | read_buffer: None, 121 | }; 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/proxy/mod.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | fs::File, 3 | io::{self, Read}, 4 | sync::Arc, 5 | }; 6 | 7 | use log::LevelFilter; 8 | use serde::Deserialize; 9 | use tokio::io::{split, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; 10 | 11 | use crate::{ 12 | error::Error, 13 | protocol::{ 14 | direct::connector::DirectConnector, 15 | dokodemo::acceptor::{DokodemoAcceptor, DokodemoAcceptorConfig}, 16 | mux::{ 17 | acceptor::{MuxAcceptor, MuxAcceptorConfig}, 18 | connector::{MuxConnector, MuxConnectorConfig}, 19 | }, 20 | plaintext::acceptor::{PlaintextAcceptor, PlaintextAcceptorConfig}, 21 | socks5::acceptor::{Socks5Acceptor, Socks5AcceptorConfig}, 22 | tls::{ 23 | acceptor::{TrojanTlsAcceptor, TrojanTlsAcceptorConfig}, 24 | connector::{TrojanTlsConnector, TrojanTlsConnectorConfig}, 25 | }, 26 | trojan::{ 27 | acceptor::{TrojanAcceptor, TrojanAcceptorConfig}, 28 | connector::{TrojanConnector, TrojanConnectorConfig}, 29 | }, 30 | websocket::{ 31 | acceptor::{WebSocketAcceptor, WebSocketAcceptorConfig}, 32 | connector::{WebSocketConnector, WebSocketConnectorConfig}, 33 | }, 34 | AcceptResult, ProxyAcceptor, ProxyConnector, ProxyTcpStream, ProxyUdpStream, UdpRead, 35 | UdpWrite, 36 | }, 37 | }; 38 | 39 | const RELAY_BUFFER_SIZE: usize = 0x4000; 40 | 41 | async fn copy_udp(r: &mut R, w: &mut W) -> io::Result<()> { 42 | let mut buf = [0u8; RELAY_BUFFER_SIZE]; 43 | loop { 44 | let (len, addr) = r.read_from(&mut buf).await?; 45 | log::debug!("udp packet addr={} len={}", addr, len); 46 | if len == 0 { 47 | break; 48 | } 49 | w.write_to(&buf[..len], &addr).await?; 50 | } 51 | Ok(()) 52 | } 53 | 54 | async fn copy_tcp( 55 | r: &mut R, 56 | w: &mut W, 57 | ) -> io::Result<()> { 58 | let mut buf = [0u8; RELAY_BUFFER_SIZE]; 59 | loop { 60 | let len = r.read(&mut buf).await?; 61 | if len == 0 { 62 | break; 63 | } 64 | w.write(&buf[..len]).await?; 65 | w.flush().await?; 66 | } 67 | Ok(()) 68 | } 69 | 70 | pub async fn relay_udp(a: T, b: U) { 71 | let (mut a_rx, mut a_tx) = a.split(); 72 | let (mut b_rx, mut b_tx) = b.split(); 73 | let t1 = copy_udp(&mut a_rx, &mut b_tx); 74 | let t2 = copy_udp(&mut b_rx, &mut a_tx); 75 | let e = tokio::select! { 76 | e = t1 => {e} 77 | e = t2 => {e} 78 | }; 79 | if let Err(e) = e { 80 | log::debug!("udp_relay err: {}", e) 81 | } 82 | let _ = T::reunite(a_rx, a_tx).close().await; 83 | let _ = U::reunite(b_rx, b_tx).close().await; 84 | log::info!("udp session ends"); 85 | } 86 | 87 | pub async fn relay_tcp(a: T, b: U) { 88 | let (mut a_rx, mut a_tx) = split(a); 89 | let (mut b_rx, mut b_tx) = split(b); 90 | let t1 = copy_tcp(&mut a_rx, &mut b_tx); 91 | let t2 = copy_tcp(&mut b_rx, &mut a_tx); 92 | let e = tokio::select! { 93 | e = t1 => {e} 94 | e = t2 => {e} 95 | }; 96 | if let Err(e) = e { 97 | log::debug!("relay_tcp err: {}", e) 98 | } 99 | let mut a = a_rx.unsplit(a_tx); 100 | let mut b = b_rx.unsplit(b_tx); 101 | let _ = a.shutdown().await; 102 | let _ = b.shutdown().await; 103 | log::info!("tcp session ends"); 104 | } 105 | 106 | #[derive(Deserialize)] 107 | struct GlobalConfig { 108 | mode: String, 109 | log_level: Option, 110 | } 111 | 112 | #[derive(Deserialize)] 113 | struct ClientConfig { 114 | socks5: Socks5AcceptorConfig, 115 | trojan: TrojanConnectorConfig, 116 | tls: TrojanTlsConnectorConfig, 117 | websocket: Option, 118 | mux: Option, 119 | } 120 | 121 | #[derive(Deserialize)] 122 | struct ServerConfig { 123 | trojan: TrojanAcceptorConfig, 124 | tls: Option, 125 | plaintext: Option, 126 | websocket: Option, 127 | mux: Option, 128 | } 129 | 130 | #[derive(Deserialize)] 131 | struct ForwardConfig { 132 | dokodemo: DokodemoAcceptorConfig, 133 | trojan: TrojanConnectorConfig, 134 | tls: TrojanTlsConnectorConfig, 135 | websocket: Option, 136 | mux: Option, 137 | } 138 | 139 | async fn run_proxy( 140 | acceptor: I, 141 | connector: O, 142 | ) -> io::Result<()> { 143 | let connector = Arc::new(connector); 144 | loop { 145 | match acceptor.accept().await { 146 | Ok(AcceptResult::Tcp((inbound, addr))) => { 147 | let connector = connector.clone(); 148 | tokio::spawn(async move { 149 | match connector.connect_tcp(&addr).await { 150 | Ok(outbound) => { 151 | log::info!("relaying tcp stream to {}", addr); 152 | relay_tcp(inbound, outbound).await; 153 | } 154 | Err(e) => { 155 | log::error!("failed to relay tcp stream to {}: {}", addr, e); 156 | } 157 | } 158 | }); 159 | } 160 | Ok(AcceptResult::Udp(inbound)) => { 161 | let connector = connector.clone(); 162 | tokio::spawn(async move { 163 | match connector.connect_udp().await { 164 | Ok(outbound) => { 165 | log::info!("relaying udp stream.."); 166 | relay_udp(inbound, outbound).await; 167 | } 168 | Err(e) => { 169 | log::error!("failed to relay tcp stream: {}", e.to_string()); 170 | } 171 | } 172 | }); 173 | } 174 | Err(e) => { 175 | log::error!("accept failed: {}", e); 176 | } 177 | } 178 | } 179 | } 180 | 181 | pub async fn launch_from_config_filename(filename: String) -> io::Result<()> { 182 | let mut file = File::open(filename)?; 183 | let mut config_string = String::new(); 184 | file.read_to_string(&mut config_string)?; 185 | launch_from_config_string(config_string).await 186 | } 187 | 188 | pub async fn launch_from_config_string(config_string: String) -> io::Result<()> { 189 | let config: GlobalConfig = toml::from_str(&config_string)?; 190 | if let Some(log_level) = config.log_level { 191 | let level = match log_level.as_str() { 192 | "trace" => LevelFilter::Trace, 193 | "debug" => LevelFilter::Debug, 194 | "info" => LevelFilter::Info, 195 | "warn" => LevelFilter::Warn, 196 | "error" => LevelFilter::Error, 197 | _ => { 198 | return Err(Error::new("invalid log_level").into()); 199 | } 200 | }; 201 | let _ = env_logger::builder().filter_level(level).try_init(); 202 | } else { 203 | let _ = env_logger::builder() 204 | .filter_level(LevelFilter::Debug) 205 | .try_init(); 206 | } 207 | match config.mode.as_str() { 208 | #[cfg(feature = "server")] 209 | "server" => { 210 | log::debug!("server mode"); 211 | let config: ServerConfig = toml::from_str(&config_string)?; 212 | let direct_connector = DirectConnector {}; 213 | if config.tls.is_none() { 214 | if config.plaintext.is_none() { 215 | return Err(Error::new("plaintext/tls section not found").into()); 216 | } 217 | let direct_acceptor = PlaintextAcceptor::new(&config.plaintext.unwrap()).await?; 218 | if config.websocket.is_none() { 219 | let trojan_acceptor = TrojanAcceptor::new(&config.trojan, direct_acceptor)?; 220 | if config.mux.is_none() { 221 | run_proxy(trojan_acceptor, direct_connector).await?; 222 | } else { 223 | let mux_acceptor = MuxAcceptor::new(trojan_acceptor, &config.mux.unwrap())?; 224 | run_proxy(mux_acceptor, direct_connector).await?; 225 | } 226 | } else { 227 | let ws_acceptor = 228 | WebSocketAcceptor::new(&config.websocket.unwrap(), direct_acceptor)?; 229 | let trojan_acceptor = TrojanAcceptor::new(&config.trojan, ws_acceptor)?; 230 | if config.mux.is_none() { 231 | run_proxy(trojan_acceptor, direct_connector).await?; 232 | } else { 233 | let mux_acceptor = MuxAcceptor::new(trojan_acceptor, &config.mux.unwrap())?; 234 | run_proxy(mux_acceptor, direct_connector).await?; 235 | } 236 | } 237 | } else { 238 | let tls_acceptor = TrojanTlsAcceptor::new(&config.tls.unwrap()).await?; 239 | if config.websocket.is_none() { 240 | let trojan_acceptor = TrojanAcceptor::new(&config.trojan, tls_acceptor)?; 241 | if config.mux.is_none() { 242 | run_proxy(trojan_acceptor, direct_connector).await?; 243 | } else { 244 | let mux_acceptor = MuxAcceptor::new(trojan_acceptor, &config.mux.unwrap())?; 245 | run_proxy(mux_acceptor, direct_connector).await?; 246 | } 247 | } else { 248 | let ws_acceptor = 249 | WebSocketAcceptor::new(&config.websocket.unwrap(), tls_acceptor)?; 250 | let trojan_acceptor = TrojanAcceptor::new(&config.trojan, ws_acceptor)?; 251 | if config.mux.is_none() { 252 | run_proxy(trojan_acceptor, direct_connector).await?; 253 | } else { 254 | let mux_acceptor = MuxAcceptor::new(trojan_acceptor, &config.mux.unwrap())?; 255 | run_proxy(mux_acceptor, direct_connector).await?; 256 | } 257 | } 258 | } 259 | } 260 | #[cfg(feature = "client")] 261 | "client" => { 262 | log::debug!("client mode"); 263 | let config: ClientConfig = toml::from_str(&config_string)?; 264 | let socks5_acceptor = Socks5Acceptor::new(&config.socks5).await?; 265 | let tls_connector = TrojanTlsConnector::new(&config.tls)?; 266 | if config.websocket.is_none() { 267 | let trojan_connector = TrojanConnector::new(&config.trojan, tls_connector)?; 268 | if config.mux.is_none() { 269 | run_proxy(socks5_acceptor, trojan_connector).await?; 270 | } else { 271 | let mux_connector = 272 | MuxConnector::new(&config.mux.unwrap(), trojan_connector).unwrap(); 273 | run_proxy(socks5_acceptor, mux_connector).await?; 274 | } 275 | } else { 276 | let ws_connector = 277 | WebSocketConnector::new(&config.websocket.unwrap(), tls_connector)?; 278 | let trojan_connector = TrojanConnector::new(&config.trojan, ws_connector)?; 279 | if config.mux.is_none() { 280 | run_proxy(socks5_acceptor, trojan_connector).await?; 281 | } else { 282 | let mux_connector = 283 | MuxConnector::new(&config.mux.unwrap(), trojan_connector).unwrap(); 284 | run_proxy(socks5_acceptor, mux_connector).await?; 285 | } 286 | } 287 | } 288 | #[cfg(feature = "forward")] 289 | "forward" => { 290 | log::debug!("forward mode"); 291 | let config: ForwardConfig = toml::from_str(&config_string)?; 292 | let dokodemo_acceptor = DokodemoAcceptor::new(&config.dokodemo).await?; 293 | let tls_connector = TrojanTlsConnector::new(&config.tls)?; 294 | if config.websocket.is_none() { 295 | let trojan_connector = TrojanConnector::new(&config.trojan, tls_connector)?; 296 | if config.mux.is_none() { 297 | run_proxy(dokodemo_acceptor, trojan_connector).await?; 298 | } else { 299 | let mux_connector = 300 | MuxConnector::new(&config.mux.unwrap(), trojan_connector).unwrap(); 301 | run_proxy(dokodemo_acceptor, mux_connector).await?; 302 | } 303 | } else { 304 | let ws_connector = 305 | WebSocketConnector::new(&config.websocket.unwrap(), tls_connector)?; 306 | let trojan_connector = TrojanConnector::new(&config.trojan, ws_connector)?; 307 | if config.mux.is_none() { 308 | run_proxy(dokodemo_acceptor, trojan_connector).await?; 309 | } else { 310 | let mux_connector = 311 | MuxConnector::new(&config.mux.unwrap(), trojan_connector).unwrap(); 312 | run_proxy(dokodemo_acceptor, mux_connector).await?; 313 | } 314 | } 315 | } 316 | _ => { 317 | log::error!("invalid mode: {}", config.mode.as_str()); 318 | } 319 | } 320 | Ok(()) 321 | } 322 | --------------------------------------------------------------------------------