Compare commits

..
24 Commits
Author SHA1 Message Date
patterniha 1e6feeb12f Update timer.go 2026-11-29 16:11:23 +09:00
SVLAVRandGitHub ded8443fee XDNS finalmask: Validate fragmented upload length at server side (#7507)
Fixes https://github.com/XTLS/Xray-core/issues/7499#issuecomment-7225248676
2026-11-27 18:25:34 +00:00
𐲓𐳛𐳪𐳂𐳐 𐲀𐳢𐳦𐳫𐳢 𐲥𐳔𐳛𐳪𐳌𐳑𐳖𐳇andGitHub 5780f0df90 Config: Remove legacy nested format in every proxy outbound (#7505)
https://github.com/XTLS/Xray-core/pull/7364#issuecomment-7142063028
2026-11-27 16:50:08 +00:00
风扇滑翔翼andGitHub 4d0bfb4d0d DialSystem: Print domain for lookup failure (#7489)
Closes https://github.com/XTLS/Xray-core/issues/7479
2026-11-26 21:18:21 +00:00
db6664bd68 SS2022 proxy: Refinements & fixes (#7488)
https://github.com/XTLS/Xray-core/pull/7194#issuecomment-6250856095

Closes https://github.com/XTLS/Xray-core/issues/7486

---------

Co-authored-by: Roman Rublev <roman171107@gmail.com>
2026-11-26 21:09:53 +00:00
67756b3674 common/bytespool, common/buf: Pool array pointers to avoid allocations (#7491)
https://github.com/XTLS/Xray-core/pull/7487#issuecomment-7196411530

---------

Co-authored-by: 风扇滑翔翼 <Fangliding.fshxy@outlook.com>
2026-11-26 18:33:27 +00:00
fanymagnetandGitHub 9576662b8e Hysteria proxy: Port v2.14.0 UDP forwarding optimizations; Bump quic-go (#7487)
https://github.com/XTLS/Xray-core/issues/7419#issuecomment-7063773710

Closes https://github.com/XTLS/Xray-core/issues/7484#issuecomment-7188906214
2026-11-26 18:32:33 +00:00
RPRXandRPRXX c5ccb356aa XDRIVE transport: VLESS Multiplex's maxConcurrency is at least 128, maxReuseTimes is unlimited; Automatically enable Mux at client side; Reject non-Mux/Rvs requests at server side
https://github.com/XTLS/Xray-core/issues/7358#issuecomment-6785007489
https://github.com/XTLS/Xray-core/issues/7208#issuecomment-7178588017
https://github.com/XTLS/Xray-core/pull/7364#issuecomment-7190558980
2026-11-26 16:50:31 +00:00
b56ffef338 WebSocket transport, XHTTP server: Reduce some goroutines by switching to task.Periodic (#7470)
https://github.com/XTLS/Xray-core/pull/7463#issuecomment-7081595080
https://github.com/XTLS/Xray-core/pull/7470#issuecomment-7131388265
https://github.com/XTLS/Xray-core/pull/7470#issuecomment-7163168321

---------

Co-authored-by: StarProxima <34741787+StarProxima@users.noreply.github.com>
2026-11-25 14:37:40 +00:00
862e59a2f2 TUN inbound: Consolidate files and remove unneeded tests; Rename wfp_leak.go to wfp_block.go (#7482)
https://github.com/XTLS/Xray-core/pull/7460#issuecomment-7131171930

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:29:26 +00:00
RPRXandGitHub 35805f9377 XHTTP transport: Print warning when using VLESS Multiplex at client side, instead of blocking it at server side
https://github.com/XTLS/Xray-core/pull/7364#issuecomment-7141663413
https://github.com/XTLS/Xray-core/pull/6755#issuecomment-5720463978
https://github.com/XTLS/Xray-core/pull/6755#issuecomment-7160365746
2026-11-25 11:54:12 +00:00
5d8b20239f VLESS outbound: Better UDP/443 dropping (#7467)
https://github.com/XTLS/Xray-core/pull/7465#issuecomment-7081110276

---------

Co-authored-by: StarProxima <34741787+StarProxima@users.noreply.github.com>
2026-11-24 23:03:44 +00:00
e17392a96e VLESS Multiplex, Reverse Proxy: Refactor to move code into VLESS; Mux only uses settings.multiplex in VLESS/VMess outbound (#7364)
https://github.com/XTLS/Xray-core/pull/6748#issuecomment-5752780799
https://github.com/XTLS/Xray-core/issues/7240#issuecomment-6439951754
https://github.com/XTLS/Xray-core/pull/4231#issuecomment-6679992732
https://github.com/XTLS/Xray-core/pull/7355#issuecomment-6739539943
https://github.com/XTLS/Xray-core/pull/7359#issuecomment-6742147165
https://github.com/XTLS/Xray-core/pull/7364#issuecomment-6784892866
https://github.com/XTLS/Xray-core/pull/7364#issuecomment-6812285253
https://github.com/XTLS/Xray-core/pull/7364#issuecomment-6842747639
https://github.com/XTLS/Xray-core/pull/4231#issuecomment-7012427059
https://github.com/XTLS/Xray-core/pull/7364#issuecomment-7108550396
https://github.com/XTLS/Xray-core/pull/7364#issuecomment-7129493942
https://github.com/XTLS/Xray-core/pull/7364#issuecomment-7130454962

---------

Co-authored-by: Codex <codex@users.noreply.github.com>
Co-authored-by: RPRX <63339210+RPRX@users.noreply.github.com>
2026-11-24 18:20:46 +00:00
RanTheandGitHub 15b2499d34 XDNS finalmask: Add alphabet to domains for UDP/53 in Iran (#7457)
https://github.com/XTLS/Xray-core/pull/7457#issuecomment-7075534791
2026-11-24 13:00:50 +00:00
PlangtoandGitHub d9131d381c TUN inbound: Support configurable Wintun adapter guid on Windows (#7460)
Closes https://github.com/XTLS/Xray-core/issues/7458
2026-11-24 12:09:36 +00:00
风扇滑翔翼andGitHub 8c7447fd2d DNS outbound: Add lock to TCP DNS handler (#7473)
Fixes https://github.com/XTLS/Xray-core/issues/7462
2026-11-24 11:14:39 +00:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
4dac768567 Bump lukechampine.com/blake3 from 1.4.1 to 1.5.1 (#7478)
Bumps lukechampine.com/blake3 from 1.4.1 to 1.5.1.

---
updated-dependencies:
- dependency-name: lukechampine.com/blake3
  dependency-version: 1.5.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-24 01:43:04 +00:00
RPRXandRPRXX dfad7776ee SECURITY.md: Add Exceptions (should be reported via public Issues)
https://github.com/XTLS/Xray-core/pull/7429#issuecomment-7019836362
2026-11-24 00:24:11 +00:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
e00dbb963c Bump golang.org/x/net from 0.62.0 to 0.63.0 (#7475)
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.62.0 to 0.63.0.
- [Commits](https://github.com/golang/net/compare/v0.62.0...v0.63.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-version: 0.63.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-23 21:00:11 +00:00
a9c42c1bd7 README.md: Fix star history chart; Add Project listing criteria; Add CONTRIBUTING.md and PULL_REQUEST_TEMPLATE.md (#7429)
https://github.com/XTLS/Xray-core/issues/7419#issuecomment-6900822011
https://github.com/XTLS/Xray-core/issues/7419#issuecomment-6907278358
https://github.com/XTLS/Xray-core/issues/7419#issuecomment-6970052067
https://github.com/XTLS/Xray-core/pull/7429#issuecomment-6984295234
https://github.com/XTLS/Xray-core/pull/7429#issuecomment-6985957550
https://github.com/XTLS/Xray-core/pull/7429#issuecomment-7069961755

---------

Co-authored-by: RPRX <63339210+RPRX@users.noreply.github.com>
2026-11-23 18:17:56 +00:00
AliceandGitHub 74cbdf46d8 README.md: Add keqdroid to Windows, Android and Linux in GUI Clients (#7446)
https://github.com/XTLS/Xray-core/pull/7429#issuecomment-6985957550
2026-11-21 21:38:21 +00:00
3dee8518c1 HTTPUpgrade client: Close the connection when the upgrade fails (#7395)
https://github.com/XTLS/Xray-core/pull/7395#issuecomment-6884592648

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 20:40:13 +00:00
MeowandGitHub 8f0bb9fbfa Outbounds: Avoid circular dependencies with the built-in DNS (#7425)
https://github.com/XTLS/Xray-core/pull/7425#issuecomment-6900056768
https://github.com/XTLS/Xray-core/pull/7425#issuecomment-6953371666
https://github.com/XTLS/Xray-core/pull/7425#issuecomment-7023506796
2026-11-21 20:37:44 +00:00
yangdujunandGitHub 5225121aab XMC finalmask: Yggdrasil third-party login and texture verification (#7416)
Closes https://github.com/XTLS/Xray-core/issues/7394
2026-11-21 20:15:31 +00:00
151 changed files with 7275 additions and 6004 deletions
+5
View File
@@ -0,0 +1,5 @@
<!--
Read CONTRIBUTING.md before opening a pull request.
Human-led pull requests can use a normal description.
For agent-led pull requests, disclose each AI tool and model, then paste the complete conversation directly in a collapsed <details> block in this PR body. External transcript links are not accepted.
-->
+29
View File
@@ -0,0 +1,29 @@
# Contributing to Xray-core
We review pull requests that address a concrete problem or an agreed proposal. Please keep each change focused and provide evidence that maintainers can check.
## Bug fixes
A bug-fix pull request must link an existing issue filed using the issue template. Summarize the code change and verification in the pull request, and add a regression test when practical. A speculative fix without a demonstrated problem is not ready for a pull request.
## Features
Propose the use case and intended design in an issue before implementing it. Wait for a maintainer to accept the proposal. Explain how the change fits the existing architecture and any compatibility impact.
## Refactors
Propose the scope in an issue and wait for maintainer acceptance before implementing it. Show which complexity the change removes and why the resulting design is easier to understand. Prefer a reduction in code and moving parts, but line count alone is not the review criterion. Preserve observable behavior and test both old-to-new and new-to-old client/server connections when protocol or network behavior is affected.
## AI involvement and author responsibility
AI assistance does not require a conversation record when the author selects or verifies the problem, directs the approach, reviews every changed line, verifies the result, and personally responds to review feedback. The author must be able to explain every changed line and maintain the change. A pull request meeting these conditions is considered human-led, regardless of whether AI wrote the code or who pushed the commits. Such pull requests may ignore the agent-led requirements below.
If an AI agent independently selected the task or made key implementation decisions without ongoing human direction, the pull request is agent-led even if a person submits it manually. Disclose each tool and model and paste the complete prompt-and-response record for every session used for the pull request, including retries and changes after review feedback, inside a collapsed `<details>` block in the pull request description. External links, summaries, and selected excerpts are insufficient. A transcript does not replace the author's review, verification, or responsibility for responding to maintainers.
In agent-led pull requests, commits containing AI-generated changes must credit the specific LLM as their author or co-author.
We do not oppose the use of AI, but agent-led pull requests must have a human author who responds to maintainer feedback for several weeks after submission. Dishonest declarations, fabricated verification, intentionally incomplete records, or abandoning an agent-led pull request are prohibited and may result in being blocked from contributing to Xray-core.
## Review
Maintainers may ask for missing evidence before reviewing code or close a pull request that is outside the agreed scope. The contributor is responsible for understanding, testing, and explaining the change, regardless of the tools used to produce it.
+28 -39
View File
@@ -2,8 +2,6 @@
[Project X](https://github.com/XTLS) originates from XTLS protocol, providing a set of network tools such as [Xray-core](https://github.com/XTLS/Xray-core) and [REALITY](https://github.com/XTLS/REALITY). [Project X](https://github.com/XTLS) originates from XTLS protocol, providing a set of network tools such as [Xray-core](https://github.com/XTLS/Xray-core) and [REALITY](https://github.com/XTLS/REALITY).
[README](https://github.com/XTLS/Xray-core#readme) is open, so feel free to submit your project [here](https://github.com/XTLS/Xray-core/pulls).
## Sponsors ## Sponsors
[![Remnawave](https://github.com/user-attachments/assets/a22d34ae-01ee-441c-843a-85356748ed1e)](https://docs.rw) [![Remnawave](https://github.com/user-attachments/assets/a22d34ae-01ee-441c-843a-85356748ed1e)](https://docs.rw)
@@ -41,10 +39,10 @@
## Telegram ## Telegram
[Project X](https://t.me/projectXray)
[Project X Channel](https://t.me/projectXtls) [Project X Channel](https://t.me/projectXtls)
[Project X](https://t.me/projectXray) (中文 / English)
[Project VLESS](https://t.me/projectVless) (Русский) [Project VLESS](https://t.me/projectVless) (Русский)
[Project XHTTP](https://t.me/projectXhttp) (Persian) [Project XHTTP](https://t.me/projectXhttp) (Persian)
@@ -53,7 +51,6 @@
- Linux Script - Linux Script
- [XTLS/Xray-install](https://github.com/XTLS/Xray-install) (**Official**) - [XTLS/Xray-install](https://github.com/XTLS/Xray-install) (**Official**)
- [tempest](https://github.com/team-cloudchaser/tempest) (supports [`systemd`](https://systemd.io) and [OpenRC](https://github.com/OpenRC/openrc); Linux-only)
- Docker - Docker
- [ghcr.io/xtls/xray-core](https://ghcr.io/xtls/xray-core) (**Official**) - [ghcr.io/xtls/xray-core](https://ghcr.io/xtls/xray-core) (**Official**)
- [teddysun/xray](https://hub.docker.com/r/teddysun/xray) - [teddysun/xray](https://hub.docker.com/r/teddysun/xray)
@@ -69,12 +66,10 @@
- [TX-UI](https://github.com/AghayeCoder/tx-ui) - [TX-UI](https://github.com/AghayeCoder/tx-ui)
- [CELERITY](https://github.com/ClickDevTech/CELERITY-panel) - [CELERITY](https://github.com/ClickDevTech/CELERITY-panel)
- One Click - One Click
- [Xray-REALITY](https://github.com/zxcvos/Xray-script), [xray-reality](https://github.com/sajjaddg/xray-reality), [reality-ezpz](https://github.com/aleskxyz/reality-ezpz) - [xray-reality](https://github.com/sajjaddg/xray-reality), [Xray_bash_onekey](https://github.com/hello-yunshu/Xray_bash_onekey)
- [Xray_bash_onekey](https://github.com/hello-yunshu/Xray_bash_onekey), [XTool](https://github.com/LordPenguin666/XTool), [VPainLess](https://github.com/vpainless/vpainless) - [v2ray-agent](https://github.com/mack-a/v2ray-agent), [Xray_onekey](https://github.com/wulabing/Xray_onekey)
- [v2ray-agent](https://github.com/mack-a/v2ray-agent), [Xray_onekey](https://github.com/wulabing/Xray_onekey), [ProxySU](https://github.com/proxysu/ProxySU)
- Magisk - Magisk
- [Magic_V2Ray](https://github.com/vincentng295/Magic_V2Ray) - [Magic_V2Ray](https://github.com/vincentng295/Magic_V2Ray)
- [Xray_For_Magisk](https://github.com/E7KMbb/Xray_For_Magisk)
- Homebrew - Homebrew
- `brew install xray` - `brew install xray`
@@ -86,14 +81,7 @@
- [All-in-One-fallbacks-Nginx](https://github.com/XTLS/Xray-examples/tree/main/All-in-One-fallbacks-Nginx) - [All-in-One-fallbacks-Nginx](https://github.com/XTLS/Xray-examples/tree/main/All-in-One-fallbacks-Nginx)
- Xray-examples - Xray-examples
- [XTLS/Xray-examples](https://github.com/XTLS/Xray-examples) - [XTLS/Xray-examples](https://github.com/XTLS/Xray-examples)
- [chika0801/Xray-examples](https://github.com/chika0801/Xray-examples)
- [lxhao61/integrated-examples](https://github.com/lxhao61/integrated-examples) - [lxhao61/integrated-examples](https://github.com/lxhao61/integrated-examples)
- Tutorial
- [XTLS Vision](https://github.com/chika0801/Xray-install)
- [REALITY (English)](https://cscot.pages.dev/2023/03/02/Xray-REALITY-tutorial/)
- [XTLS-Iran-Reality (English)](https://github.com/SasukeFreestyle/XTLS-Iran-Reality)
- [Xray REALITY with 'steal oneself' (English)](https://computerscot.github.io/vless-xtls-utls-reality-steal-oneself.html)
- [Xray with WireGuard inbound (English)](https://g800.pages.dev/wireguard)
## GUI Clients ## GUI Clients
@@ -106,49 +94,52 @@
- [fancyss](https://github.com/hq450/fancyss) - [fancyss](https://github.com/hq450/fancyss)
- Windows - Windows
- [v2rayN](https://github.com/2dust/v2rayN) - [v2rayN](https://github.com/2dust/v2rayN)
- [Furious](https://github.com/LorenEteval/Furious)
- [Invisible Man - Xray](https://github.com/InvisibleManVPN/InvisibleMan-XRayClient)
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
- [GenyConnect](https://github.com/genyleap/GenyConnect) - [GenyConnect](https://github.com/genyleap/GenyConnect)
- [OneXray](https://github.com/OneXray/OneXray) - [OneXray](https://github.com/OneXray/OneXray)
- [XrayUI-dev](https://github.com/PhoenixNil/XrayUI-dev) - [XrayUI-dev](https://github.com/PhoenixNil/XrayUI-dev)
- [keqdroid](https://github.com/Lemonochka/keqdroid)
- Android - Android
- [v2rayNG](https://github.com/2dust/v2rayNG) - [v2rayNG](https://github.com/2dust/v2rayNG)
- [X-flutter](https://github.com/XTLS/X-flutter)
- [SaeedDev94/Xray](https://github.com/SaeedDev94/Xray) - [SaeedDev94/Xray](https://github.com/SaeedDev94/Xray)
- [SimpleXray](https://github.com/lhear/SimpleXray) - [SimpleXray](https://github.com/lhear/SimpleXray)
- [XrayFA](https://github.com/Q7DF1/XrayFA) - [XrayFA](https://github.com/Q7DF1/XrayFA)
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
- [OneXray](https://github.com/OneXray/OneXray) - [OneXray](https://github.com/OneXray/OneXray)
- [AsteriskNG](https://github.com/Asterisk4Magisk/AsteriskNG) - [AsteriskNG](https://github.com/Asterisk4Magisk/AsteriskNG)
- [keqdroid](https://github.com/Lemonochka/keqdroid)
- iOS & macOS arm64 & tvOS - iOS & macOS arm64 & tvOS
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215) | [Happ RU](https://apps.apple.com/ru/app/happ-proxy-utility-plus/id6746188973) | [Happ tvOS](https://apps.apple.com/us/app/happ-proxy-utility-for-tv/id6748297274) - [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215) | [Happ tvOS](https://apps.apple.com/us/app/happ-proxy-utility-for-tv/id6748297274)
- [Streisand](https://apps.apple.com/app/streisand/id6450534064) - [Streisand](https://apps.apple.com/app/streisand/id6450534064)
- [OneXray](https://github.com/OneXray/OneXray) - [OneXray](https://github.com/OneXray/OneXray)
- [INCY](https://apps.apple.com/en/app/incy/id6756943388) - [INCY](https://apps.apple.com/en/app/incy/id6756943388)
- macOS arm64 & x64 - macOS arm64 & x64
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215) | [Happ RU](https://apps.apple.com/ru/app/happ-proxy-utility-plus/id6746188973) - [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215)
- [V2rayU](https://github.com/yanue/V2rayU) - [V2rayU](https://github.com/yanue/V2rayU)
- [V2RayXS](https://github.com/tzmax/V2RayXS) - [V2RayXS](https://github.com/tzmax/V2RayXS)
- [Furious](https://github.com/LorenEteval/Furious)
- [OneXray](https://github.com/OneXray/OneXray) - [OneXray](https://github.com/OneXray/OneXray)
- [GoXRay](https://github.com/goxray/desktop)
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
- [v2rayN](https://github.com/2dust/v2rayN) - [v2rayN](https://github.com/2dust/v2rayN)
- [GenyConnect](https://github.com/genyleap/GenyConnect) - [GenyConnect](https://github.com/genyleap/GenyConnect)
- [INCY](https://apps.apple.com/en/app/incy/id6756943388) - [INCY](https://apps.apple.com/en/app/incy/id6756943388)
- Linux - Linux
- [v2rayA](https://github.com/v2rayA/v2rayA) - [v2rayA](https://github.com/v2rayA/v2rayA)
- [Furious](https://github.com/LorenEteval/Furious)
- [GorzRay](https://github.com/ketetefid/GorzRay)
- [GoXRay](https://github.com/goxray/desktop)
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
- [v2rayN](https://github.com/2dust/v2rayN) - [v2rayN](https://github.com/2dust/v2rayN)
- [GenyConnect](https://github.com/genyleap/GenyConnect) - [GenyConnect](https://github.com/genyleap/GenyConnect)
- [OneXray](https://github.com/OneXray/OneXray) - [OneXray](https://github.com/OneXray/OneXray)
- [keqdroid](https://github.com/Lemonochka/keqdroid)
- HarmonyOS - HarmonyOS
- [Hey](https://github.com/popsiclelmlm/Hey) - [Hey](https://github.com/popsiclelmlm/Hey)
<details>
<summary>Project listing criteria</summary>
To submit a project to the [README](https://github.com/XTLS/Xray-core#readme), open a [pull request](https://github.com/XTLS/Xray-core/pulls). Projects are listed under these rules:
- Only submit projects that build their core experience on Xray-core and follow Xray's protocol choices and security requirements; merely offering it as an interchangeable core does not qualify.
- Projects must have been maintained for at least one month and have at least 30 stars.
- Projects with no activity for three months will be removed.
- Closed-source iOS clients must be submitted by their developers.
</details>
## Others that support VLESS, XTLS, REALITY, XUDP, PLUX... ## Others that support VLESS, XTLS, REALITY, XUDP, PLUX...
- iOS & macOS arm64 & tvOS - iOS & macOS arm64 & tvOS
@@ -163,14 +154,8 @@
- Xray Wrapper - Xray Wrapper
- [XTLS/libXray](https://github.com/XTLS/libXray) - [XTLS/libXray](https://github.com/XTLS/libXray)
- [xtls-sdk](https://github.com/remnawave/xtls-sdk) - [xtls-sdk](https://github.com/remnawave/xtls-sdk)
- [xtlsapi](https://github.com/hiddify/xtlsapi)
- [AndroidLibXrayLite](https://github.com/2dust/AndroidLibXrayLite) - [AndroidLibXrayLite](https://github.com/2dust/AndroidLibXrayLite)
- [flutter_vless](https://github.com/XIIIFOX/flutter_vless) - [flutter_vless](https://github.com/XIIIFOX/flutter_vless)
- [Xray-core-python](https://github.com/LorenEteval/Xray-core-python)
- [xray-api](https://github.com/XVGuardian/xray-api)
- [XrayR](https://github.com/XrayR-project/XrayR)
- [XrayR-release](https://github.com/XrayR-project/XrayR-release)
- [XrayR-V2Board](https://github.com/missuo/XrayR-V2Board)
- Cores - Cores
- [Amnezia VPN](https://github.com/amnezia-vpn) - [Amnezia VPN](https://github.com/amnezia-vpn)
- [mihomo](https://github.com/MetaCubeX/mihomo) - [mihomo](https://github.com/MetaCubeX/mihomo)
@@ -178,9 +163,9 @@
## Contributing ## Contributing
[Code of Conduct](https://github.com/XTLS/Xray-core/blob/main/CODE_OF_CONDUCT.md) For code contributions, please read [CONTRIBUTING.md](CONTRIBUTING.md) and [Code of Conduct](https://github.com/XTLS/Xray-core/blob/main/CODE_OF_CONDUCT.md) before opening a pull request.
[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/XTLS/Xray-core) [Ask DeepWiki](https://deepwiki.com/XTLS/Xray-core) might be helpful.
## Credits ## Credits
@@ -263,4 +248,8 @@ GOOS=linux GOARCH=mipsle GOMIPS=softfloat CGO_ENABLED=0 go build -o xray -trimpa
## Stargazers over time ## Stargazers over time
[![Stargazers over time](https://starchart.cc/XTLS/Xray-core.svg)](https://starchart.cc/XTLS/Xray-core) <picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xtls/xray-core&type=date&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xtls/xray-core&type=date&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xtls/xray-core&type=date&legend=top-left" />
</picture>
+6
View File
@@ -2,4 +2,10 @@
If you found an issue related to security vulnerability or protocol-identification problem, please report it to us via "[Report a vulnerability](https://github.com/XTLS/Xray-core/security/advisories/new)" privately, instead of publish it publicly before we release the fixed version. If you found an issue related to security vulnerability or protocol-identification problem, please report it to us via "[Report a vulnerability](https://github.com/XTLS/Xray-core/security/advisories/new)" privately, instead of publish it publicly before we release the fixed version.
Exceptions:
- ANY crash/panic bugs, memory/goroutine leaks, they should be reported via public [Issues](https://github.com/XTLS/Xray-core/issues) regardless of the cause
- existing publicly discussed issues (known issues), or upstream problems such as uTLS browser fingerprints
- undocumented/unexpected configs, low-impact vulnerabilities in the real world, they can be discussed publicly
Thanks for your contribution to the FREE Internet! Thanks for your contribution to the FREE Internet!
+16 -8
View File
@@ -26,9 +26,16 @@ import (
var errSniffingTimeout = errors.New("timeout on sniffing") var errSniffingTimeout = errors.New("timeout on sniffing")
// Native readers own attempted-input accounting, timeout and interruption.
type nativeReader interface {
buf.TimeoutReader
common.Interruptible
SetUplinkCounter(stats.Counter)
}
type cachedReader struct { type cachedReader struct {
sync.Mutex sync.Mutex
reader buf.TimeoutReader // *pipe.Reader or *buf.TimeoutWrapperReader reader buf.TimeoutReader
cache buf.MultiBuffer cache buf.MultiBuffer
} }
@@ -86,9 +93,7 @@ func (r *cachedReader) Interrupt() {
r.cache = buf.ReleaseMulti(r.cache) r.cache = buf.ReleaseMulti(r.cache)
} }
r.Unlock() r.Unlock()
if p, ok := r.reader.(*pipe.Reader); ok { common.Interrupt(r.reader)
p.Interrupt()
}
} }
// DefaultDispatcher is a default implementation of Dispatcher. // DefaultDispatcher is a default implementation of Dispatcher.
@@ -194,15 +199,13 @@ func WrapLink(ctx context.Context, policyManager policy.Manager, statsManager st
user = sessionInbound.User user = sessionInbound.User
} }
link.Reader = &buf.TimeoutWrapperReader{Reader: link.Reader} var uplinkCounter stats.Counter
if user != nil && len(user.Email) > 0 { if user != nil && len(user.Email) > 0 {
p := policyManager.ForLevel(user.Level) p := policyManager.ForLevel(user.Level)
if p.Stats.UserUplink { if p.Stats.UserUplink {
name := "user>>>" + user.Email + ">>>traffic>>>uplink" name := "user>>>" + user.Email + ">>>traffic>>>uplink"
if c, _ := statsManager.GetOrRegisterCounter(name); c != nil { uplinkCounter, _ = statsManager.GetOrRegisterCounter(name)
link.Reader.(*buf.TimeoutWrapperReader).Counter = c
}
} }
if p.Stats.UserDownlink { if p.Stats.UserDownlink {
name := "user>>>" + user.Email + ">>>traffic>>>downlink" name := "user>>>" + user.Email + ">>>traffic>>>downlink"
@@ -218,6 +221,11 @@ func WrapLink(ctx context.Context, policyManager policy.Manager, statsManager st
} }
} }
if reader, ok := link.Reader.(nativeReader); ok {
reader.SetUplinkCounter(uplinkCounter)
} else {
link.Reader = &buf.TimeoutWrapperReader{Reader: link.Reader, Counter: uplinkCounter}
}
return link return link
} }
+33 -121
View File
@@ -328,13 +328,12 @@ func (*OutboundConfig) Descriptor() ([]byte, []int) {
type SenderConfig struct { type SenderConfig struct {
state protoimpl.MessageState `protogen:"open.v1"` state protoimpl.MessageState `protogen:"open.v1"`
// Send traffic through the given IP. Only IP is allowed. // Send traffic through the given IP. Only IP is allowed.
Via *net.IPOrDomain `protobuf:"bytes,1,opt,name=via,proto3" json:"via,omitempty"` Via *net.IPOrDomain `protobuf:"bytes,1,opt,name=via,proto3" json:"via,omitempty"`
StreamSettings *internet.StreamConfig `protobuf:"bytes,2,opt,name=stream_settings,json=streamSettings,proto3" json:"stream_settings,omitempty"` StreamSettings *internet.StreamConfig `protobuf:"bytes,2,opt,name=stream_settings,json=streamSettings,proto3" json:"stream_settings,omitempty"`
MultiplexSettings *MultiplexingConfig `protobuf:"bytes,4,opt,name=multiplex_settings,json=multiplexSettings,proto3" json:"multiplex_settings,omitempty"` ViaCidr string `protobuf:"bytes,5,opt,name=via_cidr,json=viaCidr,proto3" json:"via_cidr,omitempty"`
ViaCidr string `protobuf:"bytes,5,opt,name=via_cidr,json=viaCidr,proto3" json:"via_cidr,omitempty"` TargetStrategy internet.DomainStrategy `protobuf:"varint,6,opt,name=target_strategy,json=targetStrategy,proto3,enum=xray.transport.internet.DomainStrategy" json:"target_strategy,omitempty"`
TargetStrategy internet.DomainStrategy `protobuf:"varint,6,opt,name=target_strategy,json=targetStrategy,proto3,enum=xray.transport.internet.DomainStrategy" json:"target_strategy,omitempty"` unknownFields protoimpl.UnknownFields
unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache
sizeCache protoimpl.SizeCache
} }
func (x *SenderConfig) Reset() { func (x *SenderConfig) Reset() {
@@ -381,13 +380,6 @@ func (x *SenderConfig) GetStreamSettings() *internet.StreamConfig {
return nil return nil
} }
func (x *SenderConfig) GetMultiplexSettings() *MultiplexingConfig {
if x != nil {
return x.MultiplexSettings
}
return nil
}
func (x *SenderConfig) GetViaCidr() string { func (x *SenderConfig) GetViaCidr() string {
if x != nil { if x != nil {
return x.ViaCidr return x.ViaCidr
@@ -402,78 +394,6 @@ func (x *SenderConfig) GetTargetStrategy() internet.DomainStrategy {
return internet.DomainStrategy(0) return internet.DomainStrategy(0)
} }
type MultiplexingConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Whether or not Mux is enabled.
Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"`
// Max number of concurrent connections that one Mux connection can handle.
Concurrency int32 `protobuf:"varint,2,opt,name=concurrency,proto3" json:"concurrency,omitempty"`
// Transport XUDP in another Mux.
XudpConcurrency int32 `protobuf:"varint,3,opt,name=xudpConcurrency,proto3" json:"xudpConcurrency,omitempty"`
// "reject" (default), "allow" or "skip".
XudpProxyUDP443 string `protobuf:"bytes,4,opt,name=xudpProxyUDP443,proto3" json:"xudpProxyUDP443,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *MultiplexingConfig) Reset() {
*x = MultiplexingConfig{}
mi := &file_app_proxyman_config_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *MultiplexingConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*MultiplexingConfig) ProtoMessage() {}
func (x *MultiplexingConfig) ProtoReflect() protoreflect.Message {
mi := &file_app_proxyman_config_proto_msgTypes[6]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use MultiplexingConfig.ProtoReflect.Descriptor instead.
func (*MultiplexingConfig) Descriptor() ([]byte, []int) {
return file_app_proxyman_config_proto_rawDescGZIP(), []int{6}
}
func (x *MultiplexingConfig) GetEnabled() bool {
if x != nil {
return x.Enabled
}
return false
}
func (x *MultiplexingConfig) GetConcurrency() int32 {
if x != nil {
return x.Concurrency
}
return 0
}
func (x *MultiplexingConfig) GetXudpConcurrency() int32 {
if x != nil {
return x.XudpConcurrency
}
return 0
}
func (x *MultiplexingConfig) GetXudpProxyUDP443() string {
if x != nil {
return x.XudpProxyUDP443
}
return ""
}
var File_app_proxyman_config_proto protoreflect.FileDescriptor var File_app_proxyman_config_proto protoreflect.FileDescriptor
const file_app_proxyman_config_proto_rawDesc = "" + const file_app_proxyman_config_proto_rawDesc = "" +
@@ -498,18 +418,12 @@ const file_app_proxyman_config_proto_rawDesc = "" +
"\x03tag\x18\x01 \x01(\tR\x03tag\x12M\n" + "\x03tag\x18\x01 \x01(\tR\x03tag\x12M\n" +
"\x11receiver_settings\x18\x02 \x01(\v2 .xray.common.serial.TypedMessageR\x10receiverSettings\x12G\n" + "\x11receiver_settings\x18\x02 \x01(\v2 .xray.common.serial.TypedMessageR\x10receiverSettings\x12G\n" +
"\x0eproxy_settings\x18\x03 \x01(\v2 .xray.common.serial.TypedMessageR\rproxySettings\"\x10\n" + "\x0eproxy_settings\x18\x03 \x01(\v2 .xray.common.serial.TypedMessageR\rproxySettings\"\x10\n" +
"\x0eOutboundConfig\"\xd6\x02\n" + "\x0eOutboundConfig\"\x9a\x02\n" +
"\fSenderConfig\x12-\n" + "\fSenderConfig\x12-\n" +
"\x03via\x18\x01 \x01(\v2\x1b.xray.common.net.IPOrDomainR\x03via\x12N\n" + "\x03via\x18\x01 \x01(\v2\x1b.xray.common.net.IPOrDomainR\x03via\x12N\n" +
"\x0fstream_settings\x18\x02 \x01(\v2%.xray.transport.internet.StreamConfigR\x0estreamSettings\x12T\n" + "\x0fstream_settings\x18\x02 \x01(\v2%.xray.transport.internet.StreamConfigR\x0estreamSettings\x12\x19\n" +
"\x12multiplex_settings\x18\x04 \x01(\v2%.xray.app.proxyman.MultiplexingConfigR\x11multiplexSettings\x12\x19\n" +
"\bvia_cidr\x18\x05 \x01(\tR\aviaCidr\x12P\n" + "\bvia_cidr\x18\x05 \x01(\tR\aviaCidr\x12P\n" +
"\x0ftarget_strategy\x18\x06 \x01(\x0e2'.xray.transport.internet.DomainStrategyR\x0etargetStrategyJ\x04\b\x03\x10\x04\"\xa4\x01\n" + "\x0ftarget_strategy\x18\x06 \x01(\x0e2'.xray.transport.internet.DomainStrategyR\x0etargetStrategyJ\x04\b\x03\x10\x04J\x04\b\x04\x10\x05R\x12multiplex_settingsBU\n" +
"\x12MultiplexingConfig\x12\x18\n" +
"\aenabled\x18\x01 \x01(\bR\aenabled\x12 \n" +
"\vconcurrency\x18\x02 \x01(\x05R\vconcurrency\x12(\n" +
"\x0fxudpConcurrency\x18\x03 \x01(\x05R\x0fxudpConcurrency\x12(\n" +
"\x0fxudpProxyUDP443\x18\x04 \x01(\tR\x0fxudpProxyUDP443BU\n" +
"\x15com.xray.app.proxymanP\x01Z&github.com/xtls/xray-core/app/proxyman\xaa\x02\x11Xray.App.Proxymanb\x06proto3" "\x15com.xray.app.proxymanP\x01Z&github.com/xtls/xray-core/app/proxyman\xaa\x02\x11Xray.App.Proxymanb\x06proto3"
var ( var (
@@ -524,7 +438,7 @@ func file_app_proxyman_config_proto_rawDescGZIP() []byte {
return file_app_proxyman_config_proto_rawDescData return file_app_proxyman_config_proto_rawDescData
} }
var file_app_proxyman_config_proto_msgTypes = make([]protoimpl.MessageInfo, 7) var file_app_proxyman_config_proto_msgTypes = make([]protoimpl.MessageInfo, 6)
var file_app_proxyman_config_proto_goTypes = []any{ var file_app_proxyman_config_proto_goTypes = []any{
(*InboundConfig)(nil), // 0: xray.app.proxyman.InboundConfig (*InboundConfig)(nil), // 0: xray.app.proxyman.InboundConfig
(*SniffingConfig)(nil), // 1: xray.app.proxyman.SniffingConfig (*SniffingConfig)(nil), // 1: xray.app.proxyman.SniffingConfig
@@ -532,33 +446,31 @@ var file_app_proxyman_config_proto_goTypes = []any{
(*InboundHandlerConfig)(nil), // 3: xray.app.proxyman.InboundHandlerConfig (*InboundHandlerConfig)(nil), // 3: xray.app.proxyman.InboundHandlerConfig
(*OutboundConfig)(nil), // 4: xray.app.proxyman.OutboundConfig (*OutboundConfig)(nil), // 4: xray.app.proxyman.OutboundConfig
(*SenderConfig)(nil), // 5: xray.app.proxyman.SenderConfig (*SenderConfig)(nil), // 5: xray.app.proxyman.SenderConfig
(*MultiplexingConfig)(nil), // 6: xray.app.proxyman.MultiplexingConfig (*geodata.DomainRule)(nil), // 6: xray.common.geodata.DomainRule
(*geodata.DomainRule)(nil), // 7: xray.common.geodata.DomainRule (*geodata.IPRule)(nil), // 7: xray.common.geodata.IPRule
(*geodata.IPRule)(nil), // 8: xray.common.geodata.IPRule (*net.PortList)(nil), // 8: xray.common.net.PortList
(*net.PortList)(nil), // 9: xray.common.net.PortList (*net.IPOrDomain)(nil), // 9: xray.common.net.IPOrDomain
(*net.IPOrDomain)(nil), // 10: xray.common.net.IPOrDomain (*internet.StreamConfig)(nil), // 10: xray.transport.internet.StreamConfig
(*internet.StreamConfig)(nil), // 11: xray.transport.internet.StreamConfig (*serial.TypedMessage)(nil), // 11: xray.common.serial.TypedMessage
(*serial.TypedMessage)(nil), // 12: xray.common.serial.TypedMessage (internet.DomainStrategy)(0), // 12: xray.transport.internet.DomainStrategy
(internet.DomainStrategy)(0), // 13: xray.transport.internet.DomainStrategy
} }
var file_app_proxyman_config_proto_depIdxs = []int32{ var file_app_proxyman_config_proto_depIdxs = []int32{
7, // 0: xray.app.proxyman.SniffingConfig.domains_excluded:type_name -> xray.common.geodata.DomainRule 6, // 0: xray.app.proxyman.SniffingConfig.domains_excluded:type_name -> xray.common.geodata.DomainRule
8, // 1: xray.app.proxyman.SniffingConfig.ips_excluded:type_name -> xray.common.geodata.IPRule 7, // 1: xray.app.proxyman.SniffingConfig.ips_excluded:type_name -> xray.common.geodata.IPRule
9, // 2: xray.app.proxyman.ReceiverConfig.port_list:type_name -> xray.common.net.PortList 8, // 2: xray.app.proxyman.ReceiverConfig.port_list:type_name -> xray.common.net.PortList
10, // 3: xray.app.proxyman.ReceiverConfig.listen:type_name -> xray.common.net.IPOrDomain 9, // 3: xray.app.proxyman.ReceiverConfig.listen:type_name -> xray.common.net.IPOrDomain
11, // 4: xray.app.proxyman.ReceiverConfig.stream_settings:type_name -> xray.transport.internet.StreamConfig 10, // 4: xray.app.proxyman.ReceiverConfig.stream_settings:type_name -> xray.transport.internet.StreamConfig
1, // 5: xray.app.proxyman.ReceiverConfig.sniffing_settings:type_name -> xray.app.proxyman.SniffingConfig 1, // 5: xray.app.proxyman.ReceiverConfig.sniffing_settings:type_name -> xray.app.proxyman.SniffingConfig
12, // 6: xray.app.proxyman.InboundHandlerConfig.receiver_settings:type_name -> xray.common.serial.TypedMessage 11, // 6: xray.app.proxyman.InboundHandlerConfig.receiver_settings:type_name -> xray.common.serial.TypedMessage
12, // 7: xray.app.proxyman.InboundHandlerConfig.proxy_settings:type_name -> xray.common.serial.TypedMessage 11, // 7: xray.app.proxyman.InboundHandlerConfig.proxy_settings:type_name -> xray.common.serial.TypedMessage
10, // 8: xray.app.proxyman.SenderConfig.via:type_name -> xray.common.net.IPOrDomain 9, // 8: xray.app.proxyman.SenderConfig.via:type_name -> xray.common.net.IPOrDomain
11, // 9: xray.app.proxyman.SenderConfig.stream_settings:type_name -> xray.transport.internet.StreamConfig 10, // 9: xray.app.proxyman.SenderConfig.stream_settings:type_name -> xray.transport.internet.StreamConfig
6, // 10: xray.app.proxyman.SenderConfig.multiplex_settings:type_name -> xray.app.proxyman.MultiplexingConfig 12, // 10: xray.app.proxyman.SenderConfig.target_strategy:type_name -> xray.transport.internet.DomainStrategy
13, // 11: xray.app.proxyman.SenderConfig.target_strategy:type_name -> xray.transport.internet.DomainStrategy 11, // [11:11] is the sub-list for method output_type
12, // [12:12] is the sub-list for method output_type 11, // [11:11] is the sub-list for method input_type
12, // [12:12] is the sub-list for method input_type 11, // [11:11] is the sub-list for extension type_name
12, // [12:12] is the sub-list for extension type_name 11, // [11:11] is the sub-list for extension extendee
12, // [12:12] is the sub-list for extension extendee 0, // [0:11] is the sub-list for field type_name
0, // [0:12] is the sub-list for field type_name
} }
func init() { file_app_proxyman_config_proto_init() } func init() { file_app_proxyman_config_proto_init() }
@@ -572,7 +484,7 @@ func file_app_proxyman_config_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(), GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_proxyman_config_proto_rawDesc), len(file_app_proxyman_config_proto_rawDesc)), RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_proxyman_config_proto_rawDesc), len(file_app_proxyman_config_proto_rawDesc)),
NumEnums: 0, NumEnums: 0,
NumMessages: 7, NumMessages: 6,
NumExtensions: 0, NumExtensions: 0,
NumServices: 0, NumServices: 0,
}, },
+2 -13
View File
@@ -57,19 +57,8 @@ message SenderConfig {
// Send traffic through the given IP. Only IP is allowed. // Send traffic through the given IP. Only IP is allowed.
xray.common.net.IPOrDomain via = 1; xray.common.net.IPOrDomain via = 1;
xray.transport.internet.StreamConfig stream_settings = 2; xray.transport.internet.StreamConfig stream_settings = 2;
reserved 3; reserved 3, 4;
MultiplexingConfig multiplex_settings = 4; reserved "multiplex_settings";
string via_cidr = 5; string via_cidr = 5;
xray.transport.internet.DomainStrategy target_strategy = 6; xray.transport.internet.DomainStrategy target_strategy = 6;
} }
message MultiplexingConfig {
// Whether or not Mux is enabled.
bool enabled = 1;
// Max number of concurrent connections that one Mux connection can handle.
int32 concurrency = 2;
// Transport XUDP in another Mux.
int32 xudpConcurrency = 3;
// "reject" (default), "allow" or "skip".
string xudpProxyUDP443 = 4;
}
+8 -7
View File
@@ -6,12 +6,12 @@ import (
"github.com/xtls/xray-core/app/proxyman" "github.com/xtls/xray-core/app/proxyman"
"github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/mux"
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/core" "github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/features/policy" "github.com/xtls/xray-core/features/policy"
"github.com/xtls/xray-core/features/routing"
"github.com/xtls/xray-core/features/stats" "github.com/xtls/xray-core/features/stats"
"github.com/xtls/xray-core/proxy" "github.com/xtls/xray-core/proxy"
"github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet"
@@ -48,7 +48,6 @@ type AlwaysOnInboundHandler struct {
receiverConfig *proxyman.ReceiverConfig receiverConfig *proxyman.ReceiverConfig
proxy proxy.Inbound proxy proxy.Inbound
workers []worker workers []worker
mux *mux.Server
tag string tag string
} }
@@ -82,11 +81,14 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
return nil, errors.New("not an inbound proxy.") return nil, errors.New("not an inbound proxy.")
} }
dispatcher := new(struct{ routing.Dispatcher })
if err := core.RequireFeatures(ctx, func(d routing.Dispatcher) { dispatcher.Dispatcher = d }); err != nil {
return nil, err
}
h := &AlwaysOnInboundHandler{ h := &AlwaysOnInboundHandler{
receiverConfig: receiverConfig, receiverConfig: receiverConfig,
proxyConfig: proxyConfig, proxyConfig: proxyConfig,
proxy: p, proxy: p,
mux: mux.NewServer(ctx),
tag: tag, tag: tag,
} }
@@ -117,7 +119,7 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
proxy: p, proxy: p,
stream: mss, stream: mss,
tag: tag, tag: tag,
dispatcher: h.mux, dispatcher: dispatcher,
sniffingRequest: sniffingRequest, sniffingRequest: sniffingRequest,
uplinkCounter: uplinkCounter, uplinkCounter: uplinkCounter,
downlinkCounter: downlinkCounter, downlinkCounter: downlinkCounter,
@@ -139,7 +141,7 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
stream: mss, stream: mss,
recvOrigDest: receiverConfig.ReceiveOriginalDestination, recvOrigDest: receiverConfig.ReceiveOriginalDestination,
tag: tag, tag: tag,
dispatcher: h.mux, dispatcher: dispatcher,
sniffingRequest: sniffingRequest, sniffingRequest: sniffingRequest,
uplinkCounter: uplinkCounter, uplinkCounter: uplinkCounter,
downlinkCounter: downlinkCounter, downlinkCounter: downlinkCounter,
@@ -154,7 +156,7 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
proxy: p, proxy: p,
address: address, address: address,
port: net.Port(port), port: net.Port(port),
dispatcher: h.mux, dispatcher: dispatcher,
sniffingRequest: sniffingRequest, sniffingRequest: sniffingRequest,
uplinkCounter: uplinkCounter, uplinkCounter: uplinkCounter,
downlinkCounter: downlinkCounter, downlinkCounter: downlinkCounter,
@@ -192,7 +194,6 @@ func (h *AlwaysOnInboundHandler) Close() error {
for _, worker := range h.workers { for _, worker := range h.workers {
errs = append(errs, worker.Close()) errs = append(errs, worker.Close())
} }
errs = append(errs, h.mux.Close())
errs = append(errs, common.Close(h.proxy)) errs = append(errs, common.Close(h.proxy))
if err := errors.Combine(errs...); err != nil { if err := errors.Combine(errs...); err != nil {
return errors.New("failed to close all resources").Base(err) return errors.New("failed to close all resources").Base(err)
-4
View File
@@ -7,7 +7,6 @@ import (
"github.com/xtls/xray-core/app/proxyman" "github.com/xtls/xray-core/app/proxyman"
"github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/core" "github.com/xtls/xray-core/core"
@@ -184,9 +183,6 @@ func NewHandler(ctx context.Context, config *core.InboundHandlerConfig) (inbound
Mark: streamSettings.SocketSettings.Mark, Mark: streamSettings.SocketSettings.Mark,
}) })
} }
if streamSettings != nil && (streamSettings.ProtocolName == "splithttp" || streamSettings.ProtocolName == "masque") {
ctx = session.ContextWithAllowedNetwork(ctx, net.Network_UDP)
}
return NewAlwaysOnInboundHandler(ctx, tag, receiverSettings, proxySettings) return NewAlwaysOnInboundHandler(ctx, tag, receiverSettings, proxySettings)
} }
+34 -111
View File
@@ -13,7 +13,6 @@ import (
"github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/mux"
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/common/session"
@@ -60,9 +59,6 @@ type Handler struct {
streamSettings *internet.MemoryStreamConfig streamSettings *internet.MemoryStreamConfig
proxyConfig proto.Message proxyConfig proto.Message
proxy proxy.Outbound proxy proxy.Outbound
mux *mux.ClientManager
xudp *mux.ClientManager
udp443 string
uplinkCounter stats.Counter uplinkCounter stats.Counter
downlinkCounter stats.Counter downlinkCounter stats.Counter
} }
@@ -117,57 +113,6 @@ func NewHandler(ctx context.Context, config *core.OutboundHandlerConfig) (outbou
return nil, errors.New("not an outbound handler") return nil, errors.New("not an outbound handler")
} }
if h.senderSettings != nil && h.senderSettings.MultiplexSettings != nil {
if config := h.senderSettings.MultiplexSettings; config.Enabled {
if config.Concurrency < 0 {
h.mux = &mux.ClientManager{Enabled: false}
}
if config.Concurrency == 0 {
config.Concurrency = 8 // same as before
}
if config.Concurrency > 0 && config.Concurrency < 128 && h.streamSettings != nil && h.streamSettings.ProtocolName == "xdrive" {
config.Concurrency = 128
}
if config.Concurrency > 0 {
h.mux = &mux.ClientManager{
Enabled: true,
Picker: &mux.IncrementalWorkerPicker{
Factory: &mux.DialingWorkerFactory{
Proxy: proxyHandler,
Dialer: h,
Strategy: mux.ClientStrategy{
MaxConcurrency: uint32(config.Concurrency),
MaxConnection: 1024,
},
},
},
}
}
if config.XudpConcurrency < 0 {
h.xudp = &mux.ClientManager{Enabled: false}
}
if config.XudpConcurrency == 0 {
h.xudp = nil // same as before
}
if config.XudpConcurrency > 0 {
h.xudp = &mux.ClientManager{
Enabled: true,
Picker: &mux.IncrementalWorkerPicker{
Factory: &mux.DialingWorkerFactory{
Proxy: proxyHandler,
Dialer: h,
Strategy: mux.ClientStrategy{
MaxConcurrency: uint32(config.XudpConcurrency),
MaxConnection: 1024,
},
},
},
}
}
h.udp443 = config.XudpProxyUDP443
}
}
h.proxy = proxyHandler h.proxy = proxyHandler
return h, nil return h, nil
} }
@@ -181,65 +126,44 @@ func (h *Handler) Tag() string {
func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) { func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) {
outbounds := session.OutboundsFromContext(ctx) outbounds := session.OutboundsFromContext(ctx)
ob := outbounds[len(outbounds)-1] ob := outbounds[len(outbounds)-1]
content := session.ContentFromContext(ctx) if h.senderSettings != nil && h.senderSettings.TargetStrategy.HasStrategy() && ob.Target.Address.Family().IsDomain() {
if h.senderSettings != nil && h.senderSettings.TargetStrategy.HasStrategy() && ob.Target.Address.Family().IsDomain() && (content == nil || !content.SkipDNSResolve) { if session.SkipDNSResolveFromContext(ctx) {
strategy := h.senderSettings.TargetStrategy errors.LogInfo(ctx, "bypassing targetStrategy ", h.senderSettings.TargetStrategy, " for ", ob.Target, "; preserving target domain")
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil {
strategy = strategy.GetDynamicStrategy(ob.OriginalTarget.Address.Family())
}
ips, err := internet.LookupForIP(ob.Target.Address.Domain(), strategy, nil)
if err != nil {
errors.LogInfoInner(ctx, err, "failed to resolve ip for target ", ob.Target.Address.Domain())
if h.senderSettings.TargetStrategy.ForceIP() {
err := errors.New("failed to resolve ip for target ", ob.Target.Address.Domain()).Base(err)
session.SubmitOutboundErrorToOriginator(ctx, err)
common.Interrupt(link.Writer)
common.Interrupt(link.Reader)
return
}
} else { } else {
unchangedDomain := ob.Target.Address.Domain() strategy := h.senderSettings.TargetStrategy
ob.Target.Address = net.IPAddress(ips[dice.Roll(len(ips))]) if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil {
errors.LogInfo(ctx, "target: ", unchangedDomain, " resolved to: ", ob.Target.Address.String()) strategy = strategy.GetDynamicStrategy(ob.OriginalTarget.Address.Family())
}
ips, err := internet.LookupForIP(ob.Target.Address.Domain(), strategy, nil)
if err != nil {
errors.LogInfoInner(ctx, err, "failed to resolve ip for target ", ob.Target.Address.Domain())
if h.senderSettings.TargetStrategy.ForceIP() {
err := errors.New("failed to resolve ip for target ", ob.Target.Address.Domain()).Base(err)
session.SubmitOutboundErrorToOriginator(ctx, err)
common.Interrupt(link.Writer)
common.Interrupt(link.Reader)
return
}
} else {
unchangedDomain := ob.Target.Address.Domain()
ob.Target.Address = net.IPAddress(ips[dice.Roll(len(ips))])
errors.LogInfo(ctx, "target: ", unchangedDomain, " resolved to: ", ob.Target.Address.String())
}
} }
} }
reader, writer := link.Reader, link.Writer
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address { if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
link.Reader = &buf.EndpointOverrideReader{Reader: link.Reader, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address} link.Reader = &buf.EndpointOverrideReader{Reader: link.Reader, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
link.Writer = &buf.EndpointOverrideWriter{Writer: link.Writer, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address} link.Writer = &buf.EndpointOverrideWriter{Writer: link.Writer, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
} }
if h.mux != nil {
test := func(err error) {
if err != nil {
err := errors.New("failed to process mux outbound traffic").Base(err)
session.SubmitOutboundErrorToOriginator(ctx, err)
errors.LogInfo(ctx, err.Error())
common.Interrupt(link.Writer)
common.Interrupt(link.Reader)
}
}
if ob.Target.Network == net.Network_UDP && ob.Target.Port == 443 {
switch h.udp443 {
case "reject":
test(errors.New("XUDP rejected UDP/443 traffic"))
return
case "skip":
goto out
}
}
if h.xudp != nil && ob.Target.Network == net.Network_UDP {
if !h.xudp.Enabled {
goto out
}
test(h.xudp.Dispatch(ctx, link))
return
}
if h.mux.Enabled {
test(h.mux.Dispatch(ctx, link))
return
}
}
out:
err := h.proxy.Process(ctx, link, h) err := h.proxy.Process(ctx, link, h)
var completion interface{ DeferWriterClose() bool }
if goerrors.As(err, &completion) && completion.DeferWriterClose() {
go common.Close(writer)
common.Interrupt(reader)
return
}
var errC error var errC error
if err != nil { if err != nil {
errC = errors.Cause(err) errC = errors.Cause(err)
@@ -252,15 +176,15 @@ out:
err := errors.New("failed to process outbound traffic").Base(err) err := errors.New("failed to process outbound traffic").Base(err)
session.SubmitOutboundErrorToOriginator(ctx, err) session.SubmitOutboundErrorToOriginator(ctx, err)
errors.LogInfo(ctx, err.Error()) errors.LogInfo(ctx, err.Error())
common.Interrupt(link.Writer) common.Interrupt(writer)
} else { } else {
if errC != nil && goerrors.Is(errC, io.ErrClosedPipe) { if errC != nil && goerrors.Is(errC, io.ErrClosedPipe) {
common.Interrupt(link.Writer) common.Interrupt(writer)
} else { } else {
common.Close(link.Writer) common.Close(writer)
} }
} }
common.Interrupt(link.Reader) common.Interrupt(reader)
} }
func (h *Handler) DestIpAddress() net.IP { func (h *Handler) DestIpAddress() net.IP {
@@ -332,7 +256,6 @@ func (h *Handler) Start() error {
// Close implements common.Closable. // Close implements common.Closable.
func (h *Handler) Close() error { func (h *Handler) Close() error {
common.Close(h.mux)
common.Close(h.proxy) common.Close(h.proxy)
return nil return nil
} }
-235
View File
@@ -1,235 +0,0 @@
package reverse
import (
"context"
"time"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/mux"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/common/signal"
"github.com/xtls/xray-core/common/task"
"github.com/xtls/xray-core/features/routing"
"github.com/xtls/xray-core/transport"
"github.com/xtls/xray-core/transport/pipe"
"google.golang.org/protobuf/proto"
)
// Bridge is a component in reverse proxy, that relays connections from Portal to local address.
type Bridge struct {
dispatcher routing.Dispatcher
tag string
domain string
workers []*BridgeWorker
monitorTask *task.Periodic
}
// NewBridge creates a new Bridge instance.
func NewBridge(config *BridgeConfig, dispatcher routing.Dispatcher) (*Bridge, error) {
if config.Tag == "" {
return nil, errors.New("bridge tag is empty")
}
if config.Domain == "" {
return nil, errors.New("bridge domain is empty")
}
b := &Bridge{
dispatcher: dispatcher,
tag: config.Tag,
domain: config.Domain,
}
b.monitorTask = &task.Periodic{
Execute: b.monitor,
Interval: time.Second * 2,
}
return b, nil
}
func (b *Bridge) cleanup() {
var activeWorkers []*BridgeWorker
for _, w := range b.workers {
if w.IsActive() {
activeWorkers = append(activeWorkers, w)
}
if w.Closed() {
if w.Timer != nil {
w.Timer.SetTimeout(0)
}
}
}
if len(activeWorkers) != len(b.workers) {
b.workers = activeWorkers
}
}
func (b *Bridge) monitor() error {
b.cleanup()
var numConnections uint32
var numWorker uint32
for _, w := range b.workers {
if w.IsActive() {
numConnections += w.Connections()
numWorker++
}
}
if numWorker == 0 || numConnections/numWorker > 16 {
worker, err := NewBridgeWorker(b.domain, b.tag, b.dispatcher)
if err != nil {
errors.LogWarningInner(context.Background(), err, "failed to create bridge worker")
return nil
}
b.workers = append(b.workers, worker)
}
return nil
}
func (b *Bridge) Start() error {
return b.monitorTask.Start()
}
func (b *Bridge) Close() error {
return b.monitorTask.Close()
}
type BridgeWorker struct {
Tag string
Worker *mux.ServerWorker
Dispatcher routing.Dispatcher
State Control_State
Timer *signal.ActivityTimer
}
func NewBridgeWorker(domain string, tag string, d routing.Dispatcher) (*BridgeWorker, error) {
ctx := context.Background()
ctx = session.ContextWithInbound(ctx, &session.Inbound{
Tag: tag,
})
link, err := d.Dispatch(ctx, net.Destination{
Network: net.Network_TCP,
Address: net.DomainAddress(domain),
Port: 0,
})
if err != nil {
return nil, err
}
w := &BridgeWorker{
Dispatcher: d,
Tag: tag,
}
worker, err := mux.NewServerWorker(context.Background(), w, link)
if err != nil {
return nil, err
}
w.Worker = worker
terminate := func() {
worker.Close()
}
w.Timer = signal.CancelAfterInactivity(ctx, terminate, 60*time.Second)
return w, nil
}
func (w *BridgeWorker) Type() interface{} {
return routing.DispatcherType()
}
func (w *BridgeWorker) Start() error {
return nil
}
func (w *BridgeWorker) Close() error {
return nil
}
func (w *BridgeWorker) IsActive() bool {
return w.State == Control_ACTIVE && !w.Worker.Closed()
}
func (w *BridgeWorker) Closed() bool {
return w.Worker.Closed()
}
func (w *BridgeWorker) Connections() uint32 {
return w.Worker.ActiveConnections()
}
func (w *BridgeWorker) handleInternalConn(link *transport.Link) {
reader := link.Reader
for {
mb, err := reader.ReadMultiBuffer()
if err != nil {
if w.Timer != nil {
if w.Closed() {
w.Timer.SetTimeout(0)
} else {
w.Timer.SetTimeout(24 * time.Hour)
}
}
return
}
if w.Timer != nil {
w.Timer.Update()
}
for _, b := range mb {
var ctl Control
if err := proto.Unmarshal(b.Bytes(), &ctl); err != nil {
errors.LogInfoInner(context.Background(), err, "failed to parse proto message")
if w.Timer != nil {
w.Timer.SetTimeout(0)
}
return
}
if ctl.State != w.State {
w.State = ctl.State
}
}
}
}
func (w *BridgeWorker) Dispatch(ctx context.Context, dest net.Destination) (*transport.Link, error) {
if !isInternalDomain(dest) {
if session.InboundFromContext(ctx) == nil {
ctx = session.ContextWithInbound(ctx, &session.Inbound{
Tag: w.Tag,
})
}
return w.Dispatcher.Dispatch(ctx, dest)
}
opt := []pipe.Option{pipe.WithSizeLimit(16 * 1024)}
uplinkReader, uplinkWriter := pipe.New(opt...)
downlinkReader, downlinkWriter := pipe.New(opt...)
go w.handleInternalConn(&transport.Link{
Reader: downlinkReader,
Writer: uplinkWriter,
})
return &transport.Link{
Reader: uplinkReader,
Writer: downlinkWriter,
}, nil
}
func (w *BridgeWorker) DispatchLink(ctx context.Context, dest net.Destination, link *transport.Link) error {
if !isInternalDomain(dest) {
if session.InboundFromContext(ctx) == nil {
ctx = session.ContextWithInbound(ctx, &session.Inbound{
Tag: w.Tag,
})
}
return w.Dispatcher.DispatchLink(ctx, dest, link)
}
w.handleInternalConn(link)
return nil
}
-356
View File
@@ -1,356 +0,0 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.12
// protoc (unknown)
// source: app/reverse/config.proto
package reverse
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Control_State int32
const (
Control_ACTIVE Control_State = 0
Control_DRAIN Control_State = 1
)
// Enum value maps for Control_State.
var (
Control_State_name = map[int32]string{
0: "ACTIVE",
1: "DRAIN",
}
Control_State_value = map[string]int32{
"ACTIVE": 0,
"DRAIN": 1,
}
)
func (x Control_State) Enum() *Control_State {
p := new(Control_State)
*p = x
return p
}
func (x Control_State) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (Control_State) Descriptor() protoreflect.EnumDescriptor {
return file_app_reverse_config_proto_enumTypes[0].Descriptor()
}
func (Control_State) Type() protoreflect.EnumType {
return &file_app_reverse_config_proto_enumTypes[0]
}
func (x Control_State) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use Control_State.Descriptor instead.
func (Control_State) EnumDescriptor() ([]byte, []int) {
return file_app_reverse_config_proto_rawDescGZIP(), []int{0, 0}
}
type Control struct {
state protoimpl.MessageState `protogen:"open.v1"`
State Control_State `protobuf:"varint,1,opt,name=state,proto3,enum=xray.app.reverse.Control_State" json:"state,omitempty"`
Random []byte `protobuf:"bytes,99,opt,name=random,proto3" json:"random,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Control) Reset() {
*x = Control{}
mi := &file_app_reverse_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Control) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Control) ProtoMessage() {}
func (x *Control) ProtoReflect() protoreflect.Message {
mi := &file_app_reverse_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Control.ProtoReflect.Descriptor instead.
func (*Control) Descriptor() ([]byte, []int) {
return file_app_reverse_config_proto_rawDescGZIP(), []int{0}
}
func (x *Control) GetState() Control_State {
if x != nil {
return x.State
}
return Control_ACTIVE
}
func (x *Control) GetRandom() []byte {
if x != nil {
return x.Random
}
return nil
}
type BridgeConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"`
Domain string `protobuf:"bytes,2,opt,name=domain,proto3" json:"domain,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *BridgeConfig) Reset() {
*x = BridgeConfig{}
mi := &file_app_reverse_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *BridgeConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*BridgeConfig) ProtoMessage() {}
func (x *BridgeConfig) ProtoReflect() protoreflect.Message {
mi := &file_app_reverse_config_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use BridgeConfig.ProtoReflect.Descriptor instead.
func (*BridgeConfig) Descriptor() ([]byte, []int) {
return file_app_reverse_config_proto_rawDescGZIP(), []int{1}
}
func (x *BridgeConfig) GetTag() string {
if x != nil {
return x.Tag
}
return ""
}
func (x *BridgeConfig) GetDomain() string {
if x != nil {
return x.Domain
}
return ""
}
type PortalConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"`
Domain string `protobuf:"bytes,2,opt,name=domain,proto3" json:"domain,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *PortalConfig) Reset() {
*x = PortalConfig{}
mi := &file_app_reverse_config_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *PortalConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*PortalConfig) ProtoMessage() {}
func (x *PortalConfig) ProtoReflect() protoreflect.Message {
mi := &file_app_reverse_config_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use PortalConfig.ProtoReflect.Descriptor instead.
func (*PortalConfig) Descriptor() ([]byte, []int) {
return file_app_reverse_config_proto_rawDescGZIP(), []int{2}
}
func (x *PortalConfig) GetTag() string {
if x != nil {
return x.Tag
}
return ""
}
func (x *PortalConfig) GetDomain() string {
if x != nil {
return x.Domain
}
return ""
}
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
BridgeConfig []*BridgeConfig `protobuf:"bytes,1,rep,name=bridge_config,json=bridgeConfig,proto3" json:"bridge_config,omitempty"`
PortalConfig []*PortalConfig `protobuf:"bytes,2,rep,name=portal_config,json=portalConfig,proto3" json:"portal_config,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_app_reverse_config_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_app_reverse_config_proto_msgTypes[3]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_app_reverse_config_proto_rawDescGZIP(), []int{3}
}
func (x *Config) GetBridgeConfig() []*BridgeConfig {
if x != nil {
return x.BridgeConfig
}
return nil
}
func (x *Config) GetPortalConfig() []*PortalConfig {
if x != nil {
return x.PortalConfig
}
return nil
}
var File_app_reverse_config_proto protoreflect.FileDescriptor
const file_app_reverse_config_proto_rawDesc = "" +
"\n" +
"\x18app/reverse/config.proto\x12\x10xray.app.reverse\"x\n" +
"\aControl\x125\n" +
"\x05state\x18\x01 \x01(\x0e2\x1f.xray.app.reverse.Control.StateR\x05state\x12\x16\n" +
"\x06random\x18c \x01(\fR\x06random\"\x1e\n" +
"\x05State\x12\n" +
"\n" +
"\x06ACTIVE\x10\x00\x12\t\n" +
"\x05DRAIN\x10\x01\"8\n" +
"\fBridgeConfig\x12\x10\n" +
"\x03tag\x18\x01 \x01(\tR\x03tag\x12\x16\n" +
"\x06domain\x18\x02 \x01(\tR\x06domain\"8\n" +
"\fPortalConfig\x12\x10\n" +
"\x03tag\x18\x01 \x01(\tR\x03tag\x12\x16\n" +
"\x06domain\x18\x02 \x01(\tR\x06domain\"\x92\x01\n" +
"\x06Config\x12C\n" +
"\rbridge_config\x18\x01 \x03(\v2\x1e.xray.app.reverse.BridgeConfigR\fbridgeConfig\x12C\n" +
"\rportal_config\x18\x02 \x03(\v2\x1e.xray.app.reverse.PortalConfigR\fportalConfigBV\n" +
"\x16com.xray.proxy.reverseP\x01Z%github.com/xtls/xray-core/app/reverse\xaa\x02\x12Xray.Proxy.Reverseb\x06proto3"
var (
file_app_reverse_config_proto_rawDescOnce sync.Once
file_app_reverse_config_proto_rawDescData []byte
)
func file_app_reverse_config_proto_rawDescGZIP() []byte {
file_app_reverse_config_proto_rawDescOnce.Do(func() {
file_app_reverse_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_reverse_config_proto_rawDesc), len(file_app_reverse_config_proto_rawDesc)))
})
return file_app_reverse_config_proto_rawDescData
}
var file_app_reverse_config_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_app_reverse_config_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
var file_app_reverse_config_proto_goTypes = []any{
(Control_State)(0), // 0: xray.app.reverse.Control.State
(*Control)(nil), // 1: xray.app.reverse.Control
(*BridgeConfig)(nil), // 2: xray.app.reverse.BridgeConfig
(*PortalConfig)(nil), // 3: xray.app.reverse.PortalConfig
(*Config)(nil), // 4: xray.app.reverse.Config
}
var file_app_reverse_config_proto_depIdxs = []int32{
0, // 0: xray.app.reverse.Control.state:type_name -> xray.app.reverse.Control.State
2, // 1: xray.app.reverse.Config.bridge_config:type_name -> xray.app.reverse.BridgeConfig
3, // 2: xray.app.reverse.Config.portal_config:type_name -> xray.app.reverse.PortalConfig
3, // [3:3] is the sub-list for method output_type
3, // [3:3] is the sub-list for method input_type
3, // [3:3] is the sub-list for extension type_name
3, // [3:3] is the sub-list for extension extendee
0, // [0:3] is the sub-list for field type_name
}
func init() { file_app_reverse_config_proto_init() }
func file_app_reverse_config_proto_init() {
if File_app_reverse_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_reverse_config_proto_rawDesc), len(file_app_reverse_config_proto_rawDesc)),
NumEnums: 1,
NumMessages: 4,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_app_reverse_config_proto_goTypes,
DependencyIndexes: file_app_reverse_config_proto_depIdxs,
EnumInfos: file_app_reverse_config_proto_enumTypes,
MessageInfos: file_app_reverse_config_proto_msgTypes,
}.Build()
File_app_reverse_config_proto = out.File
file_app_reverse_config_proto_goTypes = nil
file_app_reverse_config_proto_depIdxs = nil
}
-32
View File
@@ -1,32 +0,0 @@
syntax = "proto3";
package xray.app.reverse;
option csharp_namespace = "Xray.Proxy.Reverse";
option go_package = "github.com/xtls/xray-core/app/reverse";
option java_package = "com.xray.proxy.reverse";
option java_multiple_files = true;
message Control {
enum State {
ACTIVE = 0;
DRAIN = 1;
}
State state = 1;
bytes random = 99;
}
message BridgeConfig {
string tag = 1;
string domain = 2;
}
message PortalConfig {
string tag = 1;
string domain = 2;
}
message Config {
repeated BridgeConfig bridge_config = 1;
repeated PortalConfig portal_config = 2;
}
-308
View File
@@ -1,308 +0,0 @@
package reverse
import (
"context"
"sync"
"time"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/mux"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/common/signal"
"github.com/xtls/xray-core/common/task"
"github.com/xtls/xray-core/features/outbound"
"github.com/xtls/xray-core/transport"
"github.com/xtls/xray-core/transport/pipe"
"google.golang.org/protobuf/proto"
)
type Portal struct {
ohm outbound.Manager
tag string
domain string
picker *StaticMuxPicker
client *mux.ClientManager
}
func NewPortal(config *PortalConfig, ohm outbound.Manager) (*Portal, error) {
if config.Tag == "" {
return nil, errors.New("portal tag is empty")
}
if config.Domain == "" {
return nil, errors.New("portal domain is empty")
}
picker, err := NewStaticMuxPicker()
if err != nil {
return nil, err
}
return &Portal{
ohm: ohm,
tag: config.Tag,
domain: config.Domain,
picker: picker,
client: &mux.ClientManager{
Picker: picker,
},
}, nil
}
func (p *Portal) Start() error {
return p.ohm.AddHandler(context.Background(), &Outbound{
portal: p,
tag: p.tag,
})
}
func (p *Portal) Close() error {
return p.ohm.RemoveHandler(context.Background(), p.tag)
}
func (p *Portal) HandleConnection(ctx context.Context, link *transport.Link) error {
outbounds := session.OutboundsFromContext(ctx)
ob := outbounds[len(outbounds)-1]
if ob == nil {
return errors.New("outbound metadata not found")
}
if isDomain(ob.Target, p.domain) {
muxClient, err := mux.NewClientWorker(*link, mux.ClientStrategy{})
if err != nil {
return errors.New("failed to create mux client worker").Base(err)
}
worker, err := NewPortalWorker(muxClient)
if err != nil {
return errors.New("failed to create portal worker").Base(err)
}
p.picker.AddWorker(worker)
if _, ok := link.Reader.(*pipe.Reader); !ok {
select {
case <-ctx.Done():
case <-muxClient.WaitClosed():
}
}
return nil
}
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
link.Reader = &buf.EndpointOverrideReader{Reader: link.Reader, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
link.Writer = &buf.EndpointOverrideWriter{Writer: link.Writer, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
}
return p.client.Dispatch(ctx, link)
}
type Outbound struct {
portal *Portal
tag string
}
func (o *Outbound) Tag() string {
return o.tag
}
func (o *Outbound) Dispatch(ctx context.Context, link *transport.Link) {
if err := o.portal.HandleConnection(ctx, link); err != nil {
errors.LogInfoInner(ctx, err, "failed to process reverse connection")
common.Interrupt(link.Writer)
common.Interrupt(link.Reader)
}
}
func (o *Outbound) Start() error {
return nil
}
func (o *Outbound) Close() error {
return nil
}
// SenderSettings implements outbound.Handler.
func (o *Outbound) SenderSettings() *serial.TypedMessage {
return nil
}
// ProxySettings implements outbound.Handler.
func (o *Outbound) ProxySettings() *serial.TypedMessage {
return nil
}
type StaticMuxPicker struct {
access sync.Mutex
workers []*PortalWorker
cTask *task.Periodic
}
func NewStaticMuxPicker() (*StaticMuxPicker, error) {
p := &StaticMuxPicker{}
p.cTask = &task.Periodic{
Execute: p.cleanup,
Interval: time.Second * 30,
}
p.cTask.Start()
return p, nil
}
func (p *StaticMuxPicker) cleanup() error {
p.access.Lock()
defer p.access.Unlock()
var activeWorkers []*PortalWorker
for _, w := range p.workers {
if !w.Closed() {
activeWorkers = append(activeWorkers, w)
} else {
w.timer.SetTimeout(0)
}
}
if len(activeWorkers) != len(p.workers) {
p.workers = activeWorkers
}
return nil
}
func (p *StaticMuxPicker) PickAvailable() (*mux.ClientWorker, error) {
p.access.Lock()
defer p.access.Unlock()
if len(p.workers) == 0 {
return nil, errors.New("empty worker list")
}
var minIdx int = -1
var minConn uint32 = 9999
for i, w := range p.workers {
if w.draining {
continue
}
if w.IsFull() {
continue
}
if w.client.ActiveConnections() < minConn {
minConn = w.client.ActiveConnections()
minIdx = i
}
}
if minIdx == -1 {
for i, w := range p.workers {
if w.IsFull() {
continue
}
if w.client.ActiveConnections() < minConn {
minConn = w.client.ActiveConnections()
minIdx = i
}
}
}
if minIdx != -1 {
return p.workers[minIdx].client, nil
}
return nil, errors.New("no mux client worker available")
}
func (p *StaticMuxPicker) AddWorker(worker *PortalWorker) {
p.access.Lock()
defer p.access.Unlock()
p.workers = append(p.workers, worker)
}
type PortalWorker struct {
client *mux.ClientWorker
control *task.Periodic
writer buf.Writer
reader buf.Reader
draining bool
counter uint32
timer *signal.ActivityTimer
}
func NewPortalWorker(client *mux.ClientWorker) (*PortalWorker, error) {
opt := []pipe.Option{pipe.WithSizeLimit(16 * 1024)}
uplinkReader, uplinkWriter := pipe.New(opt...)
downlinkReader, downlinkWriter := pipe.New(opt...)
ctx := context.Background()
outbounds := []*session.Outbound{{
Target: net.UDPDestination(net.DomainAddress(internalDomain), 0),
}}
ctx = session.ContextWithOutbounds(ctx, outbounds)
f := client.Dispatch(ctx, &transport.Link{
Reader: uplinkReader,
Writer: downlinkWriter,
})
if !f {
return nil, errors.New("unable to dispatch control connection")
}
terminate := func() {
client.Close()
}
w := &PortalWorker{
client: client,
reader: downlinkReader,
writer: uplinkWriter,
timer: signal.CancelAfterInactivity(ctx, terminate, 24*time.Hour), // // prevent leak
}
w.control = &task.Periodic{
Execute: w.heartbeat,
Interval: time.Second * 2,
}
w.control.Start()
return w, nil
}
func (w *PortalWorker) heartbeat() error {
if w.Closed() {
return errors.New("client worker stopped")
}
if w.draining || w.writer == nil {
return errors.New("already disposed")
}
msg := &Control{}
msg.FillInRandom()
if w.client.TotalConnections() > 256 {
w.draining = true
msg.State = Control_DRAIN
defer func() {
common.Close(w.writer)
common.Interrupt(w.reader)
w.writer = nil
}()
}
w.counter = (w.counter + 1) % 5
if w.draining || w.counter == 1 {
b, err := proto.Marshal(msg)
common.Must(err)
mb := buf.MergeBytes(nil, b)
w.timer.Update()
return w.writer.WriteMultiBuffer(mb)
}
return nil
}
func (w *PortalWorker) IsFull() bool {
return w.client.IsFull()
}
func (w *PortalWorker) Closed() bool {
return w.client.Closed()
}
-20
View File
@@ -1,20 +0,0 @@
package reverse_test
import (
"testing"
"github.com/xtls/xray-core/app/reverse"
"github.com/xtls/xray-core/common"
)
func TestStaticPickerEmpty(t *testing.T) {
picker, err := reverse.NewStaticMuxPicker()
common.Must(err)
worker, err := picker.PickAvailable()
if err == nil {
t.Error("expected error, but nil")
}
if worker != nil {
t.Error("expected nil worker, but not nil")
}
}
-94
View File
@@ -1,94 +0,0 @@
package reverse
import (
"context"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
core "github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/features/outbound"
"github.com/xtls/xray-core/features/routing"
)
const (
internalDomain = "reverse"
)
func isDomain(dest net.Destination, domain string) bool {
return dest.Address.Family().IsDomain() && dest.Address.Domain() == domain
}
func isInternalDomain(dest net.Destination) bool {
return isDomain(dest, internalDomain)
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
r := new(Reverse)
if err := core.RequireFeatures(ctx, func(d routing.Dispatcher, om outbound.Manager) error {
return r.Init(config.(*Config), d, om)
}); err != nil {
return nil, err
}
return r, nil
}))
}
type Reverse struct {
bridges []*Bridge
portals []*Portal
}
func (r *Reverse) Init(config *Config, d routing.Dispatcher, ohm outbound.Manager) error {
for _, bConfig := range config.BridgeConfig {
b, err := NewBridge(bConfig, d)
if err != nil {
return err
}
r.bridges = append(r.bridges, b)
}
for _, pConfig := range config.PortalConfig {
p, err := NewPortal(pConfig, ohm)
if err != nil {
return err
}
r.portals = append(r.portals, p)
}
return nil
}
func (r *Reverse) Type() interface{} {
return (*Reverse)(nil)
}
func (r *Reverse) Start() error {
for _, b := range r.bridges {
if err := b.Start(); err != nil {
return err
}
}
for _, p := range r.portals {
if err := p.Start(); err != nil {
return err
}
}
return nil
}
func (r *Reverse) Close() error {
var errs []error
for _, b := range r.bridges {
errs = append(errs, b.Close())
}
for _, p := range r.portals {
errs = append(errs, p.Close())
}
return errors.Combine(errs...)
}
+2 -3
View File
@@ -44,9 +44,8 @@ func (c routingContext) GetRuleTag() string {
return "" return ""
} }
// GetSkipDNSResolve is a mock implementation here to match the interface, // GetSkipDNSResolve implements routing.Context.
// SkipDNSResolve is set from dns module, no use if coming from a protobuf object? // The protobuf RoutingContext has no skip flag, so API contexts use false.
// TODO: please confirm @Vigilans
func (c routingContext) GetSkipDNSResolve() bool { func (c routingContext) GetSkipDNSResolve() bool {
return false return false
} }
+3 -23
View File
@@ -15,8 +15,6 @@ const (
var ErrBufferFull = errors.New("buffer is full") var ErrBufferFull = errors.New("buffer is full")
var pool = bytespool.GetPool(Size)
// ownership represents the data owner of the buffer. // ownership represents the data owner of the buffer.
type ownership uint8 type ownership uint8
@@ -39,16 +37,7 @@ type Buffer struct {
// New creates a Buffer with 0 length and 8K capacity, managed. // New creates a Buffer with 0 length and 8K capacity, managed.
func New() *Buffer { func New() *Buffer {
buf := pool.Get().([]byte) return &Buffer{v: bytespool.Alloc(Size)}
if cap(buf) >= Size {
buf = buf[:Size]
} else {
buf = make([]byte, Size)
}
return &Buffer{
v: buf,
}
} }
// NewExisted creates a standard size Buffer with an existed bytearray, managed. // NewExisted creates a standard size Buffer with an existed bytearray, managed.
@@ -80,16 +69,7 @@ func FromBytes(b []byte) *Buffer {
// StackNew creates a new Buffer object on stack, managed. // StackNew creates a new Buffer object on stack, managed.
// This method is for buffers that is released in the same function. // This method is for buffers that is released in the same function.
func StackNew() Buffer { func StackNew() Buffer {
buf := pool.Get().([]byte) return Buffer{v: bytespool.Alloc(Size)}
if cap(buf) >= Size {
buf = buf[:Size]
} else {
buf = make([]byte, Size)
}
return Buffer{
v: buf,
}
} }
// NewWithSize creates a Buffer with 0 length and capacity with at least the given size, bytespool's. // NewWithSize creates a Buffer with 0 length and capacity with at least the given size, bytespool's.
@@ -113,7 +93,7 @@ func (b *Buffer) Release() {
switch b.ownership { switch b.ownership {
case managed: case managed:
if cap(p) == Size { if cap(p) == Size {
pool.Put(p) bytespool.Free(p)
} }
case bytespools: case bytespools:
bytespool.Free(p) bytespool.Free(p)
+64 -52
View File
@@ -1,72 +1,84 @@
package bytespool package bytespool
import "sync" import (
"math/bits"
"sync"
)
func createAllocFunc(size int32) func() interface{} {
return func() interface{} {
return make([]byte, size)
}
}
// The following parameters controls the size of buffer pools.
// There are numPools pools. Starting from 2k size, the size of each pool is sizeMulti of the previous one.
// Package buf is guaranteed to not use buffers larger than the largest pool.
// Other packets may use larger buffers.
const ( const (
numPools = 4 minShift = 10 // 1KB
sizeMulti = 4 maxShift = 16 // 64KB
numPools = maxShift - minShift + 1
minSize = 1 << minShift
maxSize = 1 << maxShift
) )
var ( // pools hold array pointers (*[N]byte) to avoid interface boxing allocations on Put.
pool [numPools]sync.Pool var pools = [numPools]sync.Pool{
poolSize [numPools]int32 {New: func() any { return new([1 << 10]byte) }},
) {New: func() any { return new([1 << 11]byte) }},
{New: func() any { return new([1 << 12]byte) }},
func init() { {New: func() any { return new([1 << 13]byte) }},
size := int32(2048) {New: func() any { return new([1 << 14]byte) }},
for i := 0; i < numPools; i++ { {New: func() any { return new([1 << 15]byte) }},
pool[i] = sync.Pool{ {New: func() any { return new([1 << 16]byte) }},
New: createAllocFunc(size),
}
poolSize[i] = size
size *= sizeMulti
}
} }
// GetPool returns a sync.Pool that generates bytes array with at least the given size. // Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 1024.
// It may return nil if no such pool exists.
//
// xray:api:stable
func GetPool(size int32) *sync.Pool {
for idx, ps := range poolSize {
if size <= ps {
return &pool[idx]
}
}
return nil
}
// Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 2048.
// //
// xray:api:stable // xray:api:stable
func Alloc(size int32) []byte { func Alloc(size int32) []byte {
pool := GetPool(size) if size > maxSize {
if pool != nil { return make([]byte, size)
return pool.Get().([]byte) }
index := 0
if size > minSize {
index = bits.Len32(uint32(size-1)) - minShift
}
p := pools[index].Get()
switch index {
case 0:
return p.(*[1 << 10]byte)[:]
case 1:
return p.(*[1 << 11]byte)[:]
case 2:
return p.(*[1 << 12]byte)[:]
case 3:
return p.(*[1 << 13]byte)[:]
case 4:
return p.(*[1 << 14]byte)[:]
case 5:
return p.(*[1 << 15]byte)[:]
case 6:
return p.(*[1 << 16]byte)[:]
default:
panic("invalid pool index")
} }
return make([]byte, size)
} }
// Free puts a byte slice into the internal pool. // Free puts a byte slice into the internal pool.
// //
// xray:api:stable // xray:api:stable
func Free(b []byte) { func Free(b []byte) {
size := int32(cap(b)) c := cap(b)
b = b[0:cap(b)] if c < minSize || c > maxSize {
for i := numPools - 1; i >= 0; i-- { return
if size >= poolSize[i] { }
pool[i].Put(b) index := bits.Len(uint(c)) - 1 - minShift
return switch index {
} case 0:
pools[0].Put((*[1 << 10]byte)(b[:1<<10]))
case 1:
pools[1].Put((*[1 << 11]byte)(b[:1<<11]))
case 2:
pools[2].Put((*[1 << 12]byte)(b[:1<<12]))
case 3:
pools[3].Put((*[1 << 13]byte)(b[:1<<13]))
case 4:
pools[4].Put((*[1 << 14]byte)(b[:1<<14]))
case 5:
pools[5].Put((*[1 << 15]byte)(b[:1<<15]))
case 6:
pools[6].Put((*[1 << 16]byte)(b[:1<<16]))
} }
} }
+1 -1
View File
@@ -23,7 +23,7 @@ func RegisterLua(L *lua.LState) {
return 0 return 0
} }
xlua.PushWithDirectMethods(L, matcher, map[string]xlua.DirectMethod{ xlua.PushWithDirectMethods(L, matcher, map[string]xlua.DirectMethod{
"Match": newLuaDomainMatch(xlua.NewReadOnlySlicePusher[uint32](L)), "Match": newLuaDomainMatch(xlua.NewSlicePusher[uint32](L)),
"MatchAny": luaDomainMatchAny, "MatchAny": luaDomainMatchAny,
}) })
return 1 return 1
+1 -3
View File
@@ -104,9 +104,7 @@ for _, value in ipairs({matcher, domain}) do
assert(not pcall(function() return value ^ {} end)) assert(not pcall(function() return value ^ {} end))
end end
assert(domain:matchAny("example.com")) assert(domain:matchAny("example.com"))
local indices = domain:Match("example.com") assert(#domain:Match("example.com") == 1)
assert(#indices == 1)
assert(not pcall(function() indices[1] = 7 end))
assert(domain:match("example.com")[1] == 0) assert(domain:match("example.com")[1] == 0)
assert(not pcall(function() matcher:AnyMatch() end)) assert(not pcall(function() matcher:AnyMatch() end))
assert(not pcall(function() matcher:AnyMatch(matched, true) end)) assert(not pcall(function() matcher:AnyMatch(matched, true) end))
+3 -3
View File
@@ -8,10 +8,10 @@ import (
luar "layeh.com/gopher-luar" luar "layeh.com/gopher-luar"
) )
// newSlicePusher captures luar's slice metatable during state initialization. // NewSlicePusher captures luar's slice metatable during state initialization.
// The returned function wraps slices without reflection or metatable lookup, // The returned function wraps slices without reflection or metatable lookup,
// and pushes nil for nil slices. Use it with this state or its coroutines. // and pushes nil for nil slices. Use it with this state or its coroutines.
func newSlicePusher[T any](L *glua.LState) func(*glua.LState, []T) { func NewSlicePusher[T any](L *glua.LState) func(*glua.LState, []T) {
metatable := luar.MT(L, []T(nil)).LTable metatable := luar.MT(L, []T(nil)).LTable
return func(L *glua.LState, values []T) { return func(L *glua.LState, values []T) {
if values == nil { if values == nil {
@@ -38,7 +38,7 @@ func NewReadOnlySlicePusher[T any](L *glua.LState) func(*glua.LState, []T) {
}) })
setSliceReadOnly[[]T](L, readOnly) setSliceReadOnly[[]T](L, readOnly)
} }
return newSlicePusher[T](L) return NewSlicePusher[T](L)
} }
func setSliceReadOnly[S ~[]E, E any](L *glua.LState, readOnly *glua.LFunction) { func setSliceReadOnly[S ~[]E, E any](L *glua.LState, readOnly *glua.LFunction) {
+43 -21
View File
@@ -9,20 +9,53 @@ import (
luar "layeh.com/gopher-luar" luar "layeh.com/gopher-luar"
) )
func TestReadOnlySlicePusher(t *testing.T) { func TestSlicePusher(t *testing.T) {
L := glua.NewState() L := glua.NewState()
defer L.Close() defer L.Close()
push := NewReadOnlySlicePusher[int](L) push := NewSlicePusher[int](L)
values := []int{3, 5} values := []int{3, 5}
L.SetGlobal("getValues", L.NewFunction(func(L *glua.LState) int { L.SetGlobal("getValues", L.NewFunction(func(L *glua.LState) int {
push(L, values) push(L, values)
return 1 return 1
})) }))
if err := L.DoString(` if err := L.DoString(`
local co = coroutine.create(function() return getValues() end) local values = getValues()
assert(#values == 2 and values[1] == 3 and values[2] == 5)
values[2] = 7
local co = coroutine.create(function()
local values = getValues()
assert(#values == 2 and values[1] == 3 and values[2] == 7)
return true
end)
local ok, result = coroutine.resume(co) local ok, result = coroutine.resume(co)
assert(ok, result) assert(ok and result == true)
values = result `); err != nil {
t.Fatal(err)
}
if values[1] != 7 {
t.Fatal("slice storage was copied")
}
push(L, nil)
if L.Get(-1) != glua.LNil {
t.Fatal("nil slice must push Lua nil")
}
L.Pop(1)
push(L, []int{})
L.SetGlobal("empty", L.Get(-1))
L.Pop(1)
if err := L.DoString(`assert(type(empty) == "userdata" and #empty == 0)`); err != nil {
t.Fatal(err)
}
}
func TestReadOnlySlicePusher(t *testing.T) {
L := glua.NewState()
defer L.Close()
values := []int{3, 5}
NewReadOnlySlicePusher[int](L)(L, values)
L.SetGlobal("values", L.Get(-1))
L.Pop(1)
if err := L.DoString(`
assert(#values == 2 and values[1] == 3 and values[2] == 5) assert(#values == 2 and values[1] == 3 and values[2] == 5)
assert(not pcall(function() values[1] = 7 end)) assert(not pcall(function() values[1] = 7 end))
assert(not pcall(function() return values + 7 end)) assert(not pcall(function() return values + 7 end))
@@ -36,17 +69,6 @@ assert(sum == 8)
if &got[0] != &values[0] || values[0] != 3 || values[1] != 5 { if &got[0] != &values[0] || values[0] != 3 || values[1] != 5 {
t.Fatal("read-only binding copied or modified the slice") t.Fatal("read-only binding copied or modified the slice")
} }
push(L, nil)
if L.Get(-1) != glua.LNil {
t.Fatal("nil slice must push Lua nil")
}
L.Pop(1)
push(L, []int{})
L.SetGlobal("empty", L.Get(-1))
L.Pop(1)
if err := L.DoString(`assert(type(empty) == "userdata" and #empty == 0)`); err != nil {
t.Fatal(err)
}
} }
func TestReadOnlyIPSlicePusher(t *testing.T) { func TestReadOnlyIPSlicePusher(t *testing.T) {
@@ -208,23 +230,23 @@ assert(not pcall(function() return nested + nested end))
} }
} }
func TestReadOnlySlicePusherMetatablePerState(t *testing.T) { func TestSlicePusherMetatablePerState(t *testing.T) {
first := glua.NewState() first := glua.NewState()
defer first.Close() defer first.Close()
second := glua.NewState() second := glua.NewState()
defer second.Close() defer second.Close()
NewReadOnlySlicePusher[int](first)(first, []int{1}) NewSlicePusher[int](first)(first, []int{1})
NewReadOnlySlicePusher[int](second)(second, []int{1}) NewSlicePusher[int](second)(second, []int{1})
if first.Get(-1).(*glua.LUserData).Metatable == second.Get(-1).(*glua.LUserData).Metatable { if first.Get(-1).(*glua.LUserData).Metatable == second.Get(-1).(*glua.LUserData).Metatable {
t.Fatal("independent states share a slice metatable") t.Fatal("independent states share a slice metatable")
} }
} }
func BenchmarkReadOnlySlicePusher(b *testing.B) { func BenchmarkSlicePusher(b *testing.B) {
L := glua.NewState() L := glua.NewState()
defer L.Close() defer L.Close()
ips := []net.IP{net.ParseIP("127.0.0.1")} ips := []net.IP{net.ParseIP("127.0.0.1")}
pushIPs := NewReadOnlySlicePusher[net.IP](L) pushIPs := NewSlicePusher[net.IP](L)
for _, benchmark := range []struct { for _, benchmark := range []struct {
name string name string
push func(*glua.LState, []net.IP) push func(*glua.LState, []net.IP)
+4 -2
View File
@@ -671,7 +671,7 @@ string.__tostring = nil
L.SetGlobal("testNativeError", L.Get(-1)) L.SetGlobal("testNativeError", L.Get(-1))
L.Pop(1) L.Pop(1)
L.SetGlobal("testGoStruct", luar.New(L, &struct{ Value string }{"readable field"})) L.SetGlobal("testGoStruct", luar.New(L, &struct{ Value string }{"readable field"}))
NewReadOnlySlicePusher[net.IP](L)(L, []net.IP{net.ParseIP("192.0.2.1")}) NewSlicePusher[net.IP](L)(L, []net.IP{net.ParseIP("192.0.2.1")})
L.SetGlobal("testIPs", L.Get(-1)) L.SetGlobal("testIPs", L.Get(-1))
L.Pop(1) L.Pop(1)
userdata := L.NewUserData() userdata := L.NewUserData()
@@ -865,7 +865,9 @@ assert(not ok and a == "{<address> <address>}")
PushUserData(L, struct{ Pointer *int }{&target}) PushUserData(L, struct{ Pointer *int }{&target})
L.SetGlobal("testObject", L.Get(-1)) L.SetGlobal("testObject", L.Get(-1))
L.Pop(1) L.Pop(1)
L.SetGlobal("testValues", luar.New(L, []int{1})) NewSlicePusher[int](L)(L, []int{1})
L.SetGlobal("testValues", L.Get(-1))
L.Pop(1)
L.SetGlobal("testPanic", L.NewFunction(func(L *glua.LState) int { L.SetGlobal("testPanic", L.NewFunction(func(L *glua.LState) int {
panic(struct{ First, Second *int }{&target, &target}) panic(struct{ First, Second *int }{&target, &target})
})) }))
-420
View File
@@ -1,420 +0,0 @@
package mux
import (
"context"
goerrors "errors"
"io"
"sync"
"time"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/common/signal/done"
"github.com/xtls/xray-core/common/task"
"github.com/xtls/xray-core/common/xudp"
"github.com/xtls/xray-core/proxy"
"github.com/xtls/xray-core/transport"
"github.com/xtls/xray-core/transport/internet"
"github.com/xtls/xray-core/transport/pipe"
)
type ClientManager struct {
Enabled bool // whether mux is enabled from user config
Picker WorkerPicker
}
func (m *ClientManager) Dispatch(ctx context.Context, link *transport.Link) error {
for i := 0; i < 16; i++ {
worker, err := m.Picker.PickAvailable()
if err != nil {
return err
}
if worker.Dispatch(ctx, link) {
return nil
}
}
return errors.New("unable to find an available mux client")
}
type WorkerPicker interface {
PickAvailable() (*ClientWorker, error)
}
type IncrementalWorkerPicker struct {
Factory ClientWorkerFactory
access sync.Mutex
workers []*ClientWorker
cleanupTask *task.Periodic
}
func (p *IncrementalWorkerPicker) cleanupFunc() error {
p.access.Lock()
defer p.access.Unlock()
if len(p.workers) == 0 {
return errors.New("no worker")
}
p.cleanup()
return nil
}
func (p *IncrementalWorkerPicker) cleanup() {
var activeWorkers []*ClientWorker
for _, w := range p.workers {
if !w.Closed() {
activeWorkers = append(activeWorkers, w)
}
}
p.workers = activeWorkers
}
func (p *IncrementalWorkerPicker) findAvailable() int {
for idx, w := range p.workers {
if !w.IsFull() {
return idx
}
}
return -1
}
func (p *IncrementalWorkerPicker) pickInternal() (*ClientWorker, bool, error) {
p.access.Lock()
defer p.access.Unlock()
idx := p.findAvailable()
if idx >= 0 {
n := len(p.workers)
if n > 1 && idx != n-1 {
p.workers[n-1], p.workers[idx] = p.workers[idx], p.workers[n-1]
}
return p.workers[idx], false, nil
}
p.cleanup()
worker, err := p.Factory.Create()
if err != nil {
return nil, false, err
}
p.workers = append(p.workers, worker)
if p.cleanupTask == nil {
p.cleanupTask = &task.Periodic{
Interval: time.Second * 30,
Execute: p.cleanupFunc,
}
}
return worker, true, nil
}
func (p *IncrementalWorkerPicker) PickAvailable() (*ClientWorker, error) {
worker, start, err := p.pickInternal()
if start {
common.Must(p.cleanupTask.Start())
}
return worker, err
}
type ClientWorkerFactory interface {
Create() (*ClientWorker, error)
}
type DialingWorkerFactory struct {
Proxy proxy.Outbound
Dialer internet.Dialer
Strategy ClientStrategy
}
func (f *DialingWorkerFactory) Create() (*ClientWorker, error) {
opts := []pipe.Option{pipe.WithSizeLimit(64 * 1024)}
uplinkReader, upLinkWriter := pipe.New(opts...)
downlinkReader, downlinkWriter := pipe.New(opts...)
c, err := NewClientWorker(transport.Link{
Reader: downlinkReader,
Writer: upLinkWriter,
}, f.Strategy)
if err != nil {
return nil, err
}
go func(p proxy.Outbound, d internet.Dialer, c common.Closable) {
outbounds := []*session.Outbound{{
Target: net.TCPDestination(muxCoolAddress, muxCoolPort),
}}
ctx := session.ContextWithOutbounds(context.Background(), outbounds)
ctx, cancel := context.WithCancel(ctx)
if errP := p.Process(ctx, &transport.Link{Reader: uplinkReader, Writer: downlinkWriter}, d); errP != nil {
errC := errors.Cause(errP)
if !(goerrors.Is(errC, io.EOF) || goerrors.Is(errC, io.ErrClosedPipe) || goerrors.Is(errC, context.Canceled)) {
errors.LogInfoInner(ctx, errP, "failed to handler mux client connection")
}
}
common.Must(c.Close())
cancel()
}(f.Proxy, f.Dialer, c.done)
return c, nil
}
type ClientStrategy struct {
MaxConcurrency uint32
MaxConnection uint32
}
type ClientWorker struct {
sessionManager *SessionManager
link transport.Link
done *done.Instance
timer *time.Ticker
strategy ClientStrategy
}
var (
muxCoolAddress = net.DomainAddress("v1.mux.cool")
muxCoolPort = net.Port(9527)
)
// NewClientWorker creates a new mux.Client.
func NewClientWorker(stream transport.Link, s ClientStrategy) (*ClientWorker, error) {
writer := buf.NewBufferedWriter(stream.Writer)
writer.SetBuffered(false)
stream.Writer = writer
c := &ClientWorker{
sessionManager: NewSessionManager(),
link: stream,
done: done.New(),
timer: time.NewTicker(time.Second * 16),
strategy: s,
}
go c.fetchOutput()
go c.monitor()
return c, nil
}
func (m *ClientWorker) TotalConnections() uint32 {
return uint32(m.sessionManager.Count())
}
func (m *ClientWorker) ActiveConnections() uint32 {
return uint32(m.sessionManager.Size())
}
// Closed returns true if this Client is closed.
func (m *ClientWorker) Closed() bool {
return m.done.Done()
}
func (m *ClientWorker) WaitClosed() <-chan struct{} {
return m.done.Wait()
}
func (m *ClientWorker) Close() error {
return m.done.Close()
}
func (m *ClientWorker) monitor() {
defer m.timer.Stop()
for {
checkSize := m.sessionManager.Size()
checkCount := m.sessionManager.Count()
select {
case <-m.done.Wait():
m.sessionManager.Close()
common.Interrupt(m.link.Writer)
common.Interrupt(m.link.Reader)
return
case <-m.timer.C:
if m.sessionManager.CloseIfNoSessionAndIdle(checkSize, checkCount) {
common.Must(m.done.Close())
}
}
}
}
func writeFirstPayload(reader buf.Reader, writer *Writer) error {
err := buf.CopyOnceTimeout(reader, writer, time.Millisecond*100)
if err == buf.ErrNotTimeoutReader || err == buf.ErrReadTimeout {
return writer.WriteMultiBuffer(buf.MultiBuffer{})
}
if err != nil {
return err
}
return nil
}
func fetchInput(ctx context.Context, s *Session, output buf.Writer) {
outbounds := session.OutboundsFromContext(ctx)
ob := outbounds[len(outbounds)-1]
transferType := protocol.TransferTypeStream
if ob.Target.Network == net.Network_UDP {
transferType = protocol.TransferTypePacket
}
s.transferType = transferType
var inbound *session.Inbound
if session.IsReverseMuxFromContext(ctx) {
inbound = session.InboundFromContext(ctx)
}
writer := NewWriter(s.ID, ob.Target, output, transferType, xudp.GetGlobalID(ctx), inbound)
defer s.Close(false)
defer writer.Close()
errors.LogInfo(ctx, "dispatching request to ", ob.Target)
if err := writeFirstPayload(s.input, writer); err != nil {
errors.LogInfoInner(ctx, err, "failed to write first payload")
writer.hasError = true
return
}
if err := buf.Copy(s.input, writer); err != nil {
errors.LogInfoInner(ctx, err, "failed to fetch all input")
writer.hasError = true
return
}
}
func (m *ClientWorker) IsClosing() bool {
sm := m.sessionManager
if m.strategy.MaxConnection > 0 && sm.Count() >= int(m.strategy.MaxConnection) {
return true
}
return false
}
// IsFull returns true if this ClientWorker is unable to accept more connections.
// it might be because it is closing, or the number of connections has reached the limit.
func (m *ClientWorker) IsFull() bool {
if m.IsClosing() || m.Closed() {
return true
}
sm := m.sessionManager
if m.strategy.MaxConcurrency > 0 && sm.Size() >= int(m.strategy.MaxConcurrency) {
return true
}
return false
}
func (m *ClientWorker) Dispatch(ctx context.Context, link *transport.Link) bool {
if m.IsFull() {
return false
}
sm := m.sessionManager
s := sm.Allocate(&m.strategy, link.Reader, link.Writer)
if s == nil {
return false
}
go fetchInput(ctx, s, m.link.Writer)
if _, ok := link.Reader.(*pipe.Reader); !ok {
select {
case <-ctx.Done():
case <-s.done.Wait():
}
}
return true
}
func (m *ClientWorker) handleStatueKeepAlive(meta *FrameMetadata, reader *buf.BufferedReader) error {
if meta.Option.Has(OptionData) {
return buf.Copy(NewStreamReader(reader), buf.Discard)
}
return nil
}
func (m *ClientWorker) handleStatusNew(meta *FrameMetadata, reader *buf.BufferedReader) error {
if meta.Option.Has(OptionData) {
return buf.Copy(NewStreamReader(reader), buf.Discard)
}
return nil
}
func (m *ClientWorker) handleStatusKeep(meta *FrameMetadata, reader *buf.BufferedReader) error {
if !meta.Option.Has(OptionData) {
return nil
}
s, found := m.sessionManager.Get(meta.SessionID)
if !found {
// Notify remote peer to close this session.
closingWriter := NewResponseWriter(meta.SessionID, m.link.Writer, protocol.TransferTypeStream)
closingWriter.Close()
return buf.Copy(NewStreamReader(reader), buf.Discard)
}
rr := s.NewReader(reader, &meta.Target)
err := buf.Copy(rr, s.output)
if err != nil && buf.IsWriteError(err) {
errors.LogInfoInner(context.Background(), err, "failed to write to downstream. closing session ", s.ID)
s.Close(false)
return buf.Copy(rr, buf.Discard)
}
return err
}
func (m *ClientWorker) handleStatusEnd(meta *FrameMetadata, reader *buf.BufferedReader) error {
if s, found := m.sessionManager.Get(meta.SessionID); found {
s.Close(false)
}
if meta.Option.Has(OptionData) {
return buf.Copy(NewStreamReader(reader), buf.Discard)
}
return nil
}
func (m *ClientWorker) fetchOutput() {
defer func() {
common.Must(m.done.Close())
}()
reader := &buf.BufferedReader{Reader: m.link.Reader}
var meta FrameMetadata
for {
err := meta.Unmarshal(reader, false)
if err != nil {
if errors.Cause(err) != io.EOF {
errors.LogInfoInner(context.Background(), err, "failed to read metadata")
}
break
}
switch meta.SessionStatus {
case SessionStatusKeepAlive:
err = m.handleStatueKeepAlive(&meta, reader)
case SessionStatusEnd:
err = m.handleStatusEnd(&meta, reader)
case SessionStatusNew:
err = m.handleStatusNew(&meta, reader)
case SessionStatusKeep:
err = m.handleStatusKeep(&meta, reader)
default:
status := meta.SessionStatus
errors.LogError(context.Background(), "unknown status: ", status)
return
}
if err != nil {
errors.LogInfoInner(context.Background(), err, "failed to process data")
return
}
}
}
-163
View File
@@ -1,163 +0,0 @@
package mux_test
import (
"context"
"testing"
"time"
"github.com/golang/mock/gomock"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/mux"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/testing/mocks"
"github.com/xtls/xray-core/transport"
"github.com/xtls/xray-core/transport/pipe"
)
func TestIncrementalPickerFailure(t *testing.T) {
mockCtl := gomock.NewController(t)
defer mockCtl.Finish()
mockWorkerFactory := mocks.NewMuxClientWorkerFactory(mockCtl)
mockWorkerFactory.EXPECT().Create().Return(nil, errors.New("test"))
picker := mux.IncrementalWorkerPicker{
Factory: mockWorkerFactory,
}
_, err := picker.PickAvailable()
if err == nil {
t.Error("expected error, but nil")
}
}
func TestClientWorkerEOF(t *testing.T) {
reader, writer := pipe.New(pipe.WithoutSizeLimit())
common.Must(writer.Close())
worker, err := mux.NewClientWorker(transport.Link{Reader: reader, Writer: writer}, mux.ClientStrategy{})
common.Must(err)
time.Sleep(time.Millisecond * 500)
f := worker.Dispatch(context.Background(), nil)
if f {
t.Error("expected failed dispatching, but actually not")
}
}
func TestClientWorkerClose(t *testing.T) {
mockCtl := gomock.NewController(t)
defer mockCtl.Finish()
r1, w1 := pipe.New(pipe.WithoutSizeLimit())
worker1, err := mux.NewClientWorker(transport.Link{
Reader: r1,
Writer: w1,
}, mux.ClientStrategy{
MaxConcurrency: 4,
MaxConnection: 4,
})
common.Must(err)
r2, w2 := pipe.New(pipe.WithoutSizeLimit())
worker2, err := mux.NewClientWorker(transport.Link{
Reader: r2,
Writer: w2,
}, mux.ClientStrategy{
MaxConcurrency: 4,
MaxConnection: 4,
})
common.Must(err)
factory := mocks.NewMuxClientWorkerFactory(mockCtl)
gomock.InOrder(
factory.EXPECT().Create().Return(worker1, nil),
factory.EXPECT().Create().Return(worker2, nil),
)
picker := &mux.IncrementalWorkerPicker{
Factory: factory,
}
manager := &mux.ClientManager{
Picker: picker,
}
tr1, tw1 := pipe.New(pipe.WithoutSizeLimit())
ctx1 := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80),
}})
common.Must(manager.Dispatch(ctx1, &transport.Link{
Reader: tr1,
Writer: tw1,
}))
defer tw1.Close()
common.Must(w1.Close())
time.Sleep(time.Millisecond * 500)
if !worker1.Closed() {
t.Error("worker1 is not finished")
}
tr2, tw2 := pipe.New(pipe.WithoutSizeLimit())
ctx2 := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80),
}})
common.Must(manager.Dispatch(ctx2, &transport.Link{
Reader: tr2,
Writer: tw2,
}))
defer tw2.Close()
common.Must(w2.Close())
}
func TestClientWorkerUDPSource(t *testing.T) {
downR, downW := pipe.New(pipe.WithoutSizeLimit())
upR, upW := pipe.New(pipe.WithoutSizeLimit())
worker, err := mux.NewClientWorker(transport.Link{Reader: downR, Writer: upW}, mux.ClientStrategy{})
common.Must(err)
inR, inW := pipe.New(pipe.WithoutSizeLimit())
outR, outW := pipe.New(pipe.WithoutSizeLimit())
ctx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
Target: net.UDPDestination(net.ParseAddress("8.8.8.8"), 53),
}})
if !worker.Dispatch(ctx, &transport.Link{Reader: inR, Writer: outW}) {
t.Fatal("failed to dispatch")
}
b := buf.New()
b.WriteString("query")
common.Must(inW.WriteMultiBuffer(buf.MultiBuffer{b}))
mb, err := upR.ReadMultiBuffer() // New frame, the session is UDP from now on
common.Must(err)
buf.ReleaseMulti(mb)
srcs := []net.Destination{
net.UDPDestination(net.ParseAddress("1.1.1.1"), 1111),
net.UDPDestination(net.DomainAddress("example.com"), 2222),
net.UDPDestination(net.ParseAddress("3.3.3.3"), 3333),
}
w := mux.NewResponseWriter(1, downW, protocol.TransferTypePacket)
var got buf.MultiBuffer
for i := range srcs {
b := buf.New()
b.WriteString("reply")
b.UDP = &srcs[i]
common.Must(w.WriteMultiBuffer(buf.MultiBuffer{b}))
// keep earlier replies around while the next frame is parsed
mb, err := outR.ReadMultiBuffer()
common.Must(err)
got = append(got, mb...)
}
for i, b := range got {
if b.UDP == nil || *b.UDP != srcs[i] {
t.Errorf("reply %d: source = %v, want %v", i, b.UDP, srcs[i])
}
}
}
-25
View File
@@ -1,25 +0,0 @@
package mux_test
import (
"testing"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/mux"
"github.com/xtls/xray-core/common/net"
)
func BenchmarkFrameWrite(b *testing.B) {
frame := mux.FrameMetadata{
Target: net.TCPDestination(net.DomainAddress("www.example.com"), net.Port(80)),
SessionID: 1,
SessionStatus: mux.SessionStatusNew,
}
writer := buf.New()
defer writer.Release()
for i := 0; i < b.N; i++ {
common.Must(frame.WriteTo(writer))
writer.Clear()
}
}
-1
View File
@@ -1 +0,0 @@
package mux
-60
View File
@@ -1,60 +0,0 @@
package mux
import (
"io"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/crypto"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/serial"
)
// PacketReader is an io.Reader that reads whole chunk of Mux frames every time.
type PacketReader struct {
reader io.Reader
eof bool
dest net.Destination
}
// NewPacketReader creates a new PacketReader.
// dest is copied because the caller reuses it for the next frame.
func NewPacketReader(reader io.Reader, dest *net.Destination) *PacketReader {
return &PacketReader{
reader: reader,
eof: false,
dest: *dest,
}
}
// ReadMultiBuffer implements buf.Reader.
func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
if r.eof {
return nil, io.EOF
}
size, err := serial.ReadUint16(r.reader)
if err != nil {
return nil, err
}
if size > buf.Size {
return nil, errors.New("packet size too large: ", size)
}
b := buf.New()
if _, err := b.ReadFullFrom(r.reader, int32(size)); err != nil {
b.Release()
return nil, err
}
r.eof = true
if r.dest.Network == net.Network_UDP {
b.UDP = &r.dest // only one packet is read, so b owns r.dest
}
return buf.MultiBuffer{b}, nil
}
// NewStreamReader creates a new StreamReader.
func NewStreamReader(reader *buf.BufferedReader) buf.Reader {
return crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, reader, 1)
}
-386
View File
@@ -1,386 +0,0 @@
package mux
import (
"context"
"io"
"time"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/log"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/common/signal/done"
"github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/features/routing"
"github.com/xtls/xray-core/transport"
"github.com/xtls/xray-core/transport/pipe"
)
type Server struct {
dispatcher routing.Dispatcher
}
// NewServer creates a new mux.Server.
func NewServer(ctx context.Context) *Server {
s := &Server{}
core.RequireFeatures(ctx, func(d routing.Dispatcher) {
s.dispatcher = d
})
return s
}
// Type implements common.HasType.
func (s *Server) Type() interface{} {
return s.dispatcher.Type()
}
// Dispatch implements routing.Dispatcher
func (s *Server) Dispatch(ctx context.Context, dest net.Destination) (*transport.Link, error) {
if dest.Address != muxCoolAddress {
return s.dispatcher.Dispatch(ctx, dest)
}
opts := pipe.OptionsFromContext(ctx)
uplinkReader, uplinkWriter := pipe.New(opts...)
downlinkReader, downlinkWriter := pipe.New(opts...)
_, err := NewServerWorker(ctx, s.dispatcher, &transport.Link{
Reader: uplinkReader,
Writer: downlinkWriter,
})
if err != nil {
return nil, err
}
return &transport.Link{Reader: downlinkReader, Writer: uplinkWriter}, nil
}
// DispatchLink implements routing.Dispatcher
func (s *Server) DispatchLink(ctx context.Context, dest net.Destination, link *transport.Link) error {
if dest.Address != muxCoolAddress {
return s.dispatcher.DispatchLink(ctx, dest, link)
}
worker, err := NewServerWorker(ctx, s.dispatcher, link)
if err != nil {
return err
}
select {
case <-ctx.Done():
case <-worker.done.Wait():
}
return nil
}
// Start implements common.Runnable.
func (s *Server) Start() error {
return nil
}
// Close implements common.Closable.
func (s *Server) Close() error {
return nil
}
type ServerWorker struct {
dispatcher routing.Dispatcher
link *transport.Link
sessionManager *SessionManager
done *done.Instance
timer *time.Ticker
}
func NewServerWorker(ctx context.Context, d routing.Dispatcher, link *transport.Link) (*ServerWorker, error) {
writer := buf.NewBufferedWriter(link.Writer)
writer.SetBuffered(false)
worker := &ServerWorker{
dispatcher: d,
link: &transport.Link{Reader: link.Reader, Writer: writer},
sessionManager: NewSessionManager(),
done: done.New(),
timer: time.NewTicker(60 * time.Second),
}
if inbound := session.InboundFromContext(ctx); inbound != nil {
inbound.CanSpliceCopy = 3
}
go worker.run(ctx)
go worker.monitor()
return worker, nil
}
func handle(ctx context.Context, s *Session, output buf.Writer) {
writer := NewResponseWriter(s.ID, output, s.transferType)
if err := buf.Copy(s.input, writer); err != nil {
errors.LogInfoInner(ctx, err, "session ", s.ID, " ends.")
writer.hasError = true
}
writer.Close()
s.Close(false)
}
func (w *ServerWorker) monitor() {
defer w.timer.Stop()
for {
checkSize := w.sessionManager.Size()
checkCount := w.sessionManager.Count()
select {
case <-w.done.Wait():
w.sessionManager.Close()
common.Interrupt(w.link.Writer)
common.Interrupt(w.link.Reader)
return
case <-w.timer.C:
if w.sessionManager.CloseIfNoSessionAndIdle(checkSize, checkCount) {
common.Must(w.done.Close())
}
}
}
}
func (w *ServerWorker) ActiveConnections() uint32 {
return uint32(w.sessionManager.Size())
}
func (w *ServerWorker) Closed() bool {
return w.done.Done()
}
func (w *ServerWorker) WaitClosed() <-chan struct{} {
return w.done.Wait()
}
func (w *ServerWorker) Close() error {
return w.done.Close()
}
func (w *ServerWorker) handleStatusKeepAlive(meta *FrameMetadata, reader *buf.BufferedReader) error {
if meta.Option.Has(OptionData) {
return buf.Copy(NewStreamReader(reader), buf.Discard)
}
return nil
}
func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader) error {
ctx = session.SubContextFromMuxInbound(ctx)
if meta.Inbound != nil && meta.Inbound.Source.IsValid() && meta.Inbound.Local.IsValid() {
if inbound := session.InboundFromContext(ctx); inbound != nil {
newInbound := *inbound
newInbound.Source = meta.Inbound.Source
newInbound.Local = meta.Inbound.Local
ctx = session.ContextWithInbound(ctx, &newInbound)
}
}
errors.LogInfo(ctx, "received request for ", meta.Target)
{
msg := &log.AccessMessage{
To: meta.Target,
Status: log.AccessAccepted,
Reason: "",
}
if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.IsValid() {
msg.From = inbound.Source
msg.Email = inbound.User.Email
}
ctx = log.ContextWithAccessMessage(ctx, msg)
}
if network := session.AllowedNetworkFromContext(ctx); network != net.Network_Unknown {
if meta.Target.Network != network {
return errors.New("unexpected network ", meta.Target.Network) // it will break the whole Mux connection
}
}
if meta.GlobalID != [8]byte{} { // MUST ignore empty Global ID
mb, err := NewPacketReader(reader, &meta.Target).ReadMultiBuffer()
if err != nil {
return err
}
XUDPManager.Lock()
x := XUDPManager.Map[meta.GlobalID]
if x == nil {
x = &XUDP{GlobalID: meta.GlobalID}
XUDPManager.Map[meta.GlobalID] = x
XUDPManager.Unlock()
} else {
if x.Status == Initializing { // nearly impossible
XUDPManager.Unlock()
errors.LogWarningInner(ctx, errors.New("conflict"), "XUDP hit ", meta.GlobalID)
// It's not a good idea to return an err here, so just let client wait.
// Client will receive an End frame after sending a Keep frame.
return nil
}
x.Status = Initializing
XUDPManager.Unlock()
x.Mux.Close(false) // detach from previous Mux
b := buf.New()
b.Write(mb[0].Bytes())
b.UDP = mb[0].UDP
if err = x.Mux.output.WriteMultiBuffer(mb); err != nil {
x.Interrupt()
mb = buf.MultiBuffer{b}
} else {
b.Release()
mb = nil
}
errors.LogInfoInner(ctx, err, "XUDP hit ", meta.GlobalID)
}
if mb != nil {
ctx = session.ContextWithTimeoutOnly(ctx, true)
// Actually, it won't return an error in Xray-core's implementations.
link, err := w.dispatcher.Dispatch(ctx, meta.Target)
if err != nil {
XUDPManager.Lock()
delete(XUDPManager.Map, x.GlobalID)
XUDPManager.Unlock()
err = errors.New("XUDP new ", meta.GlobalID).Base(errors.New("failed to dispatch request to ", meta.Target).Base(err))
return err // it will break the whole Mux connection
}
link.Writer.WriteMultiBuffer(mb) // it's meaningless to test a new pipe
x.Mux = &Session{
input: link.Reader,
output: link.Writer,
}
errors.LogInfoInner(ctx, err, "XUDP new ", meta.GlobalID)
}
x.Mux = &Session{
input: x.Mux.input,
output: x.Mux.output,
parent: w.sessionManager,
ID: meta.SessionID,
transferType: protocol.TransferTypePacket,
XUDP: x,
}
x.Status = Active
if !w.sessionManager.Add(x.Mux) {
x.Mux.Close(false)
return errors.New("failed to add new session")
}
go handle(ctx, x.Mux, w.link.Writer)
return nil
}
link, err := w.dispatcher.Dispatch(ctx, meta.Target)
if err != nil {
if meta.Option.Has(OptionData) {
buf.Copy(NewStreamReader(reader), buf.Discard)
}
return errors.New("failed to dispatch request.").Base(err)
}
s := &Session{
input: link.Reader,
output: link.Writer,
parent: w.sessionManager,
ID: meta.SessionID,
transferType: protocol.TransferTypeStream,
}
if meta.Target.Network == net.Network_UDP {
s.transferType = protocol.TransferTypePacket
}
if !w.sessionManager.Add(s) {
s.Close(false)
return errors.New("failed to add new session")
}
go handle(ctx, s, w.link.Writer)
if !meta.Option.Has(OptionData) {
return nil
}
rr := s.NewReader(reader, &meta.Target)
err = buf.Copy(rr, s.output)
if err != nil && buf.IsWriteError(err) {
s.Close(false)
return buf.Copy(rr, buf.Discard)
}
return err
}
func (w *ServerWorker) handleStatusKeep(meta *FrameMetadata, reader *buf.BufferedReader) error {
if !meta.Option.Has(OptionData) {
return nil
}
s, found := w.sessionManager.Get(meta.SessionID)
if !found {
// Notify remote peer to close this session.
closingWriter := NewResponseWriter(meta.SessionID, w.link.Writer, protocol.TransferTypeStream)
closingWriter.Close()
return buf.Copy(NewStreamReader(reader), buf.Discard)
}
rr := s.NewReader(reader, &meta.Target)
err := buf.Copy(rr, s.output)
if err != nil && buf.IsWriteError(err) {
errors.LogInfoInner(context.Background(), err, "failed to write to downstream writer. closing session ", s.ID)
s.Close(false)
return buf.Copy(rr, buf.Discard)
}
return err
}
func (w *ServerWorker) handleStatusEnd(meta *FrameMetadata, reader *buf.BufferedReader) error {
if s, found := w.sessionManager.Get(meta.SessionID); found {
s.Close(false)
}
if meta.Option.Has(OptionData) {
return buf.Copy(NewStreamReader(reader), buf.Discard)
}
return nil
}
func (w *ServerWorker) handleFrame(ctx context.Context, reader *buf.BufferedReader) error {
var meta FrameMetadata
err := meta.Unmarshal(reader, session.IsReverseMuxFromContext(ctx))
if err != nil {
return errors.New("failed to read metadata").Base(err)
}
switch meta.SessionStatus {
case SessionStatusKeepAlive:
err = w.handleStatusKeepAlive(&meta, reader)
case SessionStatusEnd:
err = w.handleStatusEnd(&meta, reader)
case SessionStatusNew:
err = w.handleStatusNew(session.ContextWithIsReverseMux(ctx, false), &meta, reader)
case SessionStatusKeep:
err = w.handleStatusKeep(&meta, reader)
default:
status := meta.SessionStatus
return errors.New("unknown status: ", status)
}
if err != nil {
return errors.New("failed to process data").Base(err)
}
return nil
}
func (w *ServerWorker) run(ctx context.Context) {
defer func() {
common.Must(w.done.Close())
}()
reader := &buf.BufferedReader{Reader: w.link.Reader}
for {
select {
case <-ctx.Done():
return
default:
err := w.handleFrame(ctx, reader)
if err != nil {
if errors.Cause(err) != io.EOF {
errors.LogInfoInner(ctx, err, "unexpected EOF")
}
return
}
}
}
}
-254
View File
@@ -1,254 +0,0 @@
package mux
import (
"context"
"io"
"runtime"
"sync"
"time"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/signal/done"
"github.com/xtls/xray-core/transport/pipe"
)
type SessionManager struct {
sync.RWMutex
sessions map[uint16]*Session
count uint16
closed bool
}
func NewSessionManager() *SessionManager {
return &SessionManager{
count: 0,
sessions: make(map[uint16]*Session, 16),
}
}
func (m *SessionManager) Closed() bool {
m.RLock()
defer m.RUnlock()
return m.closed
}
func (m *SessionManager) Size() int {
m.RLock()
defer m.RUnlock()
return len(m.sessions)
}
func (m *SessionManager) Count() int {
m.RLock()
defer m.RUnlock()
return int(m.count)
}
func (m *SessionManager) Allocate(Strategy *ClientStrategy, input buf.Reader, output buf.Writer) *Session {
m.Lock()
defer m.Unlock()
MaxConcurrency := int(Strategy.MaxConcurrency)
MaxConnection := uint16(Strategy.MaxConnection)
if m.closed || (MaxConcurrency > 0 && len(m.sessions) >= MaxConcurrency) || (MaxConnection > 0 && m.count >= MaxConnection) {
return nil
}
m.count++
s := &Session{
input: input,
output: output,
ID: m.count,
parent: m,
done: done.New(),
}
m.sessions[s.ID] = s
return s
}
func (m *SessionManager) Add(s *Session) bool {
m.Lock()
defer m.Unlock()
if m.closed {
return false
}
m.count++
m.sessions[s.ID] = s
return true
}
func (m *SessionManager) Remove(locked bool, id uint16) {
if !locked {
m.Lock()
defer m.Unlock()
}
locked = true
if m.closed {
return
}
delete(m.sessions, id)
/*
if len(m.sessions) == 0 {
m.sessions = make(map[uint16]*Session, 16)
}
*/
}
func (m *SessionManager) Get(id uint16) (*Session, bool) {
m.RLock()
defer m.RUnlock()
if m.closed {
return nil, false
}
s, found := m.sessions[id]
return s, found
}
func (m *SessionManager) CloseIfNoSessionAndIdle(checkSize int, checkCount int) bool {
m.Lock()
defer m.Unlock()
if m.closed {
return true
}
if len(m.sessions) != 0 || checkSize != 0 || checkCount != int(m.count) {
return false
}
m.closed = true
m.sessions = nil
return true
}
func (m *SessionManager) Close() error {
m.Lock()
defer m.Unlock()
if m.closed {
return nil
}
m.closed = true
for _, s := range m.sessions {
s.Close(true)
}
m.sessions = nil
return nil
}
// Session represents a client connection in a Mux connection.
type Session struct {
input buf.Reader
output buf.Writer
parent *SessionManager
ID uint16
transferType protocol.TransferType
closed bool
done *done.Instance
XUDP *XUDP
}
// Close closes all resources associated with this session.
func (s *Session) Close(locked bool) error {
if !locked {
s.parent.Lock()
defer s.parent.Unlock()
}
locked = true
if s.closed {
return nil
}
s.closed = true
if s.done != nil {
s.done.Close()
}
if s.XUDP == nil {
common.Interrupt(s.input)
common.Close(s.output)
} else {
// Stop existing handle(), then trigger writer.Close().
// Note that s.output may be dispatcher.SizeStatWriter.
s.input.(*pipe.Reader).ReturnAnError(io.EOF)
runtime.Gosched()
// If the error set by ReturnAnError still exists, clear it.
s.input.(*pipe.Reader).Recover()
XUDPManager.Lock()
if s.XUDP.Status == Active {
s.XUDP.Expire = time.Now().Add(time.Minute)
s.XUDP.Status = Expiring
errors.LogDebug(context.Background(), "XUDP put ", s.XUDP.GlobalID)
}
XUDPManager.Unlock()
}
s.parent.Remove(locked, s.ID)
return nil
}
// NewReader creates a buf.Reader based on the transfer type of this Session.
func (s *Session) NewReader(reader *buf.BufferedReader, dest *net.Destination) buf.Reader {
if s.transferType == protocol.TransferTypeStream {
return NewStreamReader(reader)
}
return NewPacketReader(reader, dest)
}
const (
Initializing = 0
Active = 1
Expiring = 2
)
type XUDP struct {
GlobalID [8]byte
Status uint64
Expire time.Time
Mux *Session
}
func (x *XUDP) Interrupt() {
common.Interrupt(x.Mux.input)
common.Close(x.Mux.output)
}
var XUDPManager struct {
sync.Mutex
Map map[[8]byte]*XUDP
}
func init() {
XUDPManager.Map = make(map[[8]byte]*XUDP)
go func() {
for {
time.Sleep(time.Minute)
now := time.Now()
XUDPManager.Lock()
for id, x := range XUDPManager.Map {
if x.Status == Expiring && now.After(x.Expire) {
x.Interrupt()
delete(XUDPManager.Map, id)
errors.LogDebug(context.Background(), "XUDP del ", id)
}
}
XUDPManager.Unlock()
}
}()
}
-51
View File
@@ -1,51 +0,0 @@
package mux_test
import (
"testing"
. "github.com/xtls/xray-core/common/mux"
)
func TestSessionManagerAdd(t *testing.T) {
m := NewSessionManager()
s := m.Allocate(&ClientStrategy{}, nil, nil)
if s.ID != 1 {
t.Error("id: ", s.ID)
}
if m.Size() != 1 {
t.Error("size: ", m.Size())
}
s = m.Allocate(&ClientStrategy{}, nil, nil)
if s.ID != 2 {
t.Error("id: ", s.ID)
}
if m.Size() != 2 {
t.Error("size: ", m.Size())
}
s = &Session{
ID: 4,
}
m.Add(s)
if s.ID != 4 {
t.Error("id: ", s.ID)
}
if m.Size() != 3 {
t.Error("size: ", m.Size())
}
}
func TestSessionManagerClose(t *testing.T) {
m := NewSessionManager()
s := m.Allocate(&ClientStrategy{}, nil, nil)
if m.CloseIfNoSessionAndIdle(m.Size(), m.Count()) {
t.Error("able to close")
}
m.Remove(false, s.ID)
if !m.CloseIfNoSessionAndIdle(m.Size(), m.Count()) {
t.Error("not able to close")
}
}
-136
View File
@@ -1,136 +0,0 @@
package mux
import (
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/common/session"
)
type Writer struct {
dest net.Destination
writer buf.Writer
id uint16
followup bool
hasError bool
transferType protocol.TransferType
globalID [8]byte
inbound *session.Inbound
}
func NewWriter(id uint16, dest net.Destination, writer buf.Writer, transferType protocol.TransferType, globalID [8]byte, inbound *session.Inbound) *Writer {
return &Writer{
id: id,
dest: dest,
writer: writer,
followup: false,
transferType: transferType,
globalID: globalID,
inbound: inbound,
}
}
func NewResponseWriter(id uint16, writer buf.Writer, transferType protocol.TransferType) *Writer {
return &Writer{
id: id,
writer: writer,
followup: true,
transferType: transferType,
}
}
func (w *Writer) getNextFrameMeta() FrameMetadata {
meta := FrameMetadata{
SessionID: w.id,
Target: w.dest,
GlobalID: w.globalID,
Inbound: w.inbound,
}
if w.followup {
meta.SessionStatus = SessionStatusKeep
} else {
w.followup = true
meta.SessionStatus = SessionStatusNew
}
return meta
}
func (w *Writer) writeMetaOnly() error {
meta := w.getNextFrameMeta()
b := buf.New()
if err := meta.WriteTo(b); err != nil {
return err
}
return w.writer.WriteMultiBuffer(buf.MultiBuffer{b})
}
func writeMetaWithFrame(writer buf.Writer, meta FrameMetadata, data buf.MultiBuffer) error {
frame := buf.New()
if len(data) == 1 {
frame.UDP = data[0].UDP
}
if err := meta.WriteTo(frame); err != nil {
return err
}
if _, err := serial.WriteUint16(frame, uint16(data.Len())); err != nil {
return err
}
mb2 := make(buf.MultiBuffer, 0, len(data)+1)
mb2 = append(mb2, frame)
mb2 = append(mb2, data...)
return writer.WriteMultiBuffer(mb2)
}
func (w *Writer) writeData(mb buf.MultiBuffer) error {
meta := w.getNextFrameMeta()
meta.Option.Set(OptionData)
return writeMetaWithFrame(w.writer, meta, mb)
}
// WriteMultiBuffer implements buf.Writer.
func (w *Writer) WriteMultiBuffer(mb buf.MultiBuffer) error {
defer buf.ReleaseMulti(mb)
if mb.IsEmpty() {
return w.writeMetaOnly()
}
for !mb.IsEmpty() {
var chunk buf.MultiBuffer
if w.transferType == protocol.TransferTypeStream {
mb, chunk = buf.SplitSize(mb, 8*1024)
} else {
mb2, b := buf.SplitFirst(mb)
mb = mb2
chunk = buf.MultiBuffer{b}
}
if err := w.writeData(chunk); err != nil {
return err
}
}
return nil
}
// Close implements common.Closable.
func (w *Writer) Close() error {
meta := FrameMetadata{
SessionID: w.id,
SessionStatus: SessionStatusEnd,
}
if w.hasError {
meta.Option.Set(OptionError)
}
frame := buf.New()
common.Must(meta.WriteTo(frame))
w.writer.WriteMultiBuffer(buf.MultiBuffer{frame})
return nil
}
+3
View File
@@ -128,6 +128,7 @@ func (w *UDPWriter) WriteMessage(b *buf.Buffer) error {
type TCPWriter struct { type TCPWriter struct {
buf.Writer buf.Writer
sync.Mutex
} }
func (w *TCPWriter) WriteMessage(b *buf.Buffer) error { func (w *TCPWriter) WriteMessage(b *buf.Buffer) error {
@@ -140,5 +141,7 @@ func (w *TCPWriter) WriteMessage(b *buf.Buffer) error {
size := buf.New() size := buf.New()
binary.BigEndian.PutUint16(size.Extend(2), uint16(b.Len())) binary.BigEndian.PutUint16(size.Extend(2), uint16(b.Len()))
mb = append(mb, size, b) mb = append(mb, size, b)
w.Lock()
defer w.Unlock()
return w.WriteMultiBuffer(mb) return w.WriteMultiBuffer(mb)
} }
+4 -12
View File
@@ -191,18 +191,10 @@ func getConfig() string {
{ {
"protocol": "vless", "protocol": "vless",
"settings": { "settings": {
"vnext": [ "address": "1.2.3.4",
{ "port": 1234,
"address": "1.2.3.4", "id": "4784f9b8-a879-4fec-9718-ebddefa47750",
"port": 1234, "encryption": "none"
"users": [
{
"id": "4784f9b8-a879-4fec-9718-ebddefa47750",
"encryption": "none"
}
]
}
]
}, },
"tag": "XHTTP_IN", "tag": "XHTTP_IN",
"streamSettings": { "streamSettings": {
+5
View File
@@ -77,6 +77,11 @@ func ContentFromContext(ctx context.Context) *Content {
return nil return nil
} }
func SkipDNSResolveFromContext(ctx context.Context) bool {
content := ContentFromContext(ctx)
return content != nil && content.SkipDNSResolve
}
func ContextWithIsReverseMux(ctx context.Context, isReverseMux bool) context.Context { func ContextWithIsReverseMux(ctx context.Context, isReverseMux bool) context.Context {
return context.WithValue(ctx, isReverseMuxKey, isReverseMux) return context.WithValue(ctx, isReverseMuxKey, isReverseMux)
} }
+4 -1
View File
@@ -70,8 +70,11 @@ func (t *ActivityTimer) SetTimeout(timeout time.Duration) {
Execute: t.check, Execute: t.check,
} }
common.CloseIfExists(t.checkTask) common.CloseIfExists(t.checkTask)
select {
case <-t.updated:
default:
}
t.checkTask = newCheckTask t.checkTask = newCheckTask
t.Update()
common.Must(newCheckTask.Start()) common.Must(newCheckTask.Start())
} }
+3 -7
View File
@@ -58,15 +58,11 @@ func (t *Periodic) Start() error {
return nil return nil
} }
t.running = true t.running = true
t.timer = time.AfterFunc(t.Interval, func() {
t.checkedExecute()
})
t.access.Unlock() t.access.Unlock()
if err := t.checkedExecute(); err != nil {
t.access.Lock()
t.running = false
t.access.Unlock()
return err
}
return nil return nil
} }
+6 -6
View File
@@ -20,17 +20,17 @@ func TestPeriodicTaskStop(t *testing.T) {
common.Must(task.Start()) common.Must(task.Start())
time.Sleep(time.Second * 5) time.Sleep(time.Second * 5)
common.Must(task.Close()) common.Must(task.Close())
if value != 3 { if value != 2 {
t.Fatal("expected 3, but got ", value) t.Fatal("expected 2, but got ", value)
} }
time.Sleep(time.Second * 4) time.Sleep(time.Second * 4)
if value != 3 { if value != 2 {
t.Fatal("expected 3, but got ", value) t.Fatal("expected 2, but got ", value)
} }
common.Must(task.Start()) common.Must(task.Start())
time.Sleep(time.Second * 3) time.Sleep(time.Second * 3)
if value != 5 { if value != 3 {
t.Fatal("Expected 5, but ", value) t.Fatal("Expected 3, but ", value)
} }
common.Must(task.Close()) common.Must(task.Close())
} }
-1
View File
@@ -2,7 +2,6 @@ package core
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/io.go -mock_names Reader=Reader,Writer=Writer io Reader,Writer //go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/io.go -mock_names Reader=Reader,Writer=Writer io Reader,Writer
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/log.go -mock_names Handler=LogHandler github.com/xtls/xray-core/common/log Handler //go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/log.go -mock_names Handler=LogHandler github.com/xtls/xray-core/common/log Handler
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/mux.go -mock_names ClientWorkerFactory=MuxClientWorkerFactory github.com/xtls/xray-core/common/mux ClientWorkerFactory
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/dns.go -mock_names Client=DNSClient github.com/xtls/xray-core/features/dns Client //go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/dns.go -mock_names Client=DNSClient github.com/xtls/xray-core/features/dns Client
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/outbound.go -mock_names Manager=OutboundManager,HandlerSelector=OutboundHandlerSelector github.com/xtls/xray-core/features/outbound Manager,HandlerSelector //go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/outbound.go -mock_names Manager=OutboundManager,HandlerSelector=OutboundHandlerSelector github.com/xtls/xray-core/features/outbound Manager,HandlerSelector
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/proxy.go -mock_names Inbound=ProxyInbound,Outbound=ProxyOutbound github.com/xtls/xray-core/proxy Inbound,Outbound //go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/proxy.go -mock_names Inbound=ProxyInbound,Outbound=ProxyOutbound github.com/xtls/xray-core/proxy Inbound,Outbound
+8 -8
View File
@@ -3,7 +3,7 @@ module github.com/xtls/xray-core
go 1.27 go 1.27
require ( require (
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a
github.com/bufbuild/protocompile v0.14.1 github.com/bufbuild/protocompile v0.14.1
github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344
github.com/golang/mock v1.7.0-rc.1 github.com/golang/mock v1.7.0-rc.1
@@ -23,12 +23,12 @@ require (
github.com/xtls/reality v0.0.0-20261108101329-4bb46b2afd8b github.com/xtls/reality v0.0.0-20261108101329-4bb46b2afd8b
github.com/yuin/gopher-lua v1.1.2 github.com/yuin/gopher-lua v1.1.2
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba go4.org/netipx v0.0.0-20231129151722-fdeea329fbba
golang.org/x/crypto v0.58.0 golang.org/x/crypto v0.59.0
golang.org/x/crypto/x509roots/fallback v0.0.0-20261020153306-9f2b28d4331a golang.org/x/crypto/x509roots/fallback v0.0.0-20261020153306-9f2b28d4331a
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842
golang.org/x/net v0.62.0 golang.org/x/net v0.63.0
golang.org/x/sync v0.24.0 golang.org/x/sync v0.25.0
golang.org/x/sys v0.49.0 golang.org/x/sys v0.50.0
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2
golang.zx2c4.com/wireguard v0.0.0-20250521234502-f333402bd9cb golang.zx2c4.com/wireguard v0.0.0-20250521234502-f333402bd9cb
golang.zx2c4.com/wireguard/windows v1.1.1 golang.zx2c4.com/wireguard/windows v1.1.1
@@ -36,7 +36,7 @@ require (
google.golang.org/protobuf v1.36.12 google.golang.org/protobuf v1.36.12
h12.io/socks v1.0.3 h12.io/socks v1.0.3
layeh.com/gopher-luar v1.0.11 layeh.com/gopher-luar v1.0.11
lukechampine.com/blake3 v1.4.1 lukechampine.com/blake3 v1.5.1
mvdan.cc/gofumpt v0.12.0 mvdan.cc/gofumpt v0.12.0
) )
@@ -56,8 +56,8 @@ require (
github.com/vishvananda/netns v0.0.5 // indirect github.com/vishvananda/netns v0.0.5 // indirect
github.com/wlynxg/anet v0.0.5 // indirect github.com/wlynxg/anet v0.0.5 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/text v0.43.0 // indirect golang.org/x/text v0.44.0 // indirect
golang.org/x/tools v0.51.0 // indirect golang.org/x/tools v0.52.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260817212433-ac3dfec99bb1 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260817212433-ac3dfec99bb1 // indirect
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.6.2 // indirect google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.6.2 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect
+16 -18
View File
@@ -1,5 +1,5 @@
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c h1:cxK8qTA0YCsj68A7zLYDCfPgMTOyt3ePkHh+oXEmYU0= github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a h1:uCIlOCbXUtBkFk47HxIkQieCkV+zKv5VCDawLtj3Pkc=
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c/go.mod h1:J7UZVOMF2M1LiE3iiUZWPuy8YCPAcLJOwVURrfJCvc0= github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a/go.mod h1:J7UZVOMF2M1LiE3iiUZWPuy8YCPAcLJOwVURrfJCvc0=
github.com/bufbuild/protocompile v0.14.1 h1:iA73zAf/fyljNjQKwYzUHD6AD4R8KMasmwa/FBatYVw= github.com/bufbuild/protocompile v0.14.1 h1:iA73zAf/fyljNjQKwYzUHD6AD4R8KMasmwa/FBatYVw=
github.com/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU5DoEw9xY/FUi1c= github.com/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU5DoEw9xY/FUi1c=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
@@ -31,8 +31,6 @@ github.com/jackpal/go-nat-pmp v1.0.2 h1:KzKSgb7qkJvOUTqYl9/Hg/me3pWgBmERKrTGD7Bd
github.com/jackpal/go-nat-pmp v1.0.2/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc= github.com/jackpal/go-nat-pmp v1.0.2/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc=
github.com/juju/ratelimit v1.0.2 h1:sRxmtRiajbvrcLQT7S+JbqU0ntsb9W2yhSdNN8tWfaI= github.com/juju/ratelimit v1.0.2 h1:sRxmtRiajbvrcLQT7S+JbqU0ntsb9W2yhSdNN8tWfaI=
github.com/juju/ratelimit v1.0.2/go.mod h1:qapgC/Gy+xNh9UxzV13HGGl/6UXNN+ct+vwSgWNm/qk= github.com/juju/ratelimit v1.0.2/go.mod h1:qapgC/Gy+xNh9UxzV13HGGl/6UXNN+ct+vwSgWNm/qk=
github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=
github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI= github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/cpuid/v2 v2.4.2 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ= github.com/klauspost/cpuid/v2 v2.4.2 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ=
@@ -97,8 +95,8 @@ go4.org/netipx v0.0.0-20231129151722-fdeea329fbba h1:0b9z3AuHCjxk0x/opv64kcgZLBs
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y= go4.org/netipx v0.0.0-20231129151722-fdeea329fbba/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
golang.org/x/crypto/x509roots/fallback v0.0.0-20261020153306-9f2b28d4331a h1:V5oicZXS0oqZx30gY/apgSVD7YvNBfrIOdcMnlelJY4= golang.org/x/crypto/x509roots/fallback v0.0.0-20261020153306-9f2b28d4331a h1:V5oicZXS0oqZx30gY/apgSVD7YvNBfrIOdcMnlelJY4=
golang.org/x/crypto/x509roots/fallback v0.0.0-20261020153306-9f2b28d4331a/go.mod h1:HPze8vhfG6fO06AM+VSvxRm4E3+5Yk375mgrJ5M2z1E= golang.org/x/crypto/x509roots/fallback v0.0.0-20261020153306-9f2b28d4331a/go.mod h1:HPze8vhfG6fO06AM+VSvxRm4E3+5Yk375mgrJ5M2z1E=
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 h1:vr/HnozRka3pE4EsMEg1lgkXJkTFJCVUX+S/ZT6wYzM= golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 h1:vr/HnozRka3pE4EsMEg1lgkXJkTFJCVUX+S/ZT6wYzM=
@@ -109,12 +107,12 @@ golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -123,22 +121,22 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU=
golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI= golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA= golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@@ -170,7 +168,7 @@ h12.io/socks v1.0.3 h1:Ka3qaQewws4j4/eDQnOdpr4wXsC//dXtWvftlIcCQUo=
h12.io/socks v1.0.3/go.mod h1:AIhxy1jOId/XCz9BO+EIgNL2rQiPTBNnOfnVnQ+3Eck= h12.io/socks v1.0.3/go.mod h1:AIhxy1jOId/XCz9BO+EIgNL2rQiPTBNnOfnVnQ+3Eck=
layeh.com/gopher-luar v1.0.11 h1:8zJudpKI6HWkoh9eyyNFaTM79PY6CAPcIr6X/KTiliw= layeh.com/gopher-luar v1.0.11 h1:8zJudpKI6HWkoh9eyyNFaTM79PY6CAPcIr6X/KTiliw=
layeh.com/gopher-luar v1.0.11/go.mod h1:TPnIVCZ2RJBndm7ohXyaqfhzjlZ+OA2SZR/YwL8tECk= layeh.com/gopher-luar v1.0.11/go.mod h1:TPnIVCZ2RJBndm7ohXyaqfhzjlZ+OA2SZR/YwL8tECk=
lukechampine.com/blake3 v1.4.1 h1:I3Smz7gso8w4/TunLKec6K2fn+kyKtDxr/xcQEN84Wg= lukechampine.com/blake3 v1.5.1 h1:ITRyxe0LlLZcPUWOZ3Taz8mbug/ptn7jbbeeij5ZiPo=
lukechampine.com/blake3 v1.4.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo= lukechampine.com/blake3 v1.5.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo=
mvdan.cc/gofumpt v0.12.0 h1:1Lbudkz2kpM9Cjz2pL4M19u7q+GaEhCTNf7N9mfpcho= mvdan.cc/gofumpt v0.12.0 h1:1Lbudkz2kpM9Cjz2pL4M19u7q+GaEhCTNf7N9mfpcho=
mvdan.cc/gofumpt v0.12.0/go.mod h1:SmBHHrljiZu/uoypeKup3rFzP6eoC9UwCp2iH5E3jZA= mvdan.cc/gofumpt v0.12.0/go.mod h1:SmBHHrljiZu/uoypeKup3rFzP6eoC9UwCp2iH5E3jZA=
+24 -63
View File
@@ -1,9 +1,6 @@
package conf package conf
import ( import (
"encoding/json"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/protocol" "github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/proxy/http" "github.com/xtls/xray-core/proxy/http"
@@ -49,73 +46,37 @@ func (c *HTTPServerConfig) Build() (proto.Message, error) {
return config, nil return config, nil
} }
type HTTPRemoteConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Users []json.RawMessage `json:"users"`
}
type HTTPClientConfig struct { type HTTPClientConfig struct {
Address *Address `json:"address"` Address *Address `json:"address"`
Port uint16 `json:"port"` Port uint16 `json:"port"`
Level uint32 `json:"level"` Level uint32 `json:"level"`
Email string `json:"email"` Email string `json:"email"`
Username string `json:"user"` Username string `json:"user"`
Password string `json:"pass"` Password string `json:"pass"`
Servers []*HTTPRemoteConfig `json:"servers"` Headers map[string]string `json:"headers"`
Headers map[string]string `json:"headers"`
} }
func (v *HTTPClientConfig) Build() (proto.Message, error) { func (v *HTTPClientConfig) Build() (proto.Message, error) {
config := new(http.ClientConfig) config := new(http.ClientConfig)
if v.Address != nil {
v.Servers = []*HTTPRemoteConfig{ server := &protocol.ServerEndpoint{
{ Address: v.Address.Build(),
Address: v.Address, Port: uint32(v.Port),
Port: v.Port,
},
}
if len(v.Username) > 0 {
v.Servers[0].Users = []json.RawMessage{{}}
}
} }
if len(v.Servers) != 1 { if len(v.Username) > 0 {
return nil, errors.New(`HTTP settings: "servers" should have one and only one member. Multiple endpoints in "servers" should use multiple HTTP outbounds and routing balancer instead`) account := &HTTPAccount{
} Username: v.Username,
for _, serverConfig := range v.Servers { Password: v.Password,
if len(serverConfig.Users) > 1 { }
return nil, errors.New(`HTTP servers: "users" should have one member at most. Multiple members in "users" should use multiple HTTP outbounds and routing balancer instead`) user := &protocol.User{
} Level: v.Level,
server := &protocol.ServerEndpoint{ Email: v.Email,
Address: serverConfig.Address.Build(), Account: serial.ToTypedMessage(account.Build()),
Port: uint32(serverConfig.Port), }
} server.User = user
for _, rawUser := range serverConfig.Users {
user := new(protocol.User)
if v.Address != nil {
user.Level = v.Level
user.Email = v.Email
} else {
if err := json.Unmarshal(rawUser, user); err != nil {
return nil, errors.New("failed to parse HTTP user").Base(err)
}
}
account := new(HTTPAccount)
if v.Address != nil {
account.Username = v.Username
account.Password = v.Password
} else {
if err := json.Unmarshal(rawUser, account); err != nil {
return nil, errors.New("failed to parse HTTP account").Base(err)
}
}
user.Account = serial.ToTypedMessage(account.Build())
server.User = user
break
}
config.Server = server
break
} }
config.Server = server
config.Header = make([]*http.Header, 0, 32) config.Header = make([]*http.Header, 0, 32)
for key, value := range v.Headers { for key, value := range v.Headers {
config.Header = append(config.Header, &http.Header{ config.Header = append(config.Header, &http.Header{
-56
View File
@@ -1,56 +0,0 @@
package conf
import (
"github.com/xtls/xray-core/app/reverse"
"google.golang.org/protobuf/proto"
)
type BridgeConfig struct {
Tag string `json:"tag"`
Domain string `json:"domain"`
}
func (c *BridgeConfig) Build() (*reverse.BridgeConfig, error) {
return &reverse.BridgeConfig{
Tag: c.Tag,
Domain: c.Domain,
}, nil
}
type PortalConfig struct {
Tag string `json:"tag"`
Domain string `json:"domain"`
}
func (c *PortalConfig) Build() (*reverse.PortalConfig, error) {
return &reverse.PortalConfig{
Tag: c.Tag,
Domain: c.Domain,
}, nil
}
type ReverseConfig struct {
Bridges []BridgeConfig `json:"bridges"`
Portals []PortalConfig `json:"portals"`
}
func (c *ReverseConfig) Build() (proto.Message, error) {
config := &reverse.Config{}
for _, bconfig := range c.Bridges {
b, err := bconfig.Build()
if err != nil {
return nil, err
}
config.BridgeConfig = append(config.BridgeConfig, b)
}
for _, pconfig := range c.Portals {
p, err := pconfig.Build()
if err != nil {
return nil, err
}
config.PortalConfig = append(config.PortalConfig, p)
}
return config, nil
}
-45
View File
@@ -1,45 +0,0 @@
package conf_test
import (
"testing"
"github.com/xtls/xray-core/app/reverse"
"github.com/xtls/xray-core/infra/conf"
)
func TestReverseConfig(t *testing.T) {
creator := func() conf.Buildable {
return new(conf.ReverseConfig)
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"bridges": [{
"tag": "test",
"domain": "test.example.com"
}]
}`,
Parser: loadJSON(creator),
Output: &reverse.Config{
BridgeConfig: []*reverse.BridgeConfig{
{Tag: "test", Domain: "test.example.com"},
},
},
},
{
Input: `{
"portals": [{
"tag": "test",
"domain": "test.example.com"
}]
}`,
Parser: loadJSON(creator),
Output: &reverse.Config{
PortalConfig: []*reverse.PortalConfig{
{Tag: "test", Domain: "test.example.com"},
},
},
},
})
}
+22 -48
View File
@@ -177,7 +177,7 @@ func buildShadowsocks2022(v *ShadowsocksServerConfig) (proto.Message, error) {
return config, nil return config, nil
} }
type ShadowsocksServerTarget struct { type ShadowsocksClientConfig struct {
Address *Address `json:"address"` Address *Address `json:"address"`
Port uint16 `json:"port"` Port uint16 `json:"port"`
Level byte `json:"level"` Level byte `json:"level"`
@@ -186,69 +186,43 @@ type ShadowsocksServerTarget struct {
Password string `json:"password"` Password string `json:"password"`
} }
type ShadowsocksClientConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level byte `json:"level"`
Email string `json:"email"`
Cipher string `json:"method"`
Password string `json:"password"`
Servers []*ShadowsocksServerTarget `json:"servers"`
}
func (v *ShadowsocksClientConfig) Build() (proto.Message, error) { func (v *ShadowsocksClientConfig) Build() (proto.Message, error) {
errors.PrintNonRemovalDeprecatedFeatureWarning("Shadowsocks (with no Forward Secrecy, etc.)", "VLESS Encryption") errors.PrintNonRemovalDeprecatedFeatureWarning("Shadowsocks (with no Forward Secrecy, etc.)", "VLESS Encryption")
if v.Address != nil { if v.Address == nil {
v.Servers = []*ShadowsocksServerTarget{
{
Address: v.Address,
Port: v.Port,
Level: v.Level,
Email: v.Email,
Cipher: v.Cipher,
Password: v.Password,
},
}
}
if len(v.Servers) != 1 {
return nil, errors.New(`Shadowsocks settings: "servers" should have one and only one member. Multiple endpoints in "servers" should use multiple Shadowsocks outbounds and routing balancer instead`)
}
server := v.Servers[0]
if server.Address == nil {
return nil, errors.New("Shadowsocks server address is not set.") return nil, errors.New("Shadowsocks server address is not set.")
} }
if server.Port == 0 { if v.Port == 0 {
return nil, errors.New("Invalid Shadowsocks port.") return nil, errors.New("Invalid Shadowsocks port.")
} }
if server.Password == "" { if v.Password == "" {
return nil, errors.New("Shadowsocks password is not specified.") return nil, errors.New("Shadowsocks password is not specified.")
} }
if _, err := shadowsocks_2022.GetCipherMethod(server.Cipher); err == nil { if _, err := shadowsocks_2022.GetCipherMethod(v.Cipher); err == nil {
config := new(shadowsocks_2022.ClientConfig) config := &shadowsocks_2022.ClientConfig{
config.Address = server.Address.Build() Address: v.Address.Build(),
config.Port = uint32(server.Port) Port: uint32(v.Port),
config.Method = server.Cipher Method: v.Cipher,
config.Key = server.Password Key: v.Password,
}
return config, nil return config, nil
} }
config := new(shadowsocks.ClientConfig) config := new(shadowsocks.ClientConfig)
account := &shadowsocks.Account{ if cipherFromString(v.Cipher) == shadowsocks.CipherType_UNKNOWN {
Password: server.Password, return nil, errors.New("unknown cipher method: ", v.Cipher)
}
account.CipherType = cipherFromString(server.Cipher)
if account.CipherType == shadowsocks.CipherType_UNKNOWN {
return nil, errors.New("unknown cipher method: ", server.Cipher)
} }
ss := &protocol.ServerEndpoint{ ss := &protocol.ServerEndpoint{
Address: server.Address.Build(), Address: v.Address.Build(),
Port: uint32(server.Port), Port: uint32(v.Port),
User: &protocol.User{ User: &protocol.User{
Level: uint32(server.Level), Level: uint32(v.Level),
Email: server.Email, Email: v.Email,
Account: serial.ToTypedMessage(account), Account: serial.ToTypedMessage(&shadowsocks.Account{
Password: v.Password,
CipherType: cipherFromString(v.Cipher),
}),
}, },
} }
config.Server = ss config.Server = ss
+23 -62
View File
@@ -1,9 +1,6 @@
package conf package conf
import ( import (
"encoding/json"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/protocol" "github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/proxy/socks" "github.com/xtls/xray-core/proxy/socks"
@@ -67,71 +64,35 @@ func (v *SocksServerConfig) Build() (proto.Message, error) {
return config, nil return config, nil
} }
type SocksRemoteConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Users []json.RawMessage `json:"users"`
}
type SocksClientConfig struct { type SocksClientConfig struct {
Address *Address `json:"address"` Address *Address `json:"address"`
Port uint16 `json:"port"` Port uint16 `json:"port"`
Level uint32 `json:"level"` Level uint32 `json:"level"`
Email string `json:"email"` Email string `json:"email"`
Username string `json:"user"` Username string `json:"user"`
Password string `json:"pass"` Password string `json:"pass"`
Servers []*SocksRemoteConfig `json:"servers"`
} }
func (v *SocksClientConfig) Build() (proto.Message, error) { func (v *SocksClientConfig) Build() (proto.Message, error) {
config := new(socks.ClientConfig) config := new(socks.ClientConfig)
if v.Address != nil {
v.Servers = []*SocksRemoteConfig{ server := &protocol.ServerEndpoint{
{ Address: v.Address.Build(),
Address: v.Address, Port: uint32(v.Port),
Port: v.Port,
},
}
if len(v.Username) > 0 {
v.Servers[0].Users = []json.RawMessage{{}}
}
} }
if len(v.Servers) != 1 { if len(v.Username) > 0 {
return nil, errors.New(`SOCKS settings: "servers" should have one and only one member. Multiple endpoints in "servers" should use multiple SOCKS outbounds and routing balancer instead`) account := &SocksAccount{
} Username: v.Username,
for _, serverConfig := range v.Servers { Password: v.Password,
if len(serverConfig.Users) > 1 { }
return nil, errors.New(`SOCKS servers: "users" should have one member at most. Multiple members in "users" should use multiple SOCKS outbounds and routing balancer instead`) user := &protocol.User{
} Level: v.Level,
server := &protocol.ServerEndpoint{ Email: v.Email,
Address: serverConfig.Address.Build(), Account: serial.ToTypedMessage(account.Build()),
Port: uint32(serverConfig.Port), }
} server.User = user
for _, rawUser := range serverConfig.Users {
user := new(protocol.User)
if v.Address != nil {
user.Level = v.Level
user.Email = v.Email
} else {
if err := json.Unmarshal(rawUser, user); err != nil {
return nil, errors.New("failed to parse Socks user").Base(err)
}
}
account := new(SocksAccount)
if v.Address != nil {
account.Username = v.Username
account.Password = v.Password
} else {
if err := json.Unmarshal(rawUser, account); err != nil {
return nil, errors.New("failed to parse socks account").Base(err)
}
}
user.Account = serial.ToTypedMessage(account.Build())
server.User = user
break
}
config.Server = server
break
} }
config.Server = server
return config, nil return config, nil
} }
-29
View File
@@ -53,35 +53,6 @@ func TestSocksOutboundConfig(t *testing.T) {
} }
runMultiTestCase(t, []TestCase{ runMultiTestCase(t, []TestCase{
{
Input: `{
"servers": [{
"address": "127.0.0.1",
"port": 1234,
"users": [
{"user": "test user", "pass": "test pass", "email": "test@email.com"}
]
}]
}`,
Parser: loadJSON(creator),
Output: &socks.ClientConfig{
Server: &protocol.ServerEndpoint{
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: 1234,
User: &protocol.User{
Email: "test@email.com",
Account: serial.ToTypedMessage(&socks.Account{
Username: "test user",
Password: "test pass",
}),
},
},
},
},
{ {
Input: `{ Input: `{
"address": "127.0.0.1", "address": "127.0.0.1",
+95 -19
View File
@@ -2,6 +2,8 @@ package conf
import ( import (
"context" "context"
"crypto/rand"
"crypto/rsa"
"crypto/x509" "crypto/x509"
"encoding/base64" "encoding/base64"
"encoding/hex" "encoding/hex"
@@ -865,6 +867,7 @@ type XDNSDomain struct {
LabelLimit int32 `json:"labelLimit"` LabelLimit int32 `json:"labelLimit"`
Types []int32 `json:"types"` Types []int32 `json:"types"`
Edns0 int32 `json:"edns0"` Edns0 int32 `json:"edns0"`
Alphabet string `json:"alphabet"`
} }
type XDNSResolver struct { type XDNSResolver struct {
@@ -891,7 +894,7 @@ func (c *XDNS) Build() (proto.Message, error) {
c.Domains[i].LabelLimit = 63 c.Domains[i].LabelLimit = 63
} }
for j := range c.Domains[i].Names { for j := range c.Domains[i].Names {
domain, err := xdns.NewDomain(c.Domains[i].Names[j], int(c.Domains[i].LenLimit), int(c.Domains[i].LabelLimit), []uint16{1, 5, 16, 28}, uint16(c.Domains[i].Edns0)) domain, err := xdns.NewDomain(c.Domains[i].Names[j], int(c.Domains[i].LenLimit), int(c.Domains[i].LabelLimit), []uint16{1, 5, 16, 28}, uint16(c.Domains[i].Edns0), c.Domains[i].Alphabet)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -902,6 +905,7 @@ func (c *XDNS) Build() (proto.Message, error) {
LabelLimit: c.Domains[i].LabelLimit, LabelLimit: c.Domains[i].LabelLimit,
Types: c.Domains[i].Types, Types: c.Domains[i].Types,
Edns0: c.Domains[i].Edns0, Edns0: c.Domains[i].Edns0,
Alphabet: c.Domains[i].Alphabet,
}) })
} }
} }
@@ -961,10 +965,11 @@ func (c *XDNS) Build() (proto.Message, error) {
} }
type XMC struct { type XMC struct {
Hostname string `json:"hostname"` Hostname string `json:"hostname"`
Profiles []XMCProfile `json:"profiles"` Profiles []XMCProfile `json:"profiles"`
Password string `json:"password"` Password string `json:"password"`
Paddings []XMCPaddingTurn `json:"paddings,omitempty"` Paddings []XMCPaddingTurn `json:"paddings,omitempty"`
Yggdrasil *XMCYggdrasil `json:"yggdrasil,omitempty"`
// A configured list is the complete padding schedule and replaces the // A configured list is the complete padding schedule and replaces the
// built-in preset entirely, including the preset's Play-state join tail. // built-in preset entirely, including the preset's Play-state join tail.
// NoPadding disables padding. An explicit empty "paddings" array means the // NoPadding disables padding. An explicit empty "paddings" array means the
@@ -982,6 +987,19 @@ type XMCPaddingTurn struct {
Delay string `json:"delay,omitempty"` Delay string `json:"delay,omitempty"`
} }
// XMCYggdrasil enables third-party login through a Yggdrasil API server such
// as Blessing Skin. The client authenticates with the API and the server
// verifies players through its hasJoined endpoint.
type XMCYggdrasil struct {
// API root of the Yggdrasil API, for example
// https://skin.example.com/api/yggdrasil
API string `json:"api"`
Username string `json:"username"`
Password string `json:"password"`
// Optional player name, required when the account owns several players.
Player string `json:"player"`
}
type XMCProfile struct { type XMCProfile struct {
// Resolve the UUID by username, then request the session profile with // Resolve the UUID by username, then request the session profile with
// unsigned=false. Client and server must use the same signed profile. // unsigned=false. Client and server must use the same signed profile.
@@ -1015,16 +1033,6 @@ func (c *XMCProfile) Build() (*xmc.Profile, error) {
} }
func (c *XMC) Build() (proto.Message, error) { func (c *XMC) Build() (proto.Message, error) {
if len(c.Profiles) == 0 {
return nil, fmt.Errorf("minecraft profiles are required")
}
if c.Password == "" {
return nil, fmt.Errorf("empty password")
}
if len(c.Password) > xmc.MaxLegacyPasswordLength {
return nil, fmt.Errorf("minecraft password is longer than %d bytes", xmc.MaxLegacyPasswordLength)
}
// An explicit empty array is different from an absent field: json leaves // An explicit empty array is different from an absent field: json leaves
// Paddings nil when it is absent, so the user can turn padding off without // Paddings nil when it is absent, so the user can turn padding off without
// a second switch. // a second switch.
@@ -1032,7 +1040,7 @@ func (c *XMC) Build() (proto.Message, error) {
if noPadding && len(c.Paddings) > 0 { if noPadding && len(c.Paddings) > 0 {
return nil, fmt.Errorf("minecraft padding: noPadding and paddings are exclusive") return nil, fmt.Errorf("minecraft padding: noPadding and paddings are exclusive")
} }
config := &xmc.Config{Password: c.Password, Hostname: c.Hostname, NoPadding: noPadding} config := &xmc.Config{Hostname: c.Hostname, NoPadding: noPadding}
for i, turn := range c.Paddings { for i, turn := range c.Paddings {
minimum, maximum, err := ParseRangeString(turn.Length) minimum, maximum, err := ParseRangeString(turn.Length)
if err != nil { if err != nil {
@@ -1065,9 +1073,75 @@ func (c *XMC) Build() (proto.Message, error) {
return nil, fmt.Errorf("minecraft padding: %w", err) return nil, fmt.Errorf("minecraft padding: %w", err)
} }
rsaPrivateKey, err := xmc.DeriveRSAKey(c.Password) var yggdrasil *xmc.Yggdrasil
if err != nil { if c.Yggdrasil != nil {
return nil, fmt.Errorf("derive minecraft rsa key: %w", err) if c.Yggdrasil.API == "" {
return nil, fmt.Errorf("empty minecraft yggdrasil api")
}
apiURL, err := url.Parse(c.Yggdrasil.API)
if err != nil {
return nil, fmt.Errorf("invalid minecraft yggdrasil api: %w", err)
}
if apiURL.Scheme != "http" && apiURL.Scheme != "https" {
return nil, fmt.Errorf("invalid minecraft yggdrasil api scheme: %q", apiURL.Scheme)
}
if apiURL.Host == "" {
return nil, fmt.Errorf("invalid minecraft yggdrasil api: missing host")
}
if apiURL.RawQuery != "" || apiURL.Fragment != "" {
return nil, fmt.Errorf("invalid minecraft yggdrasil api: query and fragment are not allowed")
}
if (c.Yggdrasil.Username == "") != (c.Yggdrasil.Password == "") {
return nil, fmt.Errorf("minecraft yggdrasil username and password must be set together")
}
if c.Yggdrasil.Player != "" && !xmcUsernamePattern.MatchString(c.Yggdrasil.Player) {
return nil, fmt.Errorf("invalid minecraft yggdrasil player: %q", c.Yggdrasil.Player)
}
yggdrasil = &xmc.Yggdrasil{
Api: strings.TrimSuffix(c.Yggdrasil.API, "/"),
Username: c.Yggdrasil.Username,
Password: c.Yggdrasil.Password,
Player: c.Yggdrasil.Player,
}
} else if len(c.Profiles) == 0 {
return nil, fmt.Errorf("minecraft profiles are required")
}
var (
rsaPrivateKey *rsa.PrivateKey
password string
)
if yggdrasil != nil {
// Yggdrasil mode binds the transport through the session hash: the
// client joins with the server's actual public key and the server
// checks hasJoined. The key pair is therefore generated per process
// instead of being derived from the password.
generated, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
return nil, fmt.Errorf("generate minecraft rsa key: %w", err)
}
rsaPrivateKey = generated
warning := `XMC: Yggdrasil mode is enabled. The RSA key pair is generated randomly and "password" is no longer used to derive it or to authenticate the transport; players are verified through ` + yggdrasil.Api + ` (client /join, server /hasJoined). Both ends must be able to reach the Yggdrasil API.`
if c.Password != "" {
warning += ` The configured "password" is ignored.`
}
errors.LogWarning(context.Background(), warning)
} else {
if c.Password == "" {
return nil, fmt.Errorf("empty password")
}
if len(c.Password) > xmc.MaxLegacyPasswordLength {
return nil, fmt.Errorf("minecraft password is longer than %d bytes", xmc.MaxLegacyPasswordLength)
}
derived, err := xmc.DeriveRSAKey(c.Password)
if err != nil {
return nil, fmt.Errorf("derive minecraft rsa key: %w", err)
}
rsaPrivateKey = derived
password = c.Password
} }
rsaPublicKey, err := x509.MarshalPKIXPublicKey(&rsaPrivateKey.PublicKey) rsaPublicKey, err := x509.MarshalPKIXPublicKey(&rsaPrivateKey.PublicKey)
@@ -1084,9 +1158,11 @@ func (c *XMC) Build() (proto.Message, error) {
profiles = append(profiles, profile) profiles = append(profiles, profile)
} }
config.Password = password
config.RsaPrivateKey = x509.MarshalPKCS1PrivateKey(rsaPrivateKey) config.RsaPrivateKey = x509.MarshalPKCS1PrivateKey(rsaPrivateKey)
config.RsaPublicKey = rsaPublicKey config.RsaPublicKey = rsaPublicKey
config.Profiles = profiles config.Profiles = profiles
config.Yggdrasil = yggdrasil
return config, nil return config, nil
} }
@@ -1,6 +1,7 @@
package conf package conf
import ( import (
"crypto/x509"
"encoding/json" "encoding/json"
"strings" "strings"
"testing" "testing"
@@ -113,6 +114,96 @@ func TestXMCBuildRejectsLongPassword(t *testing.T) {
} }
} }
func TestXMCBuildYggdrasil(t *testing.T) {
built, err := (&XMC{
Password: "test-password",
Yggdrasil: &XMCYggdrasil{
API: "https://skin.example.com/api/yggdrasil/",
Username: "user@example.com",
Password: "login-password",
Player: "TestUser",
},
}).Build()
if err != nil {
t.Fatalf("build XMC config: %v", err)
}
config := built.(*xmc.Config)
if config.Yggdrasil == nil {
t.Fatal("yggdrasil config is missing")
}
if config.Yggdrasil.Api != "https://skin.example.com/api/yggdrasil" {
t.Fatalf("yggdrasil api = %q", config.Yggdrasil.Api)
}
if config.Yggdrasil.Username != "user@example.com" || config.Yggdrasil.Password != "login-password" || config.Yggdrasil.Player != "TestUser" {
t.Fatalf("unexpected yggdrasil config: %+v", config.Yggdrasil)
}
if config.Password != "" {
t.Fatalf("password must not be used in yggdrasil mode: %q", config.Password)
}
if len(config.RsaPrivateKey) == 0 || len(config.RsaPublicKey) == 0 {
t.Fatal("yggdrasil mode must build a random rsa key pair")
}
privateKey, err := x509.ParsePKCS1PrivateKey(config.RsaPrivateKey)
if err != nil {
t.Fatalf("parse generated rsa private key: %v", err)
}
publicKey, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
if err != nil {
t.Fatalf("marshal generated rsa public key: %v", err)
}
if string(publicKey) != string(config.RsaPublicKey) {
t.Fatal("generated rsa key pair does not match")
}
}
func TestXMCBuildYggdrasilServerWithoutCredentials(t *testing.T) {
built, err := (&XMC{
Yggdrasil: &XMCYggdrasil{
API: "https://skin.example.com/api/yggdrasil",
},
}).Build()
if err != nil {
t.Fatalf("build server-side XMC config: %v", err)
}
if built.(*xmc.Config).Yggdrasil == nil {
t.Fatal("yggdrasil config is missing")
}
}
func TestXMCBuildRejectsInvalidYggdrasil(t *testing.T) {
cases := []*XMCYggdrasil{
{API: ""},
{API: "ftp://skin.example.com/api/yggdrasil"},
{API: "https://skin.example.com/api/yggdrasil?foo=bar"},
{API: "https://skin.example.com/api/yggdrasil", Username: "user@example.com"},
{API: "https://skin.example.com/api/yggdrasil", Password: "login-password"},
{API: "https://skin.example.com/api/yggdrasil", Player: "bad name"},
}
for i, yggdrasil := range cases {
_, err := (&XMC{Yggdrasil: yggdrasil}).Build()
if err == nil {
t.Fatalf("case %d was accepted: %+v", i, yggdrasil)
}
}
}
func TestXMCBuildRequiresPasswordInLegacyMode(t *testing.T) {
_, err := (&XMC{
Profiles: []XMCProfile{
{
Username: "TestUser",
UUID: "00112233-4455-6677-8899-aabbccddeeff",
TexturesValue: "textures-value",
TexturesSignature: "textures-signature",
},
},
}).Build()
if err == nil || !strings.Contains(err.Error(), "empty password") {
t.Fatalf("expected empty password error, got %v", err)
}
}
func TestXMCBuildDisablesPadding(t *testing.T) { func TestXMCBuildDisablesPadding(t *testing.T) {
profile := XMCProfile{ profile := XMCProfile{
Username: "TestUser", UUID: "00112233-4455-6677-8899-aabbccddeeff", Username: "TestUser", UUID: "00112233-4455-6677-8899-aabbccddeeff",
+9 -13
View File
@@ -529,26 +529,22 @@ func TestXDriveOutboundConfig(t *testing.T) {
} }
for _, input := range []string{ for _, input := range []string{
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": 0, "xudpConcurrency": 8, "xudpProxyUDP443": "allow"}}`, `{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8, "xudpConcurrency": 8, "xudpProxyUDP443": "allow"}}, ` + xdriveStream + `}`,
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "reverse": {"tag": "r"}}, ` + xdriveStream + `}`, `{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "reverse": {"tag": "r"}}, ` + xdriveStream + `}`,
`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `}]}]}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `{"protocol": "vless", "settings": {"address": "127.0.0.1", "port": 443, ` + xdriveID + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
} { } {
if err := build(input); err != nil { if err := build(input); err != nil {
t.Errorf("%s: %v", input, err) t.Errorf("%s: %v", input, err)
} }
} }
for _, c := range []struct{ input, err string }{ for _, c := range []struct{ input, err string }{
{`{"protocol": "vless", "settings": {` + xdriveServer + `, "encryption": "none"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"encryption"`}, {`{"protocol": "vless", "settings": {` + xdriveServer + `, "encryption": "none", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"encryption"`},
{`{"protocol": "vless", "settings": {"address": "example.com", "port": 443, ` + xdriveID + `, "encryption": "none"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"encryption"`}, {`{"protocol": "vless", "settings": {"address": "example.com", "port": 443, ` + xdriveID + `, "encryption": "none", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"encryption"`},
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `}`, `"mux"`}, {`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8, "xudpProxyUDP443": "skip"}}, ` + xdriveStream + `}`, `"xudpProxyUDP443":"skip"`},
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": false}}`, `"mux"`}, {`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": -1}}`, `"mux"`}, {`{"protocol": "vless", "settings": {"address": "127.0.0.1", "port": 443, ` + xdriveID + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "xudpConcurrency": -1}}`, `"mux"`}, {`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "testpre": 1, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"testpre"`},
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "xudpProxyUDP443": "skip"}}`, `"mux"`},
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision"}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": -1}}`, `"flow"`},
{`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision"}]}]}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": -1}}`, `"flow"`},
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "testpre": 1}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"testpre"`},
{`{"protocol": "vmess", "settings": {` + xdriveServer + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`, "VLESS"}, {`{"protocol": "vmess", "settings": {` + xdriveServer + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`, "VLESS"},
{`{"protocol": "trojan", "settings": {"address": "example.com", "port": 443, "password": "p"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, "VLESS"}, {`{"protocol": "trojan", "settings": {"address": "example.com", "port": 443, "password": "p"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, "VLESS"},
{`{"protocol": "freedom", ` + xdriveStream + `}`, "VLESS"}, {`{"protocol": "freedom", ` + xdriveStream + `}`, "VLESS"},
+21 -60
View File
@@ -17,76 +17,41 @@ import (
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
) )
// TrojanServerTarget is configuration of a single trojan server // TrojanClientConfig is configuration of trojan servers
type TrojanServerTarget struct { type TrojanClientConfig struct {
Address *Address `json:"address"` Address *Address `json:"address"`
Port uint16 `json:"port"` Port uint16 `json:"port"`
Level byte `json:"level"` Level byte `json:"level"`
Email string `json:"email"` Email string `json:"email"`
Password string `json:"password"` Password string `json:"password"`
Flow string `json:"flow"`
}
// TrojanClientConfig is configuration of trojan servers
type TrojanClientConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level byte `json:"level"`
Email string `json:"email"`
Password string `json:"password"`
Flow string `json:"flow"`
Servers []*TrojanServerTarget `json:"servers"`
} }
// Build implements Buildable // Build implements Buildable
func (c *TrojanClientConfig) Build() (proto.Message, error) { func (c *TrojanClientConfig) Build() (proto.Message, error) {
errors.PrintNonRemovalDeprecatedFeatureWarning("Trojan (with no Flow, etc.)", "VLESS with Flow & Seed") errors.PrintNonRemovalDeprecatedFeatureWarning("Trojan (with no Flow, etc.)", "VLESS with Flow & Seed")
if c.Address != nil {
c.Servers = []*TrojanServerTarget{
{
Address: c.Address,
Port: c.Port,
Level: c.Level,
Email: c.Email,
Password: c.Password,
Flow: c.Flow,
},
}
}
if len(c.Servers) != 1 {
return nil, errors.New(`Trojan settings: "servers" should have one and only one member. Multiple endpoints in "servers" should use multiple Trojan outbounds and routing balancer instead`)
}
config := &trojan.ClientConfig{} config := &trojan.ClientConfig{}
for _, rec := range c.Servers { if c.Address == nil {
if rec.Address == nil { return nil, errors.New("Trojan server address is not set.")
return nil, errors.New("Trojan server address is not set.") }
} if c.Port == 0 {
if rec.Port == 0 { return nil, errors.New("Invalid Trojan port.")
return nil, errors.New("Invalid Trojan port.") }
} if c.Password == "" {
if rec.Password == "" { return nil, errors.New("Trojan password is not specified.")
return nil, errors.New("Trojan password is not specified.") }
}
if rec.Flow != "" {
return nil, errors.PrintRemovedFeatureError(`Flow for Trojan`, ``)
}
config.Server = &protocol.ServerEndpoint{ config.Server = &protocol.ServerEndpoint{
Address: rec.Address.Build(), Address: c.Address.Build(),
Port: uint32(rec.Port), Port: uint32(c.Port),
User: &protocol.User{ User: &protocol.User{
Level: uint32(rec.Level), Level: uint32(c.Level),
Email: rec.Email, Email: c.Email,
Account: serial.ToTypedMessage(&trojan.Account{ Account: serial.ToTypedMessage(&trojan.Account{
Password: rec.Password, Password: c.Password,
}), }),
}, },
}
break
} }
return config, nil return config, nil
@@ -107,7 +72,6 @@ type TrojanUserConfig struct {
Password string `json:"password"` Password string `json:"password"`
Level byte `json:"level"` Level byte `json:"level"`
Email string `json:"email"` Email string `json:"email"`
Flow string `json:"flow"`
} }
// TrojanServerConfig is Inbound configuration // TrojanServerConfig is Inbound configuration
@@ -131,9 +95,6 @@ func (c *TrojanServerConfig) Build() (proto.Message, error) {
processClient := func(idx int) error { processClient := func(idx int) error {
rawUser := c.Users[idx] rawUser := c.Users[idx]
if rawUser.Flow != "" {
return errors.PrintRemovedFeatureError(`Flow for Trojan`, ``)
}
config.Users[idx] = &protocol.User{ config.Users[idx] = &protocol.User{
Level: uint32(rawUser.Level), Level: uint32(rawUser.Level),
+9
View File
@@ -7,6 +7,7 @@ import (
"net" "net"
"runtime" "runtime"
"strconv" "strconv"
"strings"
"github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/proxy/tun" "github.com/xtls/xray-core/proxy/tun"
@@ -16,6 +17,7 @@ import (
type TunConfig struct { type TunConfig struct {
Name string `json:"name"` Name string `json:"name"`
Desc string `json:"desc"` Desc string `json:"desc"`
GUID string `json:"guid"`
MTU uint32 `json:"mtu"` MTU uint32 `json:"mtu"`
Gateway []string `json:"gateway"` Gateway []string `json:"gateway"`
DNS []string `json:"dns"` DNS []string `json:"dns"`
@@ -37,6 +39,13 @@ func (v *TunConfig) Build() (proto.Message, error) {
AutoSystemRoutingTable: v.AutoSystemRoutingTable, AutoSystemRoutingTable: v.AutoSystemRoutingTable,
AutoSystemDnsToGateway: v.AutoSystemDnsToGateway, AutoSystemDnsToGateway: v.AutoSystemDnsToGateway,
} }
if v.GUID != "" {
// only Windows gives the TUN a GUID, but a config is checked wherever it is loaded
if _, err := tun.ParseGUID(v.GUID); err != nil {
return nil, err
}
config.GUID = strings.ToLower(v.GUID)
}
leaks, err := tun.ExpandWfpBlockLeak(v.AutoSystemWfpBlockLeak) leaks, err := tun.ExpandWfpBlockLeak(v.AutoSystemWfpBlockLeak)
if err != nil { if err != nil {
return nil, err return nil, err
+46
View File
@@ -124,3 +124,49 @@ func TestTunConfigAutoSystemWfpBlockLeakUnknown(t *testing.T) {
} }
} }
} }
// TestTunConfigGUID checks that a guid is read, written back in the canonical
// form, and rejected unless it is one, on every system, even though only
// Windows gives the TUN a GUID.
func TestTunConfigGUID(t *testing.T) {
build := func(guid string) (*tun.Config, error) {
config := new(TunConfig)
if err := json.Unmarshal([]byte(`{"name": "xray0", "guid": "`+guid+`"}`), config); err != nil {
t.Fatal(err)
}
message, err := config.Build()
if err != nil {
return nil, err
}
return message.(*tun.Config), nil
}
if config, err := build("6ba7b810-9dad-11d1-80b4-00c04fd430c8"); err != nil {
t.Fatal(err)
} else if config.GUID != "6ba7b810-9dad-11d1-80b4-00c04fd430c8" {
t.Errorf("guid = %q, want it kept", config.GUID)
}
if config, err := build("6BA7B810-9DAD-11D1-80B4-00C04FD430C8"); err != nil {
t.Fatal(err)
} else if config.GUID != "6ba7b810-9dad-11d1-80b4-00c04fd430c8" {
t.Errorf("guid = %q, want it lowercased", config.GUID)
}
if config, err := build(""); err != nil {
t.Fatal(err)
} else if config.GUID != "" {
t.Errorf("guid = %q, want it empty, as the adapter GUID is derived from the name then", config.GUID)
}
for _, guid := range []string{
"xray0",
"6ba7b810-9dad-11d1-80b4-00c04fd430c",
"6ba7b8109-dad-11d1-80b4-00c04fd430c8", // the right length, a hyphen out of place
"6ba7b8109dad11d180b400c04fd430c8",
"{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
"urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8",
"6ba7b810-9dad-11d1-80b4-00c04fd430cg",
} {
if _, err := build(guid); err == nil {
t.Errorf("guid %q was accepted", guid)
}
}
}
+119 -138
View File
@@ -17,6 +17,7 @@ import (
"github.com/xtls/xray-core/common/uuid" "github.com/xtls/xray-core/common/uuid"
"github.com/xtls/xray-core/proxy/vless" "github.com/xtls/xray-core/proxy/vless"
"github.com/xtls/xray-core/proxy/vless/inbound" "github.com/xtls/xray-core/proxy/vless/inbound"
"github.com/xtls/xray-core/proxy/vless/multiplex"
"github.com/xtls/xray-core/proxy/vless/outbound" "github.com/xtls/xray-core/proxy/vless/outbound"
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
) )
@@ -236,154 +237,134 @@ func (c *VLessReverseConfig) Build() (*vless.Reverse, error) {
return r, nil return r, nil
} }
type VLessOutboundVnext struct { type MultiplexConfig struct {
Address *Address `json:"address"` Concurrency int16 `json:"concurrency"`
Port uint16 `json:"port"` XudpConcurrency int16 `json:"xudpConcurrency"`
Users []json.RawMessage `json:"users"` XudpProxyUDP443 string `json:"xudpProxyUDP443"`
}
func (c *MultiplexConfig) Build() (*vless.Multiplex, error) {
if c == nil {
return nil, nil
}
udp443 := c.XudpProxyUDP443
if udp443 == "" {
udp443 = "reject"
}
return multiplex.NormalizeConfig(&vless.Multiplex{
Concurrency: int32(c.Concurrency), XudpConcurrency: int32(c.XudpConcurrency), XudpProxyUDP443: udp443,
})
} }
type VLessOutboundConfig struct { type VLessOutboundConfig struct {
Address *Address `json:"address"` Address *Address `json:"address"`
Port uint16 `json:"port"` Port uint16 `json:"port"`
Level uint32 `json:"level"` Level uint32 `json:"level"`
Email string `json:"email"` Email string `json:"email"`
Id string `json:"id"` Id string `json:"id"`
Flow string `json:"flow"` Flow string `json:"flow"`
Seed string `json:"seed"` Seed string `json:"seed"`
Encryption string `json:"encryption"` Encryption string `json:"encryption"`
Reverse *VLessReverseConfig `json:"reverse"` Multiplex *MultiplexConfig `json:"multiplex"`
Testpre uint32 `json:"testpre"` Reverse *VLessReverseConfig `json:"reverse"`
Testseed []uint32 `json:"testseed"` Testpre uint32 `json:"testpre"`
Vnext []*VLessOutboundVnext `json:"vnext"` Testseed []uint32 `json:"testseed"`
} }
// Build implements Buildable // Build implements Buildable
func (c *VLessOutboundConfig) Build() (proto.Message, error) { func (c *VLessOutboundConfig) Build() (proto.Message, error) {
config := new(outbound.Config) multiplex, err := c.Multiplex.Build()
if c.Address != nil { if err != nil {
c.Vnext = []*VLessOutboundVnext{ return nil, err
{
Address: c.Address,
Port: c.Port,
Users: []json.RawMessage{{}},
},
}
} }
if len(c.Vnext) != 1 { config := &outbound.Config{Multiplex: multiplex}
return nil, errors.New(`VLESS settings: "vnext" should have one and only one member. Multiple endpoints in "vnext" should use multiple VLESS outbounds and routing balancer instead`)
if c.Address == nil {
return nil, errors.New(`VLESS: "address" is not set`)
} }
for _, rec := range c.Vnext { uid, err := uuid.ParseString(c.Id)
if rec.Address == nil { if err != nil {
return nil, errors.New(`VLESS vnext: "address" is not set`) return nil, err
}
if len(rec.Users) != 1 {
return nil, errors.New(`VLESS vnext: "users" should have one and only one member. Multiple members in "users" should use multiple VLESS outbounds and routing balancer instead`)
}
spec := &protocol.ServerEndpoint{
Address: rec.Address.Build(),
Port: uint32(rec.Port),
}
for _, rawUser := range rec.Users {
user := new(protocol.User)
if c.Address != nil {
user.Level = c.Level
user.Email = c.Email
} else {
if err := json.Unmarshal(rawUser, user); err != nil {
return nil, errors.New(`VLESS users: invalid user`).Base(err)
}
}
account := new(vless.Account)
if c.Address != nil {
account.Id = c.Id
account.Flow = c.Flow
//account.Seed = c.Seed
account.Encryption = c.Encryption
if c.Reverse != nil {
rvs, err := c.Reverse.Build()
if err != nil {
return nil, err
}
account.Reverse = rvs
}
account.Testpre = c.Testpre
account.Testseed = c.Testseed
} else {
if err := json.Unmarshal(rawUser, account); err != nil {
return nil, errors.New(`VLESS users: invalid user`).Base(err)
}
// validateOutboundTransportSecurity needs to see these
c.Encryption = account.Encryption
c.Address = rec.Address
if account.Reverse != nil { // may not be reached: error json unmarshal
return nil, errors.New(`VLESS users: please use simplified outbound's config style to use "reverse"`)
}
}
u, err := uuid.ParseString(account.Id)
if err != nil {
return nil, err
}
account.Id = u.String()
switch account.Flow {
case "":
case vless.XRV, vless.XRV + "-udp443":
default:
return nil, errors.New(`VLESS users: "flow" doesn't support "` + account.Flow + `" in this version`)
}
if !func() bool {
s := strings.Split(account.Encryption, ".")
if len(s) < 4 || s[0] != "mlkem768x25519plus" {
return false
}
switch s[1] {
case "native":
case "xorpub":
account.XorMode = 1
case "random":
account.XorMode = 2
default:
return false
}
switch s[2] {
case "1rtt":
case "0rtt":
account.Seconds = 1
default:
return false
}
padding := 0
for _, r := range s[3:] {
if len(r) < 20 {
padding += len(r) + 1
continue
}
if b, _ := base64.RawURLEncoding.DecodeString(r); len(b) != 32 && len(b) != 1184 {
return false
}
}
account.Encryption = account.Encryption[27+len(s[2]):]
if padding > 0 {
account.Padding = account.Encryption[:padding-1]
account.Encryption = account.Encryption[padding:]
}
return true
}() && account.Encryption != "none" {
if account.Encryption == "" {
return nil, errors.New(`VLESS users: please add/set "encryption":"none" for every user`)
}
return nil, errors.New(`VLESS users: unsupported "encryption": ` + account.Encryption)
}
user.Account = serial.ToTypedMessage(account)
spec.User = user
break
}
config.Vnext = spec
break
} }
switch c.Flow {
case "":
case vless.XRV, vless.XRV + "-udp443":
default:
return nil, errors.New(`VLESS users: "flow" doesn't support "` + c.Flow + `" in this version`)
}
spec := &protocol.ServerEndpoint{
Address: c.Address.Build(),
Port: uint32(c.Port),
}
user := &protocol.User{
Level: c.Level,
Email: c.Email,
}
account := &vless.Account{
Id: uid.String(),
Flow: c.Flow,
// Seed: c.Seed,
Encryption: c.Encryption,
Testpre: c.Testpre,
Testseed: c.Testseed,
}
if c.Reverse != nil {
rvs, err := c.Reverse.Build()
if err != nil {
return nil, err
}
account.Reverse = rvs
}
if !func() bool {
s := strings.Split(account.Encryption, ".")
if len(s) < 4 || s[0] != "mlkem768x25519plus" {
return false
}
switch s[1] {
case "native":
case "xorpub":
account.XorMode = 1
case "random":
account.XorMode = 2
default:
return false
}
switch s[2] {
case "1rtt":
case "0rtt":
account.Seconds = 1
default:
return false
}
padding := 0
for _, r := range s[3:] {
if len(r) < 20 {
padding += len(r) + 1
continue
}
if b, _ := base64.RawURLEncoding.DecodeString(r); len(b) != 32 && len(b) != 1184 {
return false
}
}
account.Encryption = account.Encryption[27+len(s[2]):]
if padding > 0 {
account.Padding = account.Encryption[:padding-1]
account.Encryption = account.Encryption[padding:]
}
return true
}() && account.Encryption != "none" {
if account.Encryption == "" {
return nil, errors.New(`VLESS users: please add/set "encryption":"none" for every user`)
}
return nil, errors.New(`VLESS users: unsupported "encryption": ` + account.Encryption)
}
user.Account = serial.ToTypedMessage(account)
spec.User = user
config.Vnext = spec
return config, nil return config, nil
} }
-35
View File
@@ -18,41 +18,6 @@ func TestVLessOutbound(t *testing.T) {
} }
runMultiTestCase(t, []TestCase{ runMultiTestCase(t, []TestCase{
{
Input: `{
"vnext": [{
"address": "example.com",
"port": 443,
"users": [
{
"id": "27848739-7e62-4138-9fd3-098a63964b6b",
"flow": "xtls-rprx-vision-udp443",
"encryption": "none",
"level": 0
}
]
}]
}`,
Parser: loadJSON(creator),
Output: &outbound.Config{
Vnext: &protocol.ServerEndpoint{
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Domain{
Domain: "example.com",
},
},
Port: 443,
User: &protocol.User{
Account: serial.ToTypedMessage(&vless.Account{
Id: "27848739-7e62-4138-9fd3-098a63964b6b",
Flow: "xtls-rprx-vision-udp443",
Encryption: "none",
}),
Level: 0,
},
},
},
},
{ {
Input: `{ Input: `{
"address": "example.com", "address": "example.com",
+35 -69
View File
@@ -102,84 +102,50 @@ func (c *VMessInboundConfig) Build() (proto.Message, error) {
return config, nil return config, nil
} }
type VMessOutboundTarget struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Users []json.RawMessage `json:"users"`
}
type VMessOutboundConfig struct { type VMessOutboundConfig struct {
Address *Address `json:"address"` Address *Address `json:"address"`
Port uint16 `json:"port"` Port uint16 `json:"port"`
Level uint32 `json:"level"` Level uint32 `json:"level"`
Email string `json:"email"` Email string `json:"email"`
ID string `json:"id"` ID string `json:"id"`
Security string `json:"security"` Security string `json:"security"`
Experiments string `json:"experiments"` Experiments string `json:"experiments"`
Receivers []*VMessOutboundTarget `json:"vnext"` Multiplex *MultiplexConfig `json:"multiplex"`
} }
// Build implements Buildable // Build implements Buildable
func (c *VMessOutboundConfig) Build() (proto.Message, error) { func (c *VMessOutboundConfig) Build() (proto.Message, error) {
errors.PrintNonRemovalDeprecatedFeatureWarning("VMess (with no Forward Secrecy, etc.)", "VLESS Encryption") errors.PrintNonRemovalDeprecatedFeatureWarning("VMess (with no Forward Secrecy, etc.)", "VLESS Encryption")
config := new(outbound.Config) multiplex, err := c.Multiplex.Build()
if c.Address != nil { if err != nil {
c.Receivers = []*VMessOutboundTarget{ return nil, err
{
Address: c.Address,
Port: c.Port,
Users: []json.RawMessage{{}},
},
}
} }
if len(c.Receivers) != 1 { config := &outbound.Config{Multiplex: multiplex}
return nil, errors.New(`VMess settings: "vnext" should have one and only one member. Multiple endpoints in "vnext" should use multiple VMess outbounds and routing balancer instead`)
}
for _, rec := range c.Receivers {
if len(rec.Users) != 1 {
return nil, errors.New(`VMess vnext: "users" should have one and only one member. Multiple members in "users" should use multiple VMess outbounds and routing balancer instead`)
}
if rec.Address == nil {
return nil, errors.New(`VMess vnext: "address" is not set`)
}
spec := &protocol.ServerEndpoint{
Address: rec.Address.Build(),
Port: uint32(rec.Port),
}
for _, rawUser := range rec.Users {
user := new(protocol.User)
if c.Address != nil {
user.Level = c.Level
user.Email = c.Email
} else {
if err := json.Unmarshal(rawUser, user); err != nil {
return nil, errors.New("invalid VMess user").Base(err)
}
}
account := new(VMessAccount)
if c.Address != nil {
account.ID = c.ID
account.Security = c.Security
account.Experiments = c.Experiments
} else {
if err := json.Unmarshal(rawUser, account); err != nil {
return nil, errors.New("invalid VMess user").Base(err)
}
}
u, err := uuid.ParseString(account.ID) if c.Address == nil {
if err != nil { return nil, errors.New(`VMess: "address" is not set`)
return nil, err
}
account.ID = u.String()
user.Account = serial.ToTypedMessage(account.Build())
spec.User = user
break
}
config.Receiver = spec
break
} }
uid, err := uuid.ParseString(c.ID)
if err != nil {
return nil, err
}
account := &VMessAccount{
ID: uid.String(),
Security: c.Security,
Experiments: c.Experiments,
}
spec := &protocol.ServerEndpoint{
Address: c.Address.Build(),
Port: uint32(c.Port),
User: &protocol.User{
Level: c.Level,
Email: c.Email,
Account: serial.ToTypedMessage(account.Build()),
},
}
config.Receiver = spec
return config, nil return config, nil
} }
-36
View File
@@ -18,42 +18,6 @@ func TestVMessOutbound(t *testing.T) {
} }
runMultiTestCase(t, []TestCase{ runMultiTestCase(t, []TestCase{
{
Input: `{
"vnext": [{
"address": "127.0.0.1",
"port": 80,
"users": [
{
"id": "e641f5ad-9397-41e3-bf1a-e8740dfed019",
"email": "love@example.com",
"level": 255
}
]
}]
}`,
Parser: loadJSON(creator),
Output: &outbound.Config{
Receiver: &protocol.ServerEndpoint{
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: 80,
User: &protocol.User{
Email: "love@example.com",
Level: 255,
Account: serial.ToTypedMessage(&vmess.Account{
Id: "e641f5ad-9397-41e3-bf1a-e8740dfed019",
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AUTO,
},
}),
},
},
},
},
{ {
Input: `{ Input: `{
"address": "127.0.0.1", "address": "127.0.0.1",
+24 -47
View File
@@ -107,30 +107,6 @@ func (c *SniffingConfig) Build() (*proxyman.SniffingConfig, error) {
}, nil }, nil
} }
type MuxConfig struct {
Enabled bool `json:"enabled"`
Concurrency int16 `json:"concurrency"`
XudpConcurrency int16 `json:"xudpConcurrency"`
XudpProxyUDP443 string `json:"xudpProxyUDP443"`
}
// Build creates MultiplexingConfig, Concurrency < 0 completely disables mux.
func (m *MuxConfig) Build() (*proxyman.MultiplexingConfig, error) {
switch m.XudpProxyUDP443 {
case "":
m.XudpProxyUDP443 = "reject"
case "reject", "allow", "skip":
default:
return nil, errors.New(`unknown "xudpProxyUDP443": `, m.XudpProxyUDP443)
}
return &proxyman.MultiplexingConfig{
Enabled: m.Enabled,
Concurrency: int32(m.Concurrency),
XudpConcurrency: int32(m.XudpConcurrency),
XudpProxyUDP443: m.XudpProxyUDP443,
}, nil
}
type InboundDetourConfig struct { type InboundDetourConfig struct {
Protocol string `json:"protocol"` Protocol string `json:"protocol"`
PortList *PortList `json:"port"` PortList *PortList `json:"port"`
@@ -213,7 +189,7 @@ func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
if _, ok := ts.(*masque.ServerConfig); !ok && receiverSettings.StreamSettings != nil && receiverSettings.StreamSettings.ProtocolName == "masque" { if _, ok := ts.(*masque.ServerConfig); !ok && receiverSettings.StreamSettings != nil && receiverSettings.StreamSettings.ProtocolName == "masque" {
return nil, errors.New("the masque transport can only be used by the masque inbound") return nil, errors.New("the masque transport can only be used by the masque inbound")
} }
if err := validateXDrive(ts, receiverSettings.StreamSettings, nil, receiverSettings.PortList); err != nil { if err := validateXDrive(ts, receiverSettings.StreamSettings, receiverSettings.PortList); err != nil {
return nil, err return nil, err
} }
@@ -231,7 +207,7 @@ type OutboundDetourConfig struct {
Settings *json.RawMessage `json:"settings"` Settings *json.RawMessage `json:"settings"`
StreamSetting *StreamConfig `json:"streamSettings"` StreamSetting *StreamConfig `json:"streamSettings"`
ProxySettings *json.RawMessage `json:"proxySettings"` ProxySettings *json.RawMessage `json:"proxySettings"`
MuxSettings *MuxConfig `json:"mux"` LegacyMux json.RawMessage `json:"mux,omitempty"`
TargetStrategy string `json:"targetStrategy"` TargetStrategy string `json:"targetStrategy"`
} }
@@ -262,7 +238,7 @@ func validateOutboundTransportSecurity(rawConfig interface{}, senderSettings *pr
} }
if tjCfg, ok := rawConfig.(*TrojanClientConfig); ok { if tjCfg, ok := rawConfig.(*TrojanClientConfig); ok {
if requiresTransportSecurity(tjCfg.Servers[0].Address) { if requiresTransportSecurity(tjCfg.Address) {
return errors.New("trojan without TLS is prohibited unless the server address is a private IP or domain") return errors.New("trojan without TLS is prohibited unless the server address is a private IP or domain")
} }
} }
@@ -270,8 +246,8 @@ func validateOutboundTransportSecurity(rawConfig interface{}, senderSettings *pr
return nil return nil
} }
// validateXDrive allows only VLESS with encryption on xdrive, and on the client Mux.Cool for every connection // validateXDrive allows only encrypted VLESS on xdrive, with native multiplex on every client connection.
func validateXDrive(ts proto.Message, ss *internet.StreamConfig, ms *proxyman.MultiplexingConfig, pl *net.PortList) error { func validateXDrive(ts proto.Message, ss *internet.StreamConfig, pl *net.PortList) error {
if ss == nil || ss.ProtocolName != "xdrive" { if ss == nil || ss.ProtocolName != "xdrive" {
return nil return nil
} }
@@ -288,9 +264,14 @@ func validateXDrive(ts proto.Message, ss *internet.StreamConfig, ms *proxyman.Mu
if account.Encryption == "none" { if account.Encryption == "none" {
return errors.New(`the xdrive transport needs VLESS "encryption", run "xray vlessenc" to get one`) return errors.New(`the xdrive transport needs VLESS "encryption", run "xray vlessenc" to get one`)
} }
// reverse opens its own mux // Reverse opens its own multiplexed connection.
if account.Reverse == nil && (ms == nil || !ms.Enabled || ms.Concurrency < 0 || ms.XudpConcurrency < 0 || ms.XudpProxyUDP443 == "skip") { if account.Reverse == nil {
return errors.New(`the xdrive transport needs "mux" enabled, with no negative "concurrency" or "xudpConcurrency" and no "xudpProxyUDP443":"skip"`) if c.Multiplex == nil {
c.Multiplex = &vless.Multiplex{Concurrency: 128}
}
if c.Multiplex.XudpProxyUDP443 == "skip" {
return errors.New(`the xdrive transport does not support "xudpProxyUDP443":"skip"`)
}
} }
if account.Testpre != 0 { if account.Testpre != 0 {
return errors.New(`the xdrive transport doesn't support VLESS "testpre"`) return errors.New(`the xdrive transport doesn't support VLESS "testpre"`)
@@ -376,14 +357,6 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
senderSettings.StreamSettings = ss senderSettings.StreamSettings = ss
} }
if c.MuxSettings != nil {
ms, err := c.MuxSettings.Build()
if err != nil {
return nil, errors.New("failed to build Mux config").Base(err)
}
senderSettings.MultiplexSettings = ms
}
settings := []byte("{}") settings := []byte("{}")
if c.Settings != nil { if c.Settings != nil {
settings = ([]byte)(*c.Settings) settings = ([]byte)(*c.Settings)
@@ -392,11 +365,20 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
if err != nil { if err != nil {
return nil, errors.New("failed to load outbound detour config for protocol ", c.Protocol).Base(err) return nil, errors.New("failed to load outbound detour config for protocol ", c.Protocol).Base(err)
} }
if c.LegacyMux != nil {
errors.LogWarning(context.Background(), `The legacy "mux" setting is ignored. To enable Multiplex for VLESS or VMess outbounds, use "settings.multiplex". If Multiplex is disabled, Xray will use ordinary outbound connections.`)
}
ts, err := rawConfig.(Buildable).Build() ts, err := rawConfig.(Buildable).Build()
if err != nil { if err != nil {
return nil, errors.New("failed to build outbound handler for protocol ", c.Protocol).Base(err) return nil, errors.New("failed to build outbound handler for protocol ", c.Protocol).Base(err)
} }
if err := validateXDrive(ts, senderSettings.StreamSettings, senderSettings.MultiplexSettings, nil); err != nil {
if senderSettings.StreamSettings != nil && senderSettings.StreamSettings.ProtocolName == "splithttp" {
if v, ok := ts.(*outbound.Config); ok && v.Multiplex != nil && v.Multiplex.Concurrency != 0 {
errors.LogWarning(context.Background(), `ATTENTION: Using VLESS Multiplex over XHTTP XMUX`)
}
}
if err := validateXDrive(ts, senderSettings.StreamSettings, nil); err != nil {
return nil, err return nil, err
} }
if err := validateOutboundTransportSecurity(rawConfig, senderSettings); err != nil { if err := validateOutboundTransportSecurity(rawConfig, senderSettings); err != nil {
@@ -478,7 +460,7 @@ type Config struct {
API *APIConfig `json:"api"` API *APIConfig `json:"api"`
Metrics *MetricsConfig `json:"metrics"` Metrics *MetricsConfig `json:"metrics"`
Stats *StatsConfig `json:"stats"` Stats *StatsConfig `json:"stats"`
Reverse *ReverseConfig `json:"reverse"` Reverse *json.RawMessage `json:"reverse"`
FakeDNS *FakeDNSConfig `json:"fakeDns"` FakeDNS *FakeDNSConfig `json:"fakeDns"`
Observatory *ObservatoryConfig `json:"observatory"` Observatory *ObservatoryConfig `json:"observatory"`
BurstObservatory *BurstObservatoryConfig `json:"burstObservatory"` BurstObservatory *BurstObservatoryConfig `json:"burstObservatory"`
@@ -680,11 +662,6 @@ func (c *Config) Build() (*core.Config, error) {
if c.Reverse != nil { if c.Reverse != nil {
return nil, errors.PrintRemovedFeatureError(`"legacy reverse"`, `"VLESS Reverse Proxy"`) return nil, errors.PrintRemovedFeatureError(`"legacy reverse"`, `"VLESS Reverse Proxy"`)
r, err := c.Reverse.Build()
if err != nil {
return nil, errors.New("failed to build reverse configuration").Base(err)
}
config.App = append(config.App, serial.ToTypedMessage(r))
} }
if c.FakeDNS != nil { if c.FakeDNS != nil {
+101 -37
View File
@@ -1,6 +1,7 @@
package conf_test package conf_test
import ( import (
"bytes"
"encoding/json" "encoding/json"
"reflect" "reflect"
"testing" "testing"
@@ -10,7 +11,6 @@ import (
"github.com/xtls/xray-core/app/log" "github.com/xtls/xray-core/app/log"
"github.com/xtls/xray-core/app/proxyman" "github.com/xtls/xray-core/app/proxyman"
"github.com/xtls/xray-core/app/router" "github.com/xtls/xray-core/app/router"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/geodata" "github.com/xtls/xray-core/common/geodata"
clog "github.com/xtls/xray-core/common/log" clog "github.com/xtls/xray-core/common/log"
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
@@ -18,6 +18,7 @@ import (
"github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/common/serial"
core "github.com/xtls/xray-core/core" core "github.com/xtls/xray-core/core"
. "github.com/xtls/xray-core/infra/conf" . "github.com/xtls/xray-core/infra/conf"
"github.com/xtls/xray-core/proxy/vless"
"github.com/xtls/xray-core/proxy/vmess" "github.com/xtls/xray-core/proxy/vmess"
"github.com/xtls/xray-core/proxy/vmess/inbound" "github.com/xtls/xray-core/proxy/vmess/inbound"
"github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet"
@@ -225,49 +226,112 @@ func TestSniffingConfig_Build(t *testing.T) {
} }
} }
func TestMuxConfig_Build(t *testing.T) { func TestMultiplexConfig_Build(t *testing.T) {
tests := []struct { for _, tc := range []struct {
name string name string
fields string fields string
want *proxyman.MultiplexingConfig want *vless.Multiplex
bad bool
}{ }{
{"default", `{"enabled": true, "concurrency": 16}`, &proxyman.MultiplexingConfig{ {name: "empty", fields: `{}`},
Enabled: true, {name: "both zero", fields: `{"concurrency":0,"xudpConcurrency":0}`},
Concurrency: 16, {name: "regular pool", fields: `{"concurrency":4}`, want: &vless.Multiplex{Concurrency: 4, XudpProxyUDP443: "reject"}},
XudpConcurrency: 0, {name: "XUDP only", fields: `{"xudpConcurrency":8}`, want: &vless.Multiplex{XudpConcurrency: 8, XudpProxyUDP443: "reject"}},
XudpProxyUDP443: "reject", {name: "negative concurrency", fields: `{"concurrency":-1,"xudpConcurrency":8}`, bad: true},
}}, {name: "negative XUDP concurrency", fields: `{"concurrency":4,"xudpConcurrency":-1}`, bad: true},
{"empty def", `{}`, &proxyman.MultiplexingConfig{ {name: "invalid UDP policy", fields: `{"concurrency":4,"xudpProxyUDP443":"invalid"}`, bad: true},
Enabled: false, } {
Concurrency: 0, t.Run(tc.name, func(t *testing.T) {
XudpConcurrency: 0, var config MultiplexConfig
XudpProxyUDP443: "reject", if err := json.Unmarshal([]byte(tc.fields), &config); err != nil {
}}, t.Fatal(err)
{"not enable", `{"enabled": false, "concurrency": 4}`, &proxyman.MultiplexingConfig{ }
Enabled: false, got, err := config.Build()
Concurrency: 4, if (err != nil) != tc.bad || !proto.Equal(got, tc.want) {
XudpConcurrency: 0, t.Fatalf("Build() = %v, %v, want config %v, error %t", got, err, tc.want, tc.bad)
XudpProxyUDP443: "reject",
}},
{"forbidden", `{"enabled": false, "concurrency": -1}`, &proxyman.MultiplexingConfig{
Enabled: false,
Concurrency: -1,
XudpConcurrency: 0,
XudpProxyUDP443: "reject",
}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
m := &MuxConfig{}
common.Must(json.Unmarshal([]byte(tt.fields), m))
if got, _ := m.Build(); !reflect.DeepEqual(got, tt.want) {
t.Errorf("MuxConfig.Build() = %v, want %v", got, tt.want)
} }
}) })
} }
} }
func TestOutboundMultiplexConfig(t *testing.T) {
tests := []struct {
name string
legacy string
native string
want *vless.Multiplex
}{
{name: "absent"},
{name: "legacy enabled", legacy: `{"enabled":true,"concurrency":16}`},
{name: "legacy disabled", legacy: `{"enabled":false}`},
{name: "legacy null", legacy: `null`},
{name: "legacy empty", legacy: `{}`},
{name: "legacy values are not decoded", legacy: `{"enabled":"ignored","concurrency":"ignored"}`},
{name: "empty native object", native: `{}`},
{name: "enabled flag alone does not create a pool", native: `{"enabled":true}`},
{
name: "positive concurrency with old enabled flag", native: `{"concurrency":4,"enabled":false}`,
want: &vless.Multiplex{Concurrency: 4, XudpProxyUDP443: "reject"},
},
{
name: "native XUDP only", native: `{"xudpConcurrency":8}`,
want: &vless.Multiplex{XudpConcurrency: 8, XudpProxyUDP443: "reject"},
},
{
name: "native options override legacy", legacy: `{"enabled":true,"concurrency":16}`,
native: `{"concurrency":4,"xudpConcurrency":8,"xudpProxyUDP443":"allow"}`,
want: &vless.Multiplex{Concurrency: 4, XudpConcurrency: 8, XudpProxyUDP443: "allow"},
},
{name: "empty native with legacy enabled", legacy: `{"enabled":true}`, native: `{}`},
}
for _, protoName := range []string{"vless", "vmess"} {
for _, tc := range tests {
t.Run(protoName+"/"+tc.name, func(t *testing.T) {
settings := `"address":"127.0.0.1","port":443,"id":"d19768cb-2891-4c3c-b45d-863f8fd64b6d"`
if protoName == "vless" {
settings += `,"encryption":"none"`
}
if tc.native != "" {
settings += `,"multiplex":` + tc.native
}
input := `{"protocol":"` + protoName + `","settings":{` + settings + `}`
if tc.legacy != "" {
input += `,"mux":` + tc.legacy
}
var config OutboundDetourConfig
if err := json.Unmarshal([]byte(input+"}"), &config); err != nil {
t.Fatal(err)
}
if got := string(config.LegacyMux); got != tc.legacy {
t.Errorf("legacy mux marker = %q, want %q", got, tc.legacy)
}
serialized, err := json.Marshal(config)
if err != nil {
t.Fatal(err)
}
if hasMux := bytes.Contains(serialized, []byte(`"mux":`)); hasMux != (tc.legacy != "") {
t.Errorf("serialized config changed legacy mux presence: %s", serialized)
}
built, err := config.Build()
if err != nil {
t.Fatal(err)
}
proxyConfig, err := built.ProxySettings.GetInstance()
if err != nil {
t.Fatal(err)
}
got := proxyConfig.(interface{ GetMultiplex() *vless.Multiplex }).GetMultiplex()
if !proto.Equal(got, tc.want) {
t.Errorf("multiplex = %v, want %v", got, tc.want)
}
})
}
}
}
func TestConfig_Override(t *testing.T) { func TestConfig_Override(t *testing.T) {
legacyReverse := json.RawMessage(`{}`)
tests := []struct { tests := []struct {
name string name string
orig *Config orig *Config
@@ -285,7 +349,7 @@ func TestConfig_Override(t *testing.T) {
Policy: &PolicyConfig{}, Policy: &PolicyConfig{},
API: &APIConfig{}, API: &APIConfig{},
Stats: &StatsConfig{}, Stats: &StatsConfig{},
Reverse: &ReverseConfig{}, Reverse: &legacyReverse,
}, },
"", "",
&Config{ &Config{
@@ -295,7 +359,7 @@ func TestConfig_Override(t *testing.T) {
Policy: &PolicyConfig{}, Policy: &PolicyConfig{},
API: &APIConfig{}, API: &APIConfig{},
Stats: &StatsConfig{}, Stats: &StatsConfig{},
Reverse: &ReverseConfig{}, Reverse: &legacyReverse,
}, },
}, },
{ {
-1
View File
@@ -24,7 +24,6 @@ import (
_ "github.com/xtls/xray-core/app/log" _ "github.com/xtls/xray-core/app/log"
_ "github.com/xtls/xray-core/app/metrics" _ "github.com/xtls/xray-core/app/metrics"
_ "github.com/xtls/xray-core/app/policy" _ "github.com/xtls/xray-core/app/policy"
_ "github.com/xtls/xray-core/app/reverse"
_ "github.com/xtls/xray-core/app/router" _ "github.com/xtls/xray-core/app/router"
_ "github.com/xtls/xray-core/app/stats" _ "github.com/xtls/xray-core/app/stats"
+24
View File
@@ -0,0 +1,24 @@
package proxy
import (
"context"
"math/rand/v2"
"time"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/signal"
)
// wait to drain all the possible incoming UDP data
// because re-established QUIC UDP may bypass the sniffer
func DropUDP(ctx context.Context, reader buf.Reader) {
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, func() {
cancel()
}, time.Duration(30+rand.N(60))*time.Second)
context.AfterFunc(ctx, func() {
common.Interrupt(reader)
})
buf.Copy(reader, buf.Discard, buf.UpdateActivity(timer))
}
+5
View File
@@ -318,6 +318,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
} }
ob.Name = "freedom" ob.Name = "freedom"
ob.CanSpliceCopy = 1 ob.CanSpliceCopy = 1
if !h.usesDialerProxy && len(h.firewall) > 0 { if !h.usesDialerProxy && len(h.firewall) > 0 {
rule := h.firewall[0] rule := h.firewall[0]
if rule.action == RuleAction_Block && rule.network == allNetworks && len(rule.port) == 0 && rule.ip == nil { if rule.action == RuleAction_Block && rule.network == allNetworks && len(rule.port) == 0 && rule.ip == nil {
@@ -350,6 +351,10 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
} }
} }
if h.resolveStrategy.HasStrategy() && session.SkipDNSResolveFromContext(ctx) {
errors.LogInfo(ctx, "DNS-origin connection to ", destination, " may recursively resolve with sockopt.domainStrategy ", h.resolveStrategy)
}
input := link.Reader input := link.Reader
output := link.Writer output := link.Writer
+39 -14
View File
@@ -5,6 +5,7 @@ import (
go_errors "errors" go_errors "errors"
"io" "io"
"math/rand" "math/rand"
"slices"
"github.com/apernet/quic-go" "github.com/apernet/quic-go"
"github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common"
@@ -174,10 +175,15 @@ func init() {
})) }))
} }
// UDPWriter is not safe for concurrent writes.
type UDPWriter struct { type UDPWriter struct {
writer io.Writer writer io.Writer
addr string addr string
buf [buf.Size]byte buf [buf.Size]byte
// Last b.UDP and its NetAddr, which allocates on every call.
lastUDP net.Destination
lastUDPAddr string
} }
func (w *UDPWriter) SendMessage(msg *UDPMessage) error { func (w *UDPWriter) SendMessage(msg *UDPMessage) error {
@@ -193,21 +199,21 @@ func (w *UDPWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
for i, b := range mb { for i, b := range mb {
addr := w.addr addr := w.addr
if b.UDP != nil { if b.UDP != nil {
addr = b.UDP.NetAddr() if *b.UDP != w.lastUDP {
w.lastUDP = *b.UDP
w.lastUDPAddr = b.UDP.NetAddr()
}
addr = w.lastUDPAddr
} }
msg := &UDPMessage{ msg := &UDPMessage{
SessionID: 0,
PacketID: 0,
FragID: 0,
FragCount: 1, FragCount: 1,
Addr: addr, Addr: addr,
Data: b.Bytes(), Data: b.Bytes(),
} }
err := w.SendMessage(msg) err := w.SendMessage(msg)
var errTooLarge *quic.DatagramTooLargeError if errTooLarge, ok := go_errors.AsType[*quic.DatagramTooLargeError](err); ok {
if go_errors.As(err, &errTooLarge) {
msg.PacketID = uint16(rand.Intn(0xFFFF)) + 1 msg.PacketID = uint16(rand.Intn(0xFFFF)) + 1
fMsgs := FragUDPMessage(msg, int(errTooLarge.MaxDatagramPayloadSize)) fMsgs := FragUDPMessage(msg, int(errTooLarge.MaxDatagramPayloadSize))
for _, fMsg := range fMsgs { for _, fMsg := range fMsgs {
@@ -228,40 +234,59 @@ func (w *UDPWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
return nil return nil
} }
// UDPReader is not safe for concurrent reads.
type UDPReader struct { type UDPReader struct {
reader io.Reader reader io.Reader
df *Defragger df *Defragger
firstBuf *buf.Buffer firstBuf *buf.Buffer
// Last message address and its parsed destination.
lastAddr string
lastDest net.Destination
packet [1500]byte
msg UDPMessage
} }
func (r *UDPReader) ReadFrom(p []byte) (n int, addr *net.Destination, err error) { func (r *UDPReader) ReadFrom(p []byte) (n int, addr *net.Destination, err error) {
for { for {
var packet [1500]byte n, err := r.reader.Read(r.packet[:])
n, err := r.reader.Read(packet[:])
if err != nil { if err != nil {
return 0, nil, err return 0, nil, err
} }
msg, err := ParseUDPMessage(packet[:n]) if err := parseUDPMessage(r.packet[:n], r.lastAddr, &r.msg); err != nil {
if err != nil {
continue continue
} }
msg := &r.msg
if msg.FragCount > 1 {
// The defragger keeps fragments between calls, so they must not alias packet.
frag := *msg
frag.Data = slices.Clone(msg.Data)
msg = &frag
}
dfMsg := r.df.Feed(msg) dfMsg := r.df.Feed(msg)
if dfMsg == nil { if dfMsg == nil {
continue continue
} }
dest, err := net.ParseDestination("udp:" + dfMsg.Addr) if dfMsg.Addr != r.lastAddr {
if err != nil { dest, err := net.ParseDestination("udp:" + dfMsg.Addr)
continue if err != nil {
continue
}
r.lastAddr = dfMsg.Addr
r.lastDest = dest
} }
if len(p) < len(dfMsg.Data) { if len(p) < len(dfMsg.Data) {
continue continue
} }
// Callers can rewrite the packet destination in place.
dest := r.lastDest
return copy(p, dfMsg.Data), &dest, nil return copy(p, dfMsg.Data), &dest, nil
} }
} }
+147
View File
@@ -0,0 +1,147 @@
package hysteria
import (
"bytes"
"io"
"testing"
"github.com/apernet/quic-go"
"github.com/xtls/xray-core/common/buf"
xnet "github.com/xtls/xray-core/common/net"
)
// datagramReader returns one datagram per Read, like a QUIC datagram stream.
type datagramReader struct {
msgs [][]byte
}
func (r *datagramReader) Read(p []byte) (int, error) {
if len(r.msgs) == 0 {
return 0, io.EOF
}
n := copy(p, r.msgs[0])
r.msgs = r.msgs[1:]
return n, nil
}
func newTestReader(msgs []UDPMessage) *UDPReader {
datagrams := make([][]byte, len(msgs))
for i := range msgs {
datagrams[i] = make([]byte, msgs[i].Size())
msgs[i].Serialize(datagrams[i])
}
return &UDPReader{reader: &datagramReader{msgs: datagrams}, df: &Defragger{}}
}
func TestUDPReaderFragments(t *testing.T) {
want := &UDPMessage{PacketID: 1, Addr: "example.com:443", Data: bytes.Repeat([]byte("0123456789"), 20)}
frags := FragUDPMessage(want, 100)
if len(frags) < 2 {
t.Fatalf("got %d fragments, want at least 2", len(frags))
}
p := make([]byte, buf.Size)
n, dest, err := newTestReader(frags).ReadFrom(p)
if err != nil {
t.Fatal(err)
}
if dest.NetAddr() != want.Addr || !bytes.Equal(p[:n], want.Data) {
t.Errorf("got %q to %v, want %q to %s", p[:n], dest, want.Data, want.Addr)
}
}
func TestUDPReaderDestinations(t *testing.T) {
msgs := []UDPMessage{
{Addr: "203.0.113.1:53", Data: []byte("first")},
{Addr: "203.0.113.1:53", Data: []byte("second")},
{Addr: "203.0.113.2:53", Data: []byte("third")},
}
r := newTestReader(msgs)
p := make([]byte, buf.Size)
for i, want := range msgs {
n, dest, err := r.ReadFrom(p)
if err != nil {
t.Fatal(err)
}
if dest.NetAddr() != want.Addr || !bytes.Equal(p[:n], want.Data) {
t.Errorf("packet %d: got %q to %v, want %q to %s", i, p[:n], dest, want.Data, want.Addr)
}
// Callers rewrite the destination in place, the next packet must not see it.
dest.Port = 5353
}
}
type captureWriter struct {
writes [][]byte
}
func (w *captureWriter) Write(p []byte) (int, error) {
w.writes = append(w.writes, bytes.Clone(p))
return len(p), nil
}
func TestUDPWriterAddress(t *testing.T) {
ip := xnet.UDPDestination(xnet.ParseAddress("203.0.113.1"), 53)
domain := xnet.UDPDestination(xnet.DomainAddress("example.com"), 53)
cw := &captureWriter{}
w := &UDPWriter{writer: cw, addr: "198.51.100.1:1"}
for _, tc := range []struct {
udp *xnet.Destination
want string
}{
{&ip, "203.0.113.1:53"},
{&domain, "example.com:53"},
{nil, "198.51.100.1:1"},
{&ip, "203.0.113.1:53"},
} {
b := buf.FromBytes([]byte("data"))
b.UDP = tc.udp
if err := w.WriteMultiBuffer(buf.MultiBuffer{b}); err != nil {
t.Fatal(err)
}
msg, err := ParseUDPMessage(cw.writes[len(cw.writes)-1])
if err != nil {
t.Fatal(err)
}
if msg.Addr != tc.want {
t.Errorf("address = %q, want %q", msg.Addr, tc.want)
}
}
}
// fragmentingWriter rejects datagrams larger than max, like a QUIC connection.
type fragmentingWriter struct {
max int
writes [][]byte
}
func (w *fragmentingWriter) Write(p []byte) (int, error) {
if len(p) > w.max {
return 0, &quic.DatagramTooLargeError{MaxDatagramPayloadSize: int64(w.max)}
}
w.writes = append(w.writes, bytes.Clone(p))
return len(p), nil
}
func TestUDPWriterFragmentation(t *testing.T) {
data := bytes.Repeat([]byte("0123456789"), 20)
fw := &fragmentingWriter{max: 100}
w := &UDPWriter{writer: fw, addr: "example.com:443"}
if err := w.WriteMultiBuffer(buf.MultiBuffer{buf.FromBytes(data)}); err != nil {
t.Fatal(err)
}
if len(fw.writes) < 2 {
t.Fatalf("got %d datagrams, want at least 2", len(fw.writes))
}
r := &UDPReader{reader: &datagramReader{msgs: fw.writes}, df: &Defragger{}}
p := make([]byte, buf.Size)
n, dest, err := r.ReadFrom(p)
if err != nil {
t.Fatal(err)
}
if dest.NetAddr() != w.addr || !bytes.Equal(p[:n], data) {
t.Errorf("got %q to %v, want %q to %s", p[:n], dest, data, w.addr)
}
}
+28 -20
View File
@@ -1,7 +1,6 @@
package hysteria package hysteria
import ( import (
"bytes"
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"io" "io"
@@ -183,35 +182,44 @@ func (m *UDPMessage) Serialize(buf []byte) int {
} }
func ParseUDPMessage(msg []byte) (*UDPMessage, error) { func ParseUDPMessage(msg []byte) (*UDPMessage, error) {
m := &UDPMessage{} m := new(UDPMessage)
buf := bytes.NewBuffer(msg) if err := parseUDPMessage(msg, "", m); err != nil {
if err := binary.Read(buf, binary.BigEndian, &m.SessionID); err != nil {
return nil, err return nil, err
} }
if err := binary.Read(buf, binary.BigEndian, &m.PacketID); err != nil { return m, nil
return nil, err }
// parseUDPMessage parses msg into m. m.Data aliases msg; m.Addr is lastAddr
// when they are equal, so an unchanged address is not allocated again.
func parseUDPMessage(msg []byte, lastAddr string, m *UDPMessage) error {
if len(msg) < 8 {
return io.ErrUnexpectedEOF
} }
if err := binary.Read(buf, binary.BigEndian, &m.FragID); err != nil { lAddr, n, err := quicvarint.Parse(msg[8:])
return nil, err
}
if err := binary.Read(buf, binary.BigEndian, &m.FragCount); err != nil {
return nil, err
}
lAddr, err := quicvarint.Read(buf)
if err != nil { if err != nil {
return nil, err return err
} }
if lAddr == 0 || lAddr > MaxMessageLength { if lAddr == 0 || lAddr > MaxMessageLength {
return nil, errors.New("invalid address length") return errors.New("invalid address length")
} }
bs := buf.Bytes() bs := msg[8+n:]
if len(bs) <= int(lAddr) { if len(bs) <= int(lAddr) {
// We use <= instead of < here as we expect at least one byte of data after the address // We use <= instead of < here as we expect at least one byte of data after the address
return nil, errors.New("invalid message length") return errors.New("invalid message length")
} }
m.Addr = string(bs[:lAddr]) *m = UDPMessage{
m.Data = bs[lAddr:] SessionID: binary.BigEndian.Uint32(msg),
return m, nil PacketID: binary.BigEndian.Uint16(msg[4:]),
FragID: msg[6],
FragCount: msg[7],
Data: bs[lAddr:],
}
if string(bs[:lAddr]) == lastAddr {
m.Addr = lastAddr
} else {
m.Addr = string(bs[:lAddr])
}
return nil
} }
// varintPut is like quicvarint.Append, but instead of appending to a slice, // varintPut is like quicvarint.Append, but instead of appending to a slice,
+49
View File
@@ -0,0 +1,49 @@
package hysteria
import (
"bytes"
"reflect"
"testing"
)
func TestParseUDPMessage(t *testing.T) {
want := &UDPMessage{PacketID: 1, FragID: 2, FragCount: 3, Addr: "example.com:443", Data: []byte("hello")}
msg := make([]byte, want.Size())
want.Serialize(msg)
for _, lastAddr := range []string{"", want.Addr, "other:1"} {
got := new(UDPMessage)
if err := parseUDPMessage(msg, lastAddr, got); err != nil {
t.Fatalf("lastAddr %q: %v", lastAddr, err)
}
if !reflect.DeepEqual(got, want) {
t.Errorf("lastAddr %q: got %+v, want %+v", lastAddr, got, want)
}
}
}
func TestParseUDPMessageInvalid(t *testing.T) {
msg := &UDPMessage{Addr: "example.com:443", Data: []byte("hello")}
buf := make([]byte, msg.Size())
msg.Serialize(buf)
zeroAddrLen := bytes.Clone(buf)
zeroAddrLen[8] = 0 // Address length varint follows the 8-byte header
noData := &UDPMessage{Addr: msg.Addr}
noDataBuf := make([]byte, noData.Size())
noData.Serialize(noDataBuf)
for _, tc := range []struct {
name string
msg []byte
}{
{"short header", buf[:7]},
{"zero address length", zeroAddrLen},
{"no data after address", noDataBuf},
} {
if _, err := ParseUDPMessage(tc.msg); err == nil {
t.Errorf("%s: expected error", tc.name)
}
}
}
+1 -1
View File
@@ -30,7 +30,7 @@ func (l *Loopback) Process(ctx context.Context, link *transport.Link, _ internet
errors.LogInfo(ctx, "opening connection to ", destination) errors.LogInfo(ctx, "opening connection to ", destination)
content := new(session.Content) content := new(session.Content)
content.SkipDNSResolve = true content.SkipDNSResolve = session.SkipDNSResolveFromContext(ctx)
content.SniffingRequest = l.sniffingRequest content.SniffingRequest = l.sniffingRequest
ctx = session.ContextWithContent(ctx, content) ctx = session.ContextWithContent(ctx, content)
+12 -18
View File
@@ -53,21 +53,23 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Inbound, error) {
return nil, err return nil, err
} }
udpCodec, err := NewUDPServerCodec(method, psk, 500*time.Second) user := &protocol.MemoryUser{
Email: config.Email,
Level: uint32(config.Level),
}
udpCodec, err := NewUDPServerCodec(method, psk, user, 500*time.Second)
if err != nil { if err != nil {
return nil, err return nil, err
} }
v := core.MustFromContext(ctx) v := core.MustFromContext(ctx)
return &Inbound{ return &Inbound{
networks: networks, networks: networks,
method: method, method: method,
psk: psk, psk: psk,
saltFilter: antireplay.NewMapFilter[[32]byte](60), saltFilter: antireplay.NewMapFilter[[32]byte](60),
user: &protocol.MemoryUser{ user: user,
Email: config.Email,
Level: uint32(config.Level),
},
udpCodec: udpCodec, udpCodec: udpCodec,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
}, nil }, nil
@@ -155,20 +157,12 @@ func (i *Inbound) processUDP(ctx context.Context, conn stat.Connection, dispatch
} }
for _, b := range mb { for _, b := range mb {
decoded, err := i.udpCodec.DecodePacket(b.Bytes()) sessionItem, decoded, err := i.udpCodec.DecodePacket(b.Bytes())
b.Release() b.Release()
if err != nil || decoded.HeaderType != HeaderTypeClient { if err != nil || decoded.HeaderType != HeaderTypeClient {
continue continue
} }
sessionItem := i.udpCodec.GetSession(decoded.SessionID)
if sessionItem.User == nil {
sessionItem.Lock()
if sessionItem.User == nil {
sessionItem.User = i.user
}
sessionItem.Unlock()
}
link := sessionItem.link.Load() link := sessionItem.link.Load()
if link != nil { if link != nil {
sessionItem.UpdateConn(conn) sessionItem.UpdateConn(conn)
+26 -76
View File
@@ -2,8 +2,6 @@ package shadowsocks_2022
import ( import (
"context" "context"
"crypto/cipher"
"encoding/binary"
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
@@ -34,16 +32,15 @@ func init() {
type MultiUserInbound struct { type MultiUserInbound struct {
sync.Mutex sync.Mutex
networks []net.Network networks []net.Network
method *CipherMethod method *CipherMethod
masterPSK []byte masterPSK []byte
usersByHash *utils.TypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser] usersByHash *utils.TypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser]
usersByEmail *utils.TypedSyncMap[string, *protocol.MemoryUser] usersByEmail *utils.TypedSyncMap[string, *protocol.MemoryUser]
userCount atomic.Int64 userCount atomic.Int64
saltFilter *antireplay.ReplayFilter[[32]byte] saltFilter *antireplay.ReplayFilter[[32]byte]
udpSessions *UDPSessionManager udpCodec *UDPMultiServerCodec
udpMasterCipher cipher.Block policyManager policy.Manager
policyManager policy.Manager
} }
func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiUserInbound, error) { func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiUserInbound, error) {
@@ -68,22 +65,21 @@ func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiU
return nil, err return nil, err
} }
masterBlock, err := method.NewBlock(masterPSK) udpCodec, err := NewUDPMultiServerCodec(method, masterPSK, 500*time.Second)
if err != nil { if err != nil {
return nil, err return nil, err
} }
v := core.MustFromContext(ctx) v := core.MustFromContext(ctx)
i := &MultiUserInbound{ i := &MultiUserInbound{
networks: networks, networks: networks,
method: method, method: method,
masterPSK: masterPSK, masterPSK: masterPSK,
usersByHash: utils.NewTypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser](), usersByHash: utils.NewTypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser](),
usersByEmail: utils.NewTypedSyncMap[string, *protocol.MemoryUser](), usersByEmail: utils.NewTypedSyncMap[string, *protocol.MemoryUser](),
saltFilter: antireplay.NewMapFilter[[32]byte](60), saltFilter: antireplay.NewMapFilter[[32]byte](60),
udpSessions: NewUDPSessionManager(500 * time.Second), udpCodec: udpCodec,
udpMasterCipher: masterBlock, policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
} }
for idx, user := range config.Users { for idx, user := range config.Users {
@@ -281,68 +277,26 @@ func (i *MultiUserInbound) processUDP(ctx context.Context, conn stat.Connection,
} }
for _, b := range mb { for _, b := range mb {
// In multi-user UDP: sessionItem, decoded, user, err := i.udpCodec.DecodePacket(b.Bytes(), func(hash [AESBlockSize]byte) (*protocol.MemoryUser, []byte, bool) {
// Packet header is 16 bytes: Encrypted(SessionID + PacketID) u, ok := i.usersByHash.Load(hash)
// Followed by 16 bytes EIH
packetBytes := b.Bytes()
if len(packetBytes) < 32+1+8+2 {
b.Release()
continue
}
var rawHeader [16]byte
i.udpMasterCipher.Decrypt(rawHeader[:], packetBytes[:16])
sessionID := binary.BigEndian.Uint64(rawHeader[:8])
packetID := binary.BigEndian.Uint64(rawHeader[8:16])
sessionItem := i.udpSessions.GetOrCreate(sessionID)
if !sessionItem.CheckPacketID(packetID) {
b.Release()
continue
}
var userPSK []byte
var currentUser *protocol.MemoryUser
sessionItem.Lock()
currentUser = sessionItem.User
userPSK = sessionItem.UserPSK
sessionItem.Unlock()
if currentUser == nil {
// Decrypt EIH
decryptedHash := DecryptUDPEIH(i.udpMasterCipher, rawHeader[:], packetBytes[16:32])
user, ok := i.usersByHash.Load(decryptedHash)
if !ok { if !ok {
b.Release() return nil, nil, false
continue
} }
currentUser = user return u, u.Account.(*MemoryAccount).Key, true
userPSK = user.Account.(*MemoryAccount).Key })
}
decoded, err := sessionItem.DecryptAESPayload(i.method, userPSK, sessionID, packetID, rawHeader[:], packetBytes[32:])
b.Release() b.Release()
if err != nil { if err != nil || decoded.HeaderType != HeaderTypeClient {
continue continue
} }
sessionItem.Lock()
if sessionItem.User == nil {
sessionItem.User = currentUser
sessionItem.UserPSK = userPSK
}
sessionItem.Unlock()
link := sessionItem.link.Load() link := sessionItem.link.Load()
if link != nil { if link != nil {
sessionItem.UpdateConn(conn) sessionItem.UpdateConn(conn)
} else { } else {
userPSK := user.Account.(*MemoryAccount).Key
var err error var err error
link, err = sessionItem.EnsureLink(ctx, conn, decoded.Destination, dispatcher, i.policyManager, func(replyDest net.Destination, payload []byte) ([]byte, error) { link, err = sessionItem.EnsureLink(ctx, conn, decoded.Destination, dispatcher, i.policyManager, func(replyDest net.Destination, payload []byte) ([]byte, error) {
return i.encodeServerUDPPacket(sessionID, userPSK, replyDest, payload) return i.udpCodec.EncodeServerPacket(decoded.SessionID, userPSK, replyDest, payload)
}) })
if err != nil { if err != nil {
continue continue
@@ -356,7 +310,3 @@ func (i *MultiUserInbound) processUDP(ctx context.Context, conn stat.Connection,
} }
} }
} }
func (i *MultiUserInbound) encodeServerUDPPacket(clientSessionID uint64, userPSK []byte, dest net.Destination, payload []byte) ([]byte, error) {
return i.udpSessions.EncodeServerPacket(i.method, userPSK, clientSessionID, dest, payload)
}
+5 -7
View File
@@ -243,16 +243,14 @@ func (i *RelayInbound) processUDP(ctx context.Context, conn stat.Connection, dis
dest.Network = net.Network_UDP dest.Network = net.Network_UDP
sessionItem := i.udpSessions.GetOrCreate(sessionID) sessionItem := i.udpSessions.GetOrCreate(sessionID)
sessionItem.Lock()
if sessionItem.User == nil { if sessionItem.User == nil {
sessionItem.Lock() sessionItem.User = &protocol.MemoryUser{
if sessionItem.User == nil { Email: targetDest.email,
sessionItem.User = &protocol.MemoryUser{ Level: targetDest.level,
Email: targetDest.email,
Level: targetDest.level,
}
} }
sessionItem.Unlock()
} }
sessionItem.Unlock()
link := sessionItem.link.Load() link := sessionItem.link.Load()
if link != nil { if link != nil {
sessionItem.UpdateConn(conn) sessionItem.UpdateConn(conn)
+3 -3
View File
@@ -30,7 +30,7 @@ type Outbound struct {
method *CipherMethod method *CipherMethod
pskList [][]byte pskList [][]byte
finalPSK []byte finalPSK []byte
udpCodec *UDPPacketCodec udpCodec *UDPClientCodec
policyManager policy.Manager policyManager policy.Manager
} }
@@ -50,9 +50,9 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Outbound, error) {
} }
finalPSK := pskList[len(pskList)-1] finalPSK := pskList[len(pskList)-1]
udpCodec, err := NewUDPPacketCodec(method, pskList) udpCodec, err := NewUDPClientCodec(method, pskList)
if err != nil { if err != nil {
return nil, errors.New("failed to create udp packet codec").Base(err) return nil, errors.New("failed to create udp client codec").Base(err)
} }
v := core.MustFromContext(ctx) v := core.MustFromContext(ctx)
+292 -147
View File
@@ -7,33 +7,78 @@ import (
"io" "io"
"math" "math"
mrand "math/rand/v2" mrand "math/rand/v2"
"sync"
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol"
) )
type UDPCodec struct { type UDPClientCodec struct {
method *CipherMethod method *CipherMethod
pskList [][]byte pskList [][]byte
psk []byte psk []byte
blockCipher cipher.Block blockCipher cipher.Block
blockCiphers []cipher.Block blockCiphers []cipher.Block
chachaCipher cipher.AEAD chachaCipher cipher.AEAD
}
func NewUDPClientCodec(method *CipherMethod, pskList [][]byte) (*UDPClientCodec, error) {
if len(pskList) == 0 {
return nil, errors.New("empty psk list")
}
if method.IsChaCha && len(pskList) > 1 {
return nil, errors.New("multi-key is not supported for chacha20-poly1305")
}
finalPSK := pskList[len(pskList)-1]
c := &UDPClientCodec{
method: method,
pskList: pskList,
psk: finalPSK,
}
var err error
if method.IsChaCha {
c.chachaCipher, err = method.NewUDPCipher(finalPSK)
} else {
c.blockCipher, err = method.NewBlock(finalPSK)
}
if err != nil {
return nil, err
}
if len(pskList) > 1 {
c.blockCiphers = make([]cipher.Block, len(pskList))
for i, psk := range pskList {
c.blockCiphers[i], err = method.NewBlock(psk)
if err != nil {
return nil, err
}
}
}
return c, nil
}
func NewUDPPacketCodec(method *CipherMethod, pskList [][]byte) (*UDPClientCodec, error) {
return NewUDPClientCodec(method, pskList)
}
type UDPServerCodec struct {
method *CipherMethod
psk []byte
user *protocol.MemoryUser
blockCipher cipher.Block
chachaCipher cipher.AEAD
sessions *UDPSessionManager sessions *UDPSessionManager
} }
type ( func NewUDPServerCodec(method *CipherMethod, psk []byte, user *protocol.MemoryUser, sessionTimeout time.Duration) (*UDPServerCodec, error) {
UDPPacketCodec = UDPCodec c := &UDPServerCodec{
UDPServerCodec = UDPCodec method: method,
) psk: psk,
user: user,
func newUDPCodec(method *CipherMethod, psk []byte) (*UDPCodec, error) { sessions: NewUDPSessionManager(sessionTimeout),
c := &UDPCodec{
method: method,
psk: psk,
} }
var err error var err error
if method.IsChaCha { if method.IsChaCha {
@@ -47,46 +92,129 @@ func newUDPCodec(method *CipherMethod, psk []byte) (*UDPCodec, error) {
return c, nil return c, nil
} }
func NewUDPPacketCodec(method *CipherMethod, pskList [][]byte) (*UDPCodec, error) { func (c *UDPServerCodec) Sessions() *UDPSessionManager {
if method.IsChaCha && len(pskList) > 1 {
return nil, errors.New("multi-key is not supported for chacha20-poly1305")
}
finalPSK := pskList[len(pskList)-1]
c, err := newUDPCodec(method, finalPSK)
if err != nil {
return nil, err
}
c.pskList = pskList
if len(pskList) > 1 {
c.blockCiphers = make([]cipher.Block, len(pskList))
for i, psk := range pskList {
c.blockCiphers[i], err = method.NewBlock(psk)
if err != nil {
return nil, err
}
}
}
return c, nil
}
func NewUDPServerCodec(method *CipherMethod, psk []byte, sessionTimeout time.Duration) (*UDPCodec, error) {
c, err := newUDPCodec(method, psk)
if err != nil {
return nil, err
}
c.sessions = NewUDPSessionManager(sessionTimeout)
return c, nil
}
func (c *UDPCodec) Sessions() *UDPSessionManager {
return c.sessions return c.sessions
} }
func (c *UDPCodec) GetSession(sessionID uint64) *ServerUDPSession { func (c *UDPServerCodec) GetSession(sessionID uint64) *ServerUDPSession {
if c.sessions == nil { if c.sessions == nil {
return nil return nil
} }
return c.sessions.GetOrCreate(sessionID) return c.sessions.Get(sessionID)
}
type UDPMultiServerCodec struct {
method *CipherMethod
masterPSK []byte
masterBlock cipher.Block
sessions *UDPSessionManager
}
func NewUDPMultiServerCodec(method *CipherMethod, masterPSK []byte, sessionTimeout time.Duration) (*UDPMultiServerCodec, error) {
if method.IsChaCha {
return nil, errors.New("multi-user is not supported for chacha20-poly1305")
}
masterBlock, err := method.NewBlock(masterPSK)
if err != nil {
return nil, err
}
return &UDPMultiServerCodec{
method: method,
masterPSK: masterPSK,
masterBlock: masterBlock,
sessions: NewUDPSessionManager(sessionTimeout),
}, nil
}
func (c *UDPMultiServerCodec) Sessions() *UDPSessionManager {
return c.sessions
}
func (c *UDPMultiServerCodec) GetSession(sessionID uint64) *ServerUDPSession {
if c.sessions == nil {
return nil
}
return c.sessions.Get(sessionID)
}
type UserLookupFunc func(hash [AESBlockSize]byte) (*protocol.MemoryUser, []byte, bool)
func (c *UDPMultiServerCodec) DecodePacket(data []byte, userLookup UserLookupFunc) (*ServerUDPSession, DecodedUDPPacket, *protocol.MemoryUser, error) {
if len(data) < 2*AESBlockSize+AEADTagSize+RequestHeaderFixedChunkLength {
return nil, DecodedUDPPacket{}, nil, ErrPacketTooShort
}
var rawHeader [16]byte
c.masterBlock.Decrypt(rawHeader[:], data[:16])
sessionID := binary.BigEndian.Uint64(rawHeader[:8])
packetID := binary.BigEndian.Uint64(rawHeader[8:16])
sessionItem := c.sessions.Get(sessionID)
var currentUser *protocol.MemoryUser
var userPSK []byte
var bodyAead cipher.AEAD
if sessionItem != nil {
sessionItem.Lock()
currentUser = sessionItem.User
userPSK = sessionItem.UserPSK
bodyAead = sessionItem.clientBodyCipher
sessionItem.Unlock()
if currentUser != nil {
if !sessionItem.CheckPacketID(packetID) {
return nil, DecodedUDPPacket{}, nil, ErrPacketIdNotUnique
}
}
}
if currentUser == nil {
decryptedHash := DecryptUDPEIH(c.masterBlock, rawHeader[:], data[16:32])
user, psk, ok := userLookup(decryptedHash)
if !ok {
return nil, DecodedUDPPacket{}, nil, errors.New("user not found")
}
currentUser = user
userPSK = psk
}
if bodyAead == nil {
bodyKey := DeriveSessionSubKey(userPSK, rawHeader[:8], c.method.KeySaltLength)
var err error
bodyAead, err = c.method.NewAEAD(bodyKey)
if err != nil {
return nil, DecodedUDPPacket{}, nil, err
}
}
bodyNonce := rawHeader[4:16]
bodyCipher := data[32:]
bodyPlain, err := bodyAead.Open(nil, bodyNonce, bodyCipher, nil)
if err != nil {
return nil, DecodedUDPPacket{}, nil, errors.New("failed to decrypt aes udp body").Base(err)
}
decoded, err := parsePlainUDPPacket(sessionID, packetID, bodyPlain)
if err != nil {
return nil, DecodedUDPPacket{}, nil, err
}
if decoded.HeaderType != HeaderTypeClient {
return nil, DecodedUDPPacket{}, nil, ErrBadHeaderType
}
if sessionItem == nil {
sessionItem = c.sessions.GetOrCreate(sessionID)
}
if !sessionItem.Commit(packetID, bodyAead, currentUser, userPSK) {
return nil, DecodedUDPPacket{}, nil, ErrPacketIdNotUnique
}
return sessionItem, decoded, currentUser, nil
}
func (c *UDPMultiServerCodec) EncodeServerPacket(clientSessionID uint64, userPSK []byte, dest net.Destination, payload []byte) ([]byte, error) {
return c.sessions.EncodeServerPacket(c.method, userPSK, clientSessionID, dest, payload)
} }
type DecodedUDPPacket struct { type DecodedUDPPacket struct {
@@ -193,44 +321,42 @@ func parsePlainUDPPacket(sessionID, packetID uint64, bodyPlain []byte) (DecodedU
}, nil }, nil
} }
func (c *UDPCodec) DecodePacket(data []byte) (DecodedUDPPacket, error) { func (c *UDPServerCodec) DecodePacket(data []byte) (*ServerUDPSession, DecodedUDPPacket, error) {
if len(data) < PacketMinimalHeaderSize { if len(data) < PacketMinimalHeaderSize {
return DecodedUDPPacket{}, ErrPacketTooShort return nil, DecodedUDPPacket{}, ErrPacketTooShort
} }
if c.method.IsChaCha { if c.method.IsChaCha {
if len(data) < PacketNonceSize+AEADTagSize { if len(data) < PacketNonceSize+AEADTagSize {
return DecodedUDPPacket{}, ErrPacketTooShort return nil, DecodedUDPPacket{}, ErrPacketTooShort
} }
nonce := data[:PacketNonceSize] nonce := data[:PacketNonceSize]
ciphertext := data[PacketNonceSize:] ciphertext := data[PacketNonceSize:]
plain, err := c.chachaCipher.Open(nil, nonce, ciphertext, nil) plain, err := c.chachaCipher.Open(nil, nonce, ciphertext, nil)
if err != nil { if err != nil {
return DecodedUDPPacket{}, errors.New("failed to decrypt chacha udp packet").Base(err) return nil, DecodedUDPPacket{}, errors.New("failed to decrypt chacha udp packet").Base(err)
} }
if len(plain) < 16+1+8+2 { if len(plain) < 16+1+8+2 {
return DecodedUDPPacket{}, ErrPacketTooShort return nil, DecodedUDPPacket{}, ErrPacketTooShort
} }
sessionID := binary.BigEndian.Uint64(plain[:8]) sessionID := binary.BigEndian.Uint64(plain[:8])
packetID := binary.BigEndian.Uint64(plain[8:16]) packetID := binary.BigEndian.Uint64(plain[8:16])
sessionItem := c.sessions.GetOrCreate(sessionID)
if !sessionItem.CheckPacketID(packetID) {
return DecodedUDPPacket{}, ErrPacketIdNotUnique
}
decoded, err := parsePlainUDPPacket(sessionID, packetID, plain[16:]) decoded, err := parsePlainUDPPacket(sessionID, packetID, plain[16:])
if err != nil { if err != nil {
return DecodedUDPPacket{}, err return nil, DecodedUDPPacket{}, err
} }
if decoded.HeaderType != HeaderTypeClient { if decoded.HeaderType != HeaderTypeClient {
return DecodedUDPPacket{}, ErrBadHeaderType return nil, DecodedUDPPacket{}, ErrBadHeaderType
} }
sessionItem.AddPacketID(packetID) sessionItem := c.sessions.GetOrCreate(sessionID)
return decoded, nil if !sessionItem.Commit(packetID, nil, c.user, c.psk) {
return nil, DecodedUDPPacket{}, ErrPacketIdNotUnique
}
return sessionItem, decoded, nil
} }
// AES mode // AES mode
@@ -239,49 +365,48 @@ func (c *UDPCodec) DecodePacket(data []byte) (DecodedUDPPacket, error) {
sessionID := binary.BigEndian.Uint64(rawHeader[:8]) sessionID := binary.BigEndian.Uint64(rawHeader[:8])
packetID := binary.BigEndian.Uint64(rawHeader[8:16]) packetID := binary.BigEndian.Uint64(rawHeader[8:16])
sessionItem := c.sessions.GetOrCreate(sessionID) sessionItem := c.sessions.Get(sessionID)
if !sessionItem.CheckPacketID(packetID) { var bodyAead cipher.AEAD
return DecodedUDPPacket{}, ErrPacketIdNotUnique if sessionItem != nil {
if !sessionItem.CheckPacketID(packetID) {
return nil, DecodedUDPPacket{}, ErrPacketIdNotUnique
}
sessionItem.Lock()
bodyAead = sessionItem.clientBodyCipher
sessionItem.Unlock()
} }
return sessionItem.DecryptAESPayload(c.method, c.psk, sessionID, packetID, rawHeader[:], data[16:])
}
func (s *ServerUDPSession) DecryptAESPayload(method *CipherMethod, psk []byte, sessionID, packetID uint64, rawHeader, bodyCipher []byte) (DecodedUDPPacket, error) {
bodyAead := s.clientBodyCipher
isNewCipher := false
if bodyAead == nil { if bodyAead == nil {
bodyKey := DeriveSessionSubKey(psk, rawHeader[:8], method.KeySaltLength) bodyKey := DeriveSessionSubKey(c.psk, rawHeader[:8], c.method.KeySaltLength)
var err error var err error
bodyAead, err = method.NewAEAD(bodyKey) bodyAead, err = c.method.NewAEAD(bodyKey)
if err != nil { if err != nil {
return DecodedUDPPacket{}, err return nil, DecodedUDPPacket{}, err
} }
isNewCipher = true
} }
bodyNonce := rawHeader[4:16] bodyNonce := rawHeader[4:16]
bodyCipher := data[16:]
bodyPlain, err := bodyAead.Open(nil, bodyNonce, bodyCipher, nil) bodyPlain, err := bodyAead.Open(nil, bodyNonce, bodyCipher, nil)
if err != nil { if err != nil {
return DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err) return nil, DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err)
} }
decoded, err := parsePlainUDPPacket(sessionID, packetID, bodyPlain) decoded, err := parsePlainUDPPacket(sessionID, packetID, bodyPlain)
if err != nil { if err != nil {
return DecodedUDPPacket{}, err return nil, DecodedUDPPacket{}, err
} }
if decoded.HeaderType != HeaderTypeClient { if decoded.HeaderType != HeaderTypeClient {
return DecodedUDPPacket{}, ErrBadHeaderType return nil, DecodedUDPPacket{}, ErrBadHeaderType
} }
s.AddPacketID(packetID) if sessionItem == nil {
sessionItem = c.sessions.GetOrCreate(sessionID)
if isNewCipher {
s.clientBodyCipher = bodyAead
} }
if !sessionItem.Commit(packetID, bodyAead, c.user, c.psk) {
return decoded, nil return nil, DecodedUDPPacket{}, ErrPacketIdNotUnique
}
return sessionItem, decoded, nil
} }
func (s *ServerUDPSession) EnsureServerState(method *CipherMethod, psk []byte) error { func (s *ServerUDPSession) EnsureServerState(method *CipherMethod, psk []byte) error {
@@ -303,6 +428,9 @@ func (s *ServerUDPSession) EnsureServerState(method *CipherMethod, psk []byte) e
if method.IsChaCha { if method.IsChaCha {
var err error var err error
s.serverChaCha, err = method.NewUDPCipher(psk) s.serverChaCha, err = method.NewUDPCipher(psk)
if err != nil {
s.ServerSessionID = 0
}
return err return err
} }
@@ -387,11 +515,12 @@ func (s *ServerUDPSession) EncodeServerPacket(method *CipherMethod, clientSessio
return res, nil return res, nil
} }
func (c *UDPCodec) EncodeServerPacket(clientSessionID uint64, dest net.Destination, payload []byte) ([]byte, error) { func (c *UDPServerCodec) EncodeServerPacket(clientSessionID uint64, dest net.Destination, payload []byte) ([]byte, error) {
return c.sessions.EncodeServerPacket(c.method, c.psk, clientSessionID, dest, payload) return c.sessions.EncodeServerPacket(c.method, c.psk, clientSessionID, dest, payload)
} }
type serverSessionState struct { type serverSessionState struct {
sync.Mutex
sessionID uint64 sessionID uint64
window *SlidingWindow window *SlidingWindow
cipher cipher.AEAD cipher cipher.AEAD
@@ -399,21 +528,24 @@ type serverSessionState struct {
} }
func (st *serverSessionState) check(packetID uint64) bool { func (st *serverSessionState) check(packetID uint64) bool {
if st.window == nil { st.Lock()
st.window = new(SlidingWindow) defer st.Unlock()
}
return st.window.Check(packetID) return st.window.Check(packetID)
} }
func (st *serverSessionState) add(packetID uint64) { func (st *serverSessionState) commit(packetID uint64, now int64) bool {
if st.window == nil { st.Lock()
st.window = new(SlidingWindow) defer st.Unlock()
if !st.window.CheckAndAdd(packetID) {
return false
} }
st.window.Add(packetID) st.lastSeen.Store(now)
return true
} }
type ClientUDPSession struct { type ClientUDPSession struct {
codec *UDPCodec mu sync.Mutex
codec *UDPClientCodec
clientSessionID uint64 clientSessionID uint64
nextPacketID atomic.Uint64 nextPacketID atomic.Uint64
clientBodyCipher cipher.AEAD clientBodyCipher cipher.AEAD
@@ -421,7 +553,7 @@ type ClientUDPSession struct {
old atomic.Pointer[serverSessionState] old atomic.Pointer[serverSessionState]
} }
func (c *UDPCodec) NewClientSession() (*ClientUDPSession, error) { func (c *UDPClientCodec) NewClientSession() (*ClientUDPSession, error) {
var sessID [8]byte var sessID [8]byte
if _, err := io.ReadFull(rand.Reader, sessID[:]); err != nil { if _, err := io.ReadFull(rand.Reader, sessID[:]); err != nil {
return nil, err return nil, err
@@ -446,51 +578,43 @@ func (c *UDPCodec) NewClientSession() (*ClientUDPSession, error) {
}, nil }, nil
} }
func (s *ClientUDPSession) getServerSession(sessionID uint64, now int64) (*serverSessionState, error) { func (s *ClientUDPSession) findServerSession(sessionID uint64, now int64) (*serverSessionState, error) {
cur := s.current.Load() if cur := s.current.Load(); cur != nil && cur.sessionID == sessionID {
if cur != nil && cur.sessionID == sessionID {
return cur, nil return cur, nil
} }
if old := s.old.Load(); old != nil {
old := s.old.Load() if old.sessionID == sessionID {
if old != nil && old.sessionID == sessionID { if now-old.lastSeen.Load() > 60 {
if now-old.lastSeen.Load() > 60 { return nil, errors.New("old server session expired")
s.old.CompareAndSwap(old, nil) }
return nil, errors.New("old server session expired") return old, nil
} }
return old, nil // Spec §3.2.4: reject newer server sessions when the last packet received from the old session is less than 1 minute old.
} if now-old.lastSeen.Load() < 60 {
return nil, errors.New("newer server session rejected: old session is less than 1 minute old")
// New server session:
// Spec §3.2.4: reject newer server sessions when the last packet received from the old session is less than 1 minute old.
if old != nil && now-old.lastSeen.Load() < 60 {
return nil, errors.New("newer server session rejected: old session is less than 1 minute old")
}
var bodyAead cipher.AEAD
if !s.codec.method.IsChaCha {
var sessBytes [8]byte
binary.BigEndian.PutUint64(sessBytes[:], sessionID)
bodyKey := DeriveSessionSubKey(s.codec.psk, sessBytes[:], s.codec.method.KeySaltLength)
var err error
bodyAead, err = s.codec.method.NewAEAD(bodyKey)
if err != nil {
return nil, err
} }
} }
return nil, nil
}
func (s *ClientUDPSession) transitionServerSession(sessionID uint64, cipher cipher.AEAD, now int64) (*serverSessionState, error) {
s.mu.Lock()
defer s.mu.Unlock()
if st, err := s.findServerSession(sessionID, now); st != nil || err != nil {
return st, err
}
newState := &serverSessionState{ newState := &serverSessionState{
sessionID: sessionID, sessionID: sessionID,
cipher: bodyAead, window: new(SlidingWindow),
cipher: cipher,
} }
newState.lastSeen.Store(now) newState.lastSeen.Store(now)
if cur == nil { if cur := s.current.Load(); cur != nil {
s.current.CompareAndSwap(nil, newState) s.old.Store(cur)
return s.current.Load(), nil
} }
s.old.Store(cur)
s.current.Store(newState) s.current.Store(newState)
return newState, nil return newState, nil
} }
@@ -505,7 +629,7 @@ func (s *ClientUDPSession) EncodePacket(dest net.Destination, payload []byte) (*
var paddingLen int var paddingLen int
if dest.Port == 53 && len(payload) < MaxPaddingLength { if dest.Port == 53 && len(payload) < MaxPaddingLength {
paddingLen = mrand.IntN(MaxPaddingLength) + 1 paddingLen = mrand.IntN(MaxPaddingLength-len(payload)) + 1
} }
addrPortLen := AddrPortLength(dest) addrPortLen := AddrPortLength(dest)
@@ -620,6 +744,8 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
return DecodedUDPPacket{}, ErrPacketTooShort return DecodedUDPPacket{}, ErrPacketTooShort
} }
now := time.Now().Unix()
if s.codec.method.IsChaCha { if s.codec.method.IsChaCha {
if len(data) < PacketNonceSize+AEADTagSize { if len(data) < PacketNonceSize+AEADTagSize {
return DecodedUDPPacket{}, ErrPacketTooShort return DecodedUDPPacket{}, ErrPacketTooShort
@@ -637,20 +763,10 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
sessionID := binary.BigEndian.Uint64(plain[:8]) sessionID := binary.BigEndian.Uint64(plain[:8])
packetID := binary.BigEndian.Uint64(plain[8:16]) packetID := binary.BigEndian.Uint64(plain[8:16])
now := time.Now().Unix()
st, err := s.getServerSession(sessionID, now)
if err != nil {
return DecodedUDPPacket{}, err
}
if !st.check(packetID) {
return DecodedUDPPacket{}, ErrPacketIdNotUnique
}
decoded, err := parsePlainUDPPacket(sessionID, packetID, plain[16:]) decoded, err := parsePlainUDPPacket(sessionID, packetID, plain[16:])
if err != nil { if err != nil {
return DecodedUDPPacket{}, err return DecodedUDPPacket{}, err
} }
if decoded.HeaderType != HeaderTypeServer { if decoded.HeaderType != HeaderTypeServer {
return DecodedUDPPacket{}, ErrBadHeaderType return DecodedUDPPacket{}, ErrBadHeaderType
} }
@@ -658,8 +774,20 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
return DecodedUDPPacket{}, errors.New("client session ID mismatch") return DecodedUDPPacket{}, errors.New("client session ID mismatch")
} }
st.add(packetID) st, err := s.findServerSession(sessionID, now)
st.lastSeen.Store(now) if err != nil {
return DecodedUDPPacket{}, err
}
if st == nil {
st, err = s.transitionServerSession(sessionID, nil, now)
if err != nil {
return DecodedUDPPacket{}, err
}
}
if !st.commit(packetID, now) {
return DecodedUDPPacket{}, ErrPacketIdNotUnique
}
return decoded, nil return decoded, nil
} }
@@ -670,19 +798,29 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
sessionID := binary.BigEndian.Uint64(rawHeader[:8]) sessionID := binary.BigEndian.Uint64(rawHeader[:8])
packetID := binary.BigEndian.Uint64(rawHeader[8:16]) packetID := binary.BigEndian.Uint64(rawHeader[8:16])
now := time.Now().Unix() st, err := s.findServerSession(sessionID, now)
st, err := s.getServerSession(sessionID, now)
if err != nil { if err != nil {
return DecodedUDPPacket{}, err return DecodedUDPPacket{}, err
} }
if !st.check(packetID) {
return DecodedUDPPacket{}, ErrPacketIdNotUnique var bodyAead cipher.AEAD
if st != nil {
if !st.check(packetID) {
return DecodedUDPPacket{}, ErrPacketIdNotUnique
}
bodyAead = st.cipher
} else {
var sessBytes [8]byte
binary.BigEndian.PutUint64(sessBytes[:], sessionID)
bodyKey := DeriveSessionSubKey(s.codec.psk, sessBytes[:], s.codec.method.KeySaltLength)
bodyAead, err = s.codec.method.NewAEAD(bodyKey)
if err != nil {
return DecodedUDPPacket{}, err
}
} }
bodyAead := st.cipher
bodyNonce := rawHeader[4:16] bodyNonce := rawHeader[4:16]
bodyCipher := data[16:] bodyPlain, err := bodyAead.Open(nil, bodyNonce, data[16:], nil)
bodyPlain, err := bodyAead.Open(nil, bodyNonce, bodyCipher, nil)
if err != nil { if err != nil {
return DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err) return DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err)
} }
@@ -691,7 +829,6 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
if err != nil { if err != nil {
return DecodedUDPPacket{}, err return DecodedUDPPacket{}, err
} }
if decoded.HeaderType != HeaderTypeServer { if decoded.HeaderType != HeaderTypeServer {
return DecodedUDPPacket{}, ErrBadHeaderType return DecodedUDPPacket{}, ErrBadHeaderType
} }
@@ -699,8 +836,16 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
return DecodedUDPPacket{}, errors.New("client session ID mismatch") return DecodedUDPPacket{}, errors.New("client session ID mismatch")
} }
st.add(packetID) if st == nil {
st.lastSeen.Store(now) st, err = s.transitionServerSession(sessionID, bodyAead, now)
if err != nil {
return DecodedUDPPacket{}, err
}
}
if !st.commit(packetID, now) {
return DecodedUDPPacket{}, ErrPacketIdNotUnique
}
return decoded, nil return decoded, nil
} }
+4 -3
View File
@@ -191,7 +191,7 @@ func TestRelayUDPSessionStabilityAndDispatch(t *testing.T) {
// Verify downstream destination can decode both packets // Verify downstream destination can decode both packets
method, err := GetCipherMethod(MethodAES128GCM) method, err := GetCipherMethod(MethodAES128GCM)
common.Must(err) common.Must(err)
destCodec, err := NewUDPServerCodec(method, destKey, 300*time.Second) destCodec, err := NewUDPServerCodec(method, destKey, nil, 300*time.Second)
common.Must(err) common.Must(err)
mu.Lock() mu.Lock()
@@ -202,7 +202,8 @@ func TestRelayUDPSessionStabilityAndDispatch(t *testing.T) {
t.Fatalf("expected 2 received packets at destination, got %d", len(pkts)) t.Fatalf("expected 2 received packets at destination, got %d", len(pkts))
} }
dec1, err := destCodec.DecodePacket(pkts[0]) dec1, dec2 := DecodedUDPPacket{}, DecodedUDPPacket{}
_, dec1, err = destCodec.DecodePacket(pkts[0])
if err != nil { if err != nil {
t.Fatalf("dest failed to decode packet 1: %v", err) t.Fatalf("dest failed to decode packet 1: %v", err)
} }
@@ -210,7 +211,7 @@ func TestRelayUDPSessionStabilityAndDispatch(t *testing.T) {
t.Fatalf("dec1 mismatch: sess=%x, pktID=%d, payload=%s", dec1.SessionID, dec1.PacketID, string(dec1.Payload)) t.Fatalf("dec1 mismatch: sess=%x, pktID=%d, payload=%s", dec1.SessionID, dec1.PacketID, string(dec1.Payload))
} }
dec2, err := destCodec.DecodePacket(pkts[1]) _, dec2, err = destCodec.DecodePacket(pkts[1])
if err != nil { if err != nil {
t.Fatalf("dest failed to decode packet 2: %v", err) t.Fatalf("dest failed to decode packet 2: %v", err)
} }
+23 -7
View File
@@ -100,19 +100,27 @@ type ServerUDPSession struct {
func (s *ServerUDPSession) CheckPacketID(packetID uint64) bool { func (s *ServerUDPSession) CheckPacketID(packetID uint64) bool {
s.Lock() s.Lock()
defer s.Unlock() defer s.Unlock()
if s.Window == nil {
s.Window = new(SlidingWindow)
}
return s.Window.Check(packetID) return s.Window.Check(packetID)
} }
func (s *ServerUDPSession) AddPacketID(packetID uint64) { func (s *ServerUDPSession) Commit(packetID uint64, bodyAead cipher.AEAD, user *protocol.MemoryUser, userPSK []byte) bool {
s.Lock() s.Lock()
defer s.Unlock() defer s.Unlock()
if s.Window == nil { if s.User != nil && user != nil && s.User != user {
s.Window = new(SlidingWindow) return false
} }
s.Window.Add(packetID) if !s.Window.CheckAndAdd(packetID) {
return false
}
if s.clientBodyCipher == nil && bodyAead != nil {
s.clientBodyCipher = bodyAead
}
if s.User == nil && user != nil {
s.User = user
s.UserPSK = userPSK
}
s.LastActive.Store(time.Now().Unix())
return true
} }
type UDPSessionManager struct { type UDPSessionManager struct {
@@ -128,6 +136,13 @@ func NewUDPSessionManager(timeout time.Duration) *UDPSessionManager {
} }
} }
func (m *UDPSessionManager) Get(sessionID uint64) *ServerUDPSession {
if s, ok := m.sessions.Load(sessionID); ok {
return s
}
return nil
}
func (m *UDPSessionManager) GetOrCreate(sessionID uint64) *ServerUDPSession { func (m *UDPSessionManager) GetOrCreate(sessionID uint64) *ServerUDPSession {
now := time.Now().Unix() now := time.Now().Unix()
if s, ok := m.sessions.Load(sessionID); ok { if s, ok := m.sessions.Load(sessionID); ok {
@@ -137,6 +152,7 @@ func (m *UDPSessionManager) GetOrCreate(sessionID uint64) *ServerUDPSession {
s := &ServerUDPSession{ s := &ServerUDPSession{
SessionID: sessionID, SessionID: sessionID,
Window: new(SlidingWindow),
manager: m, manager: m,
} }
s.LastActive.Store(now) s.LastActive.Store(now)
+9 -3
View File
@@ -63,10 +63,16 @@ func (s *ServerUDPSession) EnsureLink(
s.currentConn.Store(conn) s.currentConn.Store(conn)
sessCtx, cancel := context.WithCancel(ctx) // UDP Session might travel across multiple connections
// don't bind its lifetime to a parent context
sessCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
inbound := session.InboundFromContext(sessCtx) inbound := session.InboundFromContext(sessCtx)
if inbound != nil && s.User != nil { if inbound != nil {
inbound.User = s.User newInbound := *inbound
if s.User != nil {
newInbound.User = s.User
}
sessCtx = session.ContextWithInbound(sessCtx, &newInbound)
} }
var email string var email string
var level uint32 var level uint32
@@ -265,7 +265,7 @@ func TestUDPCodec(t *testing.T) {
clientCodec, err := NewUDPPacketCodec(method, [][]byte{psk}) clientCodec, err := NewUDPPacketCodec(method, [][]byte{psk})
common.Must(err) common.Must(err)
serverCodec, err := NewUDPServerCodec(method, psk, time.Minute) serverCodec, err := NewUDPServerCodec(method, psk, nil, time.Minute)
common.Must(err) common.Must(err)
session, err := clientCodec.NewClientSession() session, err := clientCodec.NewClientSession()
@@ -277,7 +277,7 @@ func TestUDPCodec(t *testing.T) {
rawCopy := make([]byte, pktBuf.Len()) rawCopy := make([]byte, pktBuf.Len())
copy(rawCopy, pktBuf.Bytes()) copy(rawCopy, pktBuf.Bytes())
decoded, err := serverCodec.DecodePacket(pktBuf.Bytes()) _, decoded, err := serverCodec.DecodePacket(pktBuf.Bytes())
common.Must(err) common.Must(err)
if decoded.HeaderType != HeaderTypeClient { if decoded.HeaderType != HeaderTypeClient {
@@ -291,7 +291,7 @@ func TestUDPCodec(t *testing.T) {
} }
// Replay same packet wire bytes should fail with ErrPacketIdNotUnique // Replay same packet wire bytes should fail with ErrPacketIdNotUnique
_, err = serverCodec.DecodePacket(rawCopy) _, _, err = serverCodec.DecodePacket(rawCopy)
if err != ErrPacketIdNotUnique { if err != ErrPacketIdNotUnique {
t.Fatalf("expected ErrPacketIdNotUnique on replay, got: %v", err) t.Fatalf("expected ErrPacketIdNotUnique on replay, got: %v", err)
} }
@@ -427,7 +427,7 @@ func TestClientUDPSessionMultiDestination(t *testing.T) {
clientCodec, err := NewUDPPacketCodec(method, [][]byte{rawKey}) clientCodec, err := NewUDPPacketCodec(method, [][]byte{rawKey})
common.Must(err) common.Must(err)
serverCodec, err := NewUDPServerCodec(method, rawKey, time.Minute) serverCodec, err := NewUDPServerCodec(method, rawKey, nil, time.Minute)
common.Must(err) common.Must(err)
session, err := clientCodec.NewClientSession() session, err := clientCodec.NewClientSession()
@@ -448,9 +448,9 @@ func TestClientUDPSessionMultiDestination(t *testing.T) {
defer pkt2.Release() defer pkt2.Release()
// Server decodes both // Server decodes both
dec1, err := serverCodec.DecodePacket(pkt1.Bytes()) _, dec1, err := serverCodec.DecodePacket(pkt1.Bytes())
common.Must(err) common.Must(err)
dec2, err := serverCodec.DecodePacket(pkt2.Bytes()) _, dec2, err := serverCodec.DecodePacket(pkt2.Bytes())
common.Must(err) common.Must(err)
if dec1.SessionID != session.ClientSessionID() || dec2.SessionID != session.ClientSessionID() { if dec1.SessionID != session.ClientSessionID() || dec2.SessionID != session.ClientSessionID() {
+1 -1
View File
@@ -337,7 +337,7 @@ func WriteTCPRequest(w io.Writer, method *CipherMethod, pskList [][]byte, dest n
addrPortLen := AddrPortLength(dest) addrPortLen := AddrPortLength(dest)
varHeaderLen := addrPortLen + 2 + paddingLen + payloadLen varHeaderLen := addrPortLen + 2 + paddingLen + payloadLen
totalHandshakeLen := int32(method.KeySaltLength + len(pskList)*AESBlockSize + RequestHeaderFixedChunkLength + AEADTagSize + varHeaderLen + AEADTagSize) totalHandshakeLen := int32(method.KeySaltLength + (len(pskList)-1)*AESBlockSize + RequestHeaderFixedChunkLength + AEADTagSize + varHeaderLen + AEADTagSize)
handshakeBuf := buf.NewWithSize(totalHandshakeLen) handshakeBuf := buf.NewWithSize(totalHandshakeLen)
defer handshakeBuf.Release() defer handshakeBuf.Release()
+2
View File
@@ -223,6 +223,8 @@ To make it start, wintun.dll specific for your Windows/arch must be present next
After the start network adapter with the name you chose in the config will be created in the system, and exist while Xray is running. A Wintun adapter that already has that name is reused. After the start network adapter with the name you chose in the config will be created in the system, and exist while Xray is running. A Wintun adapter that already has that name is reused.
`guid` sets the GUID of the adapter Xray creates, as in `"guid": "6ba7b810-9dad-11d1-80b4-00c04fd430c8"`, for applications that identify the adapter by something other than its name, e.g. to keep the same identity across renames. It is used only when Xray creates the adapter: a Wintun adapter that already has the name is opened as it is and keeps its own GUID, so this setting cannot change it. Without it the GUID is derived from the name with MD5, which keeps it the same for as long as the name does. The GUID must not be one that another adapter uses, and Wintun holds one session per adapter, so an adapter is in use by one engine at a time. The config is rejected, on Windows and elsewhere, if the value is not a canonical GUID; other systems ignore it.
With IPv6 turned off by the `DisabledComponents` registry value (0x10 set, as in 0xFF), errors setting up IPv6 for `gateway`, `dns` and `autoSystemRoutingTable`, clearing the IPv6 DNS servers when `dns` has none included, are only logged. Otherwise, they keep the TUN from starting. With IPv6 turned off by the `DisabledComponents` registry value (0x10 set, as in 0xFF), errors setting up IPv6 for `gateway`, `dns` and `autoSystemRoutingTable`, clearing the IPv6 DNS servers when `dns` has none included, are only logged. Otherwise, they keep the TUN from starting.
When `dns` is set, those servers are applied to the adapter. Windows is kept from registering the TUN's addresses in DNS, and its DNS cache is flushed when the TUN starts and stops. Xray's own lookups through the system's DNS servers, like those of the `localhost` DNS server with `autoOutboundsInterface`, skip them, unless another interface uses them as well, as they would lead back into the TUN. When `dns` is set, those servers are applied to the adapter. Windows is kept from registering the TUN's addresses in DNS, and its DNS cache is flushed when the TUN starts and stops. Xray's own lookups through the system's DNS servers, like those of the `localhost` DNS server with `autoOutboundsInterface`, skip them, unless another interface uses them as well, as they would lead back into the TUN.
+16
View File
@@ -5,6 +5,7 @@ import (
"net" "net"
"sync" "sync"
"github.com/google/uuid"
"github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/errors"
) )
@@ -49,3 +50,18 @@ func (updater *InterfaceUpdater) Update() {
updater.iface = got updater.iface = got
errors.LogInfo(context.Background(), "[tun] update interface ", got.Name, " ", got.Index) errors.LogInfo(context.Background(), "[tun] update interface ", got.Name, " ", got.Index)
} }
// ParseGUID parses a canonical textual GUID, as in
// "00000000-0000-0000-0000-000000000000", into the 16 bytes it denotes.
// The form is all that is accepted, not the other ones uuid.Parse takes,
// such as one without hyphens; the length check is what rules those out.
func ParseGUID(s string) ([16]byte, error) {
if len(s) != 36 {
return [16]byte{}, errors.New("invalid guid: ", s, ", want xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
}
id, err := uuid.Parse(s)
if err != nil {
return [16]byte{}, errors.New("invalid guid: ", s, ", want xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").Base(err)
}
return id, nil
}
+11 -2
View File
@@ -33,6 +33,7 @@ type Config struct {
Desc string `protobuf:"bytes,8,opt,name=desc,proto3" json:"desc,omitempty"` Desc string `protobuf:"bytes,8,opt,name=desc,proto3" json:"desc,omitempty"`
AutoSystemDnsToGateway bool `protobuf:"varint,9,opt,name=auto_system_dns_to_gateway,json=autoSystemDnsToGateway,proto3" json:"auto_system_dns_to_gateway,omitempty"` AutoSystemDnsToGateway bool `protobuf:"varint,9,opt,name=auto_system_dns_to_gateway,json=autoSystemDnsToGateway,proto3" json:"auto_system_dns_to_gateway,omitempty"`
AutoSystemWfpBlockLeak []string `protobuf:"bytes,10,rep,name=auto_system_wfp_block_leak,json=autoSystemWfpBlockLeak,proto3" json:"auto_system_wfp_block_leak,omitempty"` AutoSystemWfpBlockLeak []string `protobuf:"bytes,10,rep,name=auto_system_wfp_block_leak,json=autoSystemWfpBlockLeak,proto3" json:"auto_system_wfp_block_leak,omitempty"`
GUID string `protobuf:"bytes,11,opt,name=GUID,proto3" json:"GUID,omitempty"`
unknownFields protoimpl.UnknownFields unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache sizeCache protoimpl.SizeCache
} }
@@ -137,11 +138,18 @@ func (x *Config) GetAutoSystemWfpBlockLeak() []string {
return nil return nil
} }
func (x *Config) GetGUID() string {
if x != nil {
return x.GUID
}
return ""
}
var File_proxy_tun_config_proto protoreflect.FileDescriptor var File_proxy_tun_config_proto protoreflect.FileDescriptor
const file_proxy_tun_config_proto_rawDesc = "" + const file_proxy_tun_config_proto_rawDesc = "" +
"\n" + "\n" +
"\x16proxy/tun/config.proto\x12\x0exray.proxy.tun\"\xfa\x02\n" + "\x16proxy/tun/config.proto\x12\x0exray.proxy.tun\"\x8e\x03\n" +
"\x06Config\x12\x12\n" + "\x06Config\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\x12\x10\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12\x10\n" +
"\x03MTU\x18\x02 \x01(\rR\x03MTU\x12\x18\n" + "\x03MTU\x18\x02 \x01(\rR\x03MTU\x12\x18\n" +
@@ -154,7 +162,8 @@ const file_proxy_tun_config_proto_rawDesc = "" +
"\x04desc\x18\b \x01(\tR\x04desc\x12:\n" + "\x04desc\x18\b \x01(\tR\x04desc\x12:\n" +
"\x1aauto_system_dns_to_gateway\x18\t \x01(\bR\x16autoSystemDnsToGateway\x12:\n" + "\x1aauto_system_dns_to_gateway\x18\t \x01(\bR\x16autoSystemDnsToGateway\x12:\n" +
"\x1aauto_system_wfp_block_leak\x18\n" + "\x1aauto_system_wfp_block_leak\x18\n" +
" \x03(\tR\x16autoSystemWfpBlockLeakBL\n" + " \x03(\tR\x16autoSystemWfpBlockLeak\x12\x12\n" +
"\x04GUID\x18\v \x01(\tR\x04GUIDBL\n" +
"\x12com.xray.proxy.tunP\x01Z#github.com/xtls/xray-core/proxy/tun\xaa\x02\x0eXray.Proxy.Tunb\x06proto3" "\x12com.xray.proxy.tunP\x01Z#github.com/xtls/xray-core/proxy/tun\xaa\x02\x0eXray.Proxy.Tunb\x06proto3"
var ( var (
+1
View File
@@ -17,4 +17,5 @@ message Config {
string desc = 8; string desc = 8;
bool auto_system_dns_to_gateway = 9; bool auto_system_dns_to_gateway = 9;
repeated string auto_system_wfp_block_leak = 10; repeated string auto_system_wfp_block_leak = 10;
string GUID = 11;
} }
-390
View File
@@ -1,390 +0,0 @@
//go:build freebsd
package tun
import (
"context"
"errors"
"io/fs"
"net/netip"
"strings"
"testing"
)
type probeCall struct {
inboundTag string
source string
address string
}
// stubDNSRouting replaces the routing probe for the duration of a test and
// records how it was called, so tests can assert the probe is representative.
func stubDNSRouting(t *testing.T, err error) *[]probeCall {
t.Helper()
original := verifyDNSRouting
calls := []probeCall{}
verifyDNSRouting = func(_ context.Context, inboundTag, source, address string) error {
calls = append(calls, probeCall{inboundTag, source, address})
return err
}
t.Cleanup(func() { verifyDNSRouting = original })
return &calls
}
// recorder installs a resolvconf stub for the duration of a test and returns
// the captured invocations, each as the arguments followed by the stdin in
// angle brackets when there was one. An empty failOn succeeds every call;
// otherwise the named subcommand fails.
func recorder(t *testing.T, failOn string) *[]string {
t.Helper()
original := resolvconfRunner
calls := []string{}
resolvconfRunner = func(stdin string, args ...string) ([]byte, error) {
call := strings.Join(args, " ")
if stdin != "" {
call += " <" + stdin + ">"
}
calls = append(calls, call)
if failOn != "" && len(args) > 0 && args[0] == failOn {
return nil, errors.New("boom")
}
return nil, nil
}
t.Cleanup(func() { resolvconfRunner = original })
return &calls
}
// files replaces the resolver files read by the applied check for the
// duration of a test. A path not in the map does not exist.
func files(t *testing.T, contents map[string]string) {
t.Helper()
original := readResolverFile
readResolverFile = func(path string) ([]byte, error) {
if data, ok := contents[path]; ok {
return []byte(data), nil
}
return nil, fs.ErrNotExist
}
t.Cleanup(func() { readResolverFile = original })
}
// takenOver is what the libc subscriber writes once the TUN's nameserver is
// the exclusive one.
const takenOver = "# Generated by resolvconf\nnameserver 192.168.100.1\n"
// untouched is the DHCP-supplied resolv.conf that resolvconf=NO leaves in
// place.
const untouched = "# Generated by resolvconf\nnameserver 10.0.0.1\n"
func optedInTun() *FreeBSDTun {
return &FreeBSDTun{
options: &Config{
Name: "tun7",
Gateway: []string{"192.168.100.1/30"},
AutoSystemDnsToGateway: true,
},
name: "tun7",
gateway: netip.MustParsePrefix("192.168.100.1/30"),
local: netip.MustParseAddr("192.168.100.2"),
}
}
func joined(calls []string) string {
return strings.Join(calls, " | ")
}
func TestConfigureSystemDNSDisabledByDefault(t *testing.T) {
probes := stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
t1.options.AutoSystemDnsToGateway = false
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(*calls) != 0 || len(*probes) != 0 {
t.Errorf("nothing may run when the option is off, got %q and %d probes", joined(*calls), len(*probes))
}
if t1.systemDNSSet {
t.Error("systemDNSSet must stay false when the option is off")
}
}
func TestConfigureSystemDNSLeavesOSDNSWhenNoRoute(t *testing.T) {
stubDNSRouting(t, errors.New("no route"))
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
t.Fatal("expected an error when the probe fails")
}
if len(*calls) != 0 {
t.Errorf("resolvconf must not run when the probe fails, got %q", joined(*calls))
}
if t1.systemDNSSet {
t.Error("systemDNSSet must stay false when the probe fails")
}
}
// On FreeBSD the addresses are the other way round from Linux: the local
// address is the one after the gateway, and the gateway itself has no owner,
// so a packet to it is routed into the TUN. The probe has to carry that pair,
// and the resolver has to be pointed at the gateway.
func TestConfigureSystemDNSProbeCarriesFreeBSDPair(t *testing.T) {
probes := stubDNSRouting(t, nil)
recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(*probes) != 1 {
t.Fatalf("expected one probe, got %d", len(*probes))
}
want := probeCall{"tun", "192.168.100.2", "192.168.100.1"}
if (*probes)[0] != want {
t.Errorf("probe = %+v, want %+v", (*probes)[0], want)
}
}
func TestConfigureSystemDNSAppliesResolvconf(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !t1.systemDNSSet {
t.Fatal("systemDNSSet should be true after a successful takeover")
}
want := "-a tun7 -x <nameserver 192.168.100.1\n>"
if got := joined(*calls); got != want {
t.Errorf("resolvconf calls = %q, want %q", got, want)
}
}
// resolvconf exits 0 with resolvconf=NO in resolvconf.conf, and still records
// the entry for the interface, but runs no subscriber, so success has to be
// confirmed in what the subscribers wrote.
func TestConfigureSystemDNSRefusesWhenResolvconfDidNotApply(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": untouched})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
t.Fatal("expected an error when the nameserver did not reach a resolver")
}
if t1.systemDNSSet {
t.Error("systemDNSSet must stay false when the takeover did not take")
}
if !strings.HasSuffix(joined(*calls), "-d tun7") {
t.Errorf("expected a removal after the failed check, got %q", joined(*calls))
}
}
func TestConfigureSystemDNSIdempotent(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
before := len(*calls)
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(*calls) != before {
t.Errorf("second call must be a no-op, calls went %d -> %d", before, len(*calls))
}
}
func TestConfigureSystemDNSAddFailureIsNotDirty(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "-a")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
t.Fatal("expected an error when resolvconf -a fails")
}
if t1.systemDNSSet || t1.systemDNSDirty {
t.Error("a failed add leaves nothing to clean up")
}
if len(*calls) != 1 {
t.Errorf("nothing else may run after a failed add, got %q", joined(*calls))
}
}
// If the removal after a failed check fails too, the entry may still be
// installed, so the state has to be remembered rather than silently dropped.
func TestConfigureSystemDNSRollbackFailureKeepsDirty(t *testing.T) {
stubDNSRouting(t, nil)
recorder(t, "-d")
files(t, map[string]string{"/etc/resolv.conf": untouched})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
t.Fatal("expected an error when the check fails")
}
if !t1.systemDNSDirty {
t.Error("a failed removal must leave the resolver marked dirty")
}
if t1.systemDNSSet {
t.Error("systemDNSSet must stay false when the takeover did not complete")
}
}
// A dirty resolver is retried before anything new is applied.
func TestConfigureSystemDNSRetriesDirtyBeforeApplying(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
t1.systemDNSDirty = true
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
got := joined(*calls)
if !strings.HasPrefix(got, "-d tun7 | -a tun7") {
t.Errorf("expected the stale removal first, got %q", got)
}
if t1.systemDNSDirty {
t.Error("a successful retry should clear the dirty flag")
}
if !t1.systemDNSSet {
t.Error("the takeover should proceed once the retry succeeds")
}
}
func TestUnsetSystemDNSRemoves(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("setup failed: %v", err)
}
*calls = nil
t1.unsetSystemDNS()
if t1.systemDNSSet {
t.Error("systemDNSSet should be false after unset")
}
if got := joined(*calls); got != "-d tun7" {
t.Errorf("unset calls = %q, want %q", got, "-d tun7")
}
t1.unsetSystemDNS()
if len(*calls) != 1 {
t.Errorf("unsetSystemDNS must be idempotent, got %q", joined(*calls))
}
}
func TestUnsetSystemDNSKeepsDirtyWhenRemoveFails(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "-d")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
t1.systemDNSSet = true
t1.unsetSystemDNS()
if !t1.systemDNSDirty {
t.Error("a failed removal during unset must be remembered")
}
if got := joined(*calls); got != "-d tun7" {
t.Errorf("expected a removal attempt, got %q", got)
}
}
func TestResolvconfAppliedLibc(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": takenOver})
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
t.Errorf("resolv.conf listing the nameserver must count as applied, got %v, %v", ok, err)
}
}
func TestResolvconfAppliedNotWhenUntouched(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": untouched})
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || ok {
t.Errorf("an unchanged resolv.conf and no resolvconf.conf must not count as applied, got %v, %v", ok, err)
}
}
// With inclusive_interfaces in resolvconf.conf the exclusive marking is
// ignored and the DHCP nameservers stay listed, so the system falls back to
// them; that is the leak the option exists to close, and it must not pass.
func TestResolvconfAppliedNotWhenOthersRemain(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.1\nnameserver 10.0.0.1\n"})
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
t.Error("another nameserver alongside the TUN's must not count as applied")
}
}
// A loopback nameserver alongside is a local resolver that resolvconf feeds
// (local_unbound with the libc subscriber left on), not a leak.
func TestResolvconfAppliedWithLoopbackAlongside(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": "nameserver 127.0.0.1\nnameserver 192.168.100.1\n"})
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
t.Errorf("a loopback nameserver alongside must still count as applied, got %v, %v", ok, err)
}
}
func TestResolvconfAppliedIgnoresPrefixMatches(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.10\n"})
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
t.Error("192.168.100.10 must not match 192.168.100.1")
}
}
// local-unbound-setup turns the libc subscriber off and has resolvconf write
// unbound's forwarders instead; resolv.conf then stays pointed at loopback.
func TestResolvconfAppliedUnbound(t *testing.T) {
files(t, map[string]string{
"/etc/resolv.conf": "# Generated by resolvconf\nnameserver 127.0.0.1\noptions edns0\n",
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 192.168.100.1\n",
})
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
t.Errorf("the nameserver in unbound's forwarders must count as applied, got %v, %v", ok, err)
}
}
func TestResolvconfAppliedNotWhenUnboundUntouched(t *testing.T) {
files(t, map[string]string{
"/etc/resolv.conf": "nameserver 127.0.0.1\n",
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 10.0.0.1\n",
})
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
t.Error("unbound still forwarding to the old server must not count as applied")
}
}
func TestResolvconfAppliedReportsUnreadableResolvConf(t *testing.T) {
files(t, map[string]string{})
if _, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err == nil {
t.Error("a missing resolv.conf is an error, not a verdict")
}
}
+382
View File
@@ -3,7 +3,11 @@
package tun package tun
import ( import (
"context"
"errors"
"io/fs"
"net/netip" "net/netip"
"strings"
"testing" "testing"
"golang.org/x/net/route" "golang.org/x/net/route"
@@ -148,3 +152,381 @@ func TestDefaultRouteFamilyRejectsShortAddrs(t *testing.T) {
t.Fatal("message without addresses must not match") t.Fatal("message without addresses must not match")
} }
} }
type probeCall struct {
inboundTag string
source string
address string
}
// stubDNSRouting replaces the routing probe for the duration of a test and
// records how it was called, so tests can assert the probe is representative.
func stubDNSRouting(t *testing.T, err error) *[]probeCall {
t.Helper()
original := verifyDNSRouting
calls := []probeCall{}
verifyDNSRouting = func(_ context.Context, inboundTag, source, address string) error {
calls = append(calls, probeCall{inboundTag, source, address})
return err
}
t.Cleanup(func() { verifyDNSRouting = original })
return &calls
}
// recorder installs a resolvconf stub for the duration of a test and returns
// the captured invocations, each as the arguments followed by the stdin in
// angle brackets when there was one. An empty failOn succeeds every call;
// otherwise the named subcommand fails.
func recorder(t *testing.T, failOn string) *[]string {
t.Helper()
original := resolvconfRunner
calls := []string{}
resolvconfRunner = func(stdin string, args ...string) ([]byte, error) {
call := strings.Join(args, " ")
if stdin != "" {
call += " <" + stdin + ">"
}
calls = append(calls, call)
if failOn != "" && len(args) > 0 && args[0] == failOn {
return nil, errors.New("boom")
}
return nil, nil
}
t.Cleanup(func() { resolvconfRunner = original })
return &calls
}
// files replaces the resolver files read by the applied check for the
// duration of a test. A path not in the map does not exist.
func files(t *testing.T, contents map[string]string) {
t.Helper()
original := readResolverFile
readResolverFile = func(path string) ([]byte, error) {
if data, ok := contents[path]; ok {
return []byte(data), nil
}
return nil, fs.ErrNotExist
}
t.Cleanup(func() { readResolverFile = original })
}
// takenOver is what the libc subscriber writes once the TUN's nameserver is
// the exclusive one.
const takenOver = "# Generated by resolvconf\nnameserver 192.168.100.1\n"
// untouched is the DHCP-supplied resolv.conf that resolvconf=NO leaves in
// place.
const untouched = "# Generated by resolvconf\nnameserver 10.0.0.1\n"
func optedInTun() *FreeBSDTun {
return &FreeBSDTun{
options: &Config{
Name: "tun7",
Gateway: []string{"192.168.100.1/30"},
AutoSystemDnsToGateway: true,
},
name: "tun7",
gateway: netip.MustParsePrefix("192.168.100.1/30"),
local: netip.MustParseAddr("192.168.100.2"),
}
}
func joined(calls []string) string {
return strings.Join(calls, " | ")
}
func TestConfigureSystemDNSDisabledByDefault(t *testing.T) {
probes := stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
t1.options.AutoSystemDnsToGateway = false
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(*calls) != 0 || len(*probes) != 0 {
t.Errorf("nothing may run when the option is off, got %q and %d probes", joined(*calls), len(*probes))
}
if t1.systemDNSSet {
t.Error("systemDNSSet must stay false when the option is off")
}
}
func TestConfigureSystemDNSLeavesOSDNSWhenNoRoute(t *testing.T) {
stubDNSRouting(t, errors.New("no route"))
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
t.Fatal("expected an error when the probe fails")
}
if len(*calls) != 0 {
t.Errorf("resolvconf must not run when the probe fails, got %q", joined(*calls))
}
if t1.systemDNSSet {
t.Error("systemDNSSet must stay false when the probe fails")
}
}
// On FreeBSD the addresses are the other way round from Linux: the local
// address is the one after the gateway, and the gateway itself has no owner,
// so a packet to it is routed into the TUN. The probe has to carry that pair,
// and the resolver has to be pointed at the gateway.
func TestConfigureSystemDNSProbeCarriesFreeBSDPair(t *testing.T) {
probes := stubDNSRouting(t, nil)
recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(*probes) != 1 {
t.Fatalf("expected one probe, got %d", len(*probes))
}
want := probeCall{"tun", "192.168.100.2", "192.168.100.1"}
if (*probes)[0] != want {
t.Errorf("probe = %+v, want %+v", (*probes)[0], want)
}
}
func TestConfigureSystemDNSAppliesResolvconf(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !t1.systemDNSSet {
t.Fatal("systemDNSSet should be true after a successful takeover")
}
want := "-a tun7 -x <nameserver 192.168.100.1\n>"
if got := joined(*calls); got != want {
t.Errorf("resolvconf calls = %q, want %q", got, want)
}
}
// resolvconf exits 0 with resolvconf=NO in resolvconf.conf, and still records
// the entry for the interface, but runs no subscriber, so success has to be
// confirmed in what the subscribers wrote.
func TestConfigureSystemDNSRefusesWhenResolvconfDidNotApply(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": untouched})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
t.Fatal("expected an error when the nameserver did not reach a resolver")
}
if t1.systemDNSSet {
t.Error("systemDNSSet must stay false when the takeover did not take")
}
if !strings.HasSuffix(joined(*calls), "-d tun7") {
t.Errorf("expected a removal after the failed check, got %q", joined(*calls))
}
}
func TestConfigureSystemDNSIdempotent(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
before := len(*calls)
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(*calls) != before {
t.Errorf("second call must be a no-op, calls went %d -> %d", before, len(*calls))
}
}
func TestConfigureSystemDNSAddFailureIsNotDirty(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "-a")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
t.Fatal("expected an error when resolvconf -a fails")
}
if t1.systemDNSSet || t1.systemDNSDirty {
t.Error("a failed add leaves nothing to clean up")
}
if len(*calls) != 1 {
t.Errorf("nothing else may run after a failed add, got %q", joined(*calls))
}
}
// If the removal after a failed check fails too, the entry may still be
// installed, so the state has to be remembered rather than silently dropped.
func TestConfigureSystemDNSRollbackFailureKeepsDirty(t *testing.T) {
stubDNSRouting(t, nil)
recorder(t, "-d")
files(t, map[string]string{"/etc/resolv.conf": untouched})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
t.Fatal("expected an error when the check fails")
}
if !t1.systemDNSDirty {
t.Error("a failed removal must leave the resolver marked dirty")
}
if t1.systemDNSSet {
t.Error("systemDNSSet must stay false when the takeover did not complete")
}
}
// A dirty resolver is retried before anything new is applied.
func TestConfigureSystemDNSRetriesDirtyBeforeApplying(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
t1.systemDNSDirty = true
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
got := joined(*calls)
if !strings.HasPrefix(got, "-d tun7 | -a tun7") {
t.Errorf("expected the stale removal first, got %q", got)
}
if t1.systemDNSDirty {
t.Error("a successful retry should clear the dirty flag")
}
if !t1.systemDNSSet {
t.Error("the takeover should proceed once the retry succeeds")
}
}
func TestUnsetSystemDNSRemoves(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("setup failed: %v", err)
}
*calls = nil
t1.unsetSystemDNS()
if t1.systemDNSSet {
t.Error("systemDNSSet should be false after unset")
}
if got := joined(*calls); got != "-d tun7" {
t.Errorf("unset calls = %q, want %q", got, "-d tun7")
}
t1.unsetSystemDNS()
if len(*calls) != 1 {
t.Errorf("unsetSystemDNS must be idempotent, got %q", joined(*calls))
}
}
func TestUnsetSystemDNSKeepsDirtyWhenRemoveFails(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "-d")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
t1.systemDNSSet = true
t1.unsetSystemDNS()
if !t1.systemDNSDirty {
t.Error("a failed removal during unset must be remembered")
}
if got := joined(*calls); got != "-d tun7" {
t.Errorf("expected a removal attempt, got %q", got)
}
}
func TestResolvconfAppliedLibc(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": takenOver})
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
t.Errorf("resolv.conf listing the nameserver must count as applied, got %v, %v", ok, err)
}
}
func TestResolvconfAppliedNotWhenUntouched(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": untouched})
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || ok {
t.Errorf("an unchanged resolv.conf and no resolvconf.conf must not count as applied, got %v, %v", ok, err)
}
}
// With inclusive_interfaces in resolvconf.conf the exclusive marking is
// ignored and the DHCP nameservers stay listed, so the system falls back to
// them; that is the leak the option exists to close, and it must not pass.
func TestResolvconfAppliedNotWhenOthersRemain(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.1\nnameserver 10.0.0.1\n"})
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
t.Error("another nameserver alongside the TUN's must not count as applied")
}
}
// A loopback nameserver alongside is a local resolver that resolvconf feeds
// (local_unbound with the libc subscriber left on), not a leak.
func TestResolvconfAppliedWithLoopbackAlongside(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": "nameserver 127.0.0.1\nnameserver 192.168.100.1\n"})
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
t.Errorf("a loopback nameserver alongside must still count as applied, got %v, %v", ok, err)
}
}
func TestResolvconfAppliedIgnoresPrefixMatches(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.10\n"})
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
t.Error("192.168.100.10 must not match 192.168.100.1")
}
}
// local-unbound-setup turns the libc subscriber off and has resolvconf write
// unbound's forwarders instead; resolv.conf then stays pointed at loopback.
func TestResolvconfAppliedUnbound(t *testing.T) {
files(t, map[string]string{
"/etc/resolv.conf": "# Generated by resolvconf\nnameserver 127.0.0.1\noptions edns0\n",
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 192.168.100.1\n",
})
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
t.Errorf("the nameserver in unbound's forwarders must count as applied, got %v, %v", ok, err)
}
}
func TestResolvconfAppliedNotWhenUnboundUntouched(t *testing.T) {
files(t, map[string]string{
"/etc/resolv.conf": "nameserver 127.0.0.1\n",
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 10.0.0.1\n",
})
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
t.Error("unbound still forwarding to the old server must not count as applied")
}
}
func TestResolvconfAppliedReportsUnreadableResolvConf(t *testing.T) {
files(t, map[string]string{})
if _, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err == nil {
t.Error("a missing resolv.conf is an error, not a verdict")
}
}
-204
View File
@@ -1,204 +0,0 @@
//go:build linux && !android
package tun
import (
"context"
"strings"
"testing"
"github.com/xtls/xray-core/app/dispatcher"
appdns "github.com/xtls/xray-core/app/dns"
"github.com/xtls/xray-core/app/proxyman"
_ "github.com/xtls/xray-core/app/proxyman/inbound"
_ "github.com/xtls/xray-core/app/proxyman/outbound"
"github.com/xtls/xray-core/app/router"
"github.com/xtls/xray-core/common/geodata"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/core"
proxydns "github.com/xtls/xray-core/proxy/dns"
"github.com/xtls/xray-core/proxy/freedom"
)
const (
routeTestInboundTag = "tun"
routeTestSource = "192.168.100.1"
routeTestDNSAddress = "192.168.100.2"
)
// port53Rule sends DNS queries arriving from the interface to the dns outbound.
func port53Rule() *router.RoutingRule {
return &router.RoutingRule{
InboundTag: []string{routeTestInboundTag},
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(53)}},
TargetTag: &router.RoutingRule_Tag{Tag: "dns"},
}
}
// sourceBlockRule diverts traffic from one address, which is the shape of a rule
// that only matches because the real request carries a source.
func sourceBlockRule(ip []byte) *router.RoutingRule {
return &router.RoutingRule{
SourceIp: []*geodata.IPRule{{
Value: &geodata.IPRule_Custom{
Custom: &geodata.CIDRRule{
Cidr: &geodata.CIDR{Ip: ip, Prefix: 32},
},
},
}},
TargetTag: &router.RoutingRule_Tag{Tag: "block"},
}
}
// newRouteTestContext builds a real but unstarted instance: no TUN device, no
// running resolver. The instance is placed in the context through the key core
// exports for tests.
func newRouteTestContext(t *testing.T, withDNSApp bool, nameServers []*appdns.NameServer, rules []*router.RoutingRule) context.Context {
t.Helper()
apps := []*serial.TypedMessage{
serial.ToTypedMessage(&dispatcher.Config{}),
serial.ToTypedMessage(&proxyman.InboundConfig{}),
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
serial.ToTypedMessage(&router.Config{Rule: rules}),
}
if withDNSApp {
apps = append(apps, serial.ToTypedMessage(&appdns.Config{NameServer: nameServers}))
}
instance, err := core.New(&core.Config{
App: apps,
Outbound: []*core.OutboundHandlerConfig{
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})},
{Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})},
{Tag: "block", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
},
})
if err != nil {
t.Fatalf("core.New: %v", err)
}
t.Cleanup(func() { _ = instance.Close() })
return context.WithValue(context.Background(), core.XrayKey(1), instance)
}
func udpNameServer(ip []byte) []*appdns.NameServer {
return []*appdns.NameServer{{
Address: &net.Endpoint{
Network: net.Network_UDP,
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Ip{Ip: ip}},
Port: 53,
},
}}
}
// localNameServer is a name server pointed at "localhost", which app/dns
// resolves through the system resolver.
func localNameServer() *appdns.NameServer {
return &appdns.NameServer{
Address: &net.Endpoint{
Network: net.Network_UDP,
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Domain{Domain: "localhost"}},
Port: 53,
},
}
}
// These drive the real feature lookup and the real router. verifyDNSRouting is
// the same function ConfigureSystemDNS calls, so a false positive here is a
// false positive in the takeover decision itself, which is what assertions on
// the resolvectl arguments could never catch.
func TestVerifyDNSRoutingDecisions(t *testing.T) {
tests := []struct {
name string
withDNSApp bool
nameServers []*appdns.NameServer
rules []*router.RoutingRule
wantErr string
}{
{
name: "independent upstream reaches the dns outbound",
withDNSApp: true,
nameServers: udpNameServer([]byte{9, 9, 9, 9}),
rules: []*router.RoutingRule{port53Rule()},
wantErr: "",
},
{
name: "no dns section falls back to the system resolver",
rules: []*router.RoutingRule{port53Rule()},
wantErr: "system resolver",
},
{
name: "dns section without name servers falls back too",
withDNSApp: true,
rules: []*router.RoutingRule{port53Rule()},
wantErr: "system resolver",
},
{
// An independent upstream is not enough on its own: name servers are
// selected per domain, so a local one can still be the one chosen.
// The refusal is deliberately domain-agnostic for that reason.
name: "a local name server alongside an independent one",
withDNSApp: true,
nameServers: append(udpNameServer([]byte{9, 9, 9, 9}), localNameServer()),
rules: []*router.RoutingRule{port53Rule()},
wantErr: "system resolver",
},
{
name: "a rule on the interface address diverts the real query",
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
rules: []*router.RoutingRule{
sourceBlockRule([]byte{192, 168, 100, 1}),
port53Rule(),
},
wantErr: "does not handle DNS",
},
{
name: "a rule on another address does not match it",
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
rules: []*router.RoutingRule{
sourceBlockRule([]byte{10, 0, 0, 1}),
port53Rule(),
},
wantErr: "",
},
{
name: "no rule matches the query",
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
wantErr: "no route",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := newRouteTestContext(t, tt.withDNSApp, tt.nameServers, tt.rules)
err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, routeTestDNSAddress)
if tt.wantErr == "" {
if err != nil {
t.Fatalf("expected the takeover to be accepted, got: %v", err)
}
return
}
if err == nil {
t.Fatalf("expected the takeover to be refused with %q, got nil", tt.wantErr)
}
if !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("error = %q, want it to contain %q", err.Error(), tt.wantErr)
}
})
}
}
// Without an IPv4 gateway, the takeover uses the first IPv6 one, and the probe
// carries IPv6 addresses.
func TestVerifyDNSRoutingIPv6(t *testing.T) {
ctx := newRouteTestContext(t, true, udpNameServer([]byte{9, 9, 9, 9}), []*router.RoutingRule{port53Rule()})
if err := verifyDNSRouting(ctx, routeTestInboundTag, "fc00::1", "fc00::2"); err != nil {
t.Fatalf("expected the takeover to be accepted, got: %v", err)
}
if err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, "fc00::2"); err == nil {
t.Fatal("expected mixed IPv4 and IPv6 addresses to be refused")
}
}
@@ -9,6 +9,18 @@ import (
"testing" "testing"
"github.com/vishvananda/netlink" "github.com/vishvananda/netlink"
"github.com/xtls/xray-core/app/dispatcher"
appdns "github.com/xtls/xray-core/app/dns"
"github.com/xtls/xray-core/app/proxyman"
_ "github.com/xtls/xray-core/app/proxyman/inbound"
_ "github.com/xtls/xray-core/app/proxyman/outbound"
"github.com/xtls/xray-core/app/router"
"github.com/xtls/xray-core/common/geodata"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/core"
proxydns "github.com/xtls/xray-core/proxy/dns"
"github.com/xtls/xray-core/proxy/freedom"
) )
// testLink returns a minimal netlink.Link whose Attrs().Name is name, so the // testLink returns a minimal netlink.Link whose Attrs().Name is name, so the
@@ -443,3 +455,185 @@ func TestBuildResolvectlArgs(t *testing.T) {
}) })
} }
} }
const (
routeTestInboundTag = "tun"
routeTestSource = "192.168.100.1"
routeTestDNSAddress = "192.168.100.2"
)
// port53Rule sends DNS queries arriving from the interface to the dns outbound.
func port53Rule() *router.RoutingRule {
return &router.RoutingRule{
InboundTag: []string{routeTestInboundTag},
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(53)}},
TargetTag: &router.RoutingRule_Tag{Tag: "dns"},
}
}
// sourceBlockRule diverts traffic from one address, which is the shape of a rule
// that only matches because the real request carries a source.
func sourceBlockRule(ip []byte) *router.RoutingRule {
return &router.RoutingRule{
SourceIp: []*geodata.IPRule{{
Value: &geodata.IPRule_Custom{
Custom: &geodata.CIDRRule{
Cidr: &geodata.CIDR{Ip: ip, Prefix: 32},
},
},
}},
TargetTag: &router.RoutingRule_Tag{Tag: "block"},
}
}
// newRouteTestContext builds a real but unstarted instance: no TUN device, no
// running resolver. The instance is placed in the context through the key core
// exports for tests.
func newRouteTestContext(t *testing.T, withDNSApp bool, nameServers []*appdns.NameServer, rules []*router.RoutingRule) context.Context {
t.Helper()
apps := []*serial.TypedMessage{
serial.ToTypedMessage(&dispatcher.Config{}),
serial.ToTypedMessage(&proxyman.InboundConfig{}),
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
serial.ToTypedMessage(&router.Config{Rule: rules}),
}
if withDNSApp {
apps = append(apps, serial.ToTypedMessage(&appdns.Config{NameServer: nameServers}))
}
instance, err := core.New(&core.Config{
App: apps,
Outbound: []*core.OutboundHandlerConfig{
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})},
{Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})},
{Tag: "block", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
},
})
if err != nil {
t.Fatalf("core.New: %v", err)
}
t.Cleanup(func() { _ = instance.Close() })
return context.WithValue(context.Background(), core.XrayKey(1), instance)
}
func udpNameServer(ip []byte) []*appdns.NameServer {
return []*appdns.NameServer{{
Address: &net.Endpoint{
Network: net.Network_UDP,
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Ip{Ip: ip}},
Port: 53,
},
}}
}
// localNameServer is a name server pointed at "localhost", which app/dns
// resolves through the system resolver.
func localNameServer() *appdns.NameServer {
return &appdns.NameServer{
Address: &net.Endpoint{
Network: net.Network_UDP,
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Domain{Domain: "localhost"}},
Port: 53,
},
}
}
// These drive the real feature lookup and the real router. verifyDNSRouting is
// the same function ConfigureSystemDNS calls, so a false positive here is a
// false positive in the takeover decision itself, which is what assertions on
// the resolvectl arguments could never catch.
func TestVerifyDNSRoutingDecisions(t *testing.T) {
tests := []struct {
name string
withDNSApp bool
nameServers []*appdns.NameServer
rules []*router.RoutingRule
wantErr string
}{
{
name: "independent upstream reaches the dns outbound",
withDNSApp: true,
nameServers: udpNameServer([]byte{9, 9, 9, 9}),
rules: []*router.RoutingRule{port53Rule()},
wantErr: "",
},
{
name: "no dns section falls back to the system resolver",
rules: []*router.RoutingRule{port53Rule()},
wantErr: "system resolver",
},
{
name: "dns section without name servers falls back too",
withDNSApp: true,
rules: []*router.RoutingRule{port53Rule()},
wantErr: "system resolver",
},
{
// An independent upstream is not enough on its own: name servers are
// selected per domain, so a local one can still be the one chosen.
// The refusal is deliberately domain-agnostic for that reason.
name: "a local name server alongside an independent one",
withDNSApp: true,
nameServers: append(udpNameServer([]byte{9, 9, 9, 9}), localNameServer()),
rules: []*router.RoutingRule{port53Rule()},
wantErr: "system resolver",
},
{
name: "a rule on the interface address diverts the real query",
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
rules: []*router.RoutingRule{
sourceBlockRule([]byte{192, 168, 100, 1}),
port53Rule(),
},
wantErr: "does not handle DNS",
},
{
name: "a rule on another address does not match it",
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
rules: []*router.RoutingRule{
sourceBlockRule([]byte{10, 0, 0, 1}),
port53Rule(),
},
wantErr: "",
},
{
name: "no rule matches the query",
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
wantErr: "no route",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := newRouteTestContext(t, tt.withDNSApp, tt.nameServers, tt.rules)
err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, routeTestDNSAddress)
if tt.wantErr == "" {
if err != nil {
t.Fatalf("expected the takeover to be accepted, got: %v", err)
}
return
}
if err == nil {
t.Fatalf("expected the takeover to be refused with %q, got nil", tt.wantErr)
}
if !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("error = %q, want it to contain %q", err.Error(), tt.wantErr)
}
})
}
}
// Without an IPv4 gateway, the takeover uses the first IPv6 one, and the probe
// carries IPv6 addresses.
func TestVerifyDNSRoutingIPv6(t *testing.T) {
ctx := newRouteTestContext(t, true, udpNameServer([]byte{9, 9, 9, 9}), []*router.RoutingRule{port53Rule()})
if err := verifyDNSRouting(ctx, routeTestInboundTag, "fc00::1", "fc00::2"); err != nil {
t.Fatalf("expected the takeover to be accepted, got: %v", err)
}
if err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, "fc00::2"); err == nil {
t.Fatal("expected mixed IPv4 and IPv6 addresses to be refused")
}
}
+134 -5
View File
@@ -59,7 +59,7 @@ var _ Tun = (*WindowsTun)(nil)
// interface with the same name exist, it tried to be reused. // interface with the same name exist, it tried to be reused.
func NewTun(options *Config) (Tun, error) { func NewTun(options *Config) (Tun, error) {
// instantiate wintun adapter // instantiate wintun adapter
adapter, err := open(options.Name, options.Desc) adapter, err := open(options.Name, options.Desc, options.GUID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -82,10 +82,11 @@ func NewTun(options *Config) (Tun, error) {
return tun, nil return tun, nil
} }
func open(name, desc string) (*wintun.Adapter, error) { func open(name, desc, id string) (*wintun.Adapter, error) {
// generate a deterministic GUID from the adapter name guid, err := adapterGUID(name, id)
id := md5.Sum([]byte(name)) if err != nil {
guid := (*windows.GUID)(unsafe.Pointer(&id[0])) return nil, err
}
// try to open existing adapter by name // try to open existing adapter by name
adapter, err := wintun.OpenAdapter(name) adapter, err := wintun.OpenAdapter(name)
if err == nil { if err == nil {
@@ -99,6 +100,28 @@ func open(name, desc string) (*wintun.Adapter, error) {
return nil, err return nil, err
} }
// adapterGUID returns the GUID that an adapter created with the given name is
// to have: the configured one, if there is one, or else one derived from the name.
func adapterGUID(name, id string) (*windows.GUID, error) {
if id == "" {
// generate a deterministic GUID from the adapter name
sum := md5.Sum([]byte(name))
return (*windows.GUID)(unsafe.Pointer(&sum[0])), nil
}
raw, err := ParseGUID(id)
if err != nil {
return nil, err
}
// the groups are the field values, big-endian in the canonical bytes; Windows
// holds them little-endian in memory, which the fields take care of
return &windows.GUID{
Data1: binary.BigEndian.Uint32(raw[0:4]),
Data2: binary.BigEndian.Uint16(raw[4:6]),
Data3: binary.BigEndian.Uint16(raw[6:8]),
Data4: [8]byte(raw[8:16]),
}, nil
}
// ipv6Off tells whether DisabledComponents turns IPv6 off on the non-tunnel // ipv6Off tells whether DisabledComponents turns IPv6 off on the non-tunnel
// interfaces (0x10, as 0xFF does), the TUN among them. Windows applies it at // interfaces (0x10, as 0xFF does), the TUN among them. Windows applies it at
// boot only. // boot only.
@@ -687,3 +710,109 @@ func findOutboundInterface(tunIndex int, fixedName string) (*net.Interface, erro
} }
return net.InterfaceByIndex(int(index)) return net.InterfaceByIndex(int(index))
} }
// outboundGuard keeps Windows to the binding of autoOutboundsInterface, which
// keeps Xray's own connections out of the TUN. With weak host send or
// forwarding on for an IP version on the bound interface, Windows sends them
// where the routes lead, into the TUN, from that interface's address, and
// drops what comes back to that address through the TUN, so they stall.
//
// For the IP versions routed to the TUN, weak host send is turned off on the
// bound interface while the TUN runs, and turned on again when the TUN stops
// or another interface takes over. Forwarding is what Mobile Hotspot and
// Internet Connection Sharing need, so it is only reported.
type outboundGuard struct {
sync.Mutex
families []winipcfg.AddressFamily
luid winipcfg.LUID // of the interface last checked
name string // of that interface
turnedOff []winipcfg.AddressFamily // where weak host send was turned off on it
forwarding bool // whether forwarding was on there
stopped bool
}
// check turns weak host send off on the bound interface, and warns when
// forwarding comes on there, but not again while it stays on.
func (g *outboundGuard) check() {
g.Lock()
defer g.Unlock()
if g.stopped {
return
}
var luid winipcfg.LUID
var name string
if iface := updater.Get(); iface != nil {
luid, _ = winipcfg.LUIDFromIndex(uint32(iface.Index))
name = iface.Name
}
if luid != g.luid {
g.restoreLocked()
g.luid, g.name = luid, name
g.forwarding = false // to warn about the new interface as well
}
if luid == 0 {
return
}
var forwarding []string
for _, family := range g.families {
row, err := luid.IPInterface(family)
if err != nil {
continue // the interface lacks that IP version
}
if row.ForwardingEnabled {
forwarding = append(forwarding, familyName(family))
}
if !row.WeakHostSend {
continue
}
if err := setWeakHostSend(row, false); err != nil {
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send off for ", familyName(family), " on ", name)
continue
}
if !slices.Contains(g.turnedOff, family) {
g.turnedOff = append(g.turnedOff, family)
errors.LogInfo(context.Background(), "[tun] weak host send turned off for ", familyName(family), " on ", name, " while the TUN runs, as Windows would ignore autoOutboundsInterface")
}
}
wasOn := g.forwarding
g.forwarding = len(forwarding) > 0
if g.forwarding && !wasOn {
errors.LogWarning(context.Background(), "[tun] forwarding is on for ", strings.Join(forwarding, " and "), " on ", name, " (Mobile Hotspot and Internet Connection Sharing turn it on), so Windows ignores autoOutboundsInterface there, and Xray's own connections go into the TUN and stall: turn the hotspot off, or have it share the TUN instead of ", name)
}
}
// restore turns weak host send on again where check turned it off, for good.
func (g *outboundGuard) restore() {
g.Lock()
defer g.Unlock()
g.restoreLocked()
g.stopped = true
}
func (g *outboundGuard) restoreLocked() {
for _, family := range g.turnedOff {
row, err := g.luid.IPInterface(family)
if err == nil {
err = setWeakHostSend(row, true)
}
if err != nil {
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send on again for ", familyName(family), " on ", g.name)
}
}
g.turnedOff = nil
}
func setWeakHostSend(row *winipcfg.MibIPInterfaceRow, on bool) error {
row.WeakHostSend = on
if row.Family == windows.AF_INET {
row.SitePrefixLength = 0 // as SetIpInterfaceEntry requires for IPv4
}
return row.Set()
}
func familyName(family winipcfg.AddressFamily) string {
if family == windows.AF_INET {
return "IPv4"
}
return "IPv6"
}
-120
View File
@@ -1,120 +0,0 @@
//go:build windows
package tun
import (
"context"
"slices"
"strings"
"sync"
"github.com/xtls/xray-core/common/errors"
"golang.org/x/sys/windows"
"golang.zx2c4.com/wireguard/windows/tunnel/winipcfg"
)
// outboundGuard keeps Windows to the binding of autoOutboundsInterface, which
// keeps Xray's own connections out of the TUN. With weak host send or
// forwarding on for an IP version on the bound interface, Windows sends them
// where the routes lead, into the TUN, from that interface's address, and
// drops what comes back to that address through the TUN, so they stall.
//
// For the IP versions routed to the TUN, weak host send is turned off on the
// bound interface while the TUN runs, and turned on again when the TUN stops
// or another interface takes over. Forwarding is what Mobile Hotspot and
// Internet Connection Sharing need, so it is only reported.
type outboundGuard struct {
sync.Mutex
families []winipcfg.AddressFamily
luid winipcfg.LUID // of the interface last checked
name string // of that interface
turnedOff []winipcfg.AddressFamily // where weak host send was turned off on it
forwarding bool // whether forwarding was on there
stopped bool
}
// check turns weak host send off on the bound interface, and warns when
// forwarding comes on there, but not again while it stays on.
func (g *outboundGuard) check() {
g.Lock()
defer g.Unlock()
if g.stopped {
return
}
var luid winipcfg.LUID
var name string
if iface := updater.Get(); iface != nil {
luid, _ = winipcfg.LUIDFromIndex(uint32(iface.Index))
name = iface.Name
}
if luid != g.luid {
g.restoreLocked()
g.luid, g.name = luid, name
g.forwarding = false // to warn about the new interface as well
}
if luid == 0 {
return
}
var forwarding []string
for _, family := range g.families {
row, err := luid.IPInterface(family)
if err != nil {
continue // the interface lacks that IP version
}
if row.ForwardingEnabled {
forwarding = append(forwarding, familyName(family))
}
if !row.WeakHostSend {
continue
}
if err := setWeakHostSend(row, false); err != nil {
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send off for ", familyName(family), " on ", name)
continue
}
if !slices.Contains(g.turnedOff, family) {
g.turnedOff = append(g.turnedOff, family)
errors.LogInfo(context.Background(), "[tun] weak host send turned off for ", familyName(family), " on ", name, " while the TUN runs, as Windows would ignore autoOutboundsInterface")
}
}
wasOn := g.forwarding
g.forwarding = len(forwarding) > 0
if g.forwarding && !wasOn {
errors.LogWarning(context.Background(), "[tun] forwarding is on for ", strings.Join(forwarding, " and "), " on ", name, " (Mobile Hotspot and Internet Connection Sharing turn it on), so Windows ignores autoOutboundsInterface there, and Xray's own connections go into the TUN and stall: turn the hotspot off, or have it share the TUN instead of ", name)
}
}
// restore turns weak host send on again where check turned it off, for good.
func (g *outboundGuard) restore() {
g.Lock()
defer g.Unlock()
g.restoreLocked()
g.stopped = true
}
func (g *outboundGuard) restoreLocked() {
for _, family := range g.turnedOff {
row, err := g.luid.IPInterface(family)
if err == nil {
err = setWeakHostSend(row, true)
}
if err != nil {
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send on again for ", familyName(family), " on ", g.name)
}
}
g.turnedOff = nil
}
func setWeakHostSend(row *winipcfg.MibIPInterfaceRow, on bool) error {
row.WeakHostSend = on
if row.Family == windows.AF_INET {
row.SitePrefixLength = 0 // as SetIpInterfaceEntry requires for IPv4
}
return row.Set()
}
func familyName(family winipcfg.AddressFamily) string {
if family == windows.AF_INET {
return "IPv4"
}
return "IPv6"
}
@@ -4,6 +4,7 @@ package tun
import ( import (
"context" "context"
"crypto/md5"
go_errors "errors" go_errors "errors"
"net" "net"
"net/netip" "net/netip"
@@ -340,3 +341,46 @@ func TestFlushDNSCache(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
} }
func TestAdapterGUID(t *testing.T) {
// a configured GUID has to be the adapter GUID the text names: the groups
// are field values, not the bytes of the text in order
guid, err := adapterGUID("xray0", "01020304-0506-0708-090a-0b0c0d0e0f10")
if err != nil {
t.Fatal(err)
}
want := windows.GUID{
Data1: 0x01020304,
Data2: 0x0506,
Data3: 0x0708,
Data4: [8]byte{0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10},
}
if *guid != want {
t.Errorf("adapterGUID = %+v, want %+v", *guid, want)
}
// the same struct Windows builds from that text, and the text Windows shows
// for it
if fromText, err := windows.GUIDFromString("{01020304-0506-0708-090A-0B0C0D0E0F10}"); err != nil {
t.Fatal(err)
} else if *guid != fromText {
t.Errorf("adapterGUID = %s, want %s", guid.String(), fromText.String())
}
if got, want := guid.String(), "{01020304-0506-0708-090A-0B0C0D0E0F10}"; got != want {
t.Errorf("adapterGUID = %s, want %s", got, want)
}
// without one, the bytes of the MD5 of the name, as they always were; that
// GUID is never read back as text, so its byte order does not matter
guid, err = adapterGUID("xray0", "")
if err != nil {
t.Fatal(err)
}
sum := md5.Sum([]byte("xray0"))
if got := unsafe.Slice((*byte)(unsafe.Pointer(guid)), 16); string(got) != string(sum[:]) {
t.Errorf("adapterGUID = %x, want %x", got, sum)
}
if _, err := adapterGUID("xray0", "xray0"); err == nil {
t.Error("an invalid guid was accepted")
}
}
-14
View File
@@ -8,20 +8,6 @@ import (
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
) )
// BenchmarkUDPNewSession measures what one new UDP flow costs the
// inbound while it stays open: QUIC and DNS open many short flows, and each
// one lives until the connection idle timeout.
func BenchmarkUDPNewSession(b *testing.B) {
u := newUdpConnectionHandler(func(conn net.Conn, dest net.Destination) {}, nil)
dst := net.UDPDestination(net.ParseAddress("1.1.1.1"), 443)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
src := net.UDPDestination(net.IPAddress([]byte{10, byte(i >> 16), byte(i >> 8), byte(i)}), net.Port(1024+i%60000))
u.HandlePacket(src, dst, &buf.Buffer{})
}
}
func TestPacketQueueOrderAndClose(t *testing.T) { func TestPacketQueueOrderAndClose(t *testing.T) {
q := newPacketQueue(udpQueueLimit) q := newPacketQueue(udpQueueLimit)
for i := 0; i < 3; i++ { for i := 0; i < 3; i++ {
-82
View File
@@ -1,82 +0,0 @@
package tun
import (
"runtime"
"testing"
"github.com/xtls/xray-core/common/buf"
)
const benchBatch = 64
// Raw cost of queueing and draining a small burst, as one flow's reader does.
func BenchmarkQueueBurstChan(b *testing.B) {
ch := make(chan *buf.Buffer, udpQueueLimit)
p := &buf.Buffer{}
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for j := 0; j < benchBatch; j++ {
ch <- p
}
for j := 0; j < benchBatch; j++ {
<-ch
}
}
}
func BenchmarkQueueBurstPacketQueue(b *testing.B) {
q := newPacketQueue(udpQueueLimit)
p := &buf.Buffer{}
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for j := 0; j < benchBatch; j++ {
q.push(p)
}
for j := 0; j < benchBatch; j++ {
q.pop()
}
}
}
// Producer and consumer on different goroutines; the producer yields when the
// queue is full instead of spinning, like a blocking channel send would.
func BenchmarkQueueStreamChan(b *testing.B) {
ch := make(chan *buf.Buffer, udpQueueLimit)
p := &buf.Buffer{}
done := make(chan struct{})
go func() {
for range ch {
}
close(done)
}()
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
ch <- p
}
close(ch)
<-done
}
func BenchmarkQueueStreamPacketQueue(b *testing.B) {
q := newPacketQueue(udpQueueLimit)
p := &buf.Buffer{}
done := make(chan struct{})
go func() {
for {
if _, ok := q.pop(); !ok {
break
}
}
close(done)
}()
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for !q.push(p) {
runtime.Gosched()
}
}
q.close()
<-done
}
@@ -80,43 +80,3 @@ func TestExpandWfpBlockLeak(t *testing.T) {
} }
} }
} }
func TestLeakCovers(t *testing.T) {
for _, c := range []struct {
value string
protocol string
port uint16
covers bool
}{
{"tcp", "tcp", 1, true},
{"tcp", "udp", 53, false},
{"udp/53", "udp", 53, true},
{"udp/53", "udp", 54, false},
{"tcp/10-20", "tcp", 10, true},
{"tcp/10-20", "tcp", 20, true},
{"tcp/10-20", "tcp", 21, false},
{"tcp/10-20", "tcp", 9, false},
{"53", "udp", 53, true},
{"53", "tcp", 53, true},
{"10-20", "tcp", 15, true},
{"10-20", "udp", 21, false},
{"1.1.1.0/24:udp/53", "udp", 53, true},
{"[::/0]:tcp", "tcp", 443, true},
{"[2001:db8::/32]:53", "tcp", 53, true},
{"0.0.0.0/0:icmp", "udp", 53, false},
{"all", "udp", 53, true},
{"1.1.1.1/32:all", "tcp", 1, true},
{"allexceptlan", "udp", 53, false},
{"misconfigtun", "udp", 53, false},
{"windnsclient", "udp", 53, false},
} {
l, ok := parseLeak(c.value)
if !ok {
t.Errorf("%q was not parsed", c.value)
continue
}
if got := l.covers(c.protocol, c.port); got != c.covers {
t.Errorf("%q covers %s/%d = %v", c.value, c.protocol, c.port, got)
}
}
}
+70 -5
View File
@@ -184,6 +184,66 @@ func (x *Account) GetTestseed() []uint32 {
return nil return nil
} }
type Multiplex struct {
state protoimpl.MessageState `protogen:"open.v1"`
Concurrency int32 `protobuf:"varint,1,opt,name=concurrency,proto3" json:"concurrency,omitempty"`
XudpConcurrency int32 `protobuf:"varint,2,opt,name=xudpConcurrency,proto3" json:"xudpConcurrency,omitempty"`
XudpProxyUDP443 string `protobuf:"bytes,3,opt,name=xudpProxyUDP443,proto3" json:"xudpProxyUDP443,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Multiplex) Reset() {
*x = Multiplex{}
mi := &file_proxy_vless_account_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Multiplex) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Multiplex) ProtoMessage() {}
func (x *Multiplex) ProtoReflect() protoreflect.Message {
mi := &file_proxy_vless_account_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Multiplex.ProtoReflect.Descriptor instead.
func (*Multiplex) Descriptor() ([]byte, []int) {
return file_proxy_vless_account_proto_rawDescGZIP(), []int{2}
}
func (x *Multiplex) GetConcurrency() int32 {
if x != nil {
return x.Concurrency
}
return 0
}
func (x *Multiplex) GetXudpConcurrency() int32 {
if x != nil {
return x.XudpConcurrency
}
return 0
}
func (x *Multiplex) GetXudpProxyUDP443() string {
if x != nil {
return x.XudpProxyUDP443
}
return ""
}
var File_proxy_vless_account_proto protoreflect.FileDescriptor var File_proxy_vless_account_proto protoreflect.FileDescriptor
const file_proxy_vless_account_proto_rawDesc = "" + const file_proxy_vless_account_proto_rawDesc = "" +
@@ -203,7 +263,11 @@ const file_proxy_vless_account_proto_rawDesc = "" +
"\apadding\x18\x06 \x01(\tR\apadding\x123\n" + "\apadding\x18\x06 \x01(\tR\apadding\x123\n" +
"\areverse\x18\a \x01(\v2\x19.xray.proxy.vless.ReverseR\areverse\x12\x18\n" + "\areverse\x18\a \x01(\v2\x19.xray.proxy.vless.ReverseR\areverse\x12\x18\n" +
"\atestpre\x18\b \x01(\rR\atestpre\x12\x1a\n" + "\atestpre\x18\b \x01(\rR\atestpre\x12\x1a\n" +
"\btestseed\x18\t \x03(\rR\btestseedBR\n" + "\btestseed\x18\t \x03(\rR\btestseed\"\x81\x01\n" +
"\tMultiplex\x12 \n" +
"\vconcurrency\x18\x01 \x01(\x05R\vconcurrency\x12(\n" +
"\x0fxudpConcurrency\x18\x02 \x01(\x05R\x0fxudpConcurrency\x12(\n" +
"\x0fxudpProxyUDP443\x18\x03 \x01(\tR\x0fxudpProxyUDP443BR\n" +
"\x14com.xray.proxy.vlessP\x01Z%github.com/xtls/xray-core/proxy/vless\xaa\x02\x10Xray.Proxy.Vlessb\x06proto3" "\x14com.xray.proxy.vlessP\x01Z%github.com/xtls/xray-core/proxy/vless\xaa\x02\x10Xray.Proxy.Vlessb\x06proto3"
var ( var (
@@ -218,14 +282,15 @@ func file_proxy_vless_account_proto_rawDescGZIP() []byte {
return file_proxy_vless_account_proto_rawDescData return file_proxy_vless_account_proto_rawDescData
} }
var file_proxy_vless_account_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_proxy_vless_account_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
var file_proxy_vless_account_proto_goTypes = []any{ var file_proxy_vless_account_proto_goTypes = []any{
(*Reverse)(nil), // 0: xray.proxy.vless.Reverse (*Reverse)(nil), // 0: xray.proxy.vless.Reverse
(*Account)(nil), // 1: xray.proxy.vless.Account (*Account)(nil), // 1: xray.proxy.vless.Account
(*proxyman.SniffingConfig)(nil), // 2: xray.app.proxyman.SniffingConfig (*Multiplex)(nil), // 2: xray.proxy.vless.Multiplex
(*proxyman.SniffingConfig)(nil), // 3: xray.app.proxyman.SniffingConfig
} }
var file_proxy_vless_account_proto_depIdxs = []int32{ var file_proxy_vless_account_proto_depIdxs = []int32{
2, // 0: xray.proxy.vless.Reverse.sniffing:type_name -> xray.app.proxyman.SniffingConfig 3, // 0: xray.proxy.vless.Reverse.sniffing:type_name -> xray.app.proxyman.SniffingConfig
0, // 1: xray.proxy.vless.Account.reverse:type_name -> xray.proxy.vless.Reverse 0, // 1: xray.proxy.vless.Account.reverse:type_name -> xray.proxy.vless.Reverse
2, // [2:2] is the sub-list for method output_type 2, // [2:2] is the sub-list for method output_type
2, // [2:2] is the sub-list for method input_type 2, // [2:2] is the sub-list for method input_type
@@ -245,7 +310,7 @@ func file_proxy_vless_account_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(), GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_vless_account_proto_rawDesc), len(file_proxy_vless_account_proto_rawDesc)), RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_vless_account_proto_rawDesc), len(file_proxy_vless_account_proto_rawDesc)),
NumEnums: 0, NumEnums: 0,
NumMessages: 2, NumMessages: 3,
NumExtensions: 0, NumExtensions: 0,
NumServices: 0, NumServices: 0,
}, },
+6
View File
@@ -29,3 +29,9 @@ message Account {
uint32 testpre = 8; uint32 testpre = 8;
repeated uint32 testseed = 9; repeated uint32 testseed = 9;
} }
message Multiplex {
int32 concurrency = 1;
int32 xudpConcurrency = 2;
string xudpProxyUDP443 = 3;
}
+27 -83
View File
@@ -11,16 +11,13 @@ import (
"time" "time"
"github.com/xtls/xray-core/app/dispatcher" "github.com/xtls/xray-core/app/dispatcher"
"github.com/xtls/xray-core/app/reverse"
"github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/log" "github.com/xtls/xray-core/common/log"
"github.com/xtls/xray-core/common/mux"
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol" "github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/retry" "github.com/xtls/xray-core/common/retry"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/common/signal" "github.com/xtls/xray-core/common/signal"
"github.com/xtls/xray-core/common/task" "github.com/xtls/xray-core/common/task"
@@ -28,7 +25,6 @@ import (
"github.com/xtls/xray-core/features" "github.com/xtls/xray-core/features"
"github.com/xtls/xray-core/features/dns" "github.com/xtls/xray-core/features/dns"
"github.com/xtls/xray-core/features/extension" "github.com/xtls/xray-core/features/extension"
feature_inbound "github.com/xtls/xray-core/features/inbound"
"github.com/xtls/xray-core/features/outbound" "github.com/xtls/xray-core/features/outbound"
"github.com/xtls/xray-core/features/policy" "github.com/xtls/xray-core/features/policy"
"github.com/xtls/xray-core/features/routing" "github.com/xtls/xray-core/features/routing"
@@ -37,7 +33,10 @@ import (
"github.com/xtls/xray-core/proxy/vless" "github.com/xtls/xray-core/proxy/vless"
"github.com/xtls/xray-core/proxy/vless/encoding" "github.com/xtls/xray-core/proxy/vless/encoding"
"github.com/xtls/xray-core/proxy/vless/encryption" "github.com/xtls/xray-core/proxy/vless/encryption"
"github.com/xtls/xray-core/proxy/vless/multiplex"
"github.com/xtls/xray-core/proxy/vless/reverse"
"github.com/xtls/xray-core/transport" "github.com/xtls/xray-core/transport"
"github.com/xtls/xray-core/transport/internet"
"github.com/xtls/xray-core/transport/internet/reality" "github.com/xtls/xray-core/transport/internet/reality"
"github.com/xtls/xray-core/transport/internet/stat" "github.com/xtls/xray-core/transport/internet/stat"
"github.com/xtls/xray-core/transport/internet/tls" "github.com/xtls/xray-core/transport/internet/tls"
@@ -72,14 +71,12 @@ func init() {
// Handler is an inbound connection handler that handles messages in VLess protocol. // Handler is an inbound connection handler that handles messages in VLess protocol.
type Handler struct { type Handler struct {
inboundHandlerManager feature_inbound.Manager
policyManager policy.Manager policyManager policy.Manager
stats stats.Manager stats stats.Manager
validator vless.Validator validator vless.Validator
decryption *encryption.ServerInstance decryption *encryption.ServerInstance
outboundHandlerManager outbound.Manager outboundHandlerManager outbound.Manager
observer features.Feature observer features.Feature
defaultDispatcher routing.Dispatcher
ctx context.Context ctx context.Context
fallbacks map[string]map[string]map[string]*Fallback // or nil fallbacks map[string]map[string]map[string]*Fallback // or nil
// regexps map[string]*regexp.Regexp // or nil // regexps map[string]*regexp.Regexp // or nil
@@ -89,13 +86,11 @@ type Handler struct {
func New(ctx context.Context, config *Config, dc dns.Client, validator vless.Validator) (*Handler, error) { func New(ctx context.Context, config *Config, dc dns.Client, validator vless.Validator) (*Handler, error) {
v := core.MustFromContext(ctx) v := core.MustFromContext(ctx)
handler := &Handler{ handler := &Handler{
inboundHandlerManager: v.GetFeature(feature_inbound.ManagerType()).(feature_inbound.Manager),
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
stats: v.GetFeature(stats.ManagerType()).(stats.Manager), stats: v.GetFeature(stats.ManagerType()).(stats.Manager),
validator: validator, validator: validator,
outboundHandlerManager: v.GetFeature(outbound.ManagerType()).(outbound.Manager), outboundHandlerManager: v.GetFeature(outbound.ManagerType()).(outbound.Manager),
observer: v.GetFeature(extension.ObservatoryType()), observer: v.GetFeature(extension.ObservatoryType()),
defaultDispatcher: v.GetFeature(routing.DispatcherType()).(routing.Dispatcher),
ctx: ctx, ctx: ctx,
} }
@@ -188,7 +183,7 @@ func isMuxAndNotXUDP(request *protocol.RequestHeader, first *buf.Buffer) bool {
firstBytes[6] == 2) // Network type: UDP firstBytes[6] == 2) // Network type: UDP
} }
func (h *Handler) GetReverse(a *vless.MemoryAccount) (*Reverse, error) { func (h *Handler) GetReverse(a *vless.MemoryAccount) (*reverse.PublicEndpoint, error) {
u := h.validator.Get(a.ID.UUID()) u := h.validator.Get(a.ID.UUID())
if u == nil { if u == nil {
return nil, errors.New("reverse: user " + a.ID.String() + " doesn't exist anymore") return nil, errors.New("reverse: user " + a.ID.String() + " doesn't exist anymore")
@@ -199,25 +194,28 @@ func (h *Handler) GetReverse(a *vless.MemoryAccount) (*Reverse, error) {
} }
r := h.outboundHandlerManager.GetHandler(a.Reverse.Tag) r := h.outboundHandlerManager.GetHandler(a.Reverse.Tag)
if r == nil { if r == nil {
picker, _ := reverse.NewStaticMuxPicker() r = reverse.NewPublicEndpoint(a.Reverse.Tag, h.observer)
r = &Reverse{tag: a.Reverse.Tag, picker: picker, client: &mux.ClientManager{Picker: picker}}
for len(h.outboundHandlerManager.ListHandlers(h.ctx)) == 0 { for len(h.outboundHandlerManager.ListHandlers(h.ctx)) == 0 {
time.Sleep(time.Second) // prevents this outbound from becoming the default outbound time.Sleep(time.Second) // prevents this outbound from becoming the default outbound
} }
if err := h.outboundHandlerManager.AddHandler(h.ctx, r); err != nil { if err := h.outboundHandlerManager.AddHandler(h.ctx, r); err != nil {
r.Close()
return nil, err return nil, err
} }
} }
if r, ok := r.(*Reverse); ok { if r, ok := r.(*reverse.PublicEndpoint); ok {
return r, nil return r, nil
} }
return nil, errors.New("reverse: outbound " + a.Reverse.Tag + " is not type Reverse") return nil, errors.New("reverse: outbound " + a.Reverse.Tag + " is not type PublicEndpoint")
} }
func (h *Handler) RemoveReverse(u *protocol.MemoryUser) { func (h *Handler) RemoveReverse(u *protocol.MemoryUser) {
if u != nil { if u != nil {
a := u.Account.(*vless.MemoryAccount) a := u.Account.(*vless.MemoryAccount)
if a.Reverse != nil && a.Reverse.Tag != "" { if a.Reverse != nil && a.Reverse.Tag != "" {
if publicEndpoint, ok := h.outboundHandlerManager.GetHandler(a.Reverse.Tag).(*reverse.PublicEndpoint); ok {
publicEndpoint.Close()
}
h.outboundHandlerManager.RemoveHandler(h.ctx, a.Reverse.Tag) h.outboundHandlerManager.RemoveHandler(h.ctx, a.Reverse.Tag)
} }
} }
@@ -527,6 +525,12 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
} }
errors.LogInfo(ctx, "received request for ", request.Destination()) errors.LogInfo(ctx, "received request for ", request.Destination())
if stream, ok := session.StreamSettingsFromContext(h.ctx).(*internet.MemoryStreamConfig); ok && stream.ProtocolName == "xdrive" {
if request.Command != protocol.RequestCommandMux && request.Command != protocol.RequestCommandRvs {
return errors.New("VLESS over XDRIVE: inbound received a non-Mux/Rvs request")
}
}
inbound := session.InboundFromContext(ctx) inbound := session.InboundFromContext(ctx)
if inbound == nil { if inbound == nil {
panic("no inbound metadata") panic("no inbound metadata")
@@ -541,10 +545,6 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
return errors.New("for safety reasons, user " + account.ID.String() + " is not allowed to use forward proxy") return errors.New("for safety reasons, user " + account.ID.String() + " is not allowed to use forward proxy")
} }
responseAddons := &encoding.Addons{
// Flow: requestAddons.Flow,
}
var input *bytes.Reader var input *bytes.Reader
var rawInput **bytes.Buffer var rawInput **bytes.Buffer
switch requestAddons.Flow { switch requestAddons.Flow {
@@ -607,85 +607,29 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
} }
bufferWriter := buf.NewBufferedWriter(buf.NewWriter(connection)) bufferWriter := buf.NewBufferedWriter(buf.NewWriter(connection))
if err := encoding.EncodeResponseHeader(bufferWriter, request, responseAddons); err != nil { if err := encoding.EncodeResponseHeader(bufferWriter, request, &encoding.Addons{}); err != nil {
return errors.New("failed to encode response header").Base(err) return errors.New("failed to encode response header").Base(err)
} }
clientWriter := encoding.EncodeBodyAddons(bufferWriter, request, requestAddons, trafficState, false, ctx, connection, nil) clientWriter := encoding.EncodeBodyAddons(bufferWriter, request, requestAddons, trafficState, false, ctx, connection, nil)
bufferWriter.SetFlushNext() bufferWriter.SetFlushNext()
link := &transport.Link{Reader: clientReader, Writer: clientWriter}
if request.Command == protocol.RequestCommandRvs { if request.Command == protocol.RequestCommandRvs {
r, err := h.GetReverse(account) r, err := h.GetReverse(account)
if err != nil { if err != nil {
return err return err
} }
return r.NewMux(ctx, dispatcher.WrapLink(ctx, h.policyManager, h.stats, &transport.Link{Reader: clientReader, Writer: clientWriter}), h.observer) return r.Accept(ctx, dispatcher.WrapLink(ctx, h.policyManager, h.stats, link))
} }
if err := dispatch.DispatchLink( if request.Command == protocol.RequestCommandMux {
ctx, request.Destination(), &transport.Link{ worker := multiplex.NewServerWorker(ctx, dispatch.DispatchLink, link)
Reader: clientReader, <-worker.WaitClosed()
Writer: clientWriter, return nil
}, }
); err != nil {
if err := dispatch.DispatchLink(ctx, request.Destination(), link); err != nil {
return errors.New("failed to dispatch request").Base(err) return errors.New("failed to dispatch request").Base(err)
} }
return nil return nil
} }
type Reverse struct {
tag string
picker *reverse.StaticMuxPicker
client *mux.ClientManager
}
func (r *Reverse) Tag() string {
return r.tag
}
func (r *Reverse) NewMux(ctx context.Context, link *transport.Link, observer features.Feature) error {
muxClient, err := mux.NewClientWorker(*link, mux.ClientStrategy{})
if err != nil {
return errors.New("failed to create mux client worker").Base(err)
}
worker, err := reverse.NewPortalWorker(muxClient)
if err != nil {
return errors.New("failed to create portal worker").Base(err)
}
r.picker.AddWorker(worker)
if burstObs, ok := observer.(extension.BurstObservatory); ok {
go burstObs.Check([]string{r.Tag()})
}
select {
case <-ctx.Done():
case <-muxClient.WaitClosed():
}
return nil
}
func (r *Reverse) Dispatch(ctx context.Context, link *transport.Link) {
outbounds := session.OutboundsFromContext(ctx)
ob := outbounds[len(outbounds)-1]
if ob != nil {
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
link.Reader = &buf.EndpointOverrideReader{Reader: link.Reader, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
link.Writer = &buf.EndpointOverrideWriter{Writer: link.Writer, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
}
r.client.Dispatch(session.ContextWithIsReverseMux(ctx, true), link)
}
}
func (r *Reverse) Start() error {
return nil
}
func (r *Reverse) Close() error {
return nil
}
func (r *Reverse) SenderSettings() *serial.TypedMessage {
return nil
}
func (r *Reverse) ProxySettings() *serial.TypedMessage {
return nil
}
+256
View File
@@ -0,0 +1,256 @@
package multiplex
import (
"context"
"io"
"sync"
"time"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/transport"
)
// Control intents carry no encoded DATA or caller payload.
type carrier struct {
sync.RWMutex
sessions map[uint16]*Session
ready map[uint16]*Session // nil is a bounded END for an unknown wire ID
unknown int
count uint16
active int
client bool
link transport.Link
writeMutex sync.Mutex
control *sync.Cond
ctx context.Context
cancel context.CancelCauseFunc
timer *time.Timer
}
func newCarrier(parent context.Context, link transport.Link, idle time.Duration, client bool) *carrier {
ctx, cancel := context.WithCancelCause(parent)
c := &carrier{
sessions: make(map[uint16]*Session, 16), link: link, ctx: ctx, cancel: cancel,
client: client,
}
c.control = sync.NewCond(&c.RWMutex)
c.ready = make(map[uint16]*Session)
context.AfterFunc(c.ctx, func() { common.Interrupt(c.link.Reader) })
c.Lock()
checkSize, checkCount := c.active, c.count
c.timer = time.AfterFunc(idle, func() {
c.Lock()
defer c.Unlock()
if c.Closed() {
return
}
if c.active == 0 && checkSize == 0 && c.count == checkCount {
c.cancel(nil)
return
}
checkSize, checkCount = c.active, c.count
c.timer.Reset(idle)
})
c.Unlock()
context.AfterFunc(c.ctx, c.shutdown)
go c.controlLoop()
return c
}
func (c *carrier) admitLocked(s *Session) bool {
if c.Closed() || s.phase != outputOpen || c.sessions[s.ID] != nil {
return false
}
c.count++
c.active++
c.invalidateUnknownLocked(s.ID)
c.sessions[s.ID] = s
return true
}
func (c *carrier) queueReadyLocked(s *Session) {
if c.ready[s.ID] != s {
c.ready[s.ID] = s
c.control.Broadcast()
}
}
func (c *carrier) scheduleLocked(s *Session) {
if !c.Closed() && c.sessions[s.ID] == s && (s.phase == outputDone || s.packetReady()) {
c.queueReadyLocked(s)
}
}
func (c *carrier) invalidateUnknownLocked(id uint16) bool {
if s, ok := c.ready[id]; ok && s == nil {
delete(c.ready, id)
c.unknown--
c.control.Broadcast()
return true
}
return false
}
func (c *carrier) unknownEnd(id uint16) {
c.Lock()
defer c.Unlock()
for !c.Closed() {
if _, queued := c.ready[id]; queued || c.sessions[id] != nil {
return
}
if c.unknown < 16 {
c.ready[id] = nil
c.unknown++
c.control.Broadcast()
return
}
c.control.Wait()
}
}
func (c *carrier) controlLoop() {
c.Lock()
defer c.Unlock()
for !c.Closed() {
if len(c.ready) == 0 {
c.control.Wait()
continue
}
// Advance the iterator under the lock. Physical sends never hold it.
for id, selected := range c.ready {
c.Unlock()
c.writeMutex.Lock()
var frames buf.MultiBuffer
var err error
raw, terminal := c.responseTurn(id, selected)
if terminal {
frames = endFrame(id, selected != nil && selected.endFailed)
} else if len(raw) != 0 {
frames, err = selected.encodeBatch(&raw)
buf.ReleaseMulti(raw)
}
err = c.writeAndUnlock(frames, err)
c.Lock()
if err != nil || c.Closed() {
return
}
}
}
}
// No logical lock spans physical I/O or a codec/address callback.
func (c *carrier) writeAndUnlock(frames buf.MultiBuffer, err error) error {
if err != nil || c.Closed() {
buf.ReleaseMulti(frames)
} else if len(frames) != 0 {
if r, ok := c.link.Reader.(*responseReader); ok {
r.activity.Update()
}
err = c.link.Writer.WriteMultiBuffer(frames)
}
if err != nil {
c.cancel(err)
}
c.writeMutex.Unlock()
return err
}
func (c *carrier) ActiveConnections() uint32 {
c.RLock()
defer c.RUnlock()
return uint32(c.active)
}
func (c *carrier) Closed() bool { return c.ctx.Err() != nil }
func (c *carrier) WaitClosed() <-chan struct{} { return c.ctx.Done() }
// Err reports the first close cause, excluding normal cancellation.
func (c *carrier) Err() error {
err := context.Cause(c.ctx)
if err == context.Canceled {
return nil
}
return err
}
func (c *carrier) Close() error {
c.cancel(nil)
return nil
}
func (c *carrier) shutdown() {
c.Lock()
c.timer.Stop()
c.ready = nil
c.control.Broadcast()
sessions := c.sessions
c.sessions, c.active = nil, 0
c.Unlock()
for _, s := range sessions {
s.abort()
}
common.Interrupt(c.link.Writer)
}
func (c *carrier) readFrame(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader, accept func(context.Context, *FrameMetadata, *buf.BufferedReader) error) error {
var target *Session
data := meta.Option.Has(OptionData)
switch meta.SessionStatus {
case SessionStatusNew:
if accept != nil {
return accept(session.ContextWithIsReverseMux(ctx, false), meta, reader)
}
case SessionStatusKeep:
if !data {
return nil
}
c.RLock()
s, found := c.sessions[meta.SessionID]
if found && s.phase == outputOpen {
target = s
}
c.RUnlock()
if !found && !c.client {
c.unknownEnd(meta.SessionID)
}
case SessionStatusEnd:
c.RLock()
s := c.sessions[meta.SessionID]
c.RUnlock()
if s != nil {
s.abort()
}
case SessionStatusKeepAlive:
default:
return errors.New("unknown status: ", meta.SessionStatus)
}
if data {
return copyFramePayload(reader, target, meta.Target)
}
return nil
}
func (c *carrier) run(ctx context.Context, accept func(context.Context, *FrameMetadata, *buf.BufferedReader) error) {
var err error
defer func() { c.cancel(err) }()
reader := &buf.BufferedReader{Reader: c.link.Reader}
defer func() { buf.ReleaseMulti(reader.Buffer) }()
for !c.Closed() {
var meta FrameMetadata
err = meta.Unmarshal(reader, session.IsReverseMuxFromContext(ctx))
if errors.Cause(err) == io.EOF {
err = nil // clean EOF before the next metadata prefix
return
}
if err == nil {
err = frameReadError(c.readFrame(ctx, &meta, reader, accept))
}
if err != nil {
errors.LogInfoInner(ctx, err, "failed to process multiplex frame")
return
}
}
}
+270
View File
@@ -0,0 +1,270 @@
package multiplex
import (
"context"
"io"
"slices"
"sync"
"time"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/proxy"
"github.com/xtls/xray-core/proxy/vless"
"github.com/xtls/xray-core/transport"
)
// NormalizeConfig validates the pool settings and returns nil when both pools are off.
func NormalizeConfig(config *vless.Multiplex) (*vless.Multiplex, error) {
if config.GetConcurrency() < 0 || config.GetXudpConcurrency() < 0 {
return nil, errors.New(`multiplex "concurrency" and "xudpConcurrency" must be non-negative`)
}
switch config.GetXudpProxyUDP443() {
case "", "reject", "allow", "skip":
default:
return nil, errors.New(`unknown "xudpProxyUDP443": `, config.GetXudpProxyUDP443())
}
if config.GetConcurrency() == 0 && config.GetXudpConcurrency() == 0 {
return nil, nil
}
return config, nil
}
// Client owns the logical stream pools.
type Client struct {
config *vless.Multiplex
tcp *Pool
udp *Pool
}
func NewClient(ctx context.Context, config *vless.Multiplex, network string, open func(context.Context) (context.Context, *transport.Link, error)) *Client {
c := &Client{config: config}
maxReuseTimes := uint32(1024)
if network == "xdrive" {
maxReuseTimes = 0 // unlimited
config.Concurrency = max(config.Concurrency, 128)
if config.XudpConcurrency > 0 {
config.XudpConcurrency = max(config.XudpConcurrency, 128)
}
}
if config.Concurrency > 0 {
c.tcp = NewPool(ctx, ClientStrategy{MaxConcurrency: uint32(config.Concurrency), MaxConnection: maxReuseTimes}, open)
}
if config.XudpConcurrency > 0 {
c.udp = NewPool(ctx, ClientStrategy{MaxConcurrency: uint32(config.XudpConcurrency), MaxConnection: maxReuseTimes}, open)
}
return c
}
func (c *Client) Dispatch(ctx context.Context, link *transport.Link) (bool, error) {
if c == nil {
return false, nil
}
pool := c.tcp
outbounds := session.OutboundsFromContext(ctx)
target := outbounds[len(outbounds)-1].Target
if target.Network == net.Network_UDP && c.udp != nil {
pool = c.udp
}
if pool == nil {
return false, nil
}
if target.Network == net.Network_UDP && target.Port == 443 {
switch c.config.GetXudpProxyUDP443() {
case "reject", "":
proxy.DropUDP(ctx, link.Reader)
return true, errors.New("XUDP rejected UDP/443 traffic")
case "skip":
return false, nil
}
}
return true, Dispatch(ctx, link, pool.Admit)
}
type deferredWriterClose struct{}
func (deferredWriterClose) Error() string { return "defer link writer close" }
func (deferredWriterClose) DeferWriterClose() bool { return true }
// Dispatch runs a logical child. The caller owns the application endpoints.
func Dispatch(ctx context.Context, link *transport.Link, admit func(context.Context, *Session) error, finish ...func(context.Context)) error {
s := NewSession(ctx, link)
if err := admit(ctx, s); err != nil {
return err
}
go fetchInput(ctx, s)
callerDone := ctx.Done()
if session.TimeoutOnlyFromContext(ctx) {
callerDone = nil
}
select {
case <-callerDone:
s.Close()
case <-s.WaitClosed():
}
// The session is sealed. Only a response write already in progress can
// still hold the application writer.
writingResponse := s.writingResponse.Load()
if len(finish) != 0 {
if writingResponse {
go finish[0](s.parent.ctx)
} else {
finish[0](s.parent.ctx)
}
} else if writingResponse {
return deferredWriterClose{}
}
return nil
}
// Pool serializes unpublished opening with cancelable admission.
type Pool struct {
ctx context.Context
access sync.Mutex
opening chan struct{}
workers []*ClientWorker
strategy ClientStrategy
open func(context.Context) (context.Context, *transport.Link, error)
}
// NewPool borrows ctx; open must return a context derived from its input context.
func NewPool(ctx context.Context, strategy ClientStrategy, open func(context.Context) (context.Context, *transport.Link, error)) *Pool {
return &Pool{ctx: ctx, strategy: strategy, open: open}
}
func (p *Pool) Admit(ctx context.Context, s *Session) error {
p.access.Lock()
for {
if err := ctx.Err(); err != nil {
p.access.Unlock()
return err
}
if p.ctx.Err() != nil {
p.access.Unlock()
return io.ErrClosedPipe
}
for _, worker := range p.workers {
if worker.TryAdmit(ctx, s) {
p.access.Unlock()
return nil
}
}
if p.opening == nil {
p.opening = make(chan struct{})
break
}
wait := p.opening
p.access.Unlock()
select {
case <-ctx.Done():
return ctx.Err()
case <-p.ctx.Done():
return io.ErrClosedPipe
case <-wait:
}
p.access.Lock()
}
p.access.Unlock()
opening, cancel := context.WithCancel(p.ctx)
stopCaller := context.AfterFunc(ctx, cancel)
physicalCtx, physicalLink, err := p.open(opening)
if !stopCaller() && err == nil {
err = context.Canceled
}
if ctx.Err() != nil {
err = ctx.Err()
}
if p.ctx.Err() != nil {
err = io.ErrClosedPipe
}
p.access.Lock()
close(p.opening)
p.opening = nil
var worker *ClientWorker
if err == nil {
worker = NewClientWorker(physicalCtx, *physicalLink, p.strategy)
if !worker.TryAdmit(ctx, s) {
err = ctx.Err()
if err == nil {
err = errors.New("unable to admit multiplex child")
}
} else {
p.workers = append(p.workers, worker)
}
}
p.access.Unlock()
if err != nil {
cancel()
if physicalLink != nil {
common.Interrupt(physicalLink.Reader)
common.Interrupt(physicalLink.Writer)
}
return err
}
context.AfterFunc(worker.ctx, func() {
cancel()
p.access.Lock()
p.workers = slices.DeleteFunc(p.workers, func(current *ClientWorker) bool { return current == worker })
p.access.Unlock()
})
return nil
}
type ClientStrategy struct {
MaxConcurrency uint32
MaxConnection uint32
}
type ClientWorker struct {
*carrier
strategy ClientStrategy
}
func NewClientWorker(ctx context.Context, stream transport.Link, strategy ClientStrategy) *ClientWorker {
c := &ClientWorker{carrier: newCarrier(ctx, stream, 16*time.Second, true), strategy: strategy}
go c.run(context.Background(), nil)
return c
}
func (c *ClientWorker) TotalConnections() uint32 {
c.RLock()
defer c.RUnlock()
return uint32(c.count)
}
func writeFirstPayload(s *Session) error {
err := buf.CopyOnceTimeout(s.input, s, time.Millisecond*100)
if err == buf.ErrNotTimeoutReader || err == buf.ErrReadTimeout {
return s.WriteMultiBuffer(nil)
}
return err
}
func fetchInput(ctx context.Context, s *Session) {
var err error
defer func() { s.CloseWithError(err) }()
errors.LogInfo(ctx, "dispatching request to ", s.target)
if err = writeFirstPayload(s); err != nil {
errors.LogInfoInner(ctx, err, "failed to write first payload")
return
}
if err = buf.Copy(s.input, s); err != nil {
errors.LogInfoInner(ctx, err, "failed to fetch all input")
}
}
// TryAdmit publishes this prepared child without input or foreign cleanup.
func (m *ClientWorker) TryAdmit(ctx context.Context, s *Session) bool {
m.Lock()
defer m.Unlock()
if ctx.Err() != nil || m.Closed() || m.count == 65535 ||
(m.strategy.MaxConcurrency > 0 && m.active >= int(m.strategy.MaxConcurrency)) ||
(m.strategy.MaxConnection > 0 && uint32(m.count) >= m.strategy.MaxConnection) {
return false
}
s.parent, s.ID, s.phase, s.done = m.carrier, m.count+1, outputOpen, make(chan struct{})
return m.admitLocked(s)
}
+193
View File
@@ -0,0 +1,193 @@
package multiplex
import (
"context"
"testing"
"time"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/proxy/vless"
"github.com/xtls/xray-core/transport"
"github.com/xtls/xray-core/transport/pipe"
)
func TestClientUDP443Policy(t *testing.T) {
ctx := session.ContextWithOutbounds(t.Context(), []*session.Outbound{{
Target: net.UDPDestination(net.LocalHostIP, 443),
}})
for _, policy := range []string{"reject", "skip"} {
t.Run(policy, func(t *testing.T) {
opened := false
client := NewClient(ctx, &vless.Multiplex{Concurrency: 1, XudpProxyUDP443: policy}, "", func(context.Context) (context.Context, *transport.Link, error) {
opened = true
return nil, nil, context.Canceled
})
r, w := pipe.New()
common.Close(w)
handled, err := client.Dispatch(ctx, &transport.Link{Reader: r})
wantRejected := policy == "reject"
if opened || handled != wantRejected || (err != nil) != wantRejected {
t.Fatalf("Dispatch() = (%t, %v), opened carrier = %t, want rejected = %t without opening a carrier", handled, err, opened, wantRejected)
}
})
}
}
func TestClientWithoutPoolLeavesUDP443ToOutbound(t *testing.T) {
ctx := session.ContextWithOutbounds(t.Context(), []*session.Outbound{{
Target: net.UDPDestination(net.LocalHostIP, 443),
}})
client := NewClient(ctx, &vless.Multiplex{XudpProxyUDP443: "reject"}, "", nil)
if handled, err := client.Dispatch(ctx, &transport.Link{}); handled || err != nil {
t.Fatalf("Dispatch without a pool = (%t, %v), want fallback", handled, err)
}
}
func TestPoolFailure(t *testing.T) {
calls := 0
owner, stop := context.WithCancel(context.Background())
defer stop()
pool := NewPool(owner, ClientStrategy{}, func(context.Context) (context.Context, *transport.Link, error) {
calls++
return nil, nil, errors.New("test")
})
ctx := testOutboundContext()
s := NewSession(ctx, &transport.Link{Writer: buf.Discard})
if err := pool.Admit(ctx, s); err == nil || calls != 1 {
t.Fatalf("expected one failed opening, got %d calls and %v", calls, err)
}
}
func TestClientWorkerEOF(t *testing.T) {
reader, writer := pipe.New(pipe.WithoutSizeLimit())
common.Must(writer.Close())
worker := NewClientWorker(context.Background(), transport.Link{Reader: reader, Writer: writer}, ClientStrategy{})
select {
case <-worker.WaitClosed():
case <-time.After(3 * time.Second):
t.Fatal("worker did not close after EOF")
}
ctx := testOutboundContext()
f := worker.TryAdmit(ctx, NewSession(ctx, &transport.Link{Writer: buf.Discard}))
if f {
t.Error("expected failed dispatching, but actually not")
}
}
func TestClientWorkerClose(t *testing.T) {
r1, w1 := pipe.New(pipe.WithoutSizeLimit())
r2, w2 := pipe.New(pipe.WithoutSizeLimit())
links := []*transport.Link{{Reader: r1, Writer: w1}, {Reader: r2, Writer: w2}}
owner, stop := context.WithCancel(context.Background())
defer stop()
pool := NewPool(owner, ClientStrategy{MaxConcurrency: 4, MaxConnection: 4}, func(ctx context.Context) (context.Context, *transport.Link, error) {
if len(links) == 0 {
return nil, nil, errors.New("unexpected opening")
}
link := links[0]
links = links[1:]
return ctx, link, nil
})
ctx := testOutboundContext()
worker1 := NewSession(ctx, &transport.Link{Writer: buf.Discard})
common.Must(pool.Admit(ctx, worker1))
tr1, tw1 := pipe.New(pipe.WithoutSizeLimit())
ctx1 := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80)}})
child1 := NewSession(ctx1, &transport.Link{Reader: tr1, Writer: tw1})
common.Must(pool.Admit(ctx1, child1))
go fetchInput(ctx1, child1)
defer tw1.Close()
common.Must(w1.Close())
select {
case <-worker1.parent.WaitClosed():
case <-time.After(3 * time.Second):
t.Fatal("first worker did not close")
}
tr2, tw2 := pipe.New(pipe.WithoutSizeLimit())
ctx2 := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80)}})
child2 := NewSession(ctx2, &transport.Link{Reader: tr2, Writer: tw2})
common.Must(pool.Admit(ctx2, child2))
go fetchInput(ctx2, child2)
defer tw2.Close()
common.Must(w2.Close())
}
func TestClientWorkerUDPSource(t *testing.T) {
downR, downW := pipe.New(pipe.WithoutSizeLimit())
upR, upW := pipe.New(pipe.WithoutSizeLimit())
worker := NewClientWorker(context.Background(), transport.Link{Reader: downR, Writer: upW}, ClientStrategy{})
t.Cleanup(func() {
worker.Close()
downW.Close()
upR.Interrupt()
})
inR, inW := pipe.New(pipe.WithoutSizeLimit())
outR, outW := pipe.New(pipe.WithoutSizeLimit())
t.Cleanup(func() {
inW.Close()
outR.Interrupt()
})
ctx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
Target: net.UDPDestination(net.ParseAddress("8.8.8.8"), 53),
}})
child := NewSession(ctx, &transport.Link{Reader: inR, Writer: outW})
if !worker.TryAdmit(ctx, child) {
t.Fatal("failed to dispatch")
}
go fetchInput(ctx, child)
b := buf.New()
b.WriteString("query")
common.Must(inW.WriteMultiBuffer(buf.MultiBuffer{b}))
mb, err := upR.ReadMultiBuffer() // New frame, the session is UDP from now on
common.Must(err)
buf.ReleaseMulti(mb)
srcs := []net.Destination{
net.UDPDestination(net.ParseAddress("1.1.1.1"), 1111),
net.UDPDestination(net.DomainAddress("example.com"), 2222),
net.UDPDestination(net.ParseAddress("3.3.3.3"), 3333),
}
response := &Session{ID: 1, target: net.Destination{Network: net.Network_UDP}}
var got buf.MultiBuffer
defer func() { buf.ReleaseMulti(got) }()
for i := range srcs {
b := buf.New()
b.WriteString("reply")
b.UDP = &srcs[i]
data := buf.MultiBuffer{b}
frames, err := response.encodeBatch(&data)
buf.ReleaseMulti(data)
if err != nil {
buf.ReleaseMulti(frames)
t.Fatal(err)
}
common.Must(downW.WriteMultiBuffer(frames))
// keep earlier replies around while the next frame is parsed
mb, err := outR.ReadMultiBuffer()
common.Must(err)
got = append(got, mb...)
}
if len(got) != len(srcs) {
t.Fatalf("received %d replies, want %d", len(got), len(srcs))
}
for i, b := range got {
if string(b.Bytes()) != "reply" {
t.Errorf("reply %d: payload = %q", i, b.Bytes())
}
if b.UDP == nil || *b.UDP != srcs[i] {
t.Errorf("reply %d: source = %v, want %v", i, b.UDP, srcs[i])
}
}
}
func testOutboundContext() context.Context {
return session.ContextWithOutbounds(context.Background(), []*session.Outbound{{Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80)}})
}
+56
View File
@@ -0,0 +1,56 @@
package multiplex
import (
"context"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/signal"
"github.com/xtls/xray-core/transport"
)
type responseReader struct {
ctx context.Context
cancel context.CancelFunc
activity *signal.ActivityTimer
open func() (buf.Reader, error)
body buf.Reader
terminal error
}
func (r *responseReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
if err := r.ctx.Err(); err != nil {
return nil, err
}
if r.open != nil {
r.body, r.terminal = r.open()
r.open = nil
}
for r.terminal == nil {
data, err := r.body.ReadMultiBuffer()
r.terminal = err
if err := r.ctx.Err(); err != nil {
buf.ReleaseMulti(data)
return nil, err
}
if !data.IsEmpty() {
r.activity.Update()
return data, nil
}
buf.ReleaseMulti(data)
}
return nil, r.terminal
}
func (r *responseReader) Interrupt() {
r.cancel()
r.activity.SetTimeout(0)
}
func OpenLink(ctx context.Context, cancel context.CancelFunc, writer buf.Writer, activity *signal.ActivityTimer, openResponse func() (buf.Reader, error)) (*transport.Link, error) {
if err := ctx.Err(); err != nil {
cancel()
activity.SetTimeout(0)
return nil, err
}
return &transport.Link{Reader: &responseReader{ctx: ctx, cancel: cancel, activity: activity, open: openResponse}, Writer: writer}, nil
}

Some files were not shown because too many files have changed in this diff Show More