Compare commits

..
1 Commits
Author SHA1 Message Date
Meo597 84ce7568bb Lua: Expose Go slices as read-only 2026-11-20 05:16:13 +08:00
177 changed files with 6458 additions and 11200 deletions
-5
View File
@@ -1,5 +0,0 @@
<!--
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
@@ -1,29 +0,0 @@
# 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.
+39 -28
View File
@@ -2,6 +2,8 @@
[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)
@@ -39,9 +41,9 @@
## Telegram ## Telegram
[Project X Channel](https://t.me/projectXtls) [Project X](https://t.me/projectXray)
[Project X](https://t.me/projectXray) (中文 / English) [Project X Channel](https://t.me/projectXtls)
[Project VLESS](https://t.me/projectVless) (Русский) [Project VLESS](https://t.me/projectVless) (Русский)
@@ -51,6 +53,7 @@
- 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)
@@ -66,10 +69,12 @@
- [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/sajjaddg/xray-reality), [Xray_bash_onekey](https://github.com/hello-yunshu/Xray_bash_onekey) - [Xray-REALITY](https://github.com/zxcvos/Xray-script), [xray-reality](https://github.com/sajjaddg/xray-reality), [reality-ezpz](https://github.com/aleskxyz/reality-ezpz)
- [v2ray-agent](https://github.com/mack-a/v2ray-agent), [Xray_onekey](https://github.com/wulabing/Xray_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), [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`
@@ -81,7 +86,14 @@
- [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
@@ -94,52 +106,49 @@
- [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 tvOS](https://apps.apple.com/us/app/happ-proxy-utility-for-tv/id6748297274) - [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)
- [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](https://apps.apple.com/app/happ-proxy-utility/id6504287215) | [Happ RU](https://apps.apple.com/ru/app/happ-proxy-utility-plus/id6746188973)
- [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
@@ -154,8 +163,14 @@ To submit a project to the [README](https://github.com/XTLS/Xray-core#readme), o
- 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)
@@ -163,9 +178,9 @@ To submit a project to the [README](https://github.com/XTLS/Xray-core#readme), o
## Contributing ## Contributing
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. [Code of Conduct](https://github.com/XTLS/Xray-core/blob/main/CODE_OF_CONDUCT.md)
[Ask DeepWiki](https://deepwiki.com/XTLS/Xray-core) might be helpful. [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/XTLS/Xray-core)
## Credits ## Credits
@@ -248,8 +263,4 @@ GOOS=linux GOARCH=mipsle GOMIPS=softfloat CGO_ENABLED=0 go build -o xray -trimpa
## Stargazers over time ## Stargazers over time
<picture> [![Stargazers over time](https://starchart.cc/XTLS/Xray-core.svg)](https://starchart.cc/XTLS/Xray-core)
<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,10 +2,4 @@
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!
+8 -16
View File
@@ -26,16 +26,9 @@ 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 reader buf.TimeoutReader // *pipe.Reader or *buf.TimeoutWrapperReader
cache buf.MultiBuffer cache buf.MultiBuffer
} }
@@ -93,7 +86,9 @@ func (r *cachedReader) Interrupt() {
r.cache = buf.ReleaseMulti(r.cache) r.cache = buf.ReleaseMulti(r.cache)
} }
r.Unlock() r.Unlock()
common.Interrupt(r.reader) if p, ok := r.reader.(*pipe.Reader); ok {
p.Interrupt()
}
} }
// DefaultDispatcher is a default implementation of Dispatcher. // DefaultDispatcher is a default implementation of Dispatcher.
@@ -199,13 +194,15 @@ func WrapLink(ctx context.Context, policyManager policy.Manager, statsManager st
user = sessionInbound.User user = sessionInbound.User
} }
var uplinkCounter stats.Counter link.Reader = &buf.TimeoutWrapperReader{Reader: link.Reader}
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"
uplinkCounter, _ = statsManager.GetOrRegisterCounter(name) if c, _ := statsManager.GetOrRegisterCounter(name); c != nil {
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"
@@ -221,11 +218,6 @@ 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
} }
+115 -27
View File
@@ -330,6 +330,7 @@ type SenderConfig struct {
// 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
@@ -380,6 +381,13 @@ 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
@@ -394,6 +402,78 @@ 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 = "" +
@@ -418,12 +498,18 @@ 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\"\x9a\x02\n" + "\x0eOutboundConfig\"\xd6\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\x12\x19\n" + "\x0fstream_settings\x18\x02 \x01(\v2%.xray.transport.internet.StreamConfigR\x0estreamSettings\x12T\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\x04J\x04\b\x04\x10\x05R\x12multiplex_settingsBU\n" + "\x0ftarget_strategy\x18\x06 \x01(\x0e2'.xray.transport.internet.DomainStrategyR\x0etargetStrategyJ\x04\b\x03\x10\x04\"\xa4\x01\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 (
@@ -438,7 +524,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, 6) var file_app_proxyman_config_proto_msgTypes = make([]protoimpl.MessageInfo, 7)
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
@@ -446,31 +532,33 @@ 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
(*geodata.DomainRule)(nil), // 6: xray.common.geodata.DomainRule (*MultiplexingConfig)(nil), // 6: xray.app.proxyman.MultiplexingConfig
(*geodata.IPRule)(nil), // 7: xray.common.geodata.IPRule (*geodata.DomainRule)(nil), // 7: xray.common.geodata.DomainRule
(*net.PortList)(nil), // 8: xray.common.net.PortList (*geodata.IPRule)(nil), // 8: xray.common.geodata.IPRule
(*net.IPOrDomain)(nil), // 9: xray.common.net.IPOrDomain (*net.PortList)(nil), // 9: xray.common.net.PortList
(*internet.StreamConfig)(nil), // 10: xray.transport.internet.StreamConfig (*net.IPOrDomain)(nil), // 10: xray.common.net.IPOrDomain
(*serial.TypedMessage)(nil), // 11: xray.common.serial.TypedMessage (*internet.StreamConfig)(nil), // 11: xray.transport.internet.StreamConfig
(internet.DomainStrategy)(0), // 12: xray.transport.internet.DomainStrategy (*serial.TypedMessage)(nil), // 12: xray.common.serial.TypedMessage
(internet.DomainStrategy)(0), // 13: xray.transport.internet.DomainStrategy
} }
var file_app_proxyman_config_proto_depIdxs = []int32{ var file_app_proxyman_config_proto_depIdxs = []int32{
6, // 0: xray.app.proxyman.SniffingConfig.domains_excluded:type_name -> xray.common.geodata.DomainRule 7, // 0: xray.app.proxyman.SniffingConfig.domains_excluded:type_name -> xray.common.geodata.DomainRule
7, // 1: xray.app.proxyman.SniffingConfig.ips_excluded:type_name -> xray.common.geodata.IPRule 8, // 1: xray.app.proxyman.SniffingConfig.ips_excluded:type_name -> xray.common.geodata.IPRule
8, // 2: xray.app.proxyman.ReceiverConfig.port_list:type_name -> xray.common.net.PortList 9, // 2: xray.app.proxyman.ReceiverConfig.port_list:type_name -> xray.common.net.PortList
9, // 3: xray.app.proxyman.ReceiverConfig.listen:type_name -> xray.common.net.IPOrDomain 10, // 3: xray.app.proxyman.ReceiverConfig.listen:type_name -> xray.common.net.IPOrDomain
10, // 4: xray.app.proxyman.ReceiverConfig.stream_settings:type_name -> xray.transport.internet.StreamConfig 11, // 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
11, // 6: xray.app.proxyman.InboundHandlerConfig.receiver_settings:type_name -> xray.common.serial.TypedMessage 12, // 6: xray.app.proxyman.InboundHandlerConfig.receiver_settings:type_name -> xray.common.serial.TypedMessage
11, // 7: xray.app.proxyman.InboundHandlerConfig.proxy_settings:type_name -> xray.common.serial.TypedMessage 12, // 7: xray.app.proxyman.InboundHandlerConfig.proxy_settings:type_name -> xray.common.serial.TypedMessage
9, // 8: xray.app.proxyman.SenderConfig.via:type_name -> xray.common.net.IPOrDomain 10, // 8: xray.app.proxyman.SenderConfig.via:type_name -> xray.common.net.IPOrDomain
10, // 9: xray.app.proxyman.SenderConfig.stream_settings:type_name -> xray.transport.internet.StreamConfig 11, // 9: xray.app.proxyman.SenderConfig.stream_settings:type_name -> xray.transport.internet.StreamConfig
12, // 10: xray.app.proxyman.SenderConfig.target_strategy:type_name -> xray.transport.internet.DomainStrategy 6, // 10: xray.app.proxyman.SenderConfig.multiplex_settings:type_name -> xray.app.proxyman.MultiplexingConfig
11, // [11:11] is the sub-list for method output_type 13, // 11: xray.app.proxyman.SenderConfig.target_strategy:type_name -> xray.transport.internet.DomainStrategy
11, // [11:11] is the sub-list for method input_type 12, // [12:12] is the sub-list for method output_type
11, // [11:11] is the sub-list for extension type_name 12, // [12:12] is the sub-list for method input_type
11, // [11:11] is the sub-list for extension extendee 12, // [12:12] is the sub-list for extension type_name
0, // [0:11] is the sub-list for field type_name 12, // [12:12] is the sub-list for extension extendee
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() }
@@ -484,7 +572,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: 6, NumMessages: 7,
NumExtensions: 0, NumExtensions: 0,
NumServices: 0, NumServices: 0,
}, },
+13 -2
View File
@@ -57,8 +57,19 @@ 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, 4; reserved 3;
reserved "multiplex_settings"; MultiplexingConfig multiplex_settings = 4;
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;
}
+7 -8
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,6 +48,7 @@ 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
} }
@@ -81,14 +82,11 @@ 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,
} }
@@ -119,7 +117,7 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
proxy: p, proxy: p,
stream: mss, stream: mss,
tag: tag, tag: tag,
dispatcher: dispatcher, dispatcher: h.mux,
sniffingRequest: sniffingRequest, sniffingRequest: sniffingRequest,
uplinkCounter: uplinkCounter, uplinkCounter: uplinkCounter,
downlinkCounter: downlinkCounter, downlinkCounter: downlinkCounter,
@@ -141,7 +139,7 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
stream: mss, stream: mss,
recvOrigDest: receiverConfig.ReceiveOriginalDestination, recvOrigDest: receiverConfig.ReceiveOriginalDestination,
tag: tag, tag: tag,
dispatcher: dispatcher, dispatcher: h.mux,
sniffingRequest: sniffingRequest, sniffingRequest: sniffingRequest,
uplinkCounter: uplinkCounter, uplinkCounter: uplinkCounter,
downlinkCounter: downlinkCounter, downlinkCounter: downlinkCounter,
@@ -156,7 +154,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: dispatcher, dispatcher: h.mux,
sniffingRequest: sniffingRequest, sniffingRequest: sniffingRequest,
uplinkCounter: uplinkCounter, uplinkCounter: uplinkCounter,
downlinkCounter: downlinkCounter, downlinkCounter: downlinkCounter,
@@ -194,6 +192,7 @@ 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,6 +7,7 @@ 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"
@@ -183,6 +184,9 @@ 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)
} }
+93 -16
View File
@@ -13,6 +13,7 @@ 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"
@@ -59,6 +60,9 @@ 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
} }
@@ -113,6 +117,57 @@ 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
} }
@@ -126,10 +181,8 @@ 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]
if h.senderSettings != nil && h.senderSettings.TargetStrategy.HasStrategy() && ob.Target.Address.Family().IsDomain() { content := session.ContentFromContext(ctx)
if session.SkipDNSResolveFromContext(ctx) { if h.senderSettings != nil && h.senderSettings.TargetStrategy.HasStrategy() && ob.Target.Address.Family().IsDomain() && (content == nil || !content.SkipDNSResolve) {
errors.LogInfo(ctx, "bypassing targetStrategy ", h.senderSettings.TargetStrategy, " for ", ob.Target, "; preserving target domain")
} else {
strategy := h.senderSettings.TargetStrategy strategy := h.senderSettings.TargetStrategy
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil { if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil {
strategy = strategy.GetDynamicStrategy(ob.OriginalTarget.Address.Family()) strategy = strategy.GetDynamicStrategy(ob.OriginalTarget.Address.Family())
@@ -150,20 +203,43 @@ func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) {
errors.LogInfo(ctx, "target: ", unchangedDomain, " resolved to: ", ob.Target.Address.String()) 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 {
err := h.proxy.Process(ctx, link, h) test := func(err error) {
var completion interface{ DeferWriterClose() bool } if err != nil {
if goerrors.As(err, &completion) && completion.DeferWriterClose() { err := errors.New("failed to process mux outbound traffic").Base(err)
go common.Close(writer) session.SubmitOutboundErrorToOriginator(ctx, err)
common.Interrupt(reader) 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 return
} }
if h.mux.Enabled {
test(h.mux.Dispatch(ctx, link))
return
}
}
out:
err := h.proxy.Process(ctx, link, h)
var errC error var errC error
if err != nil { if err != nil {
errC = errors.Cause(err) errC = errors.Cause(err)
@@ -176,15 +252,15 @@ func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) {
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(writer) common.Interrupt(link.Writer)
} else { } else {
if errC != nil && goerrors.Is(errC, io.ErrClosedPipe) { if errC != nil && goerrors.Is(errC, io.ErrClosedPipe) {
common.Interrupt(writer) common.Interrupt(link.Writer)
} else { } else {
common.Close(writer) common.Close(link.Writer)
} }
} }
common.Interrupt(reader) common.Interrupt(link.Reader)
} }
func (h *Handler) DestIpAddress() net.IP { func (h *Handler) DestIpAddress() net.IP {
@@ -256,6 +332,7 @@ 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
@@ -0,0 +1,235 @@
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
}
@@ -5,7 +5,6 @@ import (
"io" "io"
"github.com/xtls/xray-core/common/dice" "github.com/xtls/xray-core/common/dice"
"github.com/xtls/xray-core/common/net"
) )
func (c *Control) FillInRandom() { func (c *Control) FillInRandom() {
@@ -14,9 +13,3 @@ func (c *Control) FillInRandom() {
c.Random = make([]byte, randomLength) c.Random = make([]byte, randomLength)
io.ReadFull(rand.Reader, c.Random) io.ReadFull(rand.Reader, c.Random)
} }
const internalDomain = "reverse"
func isInternalDomain(dest net.Destination) bool {
return dest.Address.Family().IsDomain() && dest.Address.Domain() == internalDomain
}
+356
View File
@@ -0,0 +1,356 @@
// 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
@@ -0,0 +1,32 @@
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
@@ -0,0 +1,308 @@
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
@@ -0,0 +1,20 @@
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
@@ -0,0 +1,94 @@
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...)
}
+3 -2
View File
@@ -44,8 +44,9 @@ func (c routingContext) GetRuleTag() string {
return "" return ""
} }
// GetSkipDNSResolve implements routing.Context. // GetSkipDNSResolve is a mock implementation here to match the interface,
// The protobuf RoutingContext has no skip flag, so API contexts use false. // SkipDNSResolve is set from dns module, no use if coming from a protobuf object?
// TODO: please confirm @Vigilans
func (c routingContext) GetSkipDNSResolve() bool { func (c routingContext) GetSkipDNSResolve() bool {
return false return false
} }
+23 -3
View File
@@ -15,6 +15,8 @@ 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
@@ -37,7 +39,16 @@ 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 {
return &Buffer{v: bytespool.Alloc(Size)} buf := pool.Get().([]byte)
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.
@@ -69,7 +80,16 @@ 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 {
return Buffer{v: bytespool.Alloc(Size)} buf := pool.Get().([]byte)
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.
@@ -93,7 +113,7 @@ func (b *Buffer) Release() {
switch b.ownership { switch b.ownership {
case managed: case managed:
if cap(p) == Size { if cap(p) == Size {
bytespool.Free(p) pool.Put(p)
} }
case bytespools: case bytespools:
bytespool.Free(p) bytespool.Free(p)
+53 -65
View File
@@ -1,84 +1,72 @@
package bytespool package bytespool
import ( import "sync"
"math/bits"
"sync"
)
const ( func createAllocFunc(size int32) func() interface{} {
minShift = 10 // 1KB return func() interface{} {
maxShift = 16 // 64KB return make([]byte, size)
numPools = maxShift - minShift + 1 }
minSize = 1 << minShift
maxSize = 1 << maxShift
)
// pools hold array pointers (*[N]byte) to avoid interface boxing allocations on Put.
var pools = [numPools]sync.Pool{
{New: func() any { return new([1 << 10]byte) }},
{New: func() any { return new([1 << 11]byte) }},
{New: func() any { return new([1 << 12]byte) }},
{New: func() any { return new([1 << 13]byte) }},
{New: func() any { return new([1 << 14]byte) }},
{New: func() any { return new([1 << 15]byte) }},
{New: func() any { return new([1 << 16]byte) }},
} }
// Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 1024. // 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 (
numPools = 4
sizeMulti = 4
)
var (
pool [numPools]sync.Pool
poolSize [numPools]int32
)
func init() {
size := int32(2048)
for i := 0; i < numPools; i++ {
pool[i] = sync.Pool{
New: createAllocFunc(size),
}
poolSize[i] = size
size *= sizeMulti
}
}
// GetPool returns a sync.Pool that generates bytes array with at least the given size.
// 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 {
if size > maxSize { pool := GetPool(size)
if pool != nil {
return pool.Get().([]byte)
}
return make([]byte, size) return make([]byte, size)
}
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")
}
} }
// 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) {
c := cap(b) size := int32(cap(b))
if c < minSize || c > maxSize { b = b[0:cap(b)]
for i := numPools - 1; i >= 0; i-- {
if size >= poolSize[i] {
pool[i].Put(b)
return return
} }
index := bits.Len(uint(c)) - 1 - minShift
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.NewSlicePusher[uint32](L)), "Match": newLuaDomainMatch(xlua.NewReadOnlySlicePusher[uint32](L)),
"MatchAny": luaDomainMatchAny, "MatchAny": luaDomainMatchAny,
}) })
return 1 return 1
+3 -1
View File
@@ -104,7 +104,9 @@ 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"))
assert(#domain:Match("example.com") == 1) local indices = domain:Match("example.com")
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) {
+21 -43
View File
@@ -9,53 +9,20 @@ import (
luar "layeh.com/gopher-luar" luar "layeh.com/gopher-luar"
) )
func TestSlicePusher(t *testing.T) { func TestReadOnlySlicePusher(t *testing.T) {
L := glua.NewState() L := glua.NewState()
defer L.Close() defer L.Close()
push := NewSlicePusher[int](L) push := NewReadOnlySlicePusher[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 values = getValues() local co = coroutine.create(function() return getValues() end)
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 and result == true) assert(ok, result)
`); err != nil { values = result
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))
@@ -69,6 +36,17 @@ 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) {
@@ -230,23 +208,23 @@ assert(not pcall(function() return nested + nested end))
} }
} }
func TestSlicePusherMetatablePerState(t *testing.T) { func TestReadOnlySlicePusherMetatablePerState(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()
NewSlicePusher[int](first)(first, []int{1}) NewReadOnlySlicePusher[int](first)(first, []int{1})
NewSlicePusher[int](second)(second, []int{1}) NewReadOnlySlicePusher[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 BenchmarkSlicePusher(b *testing.B) { func BenchmarkReadOnlySlicePusher(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 := NewSlicePusher[net.IP](L) pushIPs := NewReadOnlySlicePusher[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)
+2 -4
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"}))
NewSlicePusher[net.IP](L)(L, []net.IP{net.ParseIP("192.0.2.1")}) NewReadOnlySlicePusher[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,9 +865,7 @@ 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)
NewSlicePusher[int](L)(L, []int{1}) L.SetGlobal("testValues", luar.New(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
@@ -0,0 +1,420 @@
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
@@ -0,0 +1,163 @@
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])
}
}
}
@@ -1,4 +1,4 @@
package multiplex package mux
import ( import (
"encoding/binary" "encoding/binary"
@@ -9,8 +9,9 @@ import (
"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"
"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/xudp"
) )
type SessionStatus byte type SessionStatus byte
@@ -34,7 +35,12 @@ const (
TargetNetworkUDP TargetNetwork = 0x02 TargetNetworkUDP TargetNetwork = 0x02
) )
var addrParser = xudp.AddrParser var addrParser = protocol.NewAddressParser(
protocol.AddressFamilyByte(byte(protocol.AddressTypeIPv4), net.AddressFamilyIPv4),
protocol.AddressFamilyByte(byte(protocol.AddressTypeDomain), net.AddressFamilyDomain),
protocol.AddressFamilyByte(byte(protocol.AddressTypeIPv6), net.AddressFamilyIPv6),
protocol.PortThenAddress(),
)
/* /*
Frame format Frame format
@@ -79,14 +85,17 @@ func (f FrameMetadata) WriteTo(b *buf.Buffer) error {
return err return err
} }
if f.Inbound != nil { if f.Inbound != nil {
for _, dst := range [...]net.Destination{f.Inbound.Source, f.Inbound.Local} { if f.Inbound.Source.Network == net.Network_TCP || f.Inbound.Source.Network == net.Network_UDP {
if dst.Network != net.Network_TCP && dst.Network != net.Network_UDP { common.Must(b.WriteByte(byte(f.Inbound.Source.Network - 1)))
break if err := addrParser.WriteAddressPort(b, f.Inbound.Source.Address, f.Inbound.Source.Port); err != nil {
}
common.Must(b.WriteByte(byte(dst.Network - 1)))
if err := addrParser.WriteAddressPort(b, dst.Address, dst.Port); err != nil {
return err return err
} }
if f.Inbound.Local.Network == net.Network_TCP || f.Inbound.Local.Network == net.Network_UDP {
common.Must(b.WriteByte(byte(f.Inbound.Local.Network - 1)))
if err := addrParser.WriteAddressPort(b, f.Inbound.Local.Address, f.Inbound.Local.Port); err != nil {
return err
}
}
} }
} else if b.UDP != nil { // make sure it's user's proxy request } else if b.UDP != nil { // make sure it's user's proxy request
b.Write(f.GlobalID[:]) // no need to check whether it's empty b.Write(f.GlobalID[:]) // no need to check whether it's empty
@@ -103,12 +112,21 @@ func (f FrameMetadata) WriteTo(b *buf.Buffer) error {
// Unmarshal reads FrameMetadata from the given reader. // Unmarshal reads FrameMetadata from the given reader.
func (f *FrameMetadata) Unmarshal(reader io.Reader, readSourceAndLocal bool) error { func (f *FrameMetadata) Unmarshal(reader io.Reader, readSourceAndLocal bool) error {
b, err := readBlock(reader, 512, "invalid metalen ") metaLen, err := serial.ReadUint16(reader)
if err != nil { if err != nil {
return err return err
} }
if metaLen > 512 {
return errors.New("invalid metalen ", metaLen)
}
b := buf.New()
defer b.Release() defer b.Release()
return frameReadError(f.UnmarshalFromBuffer(b, readSourceAndLocal))
if _, err := b.ReadFullFrom(reader, int32(metaLen)); err != nil {
return err
}
return f.UnmarshalFromBuffer(b, readSourceAndLocal)
} }
// UnmarshalFromBuffer reads a FrameMetadata from the given buffer. // UnmarshalFromBuffer reads a FrameMetadata from the given buffer.
@@ -128,29 +146,73 @@ func (f *FrameMetadata) UnmarshalFromBuffer(b *buf.Buffer, readSourceAndLocal bo
if b.Len() < 8 { if b.Len() < 8 {
return errors.New("insufficient buffer: ", b.Len()) return errors.New("insufficient buffer: ", b.Len())
} }
b.Advance(4) network := TargetNetwork(b.Byte(4))
target, err := readDestination(b, "") b.Advance(5)
addr, port, err := addrParser.ReadAddressPort(nil, b)
if err != nil { if err != nil {
return err return errors.New("failed to parse address and port").Base(err)
}
switch network {
case TargetNetworkTCP:
f.Target = net.TCPDestination(addr, port)
case TargetNetworkUDP:
f.Target = net.UDPDestination(addr, port)
default:
return errors.New("unknown network type: ", network)
} }
f.Target = target
} }
if f.SessionStatus == SessionStatusNew && readSourceAndLocal { if f.SessionStatus == SessionStatusNew && readSourceAndLocal {
f.Inbound = &session.Inbound{} f.Inbound = &session.Inbound{}
for i, dst := range [...]*net.Destination{&f.Inbound.Source, &f.Inbound.Local} {
if b.Len() == 0 || b.Byte(0) == 0 { // heartbeat, absent endpoint, or padding if b.Len() == 0 {
break return nil // for heartbeat, etc.
} }
parsed, err := readDestination(b, [...]string{"reading source: ", "reading local: "}[i]) network := TargetNetwork(b.Byte(0))
if network == 0 {
return nil // may be padding
}
b.Advance(1)
addr, port, err := addrParser.ReadAddressPort(nil, b)
if err != nil { if err != nil {
return err return errors.New("reading source: failed to parse address and port").Base(err)
} }
*dst = parsed switch network {
case TargetNetworkTCP:
f.Inbound.Source = net.TCPDestination(addr, port)
case TargetNetworkUDP:
f.Inbound.Source = net.UDPDestination(addr, port)
default:
return errors.New("reading source: unknown network type: ", network)
} }
if b.Len() == 0 {
return nil
}
network = TargetNetwork(b.Byte(0))
if network == 0 {
return nil
}
b.Advance(1)
addr, port, err = addrParser.ReadAddressPort(nil, b)
if err != nil {
return errors.New("reading local: failed to parse address and port").Base(err)
}
switch network {
case TargetNetworkTCP:
f.Inbound.Local = net.TCPDestination(addr, port)
case TargetNetworkUDP:
f.Inbound.Local = net.UDPDestination(addr, port)
default:
return errors.New("reading local: unknown network type: ", network)
}
return nil return nil
} }
// Application data is essential, to test whether the pipe is closed.
if f.SessionStatus == SessionStatusNew && f.Option.Has(OptionData) && if f.SessionStatus == SessionStatusNew && f.Option.Has(OptionData) &&
f.Target.Network == net.Network_UDP && b.Len() >= 8 { f.Target.Network == net.Network_UDP && b.Len() >= 8 {
copy(f.GlobalID[:], b.Bytes()) copy(f.GlobalID[:], b.Bytes())
@@ -158,20 +220,3 @@ func (f *FrameMetadata) UnmarshalFromBuffer(b *buf.Buffer, readSourceAndLocal bo
return nil return nil
} }
func readDestination(b *buf.Buffer, prefix string) (net.Destination, error) {
network := TargetNetwork(b.Byte(0))
b.Advance(1)
addr, port, err := addrParser.ReadAddressPort(nil, b)
if err != nil {
return net.Destination{}, errors.New(prefix, "failed to parse address and port").Base(err)
}
switch network {
case TargetNetworkTCP:
return net.TCPDestination(addr, port), nil
case TargetNetworkUDP:
return net.UDPDestination(addr, port), nil
default:
return net.Destination{}, errors.New(prefix, "unknown network type: ", network)
}
}
+25
View File
@@ -0,0 +1,25 @@
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
@@ -0,0 +1 @@
package mux
@@ -1,4 +1,4 @@
package multiplex package mux_test
import ( import (
"io" "io"
@@ -7,8 +7,9 @@ import (
"github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp"
"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/crypto" . "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/session" "github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/transport/pipe" "github.com/xtls/xray-core/transport/pipe"
) )
@@ -32,38 +33,31 @@ func TestReaderWriter(t *testing.T) {
pReader, pWriter := pipe.New(pipe.WithSizeLimit(1024)) pReader, pWriter := pipe.New(pipe.WithSizeLimit(1024))
dest := net.TCPDestination(net.DomainAddress("example.com"), 80) dest := net.TCPDestination(net.DomainAddress("example.com"), 80)
s1 := &Session{ID: 1, target: dest, inbound: &session.Inbound{}, first: true} writer := NewWriter(1, dest, pWriter, protocol.TransferTypeStream, [8]byte{}, &session.Inbound{})
dest2 := net.TCPDestination(net.LocalHostIP, 443) dest2 := net.TCPDestination(net.LocalHostIP, 443)
s2 := &Session{ID: 2, target: dest2, inbound: &session.Inbound{}, first: true} writer2 := NewWriter(2, dest2, pWriter, protocol.TransferTypeStream, [8]byte{}, &session.Inbound{})
dest3 := net.TCPDestination(net.LocalHostIPv6, 18374) dest3 := net.TCPDestination(net.LocalHostIPv6, 18374)
s3 := &Session{ID: 3, target: dest3, inbound: &session.Inbound{}, first: true} writer3 := NewWriter(3, dest3, pWriter, protocol.TransferTypeStream, [8]byte{}, &session.Inbound{})
writePayload := func(s *Session, payload ...byte) error { writePayload := func(writer *Writer, payload ...byte) error {
b := buf.New() b := buf.New()
b.Write(payload) b.Write(payload)
data := buf.MultiBuffer{b} return writer.WriteMultiBuffer(buf.MultiBuffer{b})
defer func() { buf.ReleaseMulti(data) }()
frames, err := s.encodeBatch(&data)
if err != nil {
buf.ReleaseMulti(frames)
return err
}
return pWriter.WriteMultiBuffer(frames)
} }
common.Must(writePayload(s1, 'a', 'b', 'c', 'd')) common.Must(writePayload(writer, 'a', 'b', 'c', 'd'))
common.Must(writePayload(s2)) common.Must(writePayload(writer2))
common.Must(writePayload(s1, 'e', 'f', 'g', 'h')) common.Must(writePayload(writer, 'e', 'f', 'g', 'h'))
common.Must(writePayload(s3, 'x')) common.Must(writePayload(writer3, 'x'))
common.Must(pWriter.WriteMultiBuffer(endFrame(s1.ID, false))) writer.Close()
common.Must(pWriter.WriteMultiBuffer(endFrame(s3.ID, false))) writer3.Close()
common.Must(writePayload(s2, 'y')) common.Must(writePayload(writer2, 'y'))
common.Must(pWriter.WriteMultiBuffer(endFrame(s2.ID, false))) writer2.Close()
bytesReader := &buf.BufferedReader{Reader: pReader} bytesReader := &buf.BufferedReader{Reader: pReader}
@@ -79,7 +73,7 @@ func TestReaderWriter(t *testing.T) {
t.Error("metadata: ", r) t.Error("metadata: ", r)
} }
data, err := readAll(crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, bytesReader, 1)) data, err := readAll(NewStreamReader(bytesReader))
common.Must(err) common.Must(err)
if s := data.String(); s != "abcd" { if s := data.String(); s != "abcd" {
t.Error("data: ", s) t.Error("data: ", s)
@@ -110,7 +104,7 @@ func TestReaderWriter(t *testing.T) {
t.Error("meta: ", r) t.Error("meta: ", r)
} }
data, err := readAll(crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, bytesReader, 1)) data, err := readAll(NewStreamReader(bytesReader))
common.Must(err) common.Must(err)
if s := data.String(); s != "efgh" { if s := data.String(); s != "efgh" {
t.Error("data: ", s) t.Error("data: ", s)
@@ -129,7 +123,7 @@ func TestReaderWriter(t *testing.T) {
t.Error("meta: ", r) t.Error("meta: ", r)
} }
data, err := readAll(crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, bytesReader, 1)) data, err := readAll(NewStreamReader(bytesReader))
common.Must(err) common.Must(err)
if s := data.String(); s != "x" { if s := data.String(); s != "x" {
t.Error("data: ", s) t.Error("data: ", s)
@@ -171,7 +165,7 @@ func TestReaderWriter(t *testing.T) {
t.Error("meta: ", r) t.Error("meta: ", r)
} }
data, err := readAll(crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, bytesReader, 1)) data, err := readAll(NewStreamReader(bytesReader))
common.Must(err) common.Must(err)
if s := data.String(); s != "y" { if s := data.String(); s != "y" {
t.Error("data: ", s) t.Error("data: ", s)
+60
View File
@@ -0,0 +1,60 @@
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
@@ -0,0 +1,386 @@
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
}
}
}
}
@@ -1,16 +1,15 @@
package multiplex_test package mux_test
import ( import (
"context" "context"
"fmt"
"testing" "testing"
"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/mux"
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/common/task" "github.com/xtls/xray-core/features/routing"
"github.com/xtls/xray-core/proxy/vless/multiplex"
"github.com/xtls/xray-core/transport" "github.com/xtls/xray-core/transport"
"github.com/xtls/xray-core/transport/pipe" "github.com/xtls/xray-core/transport/pipe"
) )
@@ -33,51 +32,66 @@ func newLinkPair() (*transport.Link, *transport.Link) {
return uplink, downlink return uplink, downlink
} }
type TestDispatcher struct {
OnDispatch func(ctx context.Context, dest net.Destination) (*transport.Link, error)
}
func (d *TestDispatcher) Dispatch(ctx context.Context, dest net.Destination) (*transport.Link, error) {
return d.OnDispatch(ctx, dest)
}
func (d *TestDispatcher) DispatchLink(ctx context.Context, destination net.Destination, outbound *transport.Link) error {
return nil
}
func (d *TestDispatcher) Start() error {
return nil
}
func (d *TestDispatcher) Close() error {
return nil
}
func (*TestDispatcher) Type() interface{} {
return routing.DispatcherType()
}
func TestRegressionOutboundLeak(t *testing.T) { func TestRegressionOutboundLeak(t *testing.T) {
originalOutbounds := []*session.Outbound{{}} originalOutbounds := []*session.Outbound{{}}
serverCtx := session.ContextWithOutbounds(context.Background(), originalOutbounds) serverCtx := session.ContextWithOutbounds(context.Background(), originalOutbounds)
websiteUplink, websiteDownlink := newLinkPair() websiteUplink, websiteDownlink := newLinkPair()
dispatch := func(ctx context.Context, dest net.Destination, link *transport.Link) error { dispatcher := TestDispatcher{
// Emulate DefaultDispatcher's context mutation while forwarding real data. OnDispatch: func(ctx context.Context, dest net.Destination) (*transport.Link, error) {
// emulate what DefaultRouter.Dispatch does, and mutate something on the context
ob := session.OutboundsFromContext(ctx)[0] ob := session.OutboundsFromContext(ctx)[0]
ob.Target = dest ob.Target = dest
return task.Run(ctx, return websiteDownlink, nil
func() error { return buf.Copy(link.Reader, websiteDownlink.Writer) }, },
func() error { return buf.Copy(websiteDownlink.Reader, link.Writer) })
} }
multiplexServerUplink, multiplexServerDownlink := newLinkPair() muxServerUplink, muxServerDownlink := newLinkPair()
multiplex.NewServerWorker(serverCtx, dispatch, multiplexServerUplink) _, err := mux.NewServerWorker(serverCtx, &dispatcher, muxServerUplink)
common.Must(err)
client := multiplex.NewClientWorker(context.Background(), *multiplexServerDownlink, multiplex.ClientStrategy{}) client, err := mux.NewClientWorker(*muxServerDownlink, mux.ClientStrategy{})
common.Must(err)
clientCtx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{ clientCtx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80), Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80),
}}) }})
multiplexClientUplink, multiplexClientDownlink := newLinkPair() muxClientUplink, muxClientDownlink := newLinkPair()
dispatched := make(chan error, 1) ok := client.Dispatch(clientCtx, muxClientUplink)
go func() { if !ok {
dispatched <- multiplex.Dispatch(clientCtx, multiplexClientUplink, func(ctx context.Context, s *multiplex.Session) error { t.Error("failed to dispatch")
if !client.TryAdmit(ctx, s) {
return fmt.Errorf("unable to admit test child")
} }
return nil
})
}()
defer func() {
client.Close()
if err := <-dispatched; err != nil {
t.Error("failed to dispatch: ", err)
}
}()
{ {
b := buf.FromBytes([]byte("hello")) b := buf.FromBytes([]byte("hello"))
common.Must(multiplexClientDownlink.Writer.WriteMultiBuffer(buf.MultiBuffer{b})) common.Must(muxClientDownlink.Writer.WriteMultiBuffer(buf.MultiBuffer{b}))
} }
resMb, err := websiteUplink.Reader.ReadMultiBuffer() resMb, err := websiteUplink.Reader.ReadMultiBuffer()
@@ -92,7 +106,7 @@ func TestRegressionOutboundLeak(t *testing.T) {
common.Must(websiteUplink.Writer.WriteMultiBuffer(buf.MultiBuffer{b})) common.Must(websiteUplink.Writer.WriteMultiBuffer(buf.MultiBuffer{b}))
} }
resMb, err = multiplexClientDownlink.Reader.ReadMultiBuffer() resMb, err = muxClientDownlink.Reader.ReadMultiBuffer()
common.Must(err) common.Must(err)
res = resMb.String() res = resMb.String()
if res != "world" { if res != "world" {
+254
View File
@@ -0,0 +1,254 @@
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
@@ -0,0 +1,51 @@
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
@@ -0,0 +1,136 @@
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,7 +128,6 @@ 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 {
@@ -141,7 +140,5 @@ 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
View File
@@ -1,7 +1,6 @@
package protocol package protocol
import ( import (
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
) )
@@ -18,9 +17,6 @@ func NewServerSpec(dest net.Destination, user *MemoryUser) *ServerSpec {
} }
func NewServerSpecFromPB(spec *ServerEndpoint) (*ServerSpec, error) { func NewServerSpecFromPB(spec *ServerEndpoint) (*ServerSpec, error) {
if spec == nil || spec.Address == nil {
return nil, errors.New("server address is not set")
}
dest := net.TCPDestination(spec.Address.AsAddress(), net.Port(spec.Port)) dest := net.TCPDestination(spec.Address.AsAddress(), net.Port(spec.Port))
var dUser *MemoryUser var dUser *MemoryUser
if spec.User != nil { if spec.User != nil {
+8
View File
@@ -191,10 +191,18 @@ func getConfig() string {
{ {
"protocol": "vless", "protocol": "vless",
"settings": { "settings": {
"vnext": [
{
"address": "1.2.3.4", "address": "1.2.3.4",
"port": 1234, "port": 1234,
"users": [
{
"id": "4784f9b8-a879-4fec-9718-ebddefa47750", "id": "4784f9b8-a879-4fec-9718-ebddefa47750",
"encryption": "none" "encryption": "none"
}
]
}
]
}, },
"tag": "XHTTP_IN", "tag": "XHTTP_IN",
"streamSettings": { "streamSettings": {
-5
View File
@@ -77,11 +77,6 @@ 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)
} }
+1
View File
@@ -71,6 +71,7 @@ func (t *ActivityTimer) SetTimeout(timeout time.Duration) {
} }
common.CloseIfExists(t.checkTask) common.CloseIfExists(t.checkTask)
t.checkTask = newCheckTask t.checkTask = newCheckTask
t.Update()
common.Must(newCheckTask.Start()) common.Must(newCheckTask.Start())
} }
+7 -3
View File
@@ -58,11 +58,15 @@ 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 != 2 { if value != 3 {
t.Fatal("expected 2, but got ", value) t.Fatal("expected 3, but got ", value)
} }
time.Sleep(time.Second * 4) time.Sleep(time.Second * 4)
if value != 2 { if value != 3 {
t.Fatal("expected 2, but got ", value) t.Fatal("expected 3, but got ", value)
} }
common.Must(task.Start()) common.Must(task.Start())
time.Sleep(time.Second * 3) time.Sleep(time.Second * 3)
if value != 3 { if value != 5 {
t.Fatal("Expected 3, but ", value) t.Fatal("Expected 5, but ", value)
} }
common.Must(task.Close()) common.Must(task.Close())
} }
+1
View File
@@ -2,6 +2,7 @@ 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.65.1-0.20261109005002-2895f039137a github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c
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.59.0 golang.org/x/crypto v0.58.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.63.0 golang.org/x/net v0.62.0
golang.org/x/sync v0.25.0 golang.org/x/sync v0.24.0
golang.org/x/sys v0.50.0 golang.org/x/sys v0.49.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.5.3 lukechampine.com/blake3 v1.4.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.44.0 // indirect golang.org/x/text v0.43.0 // indirect
golang.org/x/tools v0.52.0 // indirect golang.org/x/tools v0.51.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
+18 -16
View File
@@ -1,5 +1,5 @@
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 h1:cxK8qTA0YCsj68A7zLYDCfPgMTOyt3ePkHh+oXEmYU0=
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a/go.mod h1:J7UZVOMF2M1LiE3iiUZWPuy8YCPAcLJOwVURrfJCvc0= github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c/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,6 +31,8 @@ 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=
@@ -95,8 +97,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.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
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=
@@ -107,12 +109,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.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0= golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig= golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
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.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sync v0.24.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=
@@ -121,22 +123,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.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/sys v0.49.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.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
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.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI=
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA=
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=
@@ -168,7 +170,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.5.3 h1:q4Ru9Zisjt/knP3KQYuk63VDPnREbSOA6cuL6UwrDlI= lukechampine.com/blake3 v1.4.1 h1:I3Smz7gso8w4/TunLKec6K2fn+kyKtDxr/xcQEN84Wg=
lukechampine.com/blake3 v1.5.3/go.mod h1:+mObCTICmKFFJzAZ+4qqw23+LrWOuO+Zfj3DQiNQFXs= lukechampine.com/blake3 v1.4.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=
-6
View File
@@ -47,9 +47,6 @@ type Address struct {
// MarshalJSON implements encoding/json.Marshaler.MarshalJSON // MarshalJSON implements encoding/json.Marshaler.MarshalJSON
func (v *Address) MarshalJSON() ([]byte, error) { func (v *Address) MarshalJSON() ([]byte, error) {
if v.Address == nil {
return json.Marshal(net.AnyIP.String())
}
return json.Marshal(v.Address.String()) return json.Marshal(v.Address.String())
} }
@@ -71,9 +68,6 @@ func (v *Address) Build() *net.IPOrDomain {
if v == nil { if v == nil {
return nil return nil
} }
if v.Address == nil {
return net.NewIPOrDomain(net.AnyIP)
}
return net.NewIPOrDomain(v.Address) return net.NewIPOrDomain(v.Address)
} }
+52 -13
View File
@@ -1,6 +1,9 @@
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"
@@ -46,37 +49,73 @@ 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 {
server := &protocol.ServerEndpoint{ v.Servers = []*HTTPRemoteConfig{
Address: v.Address.Build(), {
Port: uint32(v.Port), Address: v.Address,
Port: v.Port,
},
} }
if len(v.Username) > 0 { if len(v.Username) > 0 {
account := &HTTPAccount{ v.Servers[0].Users = []json.RawMessage{{}}
Username: v.Username,
Password: v.Password,
} }
user := &protocol.User{
Level: v.Level,
Email: v.Email,
Account: serial.ToTypedMessage(account.Build()),
} }
if len(v.Servers) != 1 {
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`)
}
for _, serverConfig := range v.Servers {
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`)
}
server := &protocol.ServerEndpoint{
Address: serverConfig.Address.Build(),
Port: uint32(serverConfig.Port),
}
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 server.User = user
break
} }
config.Server = server config.Server = server
break
}
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{
+1 -1
View File
@@ -12,7 +12,7 @@ import (
type HysteriaClientConfig struct { type HysteriaClientConfig struct {
Version int32 `json:"version"` Version int32 `json:"version"`
Address Address `json:"address"` Address *Address `json:"address"`
Port uint16 `json:"port"` Port uint16 `json:"port"`
} }
+4 -1
View File
@@ -12,12 +12,15 @@ import (
) )
type MasqueClientConfig struct { type MasqueClientConfig struct {
Address Address `json:"address"` Address *Address `json:"address"`
Port uint16 `json:"port"` Port uint16 `json:"port"`
RemoteDNS []string `json:"remoteDNS"` RemoteDNS []string `json:"remoteDNS"`
} }
func (c *MasqueClientConfig) Build() (proto.Message, error) { func (c *MasqueClientConfig) Build() (proto.Message, error) {
if c.Address == nil {
return nil, errors.New(`MASQUE: "address" is not set`)
}
if c.Port == 0 { if c.Port == 0 {
return nil, errors.New(`MASQUE: "port" is not set`) return nil, errors.New(`MASQUE: "port" is not set`)
} }
+56
View File
@@ -0,0 +1,56 @@
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
@@ -0,0 +1,45 @@
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"},
},
},
},
})
}
+51 -22
View File
@@ -177,8 +177,8 @@ func buildShadowsocks2022(v *ShadowsocksServerConfig) (proto.Message, error) {
return config, nil return config, nil
} }
type ShadowsocksClientConfig struct { type ShadowsocksServerTarget 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"`
@@ -186,40 +186,69 @@ type ShadowsocksClientConfig 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.Port == 0 { 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.")
}
if server.Port == 0 {
return nil, errors.New("Invalid Shadowsocks port.") return nil, errors.New("Invalid Shadowsocks port.")
} }
if v.Password == "" { if server.Password == "" {
return nil, errors.New("Shadowsocks password is not specified.") return nil, errors.New("Shadowsocks password is not specified.")
} }
if _, err := shadowsocks_2022.GetCipherMethod(v.Cipher); err == nil { if _, err := shadowsocks_2022.GetCipherMethod(server.Cipher); err == nil {
config := &shadowsocks_2022.ClientConfig{ config := new(shadowsocks_2022.ClientConfig)
Address: v.Address.Build(), config.Address = server.Address.Build()
Port: uint32(v.Port), config.Port = uint32(server.Port)
Method: v.Cipher, config.Method = server.Cipher
Key: v.Password, config.Key = server.Password
}
return config, nil return config, nil
} }
config := new(shadowsocks.ClientConfig) config := new(shadowsocks.ClientConfig)
if cipherFromString(v.Cipher) == shadowsocks.CipherType_UNKNOWN { account := &shadowsocks.Account{
return nil, errors.New("unknown cipher method: ", v.Cipher) Password: server.Password,
}
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: v.Address.Build(), Address: server.Address.Build(),
Port: uint32(v.Port), Port: uint32(server.Port),
User: &protocol.User{ User: &protocol.User{
Level: uint32(v.Level), Level: uint32(server.Level),
Email: v.Email, Email: server.Email,
Account: serial.ToTypedMessage(&shadowsocks.Account{ Account: serial.ToTypedMessage(account),
Password: v.Password,
CipherType: cipherFromString(v.Cipher),
}),
}, },
} }
config.Server = ss config.Server = ss
+52 -13
View File
@@ -1,6 +1,9 @@
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"
@@ -64,35 +67,71 @@ 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 {
server := &protocol.ServerEndpoint{ v.Servers = []*SocksRemoteConfig{
Address: v.Address.Build(), {
Port: uint32(v.Port), Address: v.Address,
Port: v.Port,
},
} }
if len(v.Username) > 0 { if len(v.Username) > 0 {
account := &SocksAccount{ v.Servers[0].Users = []json.RawMessage{{}}
Username: v.Username,
Password: v.Password,
} }
user := &protocol.User{
Level: v.Level,
Email: v.Email,
Account: serial.ToTypedMessage(account.Build()),
} }
if len(v.Servers) != 1 {
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`)
}
for _, serverConfig := range v.Servers {
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`)
}
server := &protocol.ServerEndpoint{
Address: serverConfig.Address.Build(),
Port: uint32(serverConfig.Port),
}
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 server.User = user
break
} }
config.Server = server config.Server = server
break
}
return config, nil return config, nil
} }
+29
View File
@@ -53,6 +53,35 @@ 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",
+13 -117
View File
@@ -2,8 +2,6 @@ package conf
import ( import (
"context" "context"
"crypto/rand"
"crypto/rsa"
"crypto/x509" "crypto/x509"
"encoding/base64" "encoding/base64"
"encoding/hex" "encoding/hex"
@@ -867,7 +865,6 @@ 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 {
@@ -894,7 +891,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), c.Domains[i].Alphabet) 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))
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -905,7 +902,6 @@ 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,
}) })
} }
} }
@@ -929,9 +925,6 @@ func (c *XDNS) Build() (proto.Message, error) {
return nil, err return nil, err
} }
quicConfig = proto.(*internet.QuicParams) quicConfig = proto.(*internet.QuicParams)
if quicConfig.Congestion == "brutal" {
return nil, errors.New(`XDNS: "brutal" is for Hysteria, use "force-brutal", "bbr" or "reno"`)
}
} }
for j := range c.Resolvers[i].Addrs { for j := range c.Resolvers[i].Addrs {
var u *url.URL var u *url.URL
@@ -972,23 +965,11 @@ type XMC struct {
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
// same; an absent one keeps the built-in preset. // same; an absent one keeps the built-in preset.
NoPadding bool `json:"noPadding,omitempty"` NoPadding bool `json:"noPadding,omitempty"`
// Custom payload channels that carry the tunnel byte stream and the startup
// padding. Both ends must use the same pair; empty keeps the defaults
// (xmc:data / xmc:pad). Vanilla's "minecraft" namespace is rejected.
DataChannel string `json:"dataChannel,omitempty"`
PaddingChannel string `json:"paddingChannel,omitempty"`
// Minecraft network protocol number the client advertises, for example 777
// for 26.3. Zero detects it from the peer's status response (cached per
// destination) and falls back to the newest version the mask knows. Set it to
// skip detection or to pin a version; the server follows whatever the client
// names.
ProtocolVersion uint32 `json:"protocolVersion,omitempty"`
} }
type XMCPaddingTurn struct { type XMCPaddingTurn struct {
@@ -1001,19 +982,6 @@ 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.
@@ -1047,6 +1015,16 @@ 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.
@@ -1054,21 +1032,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")
} }
if err := xmc.ValidateProtocolVersion(c.ProtocolVersion); err != nil { config := &xmc.Config{Password: c.Password, Hostname: c.Hostname, NoPadding: noPadding}
return nil, fmt.Errorf("minecraft protocolVersion: %w", err)
}
config := &xmc.Config{
Hostname: c.Hostname,
NoPadding: noPadding,
DataChannel: c.DataChannel,
PaddingChannel: c.PaddingChannel,
ProtocolVersion: c.ProtocolVersion,
}
dataChannel, paddingChannel, channelErr := config.ChannelIDs()
if channelErr != nil {
return nil, fmt.Errorf("minecraft channels: %w", channelErr)
}
config.DataChannel, config.PaddingChannel = dataChannel, paddingChannel
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 {
@@ -1101,76 +1065,10 @@ func (c *XMC) Build() (proto.Message, error) {
return nil, fmt.Errorf("minecraft padding: %w", err) return nil, fmt.Errorf("minecraft padding: %w", err)
} }
var yggdrasil *xmc.Yggdrasil rsaPrivateKey, err := xmc.DeriveRSAKey(c.Password)
if c.Yggdrasil != nil {
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 { if err != nil {
return nil, fmt.Errorf("derive minecraft rsa key: %w", err) 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)
if err != nil { if err != nil {
@@ -1186,11 +1084,9 @@ 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
} }
-181
View File
@@ -1,7 +1,6 @@
package conf package conf
import ( import (
"crypto/x509"
"encoding/json" "encoding/json"
"strings" "strings"
"testing" "testing"
@@ -114,96 +113,6 @@ 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",
@@ -242,93 +151,3 @@ func TestXMCBuildDisablesPadding(t *testing.T) {
t.Fatalf("expected an exclusive padding error, got %v", err) t.Fatalf("expected an exclusive padding error, got %v", err)
} }
} }
func xmcTestProfiles() []XMCProfile {
return []XMCProfile{{
Username: "TestUser",
UUID: "00112233-4455-6677-8899-aabbccddeeff",
TexturesValue: "textures-value",
TexturesSignature: "textures-signature",
}}
}
func TestXMCBuildChannels(t *testing.T) {
built, err := (&XMC{
Password: "test-password",
Profiles: xmcTestProfiles(),
DataChannel: "myxmc:stream",
PaddingChannel: "myxmc:noise",
}).Build()
if err != nil {
t.Fatalf("build XMC config: %v", err)
}
config := built.(*xmc.Config)
if config.DataChannel != "myxmc:stream" || config.PaddingChannel != "myxmc:noise" {
t.Fatalf("channels = %q, %q", config.DataChannel, config.PaddingChannel)
}
}
func TestXMCBuildChannelDefaults(t *testing.T) {
built, err := (&XMC{Password: "test-password", Profiles: xmcTestProfiles()}).Build()
if err != nil {
t.Fatalf("build XMC config: %v", err)
}
config := built.(*xmc.Config)
if config.DataChannel != xmc.DefaultDataChannel || config.PaddingChannel != xmc.DefaultPaddingChannel {
t.Fatalf("default channels = %q, %q", config.DataChannel, config.PaddingChannel)
}
}
func TestXMCBuildRejectsChannels(t *testing.T) {
cases := map[string]struct {
data string
padding string
}{
"vanilla_namespace": {"minecraft:data", ""},
"no_colon": {"xmcdata", ""},
"empty_path": {"xmc:", ""},
"uppercase": {"Xmc:data", ""},
"same_channel": {"xmc:same", "xmc:same"},
"too_long": {strings.Repeat("a", 129) + ":b", ""},
}
for name, test := range cases {
_, err := (&XMC{
Password: "test-password",
Profiles: xmcTestProfiles(),
DataChannel: test.data,
PaddingChannel: test.padding,
}).Build()
if err == nil || !strings.Contains(err.Error(), "channel") {
t.Fatalf("%s: expected a channel error, got %v", name, err)
}
}
}
func TestXMCBuildProtocolVersion(t *testing.T) {
profile := XMCProfile{
Username: "TestUser",
UUID: "00112233-4455-6677-8899-aabbccddeeff",
TexturesValue: "textures-value",
TexturesSignature: "textures-signature",
}
built, err := (&XMC{Password: "test-password", Profiles: []XMCProfile{profile}}).Build()
if err != nil {
t.Fatalf("build default XMC config: %v", err)
}
if got := built.(*xmc.Config).ProtocolVersion; got != 0 {
t.Fatalf("default protocol version = %d, want 0 (newest)", got)
}
built, err = (&XMC{Password: "test-password", Profiles: []XMCProfile{profile}, ProtocolVersion: 775}).Build()
if err != nil {
t.Fatalf("build XMC config with a protocol version: %v", err)
}
if got := built.(*xmc.Config).ProtocolVersion; got != 775 {
t.Fatalf("protocol version = %d, want 775", got)
}
if _, err = (&XMC{Password: "test-password", Profiles: []XMCProfile{profile}, ProtocolVersion: 778}).Build(); err == nil || !strings.Contains(err.Error(), "unsupported protocol version 778") {
t.Fatalf("expected an unknown protocol version to be rejected, got %v", err)
}
}
-3
View File
@@ -277,9 +277,6 @@ func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
return nil, errors.New(`XDRIVE: brutal is for Hysteria servers, over h3 "congestion" is "bbr" or "reno", not "`, config.QuicParams.Congestion, `"`) return nil, errors.New(`XDRIVE: brutal is for Hysteria servers, over h3 "congestion" is "bbr" or "reno", not "`, config.QuicParams.Congestion, `"`)
} }
} }
if config.ProtocolName == "splithttp" && config.QuicParams != nil && config.QuicParams.Congestion == "brutal" {
return nil, errors.New(`XHTTP: "brutal" is for Hysteria, use "force-brutal", "bbr" or "reno"`)
}
return config, nil return config, nil
} }
-3
View File
@@ -455,9 +455,6 @@ func (c *SplitHTTPConfig) Build() (proto.Message, error) {
if c.ServerMaxHeaderBytes < 0 { if c.ServerMaxHeaderBytes < 0 {
return nil, errors.New("invalid negative value of maxHeaderBytes") return nil, errors.New("invalid negative value of maxHeaderBytes")
} }
if c.ScMaxEachPostBytes.From < 0 || c.ScMaxEachPostBytes.To < 0 || (c.ScMaxEachPostBytes.To > 0 && c.ScMaxEachPostBytes.From <= 0) {
return nil, errors.New("`scMaxEachPostBytes` must be greater than 0")
}
if c.Xmux.MaxConnections.To > 0 && c.Xmux.MaxConcurrency.To > 0 { if c.Xmux.MaxConnections.To > 0 && c.Xmux.MaxConcurrency.To > 0 {
return nil, errors.New("maxConnections cannot be specified together with maxConcurrency") return nil, errors.New("maxConnections cannot be specified together with maxConcurrency")
+13 -9
View File
@@ -529,22 +529,26 @@ func TestXDriveOutboundConfig(t *testing.T) {
} }
for _, input := range []string{ for _, input := range []string{
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`,
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8, "xudpConcurrency": 8, "xudpProxyUDP443": "allow"}}, ` + xdriveStream + `}`, `{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": 0, "xudpConcurrency": 8, "xudpProxyUDP443": "allow"}}`,
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "reverse": {"tag": "r"}}, ` + xdriveStream + `}`, `{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "reverse": {"tag": "r"}}, ` + xdriveStream + `}`,
`{"protocol": "vless", "settings": {"address": "127.0.0.1", "port": 443, ` + xdriveID + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `}]}]}, ` + xdriveStream + `, "mux": {"enabled": true}}`,
} { } {
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", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"encryption"`}, {`{"protocol": "vless", "settings": {` + xdriveServer + `, "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": {"address": "example.com", "port": 443, ` + xdriveID + `, "encryption": "none"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"encryption"`},
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8, "xudpProxyUDP443": "skip"}}, ` + xdriveStream + `}`, `"xudpProxyUDP443":"skip"`}, {`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `}`, `"mux"`},
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`}, {`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": false}}`, `"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, "concurrency": -1}}`, `"mux"`},
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "testpre": 1, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"testpre"`}, {`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "xudpConcurrency": -1}}`, `"mux"`},
{`{"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"},
+52 -10
View File
@@ -17,40 +17,78 @@ import (
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
) )
// TrojanClientConfig is configuration of trojan servers // TrojanServerTarget is configuration of a single trojan server
type TrojanClientConfig struct { type TrojanServerTarget 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{}
if c.Port == 0 { for _, rec := range c.Servers {
if rec.Address == nil {
return nil, errors.New("Trojan server address is not set.")
}
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: c.Address.Build(), Address: rec.Address.Build(),
Port: uint32(c.Port), Port: uint32(rec.Port),
User: &protocol.User{ User: &protocol.User{
Level: uint32(c.Level), Level: uint32(rec.Level),
Email: c.Email, Email: rec.Email,
Account: serial.ToTypedMessage(&trojan.Account{ Account: serial.ToTypedMessage(&trojan.Account{
Password: c.Password, Password: rec.Password,
}), }),
}, },
} }
break
}
return config, nil return config, nil
} }
@@ -69,6 +107,7 @@ 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
@@ -92,6 +131,9 @@ 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,7 +7,6 @@ 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"
@@ -17,7 +16,6 @@ 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"`
@@ -39,13 +37,6 @@ 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,49 +124,3 @@ 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)
}
}
}
+139 -125
View File
@@ -17,7 +17,6 @@ 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"
) )
@@ -104,15 +103,56 @@ func (c *VLessInboundConfig) Build() (proto.Message, error) {
return nil, err return nil, err
} }
dec, err := parseVLESSEncryption(c.Decryption, false) config.Decryption = c.Decryption
if err != nil { if !func() bool {
return nil, err s := strings.Split(config.Decryption, ".")
if len(s) < 4 || s[0] != "mlkem768x25519plus" {
return false
}
switch s[1] {
case "native":
case "xorpub":
config.XorMode = 1
case "random":
config.XorMode = 2
default:
return false
}
t := strings.SplitN(strings.TrimSuffix(s[2], "s"), "-", 2)
i, err := strconv.Atoi(t[0])
if err != nil {
return false
}
config.SecondsFrom = int64(i)
if len(t) == 2 {
i, err := strconv.Atoi(t[1])
if err != nil {
return false
}
config.SecondsTo = int64(i)
}
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) != 64 {
return false
}
}
config.Decryption = config.Decryption[27+len(s[2]):]
if padding > 0 {
config.Padding = config.Decryption[:padding-1]
config.Decryption = config.Decryption[padding:]
}
return true
}() && config.Decryption != "none" {
if config.Decryption == "" {
return nil, errors.New(`VLESS settings: please add/set "decryption":"none" to every settings`)
}
return nil, errors.New(`VLESS settings: unsupported "decryption": ` + config.Decryption)
} }
config.Decryption = dec.key
config.Padding = dec.padding
config.XorMode = dec.xorMode
config.SecondsFrom = dec.secondsFrom
config.SecondsTo = dec.secondsTo
if config.Decryption != "none" && c.Fallbacks != nil { if config.Decryption != "none" && c.Fallbacks != nil {
return nil, errors.New(`VLESS settings: "fallbacks" can not be used together with "decryption"`) return nil, errors.New(`VLESS settings: "fallbacks" can not be used together with "decryption"`)
@@ -196,27 +236,14 @@ func (c *VLessReverseConfig) Build() (*vless.Reverse, error) {
return r, nil return r, nil
} }
type MultiplexConfig struct { type VLessOutboundVnext struct {
Concurrency int16 `json:"concurrency"` Address *Address `json:"address"`
XudpConcurrency int16 `json:"xudpConcurrency"` Port uint16 `json:"port"`
XudpProxyUDP443 string `json:"xudpProxyUDP443"` Users []json.RawMessage `json:"users"`
}
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"`
@@ -224,48 +251,54 @@ type VLessOutboundConfig struct {
Flow string `json:"flow"` Flow string `json:"flow"`
Seed string `json:"seed"` Seed string `json:"seed"`
Encryption string `json:"encryption"` Encryption string `json:"encryption"`
Multiplex *MultiplexConfig `json:"multiplex"`
Reverse *VLessReverseConfig `json:"reverse"` Reverse *VLessReverseConfig `json:"reverse"`
Testpre uint32 `json:"testpre"` Testpre uint32 `json:"testpre"`
Testseed []uint32 `json:"testseed"` Testseed []uint32 `json:"testseed"`
Vnext []*VLessOutboundVnext `json:"vnext"`
} }
// Build implements Buildable // Build implements Buildable
func (c *VLessOutboundConfig) Build() (proto.Message, error) { func (c *VLessOutboundConfig) Build() (proto.Message, error) {
multiplex, err := c.Multiplex.Build() config := new(outbound.Config)
if err != nil { if c.Address != nil {
return nil, err c.Vnext = []*VLessOutboundVnext{
{
Address: c.Address,
Port: c.Port,
Users: []json.RawMessage{{}},
},
} }
config := &outbound.Config{Multiplex: multiplex}
uid, err := uuid.ParseString(c.Id)
if err != nil {
return nil, err
} }
if len(c.Vnext) != 1 {
switch c.Flow { 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`)
case "": }
case vless.XRV, vless.XRV + "-udp443": for _, rec := range c.Vnext {
default: if rec.Address == nil {
return nil, errors.New(`VLESS users: "flow" doesn't support "` + c.Flow + `" in this version`) return nil, errors.New(`VLESS vnext: "address" is not set`)
}
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{ spec := &protocol.ServerEndpoint{
Address: c.Address.Build(), Address: rec.Address.Build(),
Port: uint32(c.Port), Port: uint32(rec.Port),
} }
user := &protocol.User{ for _, rawUser := range rec.Users {
Level: c.Level, user := new(protocol.User)
Email: c.Email, 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 := &vless.Account{
Id: uid.String(),
Flow: c.Flow,
// Seed: c.Seed,
Encryption: c.Encryption,
Testpre: c.Testpre,
Testseed: c.Testseed,
} }
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 { if c.Reverse != nil {
rvs, err := c.Reverse.Build() rvs, err := c.Reverse.Build()
if err != nil { if err != nil {
@@ -273,103 +306,84 @@ func (c *VLessOutboundConfig) Build() (proto.Message, error) {
} }
account.Reverse = rvs 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"`)
}
}
enc, err := parseVLESSEncryption(account.Encryption, true) u, err := uuid.ParseString(account.Id)
if err != nil { if err != nil {
return nil, err return nil, err
} }
account.Encryption = enc.key account.Id = u.String()
account.Padding = enc.padding
account.XorMode = enc.xorMode
account.Seconds = enc.seconds
user.Account = serial.ToTypedMessage(account) switch account.Flow {
spec.User = user case "":
case vless.XRV, vless.XRV + "-udp443":
config.Vnext = spec default:
return config, nil return nil, errors.New(`VLESS users: "flow" doesn't support "` + account.Flow + `" in this version`)
}
type parsedVLESSEncryption struct {
key string
padding string
xorMode uint32
seconds uint32
secondsFrom int64
secondsTo int64
}
func parseVLESSEncryption(raw string, isOutbound bool) (parsedVLESSEncryption, error) {
field, scope := "decryption", "settings"
if isOutbound {
field, scope = "encryption", "users"
} }
if raw == "" {
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: please add/set "`, field, `":"none"`) if !func() bool {
} s := strings.Split(account.Encryption, ".")
if raw == "none" {
return parsedVLESSEncryption{key: "none"}, nil
}
s := strings.Split(raw, ".")
if len(s) < 4 || s[0] != "mlkem768x25519plus" { if len(s) < 4 || s[0] != "mlkem768x25519plus" {
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: unsupported "`, field, `": `, raw) return false
} }
var out parsedVLESSEncryption
switch s[1] { switch s[1] {
case "native": case "native":
case "xorpub": case "xorpub":
out.xorMode = 1 account.XorMode = 1
case "random": case "random":
out.xorMode = 2 account.XorMode = 2
default: default:
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: unsupported "`, field, `" mode: `, s[1]) return false
} }
if isOutbound {
switch s[2] { switch s[2] {
case "1rtt": case "1rtt":
case "0rtt": case "0rtt":
out.seconds = 1 account.Seconds = 1
default: default:
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: unsupported "`, field, `" rtt: `, s[2]) return false
}
} else {
t := strings.SplitN(strings.TrimSuffix(s[2], "s"), "-", 2)
i, err := strconv.Atoi(t[0])
if err != nil {
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: invalid "`, field, `" seconds: `, s[2]).Base(err)
}
out.secondsFrom = int64(i)
if len(t) == 2 {
i, err := strconv.Atoi(t[1])
if err != nil {
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: invalid "`, field, `" seconds: `, s[2]).Base(err)
}
out.secondsTo = int64(i)
}
}
altKeyLen := 64
if isOutbound {
altKeyLen = 1184
} }
padding := 0 padding := 0
for i, r := range s[3:] { for _, r := range s[3:] {
if len(r) < 20 { if len(r) < 20 {
padding += len(r) + 1 padding += len(r) + 1
continue continue
} }
for _, r := range s[3+i:] { if b, _ := base64.RawURLEncoding.DecodeString(r); len(b) != 32 && len(b) != 1184 {
b, err := base64.RawURLEncoding.DecodeString(r) return false
if err != nil || (len(b) != 32 && len(b) != altKeyLen) {
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: invalid "`, field, `" key segment`)
} }
} }
rest := raw[27+len(s[2]):] account.Encryption = account.Encryption[27+len(s[2]):]
if padding > 0 { if padding > 0 {
out.padding = rest[:padding-1] account.Padding = account.Encryption[:padding-1]
rest = rest[padding:] account.Encryption = account.Encryption[padding:]
} }
out.key = rest return true
return out, nil }() && account.Encryption != "none" {
if account.Encryption == "" {
return nil, errors.New(`VLESS users: please add/set "encryption":"none" for every user`)
} }
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: missing "`, field, `" key segment`) return nil, errors.New(`VLESS users: unsupported "encryption": ` + account.Encryption)
}
user.Account = serial.ToTypedMessage(account)
spec.User = user
break
}
config.Vnext = spec
break
}
return config, nil
} }
+35
View File
@@ -18,6 +18,41 @@ 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",
+62 -25
View File
@@ -102,47 +102,84 @@ 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"`
Multiplex *MultiplexConfig `json:"multiplex"` Receivers []*VMessOutboundTarget `json:"vnext"`
} }
// 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")
multiplex, err := c.Multiplex.Build() config := new(outbound.Config)
if err != nil { if c.Address != nil {
return nil, err c.Receivers = []*VMessOutboundTarget{
} {
config := &outbound.Config{Multiplex: multiplex} Address: c.Address,
Port: c.Port,
uid, err := uuid.ParseString(c.ID) Users: []json.RawMessage{{}},
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()),
}, },
} }
}
if len(c.Receivers) != 1 {
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 err != nil {
return nil, err
}
account.ID = u.String()
user.Account = serial.ToTypedMessage(account.Build())
spec.User = user
break
}
config.Receiver = spec config.Receiver = spec
break
}
return config, nil return config, nil
} }
+36
View File
@@ -18,6 +18,42 @@ 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",
-7
View File
@@ -3,7 +3,6 @@ package conf
import ( import (
"encoding/base64" "encoding/base64"
"encoding/hex" "encoding/hex"
"net/netip"
"strconv" "strconv"
"strings" "strings"
@@ -125,12 +124,6 @@ func (c *WireGuardConfig) Build() (proto.Message, error) {
} }
config.Reserved = c.Reserved config.Reserved = c.Reserved
for _, s := range c.DNS {
if _, err := netip.ParseAddr(s); err != nil {
return nil, errors.New(`WireGuard: invalid "remoteDNS" `, s).Base(err)
}
}
config.IsClient = c.IsClient config.IsClient = c.IsClient
config.NoKernelTun = c.NoKernelTun config.NoKernelTun = c.NoKernelTun
config.DNS = c.DNS config.DNS = c.DNS
+48 -25
View File
@@ -107,6 +107,30 @@ 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"`
@@ -189,7 +213,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, receiverSettings.PortList); err != nil { if err := validateXDrive(ts, receiverSettings.StreamSettings, nil, receiverSettings.PortList); err != nil {
return nil, err return nil, err
} }
@@ -207,7 +231,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"`
LegacyMux json.RawMessage `json:"mux,omitempty"` MuxSettings *MuxConfig `json:"mux"`
TargetStrategy string `json:"targetStrategy"` TargetStrategy string `json:"targetStrategy"`
} }
@@ -232,13 +256,13 @@ func validateOutboundTransportSecurity(rawConfig interface{}, senderSettings *pr
if vlessCfg.Encryption != "" && vlessCfg.Encryption != "none" { if vlessCfg.Encryption != "" && vlessCfg.Encryption != "none" {
return nil return nil
} }
if requiresTransportSecurity(&vlessCfg.Address) { if requiresTransportSecurity(vlessCfg.Address) {
return errors.New("vless without TLS or other encryption is prohibited unless the server address is a private IP or domain") return errors.New("vless without TLS or other encryption is prohibited unless the server address is a private IP or domain")
} }
} }
if tjCfg, ok := rawConfig.(*TrojanClientConfig); ok { if tjCfg, ok := rawConfig.(*TrojanClientConfig); ok {
if requiresTransportSecurity(&tjCfg.Address) { if requiresTransportSecurity(tjCfg.Servers[0].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")
} }
} }
@@ -246,8 +270,8 @@ func validateOutboundTransportSecurity(rawConfig interface{}, senderSettings *pr
return nil return nil
} }
// validateXDrive allows only encrypted VLESS on xdrive, with native multiplex on every client connection. // validateXDrive allows only VLESS with encryption on xdrive, and on the client Mux.Cool for every connection
func validateXDrive(ts proto.Message, ss *internet.StreamConfig, pl *net.PortList) error { func validateXDrive(ts proto.Message, ss *internet.StreamConfig, ms *proxyman.MultiplexingConfig, pl *net.PortList) error {
if ss == nil || ss.ProtocolName != "xdrive" { if ss == nil || ss.ProtocolName != "xdrive" {
return nil return nil
} }
@@ -264,14 +288,9 @@ func validateXDrive(ts proto.Message, ss *internet.StreamConfig, pl *net.PortLis
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 multiplexed connection. // reverse opens its own mux
if account.Reverse == nil { if account.Reverse == nil && (ms == nil || !ms.Enabled || ms.Concurrency < 0 || ms.XudpConcurrency < 0 || ms.XudpProxyUDP443 == "skip") {
if c.Multiplex == nil { return errors.New(`the xdrive transport needs "mux" enabled, with no negative "concurrency" or "xudpConcurrency" and no "xudpProxyUDP443":"skip"`)
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"`)
@@ -357,6 +376,14 @@ 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)
@@ -365,20 +392,11 @@ 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 {
@@ -460,7 +478,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 *json.RawMessage `json:"reverse"` Reverse *ReverseConfig `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"`
@@ -662,6 +680,11 @@ 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 {
+36 -100
View File
@@ -1,7 +1,6 @@
package conf_test package conf_test
import ( import (
"bytes"
"encoding/json" "encoding/json"
"reflect" "reflect"
"testing" "testing"
@@ -11,6 +10,7 @@ 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,7 +18,6 @@ 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"
@@ -226,112 +225,49 @@ func TestSniffingConfig_Build(t *testing.T) {
} }
} }
func TestMultiplexConfig_Build(t *testing.T) { func TestMuxConfig_Build(t *testing.T) {
for _, tc := range []struct {
name string
fields string
want *vless.Multiplex
bad bool
}{
{name: "empty", fields: `{}`},
{name: "both zero", fields: `{"concurrency":0,"xudpConcurrency":0}`},
{name: "regular pool", fields: `{"concurrency":4}`, want: &vless.Multiplex{Concurrency: 4, XudpProxyUDP443: "reject"}},
{name: "XUDP only", fields: `{"xudpConcurrency":8}`, want: &vless.Multiplex{XudpConcurrency: 8, XudpProxyUDP443: "reject"}},
{name: "negative concurrency", fields: `{"concurrency":-1,"xudpConcurrency":8}`, bad: true},
{name: "negative XUDP concurrency", fields: `{"concurrency":4,"xudpConcurrency":-1}`, bad: true},
{name: "invalid UDP policy", fields: `{"concurrency":4,"xudpProxyUDP443":"invalid"}`, bad: true},
} {
t.Run(tc.name, func(t *testing.T) {
var config MultiplexConfig
if err := json.Unmarshal([]byte(tc.fields), &config); err != nil {
t.Fatal(err)
}
got, err := config.Build()
if (err != nil) != tc.bad || !proto.Equal(got, tc.want) {
t.Fatalf("Build() = %v, %v, want config %v, error %t", got, err, tc.want, tc.bad)
}
})
}
}
func TestOutboundMultiplexConfig(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
legacy string fields string
native string want *proxyman.MultiplexingConfig
want *vless.Multiplex
}{ }{
{name: "absent"}, {"default", `{"enabled": true, "concurrency": 16}`, &proxyman.MultiplexingConfig{
{name: "legacy enabled", legacy: `{"enabled":true,"concurrency":16}`}, Enabled: true,
{name: "legacy disabled", legacy: `{"enabled":false}`}, Concurrency: 16,
{name: "legacy null", legacy: `null`}, XudpConcurrency: 0,
{name: "legacy empty", legacy: `{}`}, XudpProxyUDP443: "reject",
{name: "legacy values are not decoded", legacy: `{"enabled":"ignored","concurrency":"ignored"}`}, }},
{name: "empty native object", native: `{}`}, {"empty def", `{}`, &proxyman.MultiplexingConfig{
{name: "enabled flag alone does not create a pool", native: `{"enabled":true}`}, Enabled: false,
{ Concurrency: 0,
name: "positive concurrency with old enabled flag", native: `{"concurrency":4,"enabled":false}`, XudpConcurrency: 0,
want: &vless.Multiplex{Concurrency: 4, XudpProxyUDP443: "reject"}, XudpProxyUDP443: "reject",
}, }},
{ {"not enable", `{"enabled": false, "concurrency": 4}`, &proxyman.MultiplexingConfig{
name: "native XUDP only", native: `{"xudpConcurrency":8}`, Enabled: false,
want: &vless.Multiplex{XudpConcurrency: 8, XudpProxyUDP443: "reject"}, Concurrency: 4,
}, XudpConcurrency: 0,
{ XudpProxyUDP443: "reject",
name: "native options override legacy", legacy: `{"enabled":true,"concurrency":16}`, }},
native: `{"concurrency":4,"xudpConcurrency":8,"xudpProxyUDP443":"allow"}`, {"forbidden", `{"enabled": false, "concurrency": -1}`, &proxyman.MultiplexingConfig{
want: &vless.Multiplex{Concurrency: 4, XudpConcurrency: 8, XudpProxyUDP443: "allow"}, Enabled: false,
}, Concurrency: -1,
{name: "empty native with legacy enabled", legacy: `{"enabled":true}`, native: `{}`}, XudpConcurrency: 0,
XudpProxyUDP443: "reject",
}},
} }
for _, protoName := range []string{"vless", "vmess"} { for _, tt := range tests {
for _, tc := range tests { t.Run(tt.name, func(t *testing.T) {
t.Run(protoName+"/"+tc.name, func(t *testing.T) { m := &MuxConfig{}
settings := `"address":"127.0.0.1","port":443,"id":"d19768cb-2891-4c3c-b45d-863f8fd64b6d"` common.Must(json.Unmarshal([]byte(tt.fields), m))
if protoName == "vless" { if got, _ := m.Build(); !reflect.DeepEqual(got, tt.want) {
settings += `,"encryption":"none"` t.Errorf("MuxConfig.Build() = %v, want %v", got, tt.want)
}
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
@@ -349,7 +285,7 @@ func TestConfig_Override(t *testing.T) {
Policy: &PolicyConfig{}, Policy: &PolicyConfig{},
API: &APIConfig{}, API: &APIConfig{},
Stats: &StatsConfig{}, Stats: &StatsConfig{},
Reverse: &legacyReverse, Reverse: &ReverseConfig{},
}, },
"", "",
&Config{ &Config{
@@ -359,7 +295,7 @@ func TestConfig_Override(t *testing.T) {
Policy: &PolicyConfig{}, Policy: &PolicyConfig{},
API: &APIConfig{}, API: &APIConfig{},
Stats: &StatsConfig{}, Stats: &StatsConfig{},
Reverse: &legacyReverse, Reverse: &ReverseConfig{},
}, },
}, },
{ {
+1
View File
@@ -24,6 +24,7 @@ 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
@@ -1,24 +0,0 @@
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,7 +318,6 @@ 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 {
@@ -351,10 +350,6 @@ 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
+11 -36
View File
@@ -5,7 +5,6 @@ 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"
@@ -175,15 +174,10 @@ 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 {
@@ -199,21 +193,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 {
if *b.UDP != w.lastUDP { addr = b.UDP.NetAddr()
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)
if errTooLarge, ok := go_errors.AsType[*quic.DatagramTooLargeError](err); ok { var errTooLarge *quic.DatagramTooLargeError
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 {
@@ -234,59 +228,40 @@ 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 {
n, err := r.reader.Read(r.packet[:]) var packet [1500]byte
n, err := r.reader.Read(packet[:])
if err != nil { if err != nil {
return 0, nil, err return 0, nil, err
} }
if err := parseUDPMessage(r.packet[:n], r.lastAddr, &r.msg); err != nil { msg, err := ParseUDPMessage(packet[:n])
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
} }
if dfMsg.Addr != r.lastAddr {
dest, err := net.ParseDestination("udp:" + dfMsg.Addr) dest, err := net.ParseDestination("udp:" + dfMsg.Addr)
if err != nil { if err != nil {
continue 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
@@ -1,147 +0,0 @@
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)
}
}
+19 -27
View File
@@ -1,6 +1,7 @@
package hysteria package hysteria
import ( import (
"bytes"
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"io" "io"
@@ -182,44 +183,35 @@ func (m *UDPMessage) Serialize(buf []byte) int {
} }
func ParseUDPMessage(msg []byte) (*UDPMessage, error) { func ParseUDPMessage(msg []byte) (*UDPMessage, error) {
m := new(UDPMessage) m := &UDPMessage{}
if err := parseUDPMessage(msg, "", m); err != nil { buf := bytes.NewBuffer(msg)
if err := binary.Read(buf, binary.BigEndian, &m.SessionID); err != nil {
return nil, err return nil, err
} }
return m, nil if err := binary.Read(buf, binary.BigEndian, &m.PacketID); err != 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
} }
lAddr, n, err := quicvarint.Parse(msg[8:]) if err := binary.Read(buf, binary.BigEndian, &m.FragID); err != nil {
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 err return nil, err
} }
if lAddr == 0 || lAddr > MaxMessageLength { if lAddr == 0 || lAddr > MaxMessageLength {
return errors.New("invalid address length") return nil, errors.New("invalid address length")
} }
bs := msg[8+n:] bs := buf.Bytes()
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 errors.New("invalid message length") return nil, errors.New("invalid message length")
} }
*m = UDPMessage{
SessionID: binary.BigEndian.Uint32(msg),
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]) m.Addr = string(bs[:lAddr])
} m.Data = bs[lAddr:]
return nil return m, 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
@@ -1,49 +0,0 @@
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 = session.SkipDNSResolveFromContext(ctx) content.SkipDNSResolve = true
content.SniffingRequest = l.sniffingRequest content.SniffingRequest = l.sniffingRequest
ctx = session.ContextWithContent(ctx, content) ctx = session.ContextWithContent(ctx, content)
+14 -8
View File
@@ -53,12 +53,7 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Inbound, error) {
return nil, err return nil, err
} }
user := &protocol.MemoryUser{ udpCodec, err := NewUDPServerCodec(method, psk, 500*time.Second)
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
} }
@@ -69,7 +64,10 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Inbound, error) {
method: method, method: method,
psk: psk, psk: psk,
saltFilter: antireplay.NewMapFilter[[32]byte](60), saltFilter: antireplay.NewMapFilter[[32]byte](60),
user: user, user: &protocol.MemoryUser{
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
@@ -157,12 +155,20 @@ func (i *Inbound) processUDP(ctx context.Context, conn stat.Connection, dispatch
} }
for _, b := range mb { for _, b := range mb {
sessionItem, decoded, err := i.udpCodec.DecodePacket(b.Bytes()) 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)
+63 -13
View File
@@ -2,6 +2,8 @@ package shadowsocks_2022
import ( import (
"context" "context"
"crypto/cipher"
"encoding/binary"
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
@@ -39,7 +41,8 @@ type MultiUserInbound struct {
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]
udpCodec *UDPMultiServerCodec udpSessions *UDPSessionManager
udpMasterCipher cipher.Block
policyManager policy.Manager policyManager policy.Manager
} }
@@ -65,7 +68,7 @@ func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiU
return nil, err return nil, err
} }
udpCodec, err := NewUDPMultiServerCodec(method, masterPSK, 500*time.Second) masterBlock, err := method.NewBlock(masterPSK)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -78,7 +81,8 @@ func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiU
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),
udpCodec: udpCodec, udpSessions: NewUDPSessionManager(500 * time.Second),
udpMasterCipher: masterBlock,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
} }
@@ -277,26 +281,68 @@ func (i *MultiUserInbound) processUDP(ctx context.Context, conn stat.Connection,
} }
for _, b := range mb { for _, b := range mb {
sessionItem, decoded, user, err := i.udpCodec.DecodePacket(b.Bytes(), func(hash [AESBlockSize]byte) (*protocol.MemoryUser, []byte, bool) { // In multi-user UDP:
u, ok := i.usersByHash.Load(hash) // Packet header is 16 bytes: Encrypted(SessionID + PacketID)
if !ok { // Followed by 16 bytes EIH
return nil, nil, false packetBytes := b.Bytes()
} if len(packetBytes) < 32+1+8+2 {
return u, u.Account.(*MemoryAccount).Key, true
})
b.Release() b.Release()
if err != nil || decoded.HeaderType != HeaderTypeClient {
continue 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 {
b.Release()
continue
}
currentUser = user
userPSK = user.Account.(*MemoryAccount).Key
}
decoded, err := sessionItem.DecryptAESPayload(i.method, userPSK, sessionID, packetID, rawHeader[:], packetBytes[32:])
b.Release()
if err != nil {
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.udpCodec.EncodeServerPacket(decoded.SessionID, userPSK, replyDest, payload) return i.encodeServerUDPPacket(sessionID, userPSK, replyDest, payload)
}) })
if err != nil { if err != nil {
continue continue
@@ -310,3 +356,7 @@ 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)
}
+2
View File
@@ -243,6 +243,7 @@ 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)
if sessionItem.User == nil {
sessionItem.Lock() sessionItem.Lock()
if sessionItem.User == nil { if sessionItem.User == nil {
sessionItem.User = &protocol.MemoryUser{ sessionItem.User = &protocol.MemoryUser{
@@ -251,6 +252,7 @@ func (i *RelayInbound) processUDP(ctx context.Context, conn stat.Connection, dis
} }
} }
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 *UDPClientCodec udpCodec *UDPPacketCodec
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 := NewUDPClientCodec(method, pskList) udpCodec, err := NewUDPPacketCodec(method, pskList)
if err != nil { if err != nil {
return nil, errors.New("failed to create udp client codec").Base(err) return nil, errors.New("failed to create udp packet codec").Base(err)
} }
v := core.MustFromContext(ctx) v := core.MustFromContext(ctx)
+130 -275
View File
@@ -7,78 +7,33 @@ 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 UDPClientCodec struct { type UDPCodec 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
} }
func NewUDPServerCodec(method *CipherMethod, psk []byte, user *protocol.MemoryUser, sessionTimeout time.Duration) (*UDPServerCodec, error) { type (
c := &UDPServerCodec{ UDPPacketCodec = UDPCodec
UDPServerCodec = UDPCodec
)
func newUDPCodec(method *CipherMethod, psk []byte) (*UDPCodec, error) {
c := &UDPCodec{
method: method, method: method,
psk: psk, psk: psk,
user: user,
sessions: NewUDPSessionManager(sessionTimeout),
} }
var err error var err error
if method.IsChaCha { if method.IsChaCha {
@@ -92,129 +47,46 @@ func NewUDPServerCodec(method *CipherMethod, psk []byte, user *protocol.MemoryUs
return c, nil return c, nil
} }
func (c *UDPServerCodec) Sessions() *UDPSessionManager { func NewUDPPacketCodec(method *CipherMethod, pskList [][]byte) (*UDPCodec, error) {
return c.sessions if method.IsChaCha && len(pskList) > 1 {
} return nil, errors.New("multi-key is not supported for chacha20-poly1305")
func (c *UDPServerCodec) GetSession(sessionID uint64) *ServerUDPSession {
if c.sessions == nil {
return nil
} }
return c.sessions.Get(sessionID) finalPSK := pskList[len(pskList)-1]
} c, err := newUDPCodec(method, finalPSK)
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 { if err != nil {
return nil, err return nil, err
} }
return &UDPMultiServerCodec{ c.pskList = pskList
method: method, if len(pskList) > 1 {
masterPSK: masterPSK, c.blockCiphers = make([]cipher.Block, len(pskList))
masterBlock: masterBlock, for i, psk := range pskList {
sessions: NewUDPSessionManager(sessionTimeout), c.blockCiphers[i], err = method.NewBlock(psk)
}, nil if err != nil {
return nil, err
}
}
}
return c, nil
} }
func (c *UDPMultiServerCodec) Sessions() *UDPSessionManager { 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 *UDPMultiServerCodec) GetSession(sessionID uint64) *ServerUDPSession { func (c *UDPCodec) GetSession(sessionID uint64) *ServerUDPSession {
if c.sessions == nil { if c.sessions == nil {
return nil return nil
} }
return c.sessions.Get(sessionID) return c.sessions.GetOrCreate(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 {
@@ -321,42 +193,44 @@ func parsePlainUDPPacket(sessionID, packetID uint64, bodyPlain []byte) (DecodedU
}, nil }, nil
} }
func (c *UDPServerCodec) DecodePacket(data []byte) (*ServerUDPSession, DecodedUDPPacket, error) { func (c *UDPCodec) DecodePacket(data []byte) (DecodedUDPPacket, error) {
if len(data) < PacketMinimalHeaderSize { if len(data) < PacketMinimalHeaderSize {
return nil, DecodedUDPPacket{}, ErrPacketTooShort return DecodedUDPPacket{}, ErrPacketTooShort
} }
if c.method.IsChaCha { if c.method.IsChaCha {
if len(data) < PacketNonceSize+AEADTagSize { if len(data) < PacketNonceSize+AEADTagSize {
return nil, DecodedUDPPacket{}, ErrPacketTooShort return 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 nil, DecodedUDPPacket{}, errors.New("failed to decrypt chacha udp packet").Base(err) return 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 nil, DecodedUDPPacket{}, ErrPacketTooShort return 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 nil, DecodedUDPPacket{}, err return DecodedUDPPacket{}, err
} }
if decoded.HeaderType != HeaderTypeClient { if decoded.HeaderType != HeaderTypeClient {
return nil, DecodedUDPPacket{}, ErrBadHeaderType return DecodedUDPPacket{}, ErrBadHeaderType
} }
sessionItem := c.sessions.GetOrCreate(sessionID) sessionItem.AddPacketID(packetID)
if !sessionItem.Commit(packetID, nil, c.user, c.psk) { return decoded, nil
return nil, DecodedUDPPacket{}, ErrPacketIdNotUnique
}
return sessionItem, decoded, nil
} }
// AES mode // AES mode
@@ -365,48 +239,49 @@ func (c *UDPServerCodec) DecodePacket(data []byte) (*ServerUDPSession, DecodedUD
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.Get(sessionID) sessionItem := c.sessions.GetOrCreate(sessionID)
var bodyAead cipher.AEAD
if sessionItem != nil {
if !sessionItem.CheckPacketID(packetID) { if !sessionItem.CheckPacketID(packetID) {
return nil, DecodedUDPPacket{}, ErrPacketIdNotUnique return 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(c.psk, rawHeader[:8], c.method.KeySaltLength) bodyKey := DeriveSessionSubKey(psk, rawHeader[:8], method.KeySaltLength)
var err error var err error
bodyAead, err = c.method.NewAEAD(bodyKey) bodyAead, err = method.NewAEAD(bodyKey)
if err != nil { if err != nil {
return nil, DecodedUDPPacket{}, err return 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 nil, DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err) return 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 nil, DecodedUDPPacket{}, err return DecodedUDPPacket{}, err
}
if decoded.HeaderType != HeaderTypeClient {
return nil, DecodedUDPPacket{}, ErrBadHeaderType
} }
if sessionItem == nil { if decoded.HeaderType != HeaderTypeClient {
sessionItem = c.sessions.GetOrCreate(sessionID) return DecodedUDPPacket{}, ErrBadHeaderType
} }
if !sessionItem.Commit(packetID, bodyAead, c.user, c.psk) {
return nil, DecodedUDPPacket{}, ErrPacketIdNotUnique s.AddPacketID(packetID)
if isNewCipher {
s.clientBodyCipher = bodyAead
} }
return sessionItem, decoded, nil
return decoded, nil
} }
func (s *ServerUDPSession) EnsureServerState(method *CipherMethod, psk []byte) error { func (s *ServerUDPSession) EnsureServerState(method *CipherMethod, psk []byte) error {
@@ -428,9 +303,6 @@ 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
} }
@@ -515,12 +387,11 @@ func (s *ServerUDPSession) EncodeServerPacket(method *CipherMethod, clientSessio
return res, nil return res, nil
} }
func (c *UDPServerCodec) EncodeServerPacket(clientSessionID uint64, dest net.Destination, payload []byte) ([]byte, error) { func (c *UDPCodec) 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
@@ -528,24 +399,21 @@ type serverSessionState struct {
} }
func (st *serverSessionState) check(packetID uint64) bool { func (st *serverSessionState) check(packetID uint64) bool {
st.Lock() if st.window == nil {
defer st.Unlock() st.window = new(SlidingWindow)
}
return st.window.Check(packetID) return st.window.Check(packetID)
} }
func (st *serverSessionState) commit(packetID uint64, now int64) bool { func (st *serverSessionState) add(packetID uint64) {
st.Lock() if st.window == nil {
defer st.Unlock() st.window = new(SlidingWindow)
if !st.window.CheckAndAdd(packetID) {
return false
} }
st.lastSeen.Store(now) st.window.Add(packetID)
return true
} }
type ClientUDPSession struct { type ClientUDPSession struct {
mu sync.Mutex codec *UDPCodec
codec *UDPClientCodec
clientSessionID uint64 clientSessionID uint64
nextPacketID atomic.Uint64 nextPacketID atomic.Uint64
clientBodyCipher cipher.AEAD clientBodyCipher cipher.AEAD
@@ -553,7 +421,7 @@ type ClientUDPSession struct {
old atomic.Pointer[serverSessionState] old atomic.Pointer[serverSessionState]
} }
func (c *UDPClientCodec) NewClientSession() (*ClientUDPSession, error) { func (c *UDPCodec) 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
@@ -578,43 +446,51 @@ func (c *UDPClientCodec) NewClientSession() (*ClientUDPSession, error) {
}, nil }, nil
} }
func (s *ClientUDPSession) findServerSession(sessionID uint64, now int64) (*serverSessionState, error) { func (s *ClientUDPSession) getServerSession(sessionID uint64, now int64) (*serverSessionState, error) {
if cur := s.current.Load(); cur != nil && cur.sessionID == sessionID { cur := s.current.Load()
if cur != nil && cur.sessionID == sessionID {
return cur, nil return cur, nil
} }
if old := s.old.Load(); old != nil {
if old.sessionID == sessionID { old := s.old.Load()
if old != nil && old.sessionID == sessionID {
if now-old.lastSeen.Load() > 60 { if now-old.lastSeen.Load() > 60 {
s.old.CompareAndSwap(old, nil)
return nil, errors.New("old server session expired") return nil, errors.New("old server session expired")
} }
return old, nil return old, nil
} }
// 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. // 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 { if old != nil && now-old.lastSeen.Load() < 60 {
return nil, errors.New("newer server session rejected: old session is less than 1 minute old") 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,
window: new(SlidingWindow), cipher: bodyAead,
cipher: cipher,
} }
newState.lastSeen.Store(now) newState.lastSeen.Store(now)
if cur := s.current.Load(); cur != nil { if cur == nil {
s.old.Store(cur) s.current.CompareAndSwap(nil, newState)
return s.current.Load(), nil
} }
s.old.Store(cur)
s.current.Store(newState) s.current.Store(newState)
return newState, nil return newState, nil
} }
@@ -629,7 +505,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-len(payload)) + 1 paddingLen = mrand.IntN(MaxPaddingLength) + 1
} }
addrPortLen := AddrPortLength(dest) addrPortLen := AddrPortLength(dest)
@@ -744,8 +620,6 @@ 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
@@ -763,10 +637,20 @@ 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
} }
@@ -774,20 +658,8 @@ 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, err := s.findServerSession(sessionID, now) st.add(packetID)
if err != nil { st.lastSeen.Store(now)
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
} }
@@ -798,29 +670,19 @@ 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])
st, err := s.findServerSession(sessionID, now) now := time.Now().Unix()
st, err := s.getServerSession(sessionID, now)
if err != nil { if err != nil {
return DecodedUDPPacket{}, err return DecodedUDPPacket{}, err
} }
var bodyAead cipher.AEAD
if st != nil {
if !st.check(packetID) { if !st.check(packetID) {
return DecodedUDPPacket{}, ErrPacketIdNotUnique return DecodedUDPPacket{}, ErrPacketIdNotUnique
} }
bodyAead = st.cipher 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
}
}
bodyNonce := rawHeader[4:16] bodyNonce := rawHeader[4:16]
bodyPlain, err := bodyAead.Open(nil, bodyNonce, data[16:], nil) bodyCipher := data[16:]
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)
} }
@@ -829,6 +691,7 @@ 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
} }
@@ -836,16 +699,8 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
return DecodedUDPPacket{}, errors.New("client session ID mismatch") return DecodedUDPPacket{}, errors.New("client session ID mismatch")
} }
if st == nil { st.add(packetID)
st, err = s.transitionServerSession(sessionID, bodyAead, now) st.lastSeen.Store(now)
if err != nil {
return DecodedUDPPacket{}, err
}
}
if !st.commit(packetID, now) {
return DecodedUDPPacket{}, ErrPacketIdNotUnique
}
return decoded, nil return decoded, nil
} }
+3 -4
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, nil, 300*time.Second) destCodec, err := NewUDPServerCodec(method, destKey, 300*time.Second)
common.Must(err) common.Must(err)
mu.Lock() mu.Lock()
@@ -202,8 +202,7 @@ 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, dec2 := DecodedUDPPacket{}, DecodedUDPPacket{} dec1, err := destCodec.DecodePacket(pkts[0])
_, 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)
} }
@@ -211,7 +210,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)
} }
+7 -23
View File
@@ -100,27 +100,19 @@ 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) Commit(packetID uint64, bodyAead cipher.AEAD, user *protocol.MemoryUser, userPSK []byte) bool { func (s *ServerUDPSession) AddPacketID(packetID uint64) {
s.Lock() s.Lock()
defer s.Unlock() defer s.Unlock()
if s.User != nil && user != nil && s.User != user { if s.Window == nil {
return false s.Window = new(SlidingWindow)
} }
if !s.Window.CheckAndAdd(packetID) { s.Window.Add(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 {
@@ -136,13 +128,6 @@ 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 {
@@ -152,7 +137,6 @@ 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)
+3 -9
View File
@@ -63,16 +63,10 @@ func (s *ServerUDPSession) EnsureLink(
s.currentConn.Store(conn) s.currentConn.Store(conn)
// UDP Session might travel across multiple connections sessCtx, cancel := context.WithCancel(ctx)
// 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 { if inbound != nil && s.User != nil {
newInbound := *inbound inbound.User = s.User
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, nil, time.Minute) serverCodec, err := NewUDPServerCodec(method, psk, 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, nil, time.Minute) serverCodec, err := NewUDPServerCodec(method, rawKey, 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)-1)*AESBlockSize + RequestHeaderFixedChunkLength + AEADTagSize + varHeaderLen + AEADTagSize) totalHandshakeLen := int32(method.KeySaltLength + len(pskList)*AESBlockSize + RequestHeaderFixedChunkLength + AEADTagSize + varHeaderLen + AEADTagSize)
handshakeBuf := buf.NewWithSize(totalHandshakeLen) handshakeBuf := buf.NewWithSize(totalHandshakeLen)
defer handshakeBuf.Release() defer handshakeBuf.Release()
-2
View File
@@ -223,8 +223,6 @@ 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,7 +5,6 @@ import (
"net" "net"
"sync" "sync"
"github.com/google/uuid"
"github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/errors"
) )
@@ -50,18 +49,3 @@ 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
}
+2 -11
View File
@@ -33,7 +33,6 @@ 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
} }
@@ -138,18 +137,11 @@ 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\"\x8e\x03\n" + "\x16proxy/tun/config.proto\x12\x0exray.proxy.tun\"\xfa\x02\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" +
@@ -162,8 +154,7 @@ 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\x16autoSystemWfpBlockLeak\x12\x12\n" + " \x03(\tR\x16autoSystemWfpBlockLeakBL\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,5 +17,4 @@ 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
@@ -0,0 +1,390 @@
//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,11 +3,7 @@
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"
@@ -152,381 +148,3 @@ 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
@@ -0,0 +1,204 @@
//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,18 +9,6 @@ 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
@@ -455,185 +443,3 @@ 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")
}
}
+5 -134
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, options.GUID) adapter, err := open(options.Name, options.Desc)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -82,11 +82,10 @@ func NewTun(options *Config) (Tun, error) {
return tun, nil return tun, nil
} }
func open(name, desc, id string) (*wintun.Adapter, error) { func open(name, desc string) (*wintun.Adapter, error) {
guid, err := adapterGUID(name, id) // generate a deterministic GUID from the adapter name
if err != nil { id := md5.Sum([]byte(name))
return nil, err guid := (*windows.GUID)(unsafe.Pointer(&id[0]))
}
// 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 {
@@ -100,28 +99,6 @@ func open(name, desc, id 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.
@@ -710,109 +687,3 @@ 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
@@ -0,0 +1,120 @@
//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,7 +4,6 @@ package tun
import ( import (
"context" "context"
"crypto/md5"
go_errors "errors" go_errors "errors"
"net" "net"
"net/netip" "net/netip"
@@ -341,46 +340,3 @@ 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")
}
}

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