mirror of
https://github.com/XTLS/Xray-core.git
synced 2026-11-25 11:01:44 +00:00
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ab3c3f9909 | ||
|
|
5d8b20239f | ||
|
|
e17392a96e | ||
|
|
15b2499d34 | ||
|
|
d9131d381c | ||
|
|
8c7447fd2d | ||
|
|
4dac768567 | ||
|
|
dfad7776ee | ||
|
|
e00dbb963c | ||
|
|
a9c42c1bd7 | ||
|
|
74cbdf46d8 | ||
|
|
3dee8518c1 | ||
|
|
8f0bb9fbfa | ||
|
|
5225121aab |
@@ -0,0 +1,5 @@
|
||||
<!--
|
||||
Read CONTRIBUTING.md before opening a pull request.
|
||||
Human-led pull requests can use a normal description.
|
||||
For agent-led pull requests, disclose each AI tool and model, then paste the complete conversation directly in a collapsed <details> block in this PR body. External transcript links are not accepted.
|
||||
-->
|
||||
@@ -0,0 +1,29 @@
|
||||
# Contributing to Xray-core
|
||||
|
||||
We review pull requests that address a concrete problem or an agreed proposal. Please keep each change focused and provide evidence that maintainers can check.
|
||||
|
||||
## Bug fixes
|
||||
|
||||
A bug-fix pull request must link an existing issue filed using the issue template. Summarize the code change and verification in the pull request, and add a regression test when practical. A speculative fix without a demonstrated problem is not ready for a pull request.
|
||||
|
||||
## Features
|
||||
|
||||
Propose the use case and intended design in an issue before implementing it. Wait for a maintainer to accept the proposal. Explain how the change fits the existing architecture and any compatibility impact.
|
||||
|
||||
## Refactors
|
||||
|
||||
Propose the scope in an issue and wait for maintainer acceptance before implementing it. Show which complexity the change removes and why the resulting design is easier to understand. Prefer a reduction in code and moving parts, but line count alone is not the review criterion. Preserve observable behavior and test both old-to-new and new-to-old client/server connections when protocol or network behavior is affected.
|
||||
|
||||
## AI involvement and author responsibility
|
||||
|
||||
AI assistance does not require a conversation record when the author selects or verifies the problem, directs the approach, reviews every changed line, verifies the result, and personally responds to review feedback. The author must be able to explain every changed line and maintain the change. A pull request meeting these conditions is considered human-led, regardless of whether AI wrote the code or who pushed the commits. Such pull requests may ignore the agent-led requirements below.
|
||||
|
||||
If an AI agent independently selected the task or made key implementation decisions without ongoing human direction, the pull request is agent-led even if a person submits it manually. Disclose each tool and model and paste the complete prompt-and-response record for every session used for the pull request, including retries and changes after review feedback, inside a collapsed `<details>` block in the pull request description. External links, summaries, and selected excerpts are insufficient. A transcript does not replace the author's review, verification, or responsibility for responding to maintainers.
|
||||
|
||||
In agent-led pull requests, commits containing AI-generated changes must credit the specific LLM as their author or co-author.
|
||||
|
||||
We do not oppose the use of AI, but agent-led pull requests must have a human author who responds to maintainer feedback for several weeks after submission. Dishonest declarations, fabricated verification, intentionally incomplete records, or abandoning an agent-led pull request are prohibited and may result in being blocked from contributing to Xray-core.
|
||||
|
||||
## Review
|
||||
|
||||
Maintainers may ask for missing evidence before reviewing code or close a pull request that is outside the agreed scope. The contributor is responsible for understanding, testing, and explaining the change, regardless of the tools used to produce it.
|
||||
@@ -2,8 +2,6 @@
|
||||
|
||||
[Project X](https://github.com/XTLS) originates from XTLS protocol, providing a set of network tools such as [Xray-core](https://github.com/XTLS/Xray-core) and [REALITY](https://github.com/XTLS/REALITY).
|
||||
|
||||
[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
|
||||
|
||||
[](https://docs.rw)
|
||||
@@ -41,10 +39,10 @@
|
||||
|
||||
## Telegram
|
||||
|
||||
[Project X](https://t.me/projectXray)
|
||||
|
||||
[Project X Channel](https://t.me/projectXtls)
|
||||
|
||||
[Project X](https://t.me/projectXray) (中文 / English)
|
||||
|
||||
[Project VLESS](https://t.me/projectVless) (Русский)
|
||||
|
||||
[Project XHTTP](https://t.me/projectXhttp) (Persian)
|
||||
@@ -53,7 +51,6 @@
|
||||
|
||||
- Linux Script
|
||||
- [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
|
||||
- [ghcr.io/xtls/xray-core](https://ghcr.io/xtls/xray-core) (**Official**)
|
||||
- [teddysun/xray](https://hub.docker.com/r/teddysun/xray)
|
||||
@@ -69,12 +66,10 @@
|
||||
- [TX-UI](https://github.com/AghayeCoder/tx-ui)
|
||||
- [CELERITY](https://github.com/ClickDevTech/CELERITY-panel)
|
||||
- One Click
|
||||
- [Xray-REALITY](https://github.com/zxcvos/Xray-script), [xray-reality](https://github.com/sajjaddg/xray-reality), [reality-ezpz](https://github.com/aleskxyz/reality-ezpz)
|
||||
- [Xray_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)
|
||||
- [xray-reality](https://github.com/sajjaddg/xray-reality), [Xray_bash_onekey](https://github.com/hello-yunshu/Xray_bash_onekey)
|
||||
- [v2ray-agent](https://github.com/mack-a/v2ray-agent), [Xray_onekey](https://github.com/wulabing/Xray_onekey)
|
||||
- Magisk
|
||||
- [Magic_V2Ray](https://github.com/vincentng295/Magic_V2Ray)
|
||||
- [Xray_For_Magisk](https://github.com/E7KMbb/Xray_For_Magisk)
|
||||
- Homebrew
|
||||
- `brew install xray`
|
||||
|
||||
@@ -86,14 +81,7 @@
|
||||
- [All-in-One-fallbacks-Nginx](https://github.com/XTLS/Xray-examples/tree/main/All-in-One-fallbacks-Nginx)
|
||||
- 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)
|
||||
- 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
|
||||
|
||||
@@ -106,49 +94,52 @@
|
||||
- [fancyss](https://github.com/hq450/fancyss)
|
||||
- Windows
|
||||
- [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)
|
||||
- [OneXray](https://github.com/OneXray/OneXray)
|
||||
- [XrayUI-dev](https://github.com/PhoenixNil/XrayUI-dev)
|
||||
- [keqdroid](https://github.com/Lemonochka/keqdroid)
|
||||
- Android
|
||||
- [v2rayNG](https://github.com/2dust/v2rayNG)
|
||||
- [X-flutter](https://github.com/XTLS/X-flutter)
|
||||
- [SaeedDev94/Xray](https://github.com/SaeedDev94/Xray)
|
||||
- [SimpleXray](https://github.com/lhear/SimpleXray)
|
||||
- [XrayFA](https://github.com/Q7DF1/XrayFA)
|
||||
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
|
||||
- [OneXray](https://github.com/OneXray/OneXray)
|
||||
- [AsteriskNG](https://github.com/Asterisk4Magisk/AsteriskNG)
|
||||
- [keqdroid](https://github.com/Lemonochka/keqdroid)
|
||||
- iOS & macOS arm64 & tvOS
|
||||
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215) | [Happ RU](https://apps.apple.com/ru/app/happ-proxy-utility-plus/id6746188973) | [Happ tvOS](https://apps.apple.com/us/app/happ-proxy-utility-for-tv/id6748297274)
|
||||
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215) | [Happ tvOS](https://apps.apple.com/us/app/happ-proxy-utility-for-tv/id6748297274)
|
||||
- [Streisand](https://apps.apple.com/app/streisand/id6450534064)
|
||||
- [OneXray](https://github.com/OneXray/OneXray)
|
||||
- [INCY](https://apps.apple.com/en/app/incy/id6756943388)
|
||||
- macOS arm64 & x64
|
||||
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215) | [Happ RU](https://apps.apple.com/ru/app/happ-proxy-utility-plus/id6746188973)
|
||||
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215)
|
||||
- [V2rayU](https://github.com/yanue/V2rayU)
|
||||
- [V2RayXS](https://github.com/tzmax/V2RayXS)
|
||||
- [Furious](https://github.com/LorenEteval/Furious)
|
||||
- [OneXray](https://github.com/OneXray/OneXray)
|
||||
- [GoXRay](https://github.com/goxray/desktop)
|
||||
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
|
||||
- [v2rayN](https://github.com/2dust/v2rayN)
|
||||
- [GenyConnect](https://github.com/genyleap/GenyConnect)
|
||||
- [INCY](https://apps.apple.com/en/app/incy/id6756943388)
|
||||
- Linux
|
||||
- [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)
|
||||
- [GenyConnect](https://github.com/genyleap/GenyConnect)
|
||||
- [OneXray](https://github.com/OneXray/OneXray)
|
||||
- [keqdroid](https://github.com/Lemonochka/keqdroid)
|
||||
- HarmonyOS
|
||||
- [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...
|
||||
|
||||
- iOS & macOS arm64 & tvOS
|
||||
@@ -163,14 +154,8 @@
|
||||
- Xray Wrapper
|
||||
- [XTLS/libXray](https://github.com/XTLS/libXray)
|
||||
- [xtls-sdk](https://github.com/remnawave/xtls-sdk)
|
||||
- [xtlsapi](https://github.com/hiddify/xtlsapi)
|
||||
- [AndroidLibXrayLite](https://github.com/2dust/AndroidLibXrayLite)
|
||||
- [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
|
||||
- [Amnezia VPN](https://github.com/amnezia-vpn)
|
||||
- [mihomo](https://github.com/MetaCubeX/mihomo)
|
||||
@@ -178,9 +163,9 @@
|
||||
|
||||
## Contributing
|
||||
|
||||
[Code of Conduct](https://github.com/XTLS/Xray-core/blob/main/CODE_OF_CONDUCT.md)
|
||||
For code contributions, please read [CONTRIBUTING.md](CONTRIBUTING.md) and [Code of Conduct](https://github.com/XTLS/Xray-core/blob/main/CODE_OF_CONDUCT.md) before opening a pull request.
|
||||
|
||||
[](https://deepwiki.com/XTLS/Xray-core)
|
||||
[Ask DeepWiki](https://deepwiki.com/XTLS/Xray-core) might be helpful.
|
||||
|
||||
## Credits
|
||||
|
||||
@@ -263,4 +248,8 @@ GOOS=linux GOARCH=mipsle GOMIPS=softfloat CGO_ENABLED=0 go build -o xray -trimpa
|
||||
|
||||
## Stargazers over time
|
||||
|
||||
[](https://starchart.cc/XTLS/Xray-core)
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xtls/xray-core&type=date&theme=dark&legend=top-left" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xtls/xray-core&type=date&legend=top-left" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xtls/xray-core&type=date&legend=top-left" />
|
||||
</picture>
|
||||
|
||||
@@ -2,4 +2,10 @@
|
||||
|
||||
If you found an issue related to security vulnerability or protocol-identification problem, please report it to us via "[Report a vulnerability](https://github.com/XTLS/Xray-core/security/advisories/new)" privately, instead of publish it publicly before we release the fixed version.
|
||||
|
||||
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!
|
||||
|
||||
@@ -26,9 +26,16 @@ import (
|
||||
|
||||
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 {
|
||||
sync.Mutex
|
||||
reader buf.TimeoutReader // *pipe.Reader or *buf.TimeoutWrapperReader
|
||||
reader buf.TimeoutReader
|
||||
cache buf.MultiBuffer
|
||||
}
|
||||
|
||||
@@ -86,9 +93,7 @@ func (r *cachedReader) Interrupt() {
|
||||
r.cache = buf.ReleaseMulti(r.cache)
|
||||
}
|
||||
r.Unlock()
|
||||
if p, ok := r.reader.(*pipe.Reader); ok {
|
||||
p.Interrupt()
|
||||
}
|
||||
common.Interrupt(r.reader)
|
||||
}
|
||||
|
||||
// DefaultDispatcher is a default implementation of Dispatcher.
|
||||
@@ -194,15 +199,13 @@ func WrapLink(ctx context.Context, policyManager policy.Manager, statsManager st
|
||||
user = sessionInbound.User
|
||||
}
|
||||
|
||||
link.Reader = &buf.TimeoutWrapperReader{Reader: link.Reader}
|
||||
var uplinkCounter stats.Counter
|
||||
|
||||
if user != nil && len(user.Email) > 0 {
|
||||
p := policyManager.ForLevel(user.Level)
|
||||
if p.Stats.UserUplink {
|
||||
name := "user>>>" + user.Email + ">>>traffic>>>uplink"
|
||||
if c, _ := statsManager.GetOrRegisterCounter(name); c != nil {
|
||||
link.Reader.(*buf.TimeoutWrapperReader).Counter = c
|
||||
}
|
||||
uplinkCounter, _ = statsManager.GetOrRegisterCounter(name)
|
||||
}
|
||||
if p.Stats.UserDownlink {
|
||||
name := "user>>>" + user.Email + ">>>traffic>>>downlink"
|
||||
@@ -218,6 +221,11 @@ func WrapLink(ctx context.Context, policyManager policy.Manager, statsManager st
|
||||
}
|
||||
}
|
||||
|
||||
if reader, ok := link.Reader.(nativeReader); ok {
|
||||
reader.SetUplinkCounter(uplinkCounter)
|
||||
} else {
|
||||
link.Reader = &buf.TimeoutWrapperReader{Reader: link.Reader, Counter: uplinkCounter}
|
||||
}
|
||||
return link
|
||||
}
|
||||
|
||||
|
||||
+33
-121
@@ -328,13 +328,12 @@ func (*OutboundConfig) Descriptor() ([]byte, []int) {
|
||||
type SenderConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
// Send traffic through the given IP. Only IP is allowed.
|
||||
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"`
|
||||
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"`
|
||||
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
|
||||
sizeCache protoimpl.SizeCache
|
||||
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"`
|
||||
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"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *SenderConfig) Reset() {
|
||||
@@ -381,13 +380,6 @@ func (x *SenderConfig) GetStreamSettings() *internet.StreamConfig {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *SenderConfig) GetMultiplexSettings() *MultiplexingConfig {
|
||||
if x != nil {
|
||||
return x.MultiplexSettings
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *SenderConfig) GetViaCidr() string {
|
||||
if x != nil {
|
||||
return x.ViaCidr
|
||||
@@ -402,78 +394,6 @@ func (x *SenderConfig) GetTargetStrategy() internet.DomainStrategy {
|
||||
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
|
||||
|
||||
const file_app_proxyman_config_proto_rawDesc = "" +
|
||||
@@ -498,18 +418,12 @@ const file_app_proxyman_config_proto_rawDesc = "" +
|
||||
"\x03tag\x18\x01 \x01(\tR\x03tag\x12M\n" +
|
||||
"\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" +
|
||||
"\x0eOutboundConfig\"\xd6\x02\n" +
|
||||
"\x0eOutboundConfig\"\x9a\x02\n" +
|
||||
"\fSenderConfig\x12-\n" +
|
||||
"\x03via\x18\x01 \x01(\v2\x1b.xray.common.net.IPOrDomainR\x03via\x12N\n" +
|
||||
"\x0fstream_settings\x18\x02 \x01(\v2%.xray.transport.internet.StreamConfigR\x0estreamSettings\x12T\n" +
|
||||
"\x12multiplex_settings\x18\x04 \x01(\v2%.xray.app.proxyman.MultiplexingConfigR\x11multiplexSettings\x12\x19\n" +
|
||||
"\x0fstream_settings\x18\x02 \x01(\v2%.xray.transport.internet.StreamConfigR\x0estreamSettings\x12\x19\n" +
|
||||
"\bvia_cidr\x18\x05 \x01(\tR\aviaCidr\x12P\n" +
|
||||
"\x0ftarget_strategy\x18\x06 \x01(\x0e2'.xray.transport.internet.DomainStrategyR\x0etargetStrategyJ\x04\b\x03\x10\x04\"\xa4\x01\n" +
|
||||
"\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" +
|
||||
"\x0ftarget_strategy\x18\x06 \x01(\x0e2'.xray.transport.internet.DomainStrategyR\x0etargetStrategyJ\x04\b\x03\x10\x04J\x04\b\x04\x10\x05R\x12multiplex_settingsBU\n" +
|
||||
"\x15com.xray.app.proxymanP\x01Z&github.com/xtls/xray-core/app/proxyman\xaa\x02\x11Xray.App.Proxymanb\x06proto3"
|
||||
|
||||
var (
|
||||
@@ -524,7 +438,7 @@ func file_app_proxyman_config_proto_rawDescGZIP() []byte {
|
||||
return file_app_proxyman_config_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_app_proxyman_config_proto_msgTypes = make([]protoimpl.MessageInfo, 7)
|
||||
var file_app_proxyman_config_proto_msgTypes = make([]protoimpl.MessageInfo, 6)
|
||||
var file_app_proxyman_config_proto_goTypes = []any{
|
||||
(*InboundConfig)(nil), // 0: xray.app.proxyman.InboundConfig
|
||||
(*SniffingConfig)(nil), // 1: xray.app.proxyman.SniffingConfig
|
||||
@@ -532,33 +446,31 @@ var file_app_proxyman_config_proto_goTypes = []any{
|
||||
(*InboundHandlerConfig)(nil), // 3: xray.app.proxyman.InboundHandlerConfig
|
||||
(*OutboundConfig)(nil), // 4: xray.app.proxyman.OutboundConfig
|
||||
(*SenderConfig)(nil), // 5: xray.app.proxyman.SenderConfig
|
||||
(*MultiplexingConfig)(nil), // 6: xray.app.proxyman.MultiplexingConfig
|
||||
(*geodata.DomainRule)(nil), // 7: xray.common.geodata.DomainRule
|
||||
(*geodata.IPRule)(nil), // 8: xray.common.geodata.IPRule
|
||||
(*net.PortList)(nil), // 9: xray.common.net.PortList
|
||||
(*net.IPOrDomain)(nil), // 10: xray.common.net.IPOrDomain
|
||||
(*internet.StreamConfig)(nil), // 11: xray.transport.internet.StreamConfig
|
||||
(*serial.TypedMessage)(nil), // 12: xray.common.serial.TypedMessage
|
||||
(internet.DomainStrategy)(0), // 13: xray.transport.internet.DomainStrategy
|
||||
(*geodata.DomainRule)(nil), // 6: xray.common.geodata.DomainRule
|
||||
(*geodata.IPRule)(nil), // 7: xray.common.geodata.IPRule
|
||||
(*net.PortList)(nil), // 8: xray.common.net.PortList
|
||||
(*net.IPOrDomain)(nil), // 9: xray.common.net.IPOrDomain
|
||||
(*internet.StreamConfig)(nil), // 10: xray.transport.internet.StreamConfig
|
||||
(*serial.TypedMessage)(nil), // 11: xray.common.serial.TypedMessage
|
||||
(internet.DomainStrategy)(0), // 12: xray.transport.internet.DomainStrategy
|
||||
}
|
||||
var file_app_proxyman_config_proto_depIdxs = []int32{
|
||||
7, // 0: xray.app.proxyman.SniffingConfig.domains_excluded:type_name -> xray.common.geodata.DomainRule
|
||||
8, // 1: xray.app.proxyman.SniffingConfig.ips_excluded:type_name -> xray.common.geodata.IPRule
|
||||
9, // 2: xray.app.proxyman.ReceiverConfig.port_list:type_name -> xray.common.net.PortList
|
||||
10, // 3: xray.app.proxyman.ReceiverConfig.listen:type_name -> xray.common.net.IPOrDomain
|
||||
11, // 4: xray.app.proxyman.ReceiverConfig.stream_settings:type_name -> xray.transport.internet.StreamConfig
|
||||
6, // 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, // 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, // 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
|
||||
12, // 6: xray.app.proxyman.InboundHandlerConfig.receiver_settings:type_name -> xray.common.serial.TypedMessage
|
||||
12, // 7: xray.app.proxyman.InboundHandlerConfig.proxy_settings:type_name -> xray.common.serial.TypedMessage
|
||||
10, // 8: xray.app.proxyman.SenderConfig.via:type_name -> xray.common.net.IPOrDomain
|
||||
11, // 9: xray.app.proxyman.SenderConfig.stream_settings:type_name -> xray.transport.internet.StreamConfig
|
||||
6, // 10: xray.app.proxyman.SenderConfig.multiplex_settings:type_name -> xray.app.proxyman.MultiplexingConfig
|
||||
13, // 11: xray.app.proxyman.SenderConfig.target_strategy:type_name -> xray.transport.internet.DomainStrategy
|
||||
12, // [12:12] is the sub-list for method output_type
|
||||
12, // [12:12] is the sub-list for method input_type
|
||||
12, // [12:12] is the sub-list for extension type_name
|
||||
12, // [12:12] is the sub-list for extension extendee
|
||||
0, // [0:12] is the sub-list for field type_name
|
||||
11, // 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
|
||||
9, // 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
|
||||
12, // 10: xray.app.proxyman.SenderConfig.target_strategy:type_name -> xray.transport.internet.DomainStrategy
|
||||
11, // [11:11] is the sub-list for method output_type
|
||||
11, // [11:11] is the sub-list for method input_type
|
||||
11, // [11:11] is the sub-list for extension type_name
|
||||
11, // [11:11] is the sub-list for extension extendee
|
||||
0, // [0:11] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_app_proxyman_config_proto_init() }
|
||||
@@ -572,7 +484,7 @@ func file_app_proxyman_config_proto_init() {
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_proxyman_config_proto_rawDesc), len(file_app_proxyman_config_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 7,
|
||||
NumMessages: 6,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
|
||||
@@ -57,19 +57,8 @@ message SenderConfig {
|
||||
// Send traffic through the given IP. Only IP is allowed.
|
||||
xray.common.net.IPOrDomain via = 1;
|
||||
xray.transport.internet.StreamConfig stream_settings = 2;
|
||||
reserved 3;
|
||||
MultiplexingConfig multiplex_settings = 4;
|
||||
reserved 3, 4;
|
||||
reserved "multiplex_settings";
|
||||
string via_cidr = 5;
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -6,12 +6,12 @@ import (
|
||||
"github.com/xtls/xray-core/app/proxyman"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"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/core"
|
||||
"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/proxy"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
@@ -48,7 +48,6 @@ type AlwaysOnInboundHandler struct {
|
||||
receiverConfig *proxyman.ReceiverConfig
|
||||
proxy proxy.Inbound
|
||||
workers []worker
|
||||
mux *mux.Server
|
||||
tag string
|
||||
}
|
||||
|
||||
@@ -82,11 +81,14 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
|
||||
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{
|
||||
receiverConfig: receiverConfig,
|
||||
proxyConfig: proxyConfig,
|
||||
proxy: p,
|
||||
mux: mux.NewServer(ctx),
|
||||
tag: tag,
|
||||
}
|
||||
|
||||
@@ -117,7 +119,7 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
|
||||
proxy: p,
|
||||
stream: mss,
|
||||
tag: tag,
|
||||
dispatcher: h.mux,
|
||||
dispatcher: dispatcher,
|
||||
sniffingRequest: sniffingRequest,
|
||||
uplinkCounter: uplinkCounter,
|
||||
downlinkCounter: downlinkCounter,
|
||||
@@ -139,7 +141,7 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
|
||||
stream: mss,
|
||||
recvOrigDest: receiverConfig.ReceiveOriginalDestination,
|
||||
tag: tag,
|
||||
dispatcher: h.mux,
|
||||
dispatcher: dispatcher,
|
||||
sniffingRequest: sniffingRequest,
|
||||
uplinkCounter: uplinkCounter,
|
||||
downlinkCounter: downlinkCounter,
|
||||
@@ -154,7 +156,7 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
|
||||
proxy: p,
|
||||
address: address,
|
||||
port: net.Port(port),
|
||||
dispatcher: h.mux,
|
||||
dispatcher: dispatcher,
|
||||
sniffingRequest: sniffingRequest,
|
||||
uplinkCounter: uplinkCounter,
|
||||
downlinkCounter: downlinkCounter,
|
||||
@@ -192,7 +194,6 @@ func (h *AlwaysOnInboundHandler) Close() error {
|
||||
for _, worker := range h.workers {
|
||||
errs = append(errs, worker.Close())
|
||||
}
|
||||
errs = append(errs, h.mux.Close())
|
||||
errs = append(errs, common.Close(h.proxy))
|
||||
if err := errors.Combine(errs...); err != nil {
|
||||
return errors.New("failed to close all resources").Base(err)
|
||||
|
||||
@@ -13,7 +13,6 @@ import (
|
||||
"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"
|
||||
@@ -60,9 +59,6 @@ type Handler struct {
|
||||
streamSettings *internet.MemoryStreamConfig
|
||||
proxyConfig proto.Message
|
||||
proxy proxy.Outbound
|
||||
mux *mux.ClientManager
|
||||
xudp *mux.ClientManager
|
||||
udp443 string
|
||||
uplinkCounter stats.Counter
|
||||
downlinkCounter stats.Counter
|
||||
}
|
||||
@@ -117,57 +113,6 @@ func NewHandler(ctx context.Context, config *core.OutboundHandlerConfig) (outbou
|
||||
return nil, errors.New("not an outbound handler")
|
||||
}
|
||||
|
||||
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
|
||||
return h, nil
|
||||
}
|
||||
@@ -181,65 +126,44 @@ func (h *Handler) Tag() string {
|
||||
func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) {
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
ob := outbounds[len(outbounds)-1]
|
||||
content := session.ContentFromContext(ctx)
|
||||
if h.senderSettings != nil && h.senderSettings.TargetStrategy.HasStrategy() && ob.Target.Address.Family().IsDomain() && (content == nil || !content.SkipDNSResolve) {
|
||||
strategy := h.senderSettings.TargetStrategy
|
||||
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil {
|
||||
strategy = strategy.GetDynamicStrategy(ob.OriginalTarget.Address.Family())
|
||||
}
|
||||
ips, err := internet.LookupForIP(ob.Target.Address.Domain(), strategy, nil)
|
||||
if err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to resolve ip for target ", ob.Target.Address.Domain())
|
||||
if h.senderSettings.TargetStrategy.ForceIP() {
|
||||
err := errors.New("failed to resolve ip for target ", ob.Target.Address.Domain()).Base(err)
|
||||
session.SubmitOutboundErrorToOriginator(ctx, err)
|
||||
common.Interrupt(link.Writer)
|
||||
common.Interrupt(link.Reader)
|
||||
return
|
||||
}
|
||||
if h.senderSettings != nil && h.senderSettings.TargetStrategy.HasStrategy() && ob.Target.Address.Family().IsDomain() {
|
||||
if session.SkipDNSResolveFromContext(ctx) {
|
||||
errors.LogInfo(ctx, "bypassing targetStrategy ", h.senderSettings.TargetStrategy, " for ", ob.Target, "; preserving target domain")
|
||||
} else {
|
||||
unchangedDomain := ob.Target.Address.Domain()
|
||||
ob.Target.Address = net.IPAddress(ips[dice.Roll(len(ips))])
|
||||
errors.LogInfo(ctx, "target: ", unchangedDomain, " resolved to: ", ob.Target.Address.String())
|
||||
strategy := h.senderSettings.TargetStrategy
|
||||
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil {
|
||||
strategy = strategy.GetDynamicStrategy(ob.OriginalTarget.Address.Family())
|
||||
}
|
||||
ips, err := internet.LookupForIP(ob.Target.Address.Domain(), strategy, nil)
|
||||
if err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to resolve ip for target ", ob.Target.Address.Domain())
|
||||
if h.senderSettings.TargetStrategy.ForceIP() {
|
||||
err := errors.New("failed to resolve ip for target ", ob.Target.Address.Domain()).Base(err)
|
||||
session.SubmitOutboundErrorToOriginator(ctx, err)
|
||||
common.Interrupt(link.Writer)
|
||||
common.Interrupt(link.Reader)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
unchangedDomain := ob.Target.Address.Domain()
|
||||
ob.Target.Address = net.IPAddress(ips[dice.Roll(len(ips))])
|
||||
errors.LogInfo(ctx, "target: ", unchangedDomain, " resolved to: ", ob.Target.Address.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
reader, writer := link.Reader, link.Writer
|
||||
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
|
||||
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}
|
||||
}
|
||||
if h.mux != nil {
|
||||
test := func(err error) {
|
||||
if err != nil {
|
||||
err := errors.New("failed to process mux outbound traffic").Base(err)
|
||||
session.SubmitOutboundErrorToOriginator(ctx, err)
|
||||
errors.LogInfo(ctx, err.Error())
|
||||
common.Interrupt(link.Writer)
|
||||
common.Interrupt(link.Reader)
|
||||
}
|
||||
}
|
||||
if ob.Target.Network == net.Network_UDP && ob.Target.Port == 443 {
|
||||
switch h.udp443 {
|
||||
case "reject":
|
||||
test(errors.New("XUDP rejected UDP/443 traffic"))
|
||||
return
|
||||
case "skip":
|
||||
goto out
|
||||
}
|
||||
}
|
||||
if h.xudp != nil && ob.Target.Network == net.Network_UDP {
|
||||
if !h.xudp.Enabled {
|
||||
goto out
|
||||
}
|
||||
test(h.xudp.Dispatch(ctx, link))
|
||||
return
|
||||
}
|
||||
if h.mux.Enabled {
|
||||
test(h.mux.Dispatch(ctx, link))
|
||||
return
|
||||
}
|
||||
}
|
||||
out:
|
||||
|
||||
err := h.proxy.Process(ctx, link, h)
|
||||
var completion interface{ DeferWriterClose() bool }
|
||||
if goerrors.As(err, &completion) && completion.DeferWriterClose() {
|
||||
go common.Close(writer)
|
||||
common.Interrupt(reader)
|
||||
return
|
||||
}
|
||||
var errC error
|
||||
if err != nil {
|
||||
errC = errors.Cause(err)
|
||||
@@ -252,15 +176,15 @@ out:
|
||||
err := errors.New("failed to process outbound traffic").Base(err)
|
||||
session.SubmitOutboundErrorToOriginator(ctx, err)
|
||||
errors.LogInfo(ctx, err.Error())
|
||||
common.Interrupt(link.Writer)
|
||||
common.Interrupt(writer)
|
||||
} else {
|
||||
if errC != nil && goerrors.Is(errC, io.ErrClosedPipe) {
|
||||
common.Interrupt(link.Writer)
|
||||
common.Interrupt(writer)
|
||||
} else {
|
||||
common.Close(link.Writer)
|
||||
common.Close(writer)
|
||||
}
|
||||
}
|
||||
common.Interrupt(link.Reader)
|
||||
common.Interrupt(reader)
|
||||
}
|
||||
|
||||
func (h *Handler) DestIpAddress() net.IP {
|
||||
@@ -332,7 +256,6 @@ func (h *Handler) Start() error {
|
||||
|
||||
// Close implements common.Closable.
|
||||
func (h *Handler) Close() error {
|
||||
common.Close(h.mux)
|
||||
common.Close(h.proxy)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,235 +0,0 @@
|
||||
package reverse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/mux"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/signal"
|
||||
"github.com/xtls/xray-core/common/task"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// Bridge is a component in reverse proxy, that relays connections from Portal to local address.
|
||||
type Bridge struct {
|
||||
dispatcher routing.Dispatcher
|
||||
tag string
|
||||
domain string
|
||||
workers []*BridgeWorker
|
||||
monitorTask *task.Periodic
|
||||
}
|
||||
|
||||
// NewBridge creates a new Bridge instance.
|
||||
func NewBridge(config *BridgeConfig, dispatcher routing.Dispatcher) (*Bridge, error) {
|
||||
if config.Tag == "" {
|
||||
return nil, errors.New("bridge tag is empty")
|
||||
}
|
||||
if config.Domain == "" {
|
||||
return nil, errors.New("bridge domain is empty")
|
||||
}
|
||||
|
||||
b := &Bridge{
|
||||
dispatcher: dispatcher,
|
||||
tag: config.Tag,
|
||||
domain: config.Domain,
|
||||
}
|
||||
b.monitorTask = &task.Periodic{
|
||||
Execute: b.monitor,
|
||||
Interval: time.Second * 2,
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (b *Bridge) cleanup() {
|
||||
var activeWorkers []*BridgeWorker
|
||||
|
||||
for _, w := range b.workers {
|
||||
if w.IsActive() {
|
||||
activeWorkers = append(activeWorkers, w)
|
||||
}
|
||||
if w.Closed() {
|
||||
if w.Timer != nil {
|
||||
w.Timer.SetTimeout(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(activeWorkers) != len(b.workers) {
|
||||
b.workers = activeWorkers
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bridge) monitor() error {
|
||||
b.cleanup()
|
||||
|
||||
var numConnections uint32
|
||||
var numWorker uint32
|
||||
|
||||
for _, w := range b.workers {
|
||||
if w.IsActive() {
|
||||
numConnections += w.Connections()
|
||||
numWorker++
|
||||
}
|
||||
}
|
||||
|
||||
if numWorker == 0 || numConnections/numWorker > 16 {
|
||||
worker, err := NewBridgeWorker(b.domain, b.tag, b.dispatcher)
|
||||
if err != nil {
|
||||
errors.LogWarningInner(context.Background(), err, "failed to create bridge worker")
|
||||
return nil
|
||||
}
|
||||
b.workers = append(b.workers, worker)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *Bridge) Start() error {
|
||||
return b.monitorTask.Start()
|
||||
}
|
||||
|
||||
func (b *Bridge) Close() error {
|
||||
return b.monitorTask.Close()
|
||||
}
|
||||
|
||||
type BridgeWorker struct {
|
||||
Tag string
|
||||
Worker *mux.ServerWorker
|
||||
Dispatcher routing.Dispatcher
|
||||
State Control_State
|
||||
Timer *signal.ActivityTimer
|
||||
}
|
||||
|
||||
func NewBridgeWorker(domain string, tag string, d routing.Dispatcher) (*BridgeWorker, error) {
|
||||
ctx := context.Background()
|
||||
ctx = session.ContextWithInbound(ctx, &session.Inbound{
|
||||
Tag: tag,
|
||||
})
|
||||
link, err := d.Dispatch(ctx, net.Destination{
|
||||
Network: net.Network_TCP,
|
||||
Address: net.DomainAddress(domain),
|
||||
Port: 0,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
w := &BridgeWorker{
|
||||
Dispatcher: d,
|
||||
Tag: tag,
|
||||
}
|
||||
|
||||
worker, err := mux.NewServerWorker(context.Background(), w, link)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
w.Worker = worker
|
||||
|
||||
terminate := func() {
|
||||
worker.Close()
|
||||
}
|
||||
w.Timer = signal.CancelAfterInactivity(ctx, terminate, 60*time.Second)
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) Type() interface{} {
|
||||
return routing.DispatcherType()
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) IsActive() bool {
|
||||
return w.State == Control_ACTIVE && !w.Worker.Closed()
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) Closed() bool {
|
||||
return w.Worker.Closed()
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) Connections() uint32 {
|
||||
return w.Worker.ActiveConnections()
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) handleInternalConn(link *transport.Link) {
|
||||
reader := link.Reader
|
||||
for {
|
||||
mb, err := reader.ReadMultiBuffer()
|
||||
if err != nil {
|
||||
if w.Timer != nil {
|
||||
if w.Closed() {
|
||||
w.Timer.SetTimeout(0)
|
||||
} else {
|
||||
w.Timer.SetTimeout(24 * time.Hour)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if w.Timer != nil {
|
||||
w.Timer.Update()
|
||||
}
|
||||
for _, b := range mb {
|
||||
var ctl Control
|
||||
if err := proto.Unmarshal(b.Bytes(), &ctl); err != nil {
|
||||
errors.LogInfoInner(context.Background(), err, "failed to parse proto message")
|
||||
if w.Timer != nil {
|
||||
w.Timer.SetTimeout(0)
|
||||
}
|
||||
return
|
||||
}
|
||||
if ctl.State != w.State {
|
||||
w.State = ctl.State
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) Dispatch(ctx context.Context, dest net.Destination) (*transport.Link, error) {
|
||||
if !isInternalDomain(dest) {
|
||||
if session.InboundFromContext(ctx) == nil {
|
||||
ctx = session.ContextWithInbound(ctx, &session.Inbound{
|
||||
Tag: w.Tag,
|
||||
})
|
||||
}
|
||||
return w.Dispatcher.Dispatch(ctx, dest)
|
||||
}
|
||||
|
||||
opt := []pipe.Option{pipe.WithSizeLimit(16 * 1024)}
|
||||
uplinkReader, uplinkWriter := pipe.New(opt...)
|
||||
downlinkReader, downlinkWriter := pipe.New(opt...)
|
||||
|
||||
go w.handleInternalConn(&transport.Link{
|
||||
Reader: downlinkReader,
|
||||
Writer: uplinkWriter,
|
||||
})
|
||||
|
||||
return &transport.Link{
|
||||
Reader: uplinkReader,
|
||||
Writer: downlinkWriter,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) DispatchLink(ctx context.Context, dest net.Destination, link *transport.Link) error {
|
||||
if !isInternalDomain(dest) {
|
||||
if session.InboundFromContext(ctx) == nil {
|
||||
ctx = session.ContextWithInbound(ctx, &session.Inbound{
|
||||
Tag: w.Tag,
|
||||
})
|
||||
}
|
||||
return w.Dispatcher.DispatchLink(ctx, dest, link)
|
||||
}
|
||||
w.handleInternalConn(link)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,356 +0,0 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.12
|
||||
// protoc (unknown)
|
||||
// source: app/reverse/config.proto
|
||||
|
||||
package reverse
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
unsafe "unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type Control_State int32
|
||||
|
||||
const (
|
||||
Control_ACTIVE Control_State = 0
|
||||
Control_DRAIN Control_State = 1
|
||||
)
|
||||
|
||||
// Enum value maps for Control_State.
|
||||
var (
|
||||
Control_State_name = map[int32]string{
|
||||
0: "ACTIVE",
|
||||
1: "DRAIN",
|
||||
}
|
||||
Control_State_value = map[string]int32{
|
||||
"ACTIVE": 0,
|
||||
"DRAIN": 1,
|
||||
}
|
||||
)
|
||||
|
||||
func (x Control_State) Enum() *Control_State {
|
||||
p := new(Control_State)
|
||||
*p = x
|
||||
return p
|
||||
}
|
||||
|
||||
func (x Control_State) String() string {
|
||||
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
|
||||
}
|
||||
|
||||
func (Control_State) Descriptor() protoreflect.EnumDescriptor {
|
||||
return file_app_reverse_config_proto_enumTypes[0].Descriptor()
|
||||
}
|
||||
|
||||
func (Control_State) Type() protoreflect.EnumType {
|
||||
return &file_app_reverse_config_proto_enumTypes[0]
|
||||
}
|
||||
|
||||
func (x Control_State) Number() protoreflect.EnumNumber {
|
||||
return protoreflect.EnumNumber(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Control_State.Descriptor instead.
|
||||
func (Control_State) EnumDescriptor() ([]byte, []int) {
|
||||
return file_app_reverse_config_proto_rawDescGZIP(), []int{0, 0}
|
||||
}
|
||||
|
||||
type Control struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
State Control_State `protobuf:"varint,1,opt,name=state,proto3,enum=xray.app.reverse.Control_State" json:"state,omitempty"`
|
||||
Random []byte `protobuf:"bytes,99,opt,name=random,proto3" json:"random,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Control) Reset() {
|
||||
*x = Control{}
|
||||
mi := &file_app_reverse_config_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *Control) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Control) ProtoMessage() {}
|
||||
|
||||
func (x *Control) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_app_reverse_config_proto_msgTypes[0]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Control.ProtoReflect.Descriptor instead.
|
||||
func (*Control) Descriptor() ([]byte, []int) {
|
||||
return file_app_reverse_config_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *Control) GetState() Control_State {
|
||||
if x != nil {
|
||||
return x.State
|
||||
}
|
||||
return Control_ACTIVE
|
||||
}
|
||||
|
||||
func (x *Control) GetRandom() []byte {
|
||||
if x != nil {
|
||||
return x.Random
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type BridgeConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"`
|
||||
Domain string `protobuf:"bytes,2,opt,name=domain,proto3" json:"domain,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *BridgeConfig) Reset() {
|
||||
*x = BridgeConfig{}
|
||||
mi := &file_app_reverse_config_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *BridgeConfig) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*BridgeConfig) ProtoMessage() {}
|
||||
|
||||
func (x *BridgeConfig) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_app_reverse_config_proto_msgTypes[1]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use BridgeConfig.ProtoReflect.Descriptor instead.
|
||||
func (*BridgeConfig) Descriptor() ([]byte, []int) {
|
||||
return file_app_reverse_config_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *BridgeConfig) GetTag() string {
|
||||
if x != nil {
|
||||
return x.Tag
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *BridgeConfig) GetDomain() string {
|
||||
if x != nil {
|
||||
return x.Domain
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type PortalConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"`
|
||||
Domain string `protobuf:"bytes,2,opt,name=domain,proto3" json:"domain,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *PortalConfig) Reset() {
|
||||
*x = PortalConfig{}
|
||||
mi := &file_app_reverse_config_proto_msgTypes[2]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *PortalConfig) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*PortalConfig) ProtoMessage() {}
|
||||
|
||||
func (x *PortalConfig) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_app_reverse_config_proto_msgTypes[2]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use PortalConfig.ProtoReflect.Descriptor instead.
|
||||
func (*PortalConfig) Descriptor() ([]byte, []int) {
|
||||
return file_app_reverse_config_proto_rawDescGZIP(), []int{2}
|
||||
}
|
||||
|
||||
func (x *PortalConfig) GetTag() string {
|
||||
if x != nil {
|
||||
return x.Tag
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *PortalConfig) GetDomain() string {
|
||||
if x != nil {
|
||||
return x.Domain
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
BridgeConfig []*BridgeConfig `protobuf:"bytes,1,rep,name=bridge_config,json=bridgeConfig,proto3" json:"bridge_config,omitempty"`
|
||||
PortalConfig []*PortalConfig `protobuf:"bytes,2,rep,name=portal_config,json=portalConfig,proto3" json:"portal_config,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Config) Reset() {
|
||||
*x = Config{}
|
||||
mi := &file_app_reverse_config_proto_msgTypes[3]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *Config) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Config) ProtoMessage() {}
|
||||
|
||||
func (x *Config) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_app_reverse_config_proto_msgTypes[3]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
|
||||
func (*Config) Descriptor() ([]byte, []int) {
|
||||
return file_app_reverse_config_proto_rawDescGZIP(), []int{3}
|
||||
}
|
||||
|
||||
func (x *Config) GetBridgeConfig() []*BridgeConfig {
|
||||
if x != nil {
|
||||
return x.BridgeConfig
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Config) GetPortalConfig() []*PortalConfig {
|
||||
if x != nil {
|
||||
return x.PortalConfig
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_app_reverse_config_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_app_reverse_config_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"\x18app/reverse/config.proto\x12\x10xray.app.reverse\"x\n" +
|
||||
"\aControl\x125\n" +
|
||||
"\x05state\x18\x01 \x01(\x0e2\x1f.xray.app.reverse.Control.StateR\x05state\x12\x16\n" +
|
||||
"\x06random\x18c \x01(\fR\x06random\"\x1e\n" +
|
||||
"\x05State\x12\n" +
|
||||
"\n" +
|
||||
"\x06ACTIVE\x10\x00\x12\t\n" +
|
||||
"\x05DRAIN\x10\x01\"8\n" +
|
||||
"\fBridgeConfig\x12\x10\n" +
|
||||
"\x03tag\x18\x01 \x01(\tR\x03tag\x12\x16\n" +
|
||||
"\x06domain\x18\x02 \x01(\tR\x06domain\"8\n" +
|
||||
"\fPortalConfig\x12\x10\n" +
|
||||
"\x03tag\x18\x01 \x01(\tR\x03tag\x12\x16\n" +
|
||||
"\x06domain\x18\x02 \x01(\tR\x06domain\"\x92\x01\n" +
|
||||
"\x06Config\x12C\n" +
|
||||
"\rbridge_config\x18\x01 \x03(\v2\x1e.xray.app.reverse.BridgeConfigR\fbridgeConfig\x12C\n" +
|
||||
"\rportal_config\x18\x02 \x03(\v2\x1e.xray.app.reverse.PortalConfigR\fportalConfigBV\n" +
|
||||
"\x16com.xray.proxy.reverseP\x01Z%github.com/xtls/xray-core/app/reverse\xaa\x02\x12Xray.Proxy.Reverseb\x06proto3"
|
||||
|
||||
var (
|
||||
file_app_reverse_config_proto_rawDescOnce sync.Once
|
||||
file_app_reverse_config_proto_rawDescData []byte
|
||||
)
|
||||
|
||||
func file_app_reverse_config_proto_rawDescGZIP() []byte {
|
||||
file_app_reverse_config_proto_rawDescOnce.Do(func() {
|
||||
file_app_reverse_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_reverse_config_proto_rawDesc), len(file_app_reverse_config_proto_rawDesc)))
|
||||
})
|
||||
return file_app_reverse_config_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_app_reverse_config_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
|
||||
var file_app_reverse_config_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
|
||||
var file_app_reverse_config_proto_goTypes = []any{
|
||||
(Control_State)(0), // 0: xray.app.reverse.Control.State
|
||||
(*Control)(nil), // 1: xray.app.reverse.Control
|
||||
(*BridgeConfig)(nil), // 2: xray.app.reverse.BridgeConfig
|
||||
(*PortalConfig)(nil), // 3: xray.app.reverse.PortalConfig
|
||||
(*Config)(nil), // 4: xray.app.reverse.Config
|
||||
}
|
||||
var file_app_reverse_config_proto_depIdxs = []int32{
|
||||
0, // 0: xray.app.reverse.Control.state:type_name -> xray.app.reverse.Control.State
|
||||
2, // 1: xray.app.reverse.Config.bridge_config:type_name -> xray.app.reverse.BridgeConfig
|
||||
3, // 2: xray.app.reverse.Config.portal_config:type_name -> xray.app.reverse.PortalConfig
|
||||
3, // [3:3] is the sub-list for method output_type
|
||||
3, // [3:3] is the sub-list for method input_type
|
||||
3, // [3:3] is the sub-list for extension type_name
|
||||
3, // [3:3] is the sub-list for extension extendee
|
||||
0, // [0:3] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_app_reverse_config_proto_init() }
|
||||
func file_app_reverse_config_proto_init() {
|
||||
if File_app_reverse_config_proto != nil {
|
||||
return
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_reverse_config_proto_rawDesc), len(file_app_reverse_config_proto_rawDesc)),
|
||||
NumEnums: 1,
|
||||
NumMessages: 4,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
GoTypes: file_app_reverse_config_proto_goTypes,
|
||||
DependencyIndexes: file_app_reverse_config_proto_depIdxs,
|
||||
EnumInfos: file_app_reverse_config_proto_enumTypes,
|
||||
MessageInfos: file_app_reverse_config_proto_msgTypes,
|
||||
}.Build()
|
||||
File_app_reverse_config_proto = out.File
|
||||
file_app_reverse_config_proto_goTypes = nil
|
||||
file_app_reverse_config_proto_depIdxs = nil
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package xray.app.reverse;
|
||||
option csharp_namespace = "Xray.Proxy.Reverse";
|
||||
option go_package = "github.com/xtls/xray-core/app/reverse";
|
||||
option java_package = "com.xray.proxy.reverse";
|
||||
option java_multiple_files = true;
|
||||
|
||||
message Control {
|
||||
enum State {
|
||||
ACTIVE = 0;
|
||||
DRAIN = 1;
|
||||
}
|
||||
|
||||
State state = 1;
|
||||
bytes random = 99;
|
||||
}
|
||||
|
||||
message BridgeConfig {
|
||||
string tag = 1;
|
||||
string domain = 2;
|
||||
}
|
||||
|
||||
message PortalConfig {
|
||||
string tag = 1;
|
||||
string domain = 2;
|
||||
}
|
||||
|
||||
message Config {
|
||||
repeated BridgeConfig bridge_config = 1;
|
||||
repeated PortalConfig portal_config = 2;
|
||||
}
|
||||
@@ -1,308 +0,0 @@
|
||||
package reverse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/mux"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/signal"
|
||||
"github.com/xtls/xray-core/common/task"
|
||||
"github.com/xtls/xray-core/features/outbound"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
type Portal struct {
|
||||
ohm outbound.Manager
|
||||
tag string
|
||||
domain string
|
||||
picker *StaticMuxPicker
|
||||
client *mux.ClientManager
|
||||
}
|
||||
|
||||
func NewPortal(config *PortalConfig, ohm outbound.Manager) (*Portal, error) {
|
||||
if config.Tag == "" {
|
||||
return nil, errors.New("portal tag is empty")
|
||||
}
|
||||
|
||||
if config.Domain == "" {
|
||||
return nil, errors.New("portal domain is empty")
|
||||
}
|
||||
|
||||
picker, err := NewStaticMuxPicker()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Portal{
|
||||
ohm: ohm,
|
||||
tag: config.Tag,
|
||||
domain: config.Domain,
|
||||
picker: picker,
|
||||
client: &mux.ClientManager{
|
||||
Picker: picker,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *Portal) Start() error {
|
||||
return p.ohm.AddHandler(context.Background(), &Outbound{
|
||||
portal: p,
|
||||
tag: p.tag,
|
||||
})
|
||||
}
|
||||
|
||||
func (p *Portal) Close() error {
|
||||
return p.ohm.RemoveHandler(context.Background(), p.tag)
|
||||
}
|
||||
|
||||
func (p *Portal) HandleConnection(ctx context.Context, link *transport.Link) error {
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
ob := outbounds[len(outbounds)-1]
|
||||
if ob == nil {
|
||||
return errors.New("outbound metadata not found")
|
||||
}
|
||||
|
||||
if isDomain(ob.Target, p.domain) {
|
||||
muxClient, err := mux.NewClientWorker(*link, mux.ClientStrategy{})
|
||||
if err != nil {
|
||||
return errors.New("failed to create mux client worker").Base(err)
|
||||
}
|
||||
|
||||
worker, err := NewPortalWorker(muxClient)
|
||||
if err != nil {
|
||||
return errors.New("failed to create portal worker").Base(err)
|
||||
}
|
||||
|
||||
p.picker.AddWorker(worker)
|
||||
|
||||
if _, ok := link.Reader.(*pipe.Reader); !ok {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-muxClient.WaitClosed():
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
|
||||
link.Reader = &buf.EndpointOverrideReader{Reader: link.Reader, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
|
||||
link.Writer = &buf.EndpointOverrideWriter{Writer: link.Writer, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
|
||||
}
|
||||
|
||||
return p.client.Dispatch(ctx, link)
|
||||
}
|
||||
|
||||
type Outbound struct {
|
||||
portal *Portal
|
||||
tag string
|
||||
}
|
||||
|
||||
func (o *Outbound) Tag() string {
|
||||
return o.tag
|
||||
}
|
||||
|
||||
func (o *Outbound) Dispatch(ctx context.Context, link *transport.Link) {
|
||||
if err := o.portal.HandleConnection(ctx, link); err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to process reverse connection")
|
||||
common.Interrupt(link.Writer)
|
||||
common.Interrupt(link.Reader)
|
||||
}
|
||||
}
|
||||
|
||||
func (o *Outbound) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o *Outbound) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SenderSettings implements outbound.Handler.
|
||||
func (o *Outbound) SenderSettings() *serial.TypedMessage {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ProxySettings implements outbound.Handler.
|
||||
func (o *Outbound) ProxySettings() *serial.TypedMessage {
|
||||
return nil
|
||||
}
|
||||
|
||||
type StaticMuxPicker struct {
|
||||
access sync.Mutex
|
||||
workers []*PortalWorker
|
||||
cTask *task.Periodic
|
||||
}
|
||||
|
||||
func NewStaticMuxPicker() (*StaticMuxPicker, error) {
|
||||
p := &StaticMuxPicker{}
|
||||
p.cTask = &task.Periodic{
|
||||
Execute: p.cleanup,
|
||||
Interval: time.Second * 30,
|
||||
}
|
||||
p.cTask.Start()
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (p *StaticMuxPicker) cleanup() error {
|
||||
p.access.Lock()
|
||||
defer p.access.Unlock()
|
||||
|
||||
var activeWorkers []*PortalWorker
|
||||
for _, w := range p.workers {
|
||||
if !w.Closed() {
|
||||
activeWorkers = append(activeWorkers, w)
|
||||
} else {
|
||||
w.timer.SetTimeout(0)
|
||||
}
|
||||
}
|
||||
|
||||
if len(activeWorkers) != len(p.workers) {
|
||||
p.workers = activeWorkers
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *StaticMuxPicker) PickAvailable() (*mux.ClientWorker, error) {
|
||||
p.access.Lock()
|
||||
defer p.access.Unlock()
|
||||
|
||||
if len(p.workers) == 0 {
|
||||
return nil, errors.New("empty worker list")
|
||||
}
|
||||
|
||||
var minIdx int = -1
|
||||
var minConn uint32 = 9999
|
||||
for i, w := range p.workers {
|
||||
if w.draining {
|
||||
continue
|
||||
}
|
||||
if w.IsFull() {
|
||||
continue
|
||||
}
|
||||
if w.client.ActiveConnections() < minConn {
|
||||
minConn = w.client.ActiveConnections()
|
||||
minIdx = i
|
||||
}
|
||||
}
|
||||
|
||||
if minIdx == -1 {
|
||||
for i, w := range p.workers {
|
||||
if w.IsFull() {
|
||||
continue
|
||||
}
|
||||
if w.client.ActiveConnections() < minConn {
|
||||
minConn = w.client.ActiveConnections()
|
||||
minIdx = i
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if minIdx != -1 {
|
||||
return p.workers[minIdx].client, nil
|
||||
}
|
||||
|
||||
return nil, errors.New("no mux client worker available")
|
||||
}
|
||||
|
||||
func (p *StaticMuxPicker) AddWorker(worker *PortalWorker) {
|
||||
p.access.Lock()
|
||||
defer p.access.Unlock()
|
||||
|
||||
p.workers = append(p.workers, worker)
|
||||
}
|
||||
|
||||
type PortalWorker struct {
|
||||
client *mux.ClientWorker
|
||||
control *task.Periodic
|
||||
writer buf.Writer
|
||||
reader buf.Reader
|
||||
draining bool
|
||||
counter uint32
|
||||
timer *signal.ActivityTimer
|
||||
}
|
||||
|
||||
func NewPortalWorker(client *mux.ClientWorker) (*PortalWorker, error) {
|
||||
opt := []pipe.Option{pipe.WithSizeLimit(16 * 1024)}
|
||||
uplinkReader, uplinkWriter := pipe.New(opt...)
|
||||
downlinkReader, downlinkWriter := pipe.New(opt...)
|
||||
|
||||
ctx := context.Background()
|
||||
outbounds := []*session.Outbound{{
|
||||
Target: net.UDPDestination(net.DomainAddress(internalDomain), 0),
|
||||
}}
|
||||
ctx = session.ContextWithOutbounds(ctx, outbounds)
|
||||
f := client.Dispatch(ctx, &transport.Link{
|
||||
Reader: uplinkReader,
|
||||
Writer: downlinkWriter,
|
||||
})
|
||||
if !f {
|
||||
return nil, errors.New("unable to dispatch control connection")
|
||||
}
|
||||
terminate := func() {
|
||||
client.Close()
|
||||
}
|
||||
w := &PortalWorker{
|
||||
client: client,
|
||||
reader: downlinkReader,
|
||||
writer: uplinkWriter,
|
||||
timer: signal.CancelAfterInactivity(ctx, terminate, 24*time.Hour), // // prevent leak
|
||||
}
|
||||
w.control = &task.Periodic{
|
||||
Execute: w.heartbeat,
|
||||
Interval: time.Second * 2,
|
||||
}
|
||||
w.control.Start()
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func (w *PortalWorker) heartbeat() error {
|
||||
if w.Closed() {
|
||||
return errors.New("client worker stopped")
|
||||
}
|
||||
|
||||
if w.draining || w.writer == nil {
|
||||
return errors.New("already disposed")
|
||||
}
|
||||
|
||||
msg := &Control{}
|
||||
msg.FillInRandom()
|
||||
|
||||
if w.client.TotalConnections() > 256 {
|
||||
w.draining = true
|
||||
msg.State = Control_DRAIN
|
||||
|
||||
defer func() {
|
||||
common.Close(w.writer)
|
||||
common.Interrupt(w.reader)
|
||||
w.writer = nil
|
||||
}()
|
||||
}
|
||||
|
||||
w.counter = (w.counter + 1) % 5
|
||||
if w.draining || w.counter == 1 {
|
||||
b, err := proto.Marshal(msg)
|
||||
common.Must(err)
|
||||
mb := buf.MergeBytes(nil, b)
|
||||
w.timer.Update()
|
||||
return w.writer.WriteMultiBuffer(mb)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *PortalWorker) IsFull() bool {
|
||||
return w.client.IsFull()
|
||||
}
|
||||
|
||||
func (w *PortalWorker) Closed() bool {
|
||||
return w.client.Closed()
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package reverse_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/app/reverse"
|
||||
"github.com/xtls/xray-core/common"
|
||||
)
|
||||
|
||||
func TestStaticPickerEmpty(t *testing.T) {
|
||||
picker, err := reverse.NewStaticMuxPicker()
|
||||
common.Must(err)
|
||||
worker, err := picker.PickAvailable()
|
||||
if err == nil {
|
||||
t.Error("expected error, but nil")
|
||||
}
|
||||
if worker != nil {
|
||||
t.Error("expected nil worker, but not nil")
|
||||
}
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
package reverse
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
core "github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/features/outbound"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
)
|
||||
|
||||
const (
|
||||
internalDomain = "reverse"
|
||||
)
|
||||
|
||||
func isDomain(dest net.Destination, domain string) bool {
|
||||
return dest.Address.Family().IsDomain() && dest.Address.Domain() == domain
|
||||
}
|
||||
|
||||
func isInternalDomain(dest net.Destination) bool {
|
||||
return isDomain(dest, internalDomain)
|
||||
}
|
||||
|
||||
func init() {
|
||||
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
|
||||
r := new(Reverse)
|
||||
if err := core.RequireFeatures(ctx, func(d routing.Dispatcher, om outbound.Manager) error {
|
||||
return r.Init(config.(*Config), d, om)
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r, nil
|
||||
}))
|
||||
}
|
||||
|
||||
type Reverse struct {
|
||||
bridges []*Bridge
|
||||
portals []*Portal
|
||||
}
|
||||
|
||||
func (r *Reverse) Init(config *Config, d routing.Dispatcher, ohm outbound.Manager) error {
|
||||
for _, bConfig := range config.BridgeConfig {
|
||||
b, err := NewBridge(bConfig, d)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.bridges = append(r.bridges, b)
|
||||
}
|
||||
|
||||
for _, pConfig := range config.PortalConfig {
|
||||
p, err := NewPortal(pConfig, ohm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.portals = append(r.portals, p)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Reverse) Type() interface{} {
|
||||
return (*Reverse)(nil)
|
||||
}
|
||||
|
||||
func (r *Reverse) Start() error {
|
||||
for _, b := range r.bridges {
|
||||
if err := b.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for _, p := range r.portals {
|
||||
if err := p.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Reverse) Close() error {
|
||||
var errs []error
|
||||
for _, b := range r.bridges {
|
||||
errs = append(errs, b.Close())
|
||||
}
|
||||
|
||||
for _, p := range r.portals {
|
||||
errs = append(errs, p.Close())
|
||||
}
|
||||
|
||||
return errors.Combine(errs...)
|
||||
}
|
||||
@@ -44,9 +44,8 @@ func (c routingContext) GetRuleTag() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// GetSkipDNSResolve is a mock implementation here to match the interface,
|
||||
// SkipDNSResolve is set from dns module, no use if coming from a protobuf object?
|
||||
// TODO: please confirm @Vigilans
|
||||
// GetSkipDNSResolve implements routing.Context.
|
||||
// The protobuf RoutingContext has no skip flag, so API contexts use false.
|
||||
func (c routingContext) GetSkipDNSResolve() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ func RegisterLua(L *lua.LState) {
|
||||
return 0
|
||||
}
|
||||
xlua.PushWithDirectMethods(L, matcher, map[string]xlua.DirectMethod{
|
||||
"Match": newLuaDomainMatch(xlua.NewReadOnlySlicePusher[uint32](L)),
|
||||
"Match": newLuaDomainMatch(xlua.NewSlicePusher[uint32](L)),
|
||||
"MatchAny": luaDomainMatchAny,
|
||||
})
|
||||
return 1
|
||||
|
||||
@@ -104,9 +104,7 @@ for _, value in ipairs({matcher, domain}) do
|
||||
assert(not pcall(function() return value ^ {} end))
|
||||
end
|
||||
assert(domain:matchAny("example.com"))
|
||||
local indices = domain:Match("example.com")
|
||||
assert(#indices == 1)
|
||||
assert(not pcall(function() indices[1] = 7 end))
|
||||
assert(#domain:Match("example.com") == 1)
|
||||
assert(domain:match("example.com")[1] == 0)
|
||||
assert(not pcall(function() matcher:AnyMatch() end))
|
||||
assert(not pcall(function() matcher:AnyMatch(matched, true) end))
|
||||
|
||||
+3
-3
@@ -8,10 +8,10 @@ import (
|
||||
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,
|
||||
// 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
|
||||
return func(L *glua.LState, values []T) {
|
||||
if values == nil {
|
||||
@@ -38,7 +38,7 @@ func NewReadOnlySlicePusher[T any](L *glua.LState) func(*glua.LState, []T) {
|
||||
})
|
||||
setSliceReadOnly[[]T](L, readOnly)
|
||||
}
|
||||
return newSlicePusher[T](L)
|
||||
return NewSlicePusher[T](L)
|
||||
}
|
||||
|
||||
func setSliceReadOnly[S ~[]E, E any](L *glua.LState, readOnly *glua.LFunction) {
|
||||
|
||||
+43
-21
@@ -9,20 +9,53 @@ import (
|
||||
luar "layeh.com/gopher-luar"
|
||||
)
|
||||
|
||||
func TestReadOnlySlicePusher(t *testing.T) {
|
||||
func TestSlicePusher(t *testing.T) {
|
||||
L := glua.NewState()
|
||||
defer L.Close()
|
||||
push := NewReadOnlySlicePusher[int](L)
|
||||
push := NewSlicePusher[int](L)
|
||||
values := []int{3, 5}
|
||||
L.SetGlobal("getValues", L.NewFunction(func(L *glua.LState) int {
|
||||
push(L, values)
|
||||
return 1
|
||||
}))
|
||||
if err := L.DoString(`
|
||||
local co = coroutine.create(function() return getValues() end)
|
||||
local values = getValues()
|
||||
assert(#values == 2 and values[1] == 3 and values[2] == 5)
|
||||
values[2] = 7
|
||||
local co = coroutine.create(function()
|
||||
local values = getValues()
|
||||
assert(#values == 2 and values[1] == 3 and values[2] == 7)
|
||||
return true
|
||||
end)
|
||||
local ok, result = coroutine.resume(co)
|
||||
assert(ok, result)
|
||||
values = result
|
||||
assert(ok and result == true)
|
||||
`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if values[1] != 7 {
|
||||
t.Fatal("slice storage was copied")
|
||||
}
|
||||
push(L, nil)
|
||||
if L.Get(-1) != glua.LNil {
|
||||
t.Fatal("nil slice must push Lua nil")
|
||||
}
|
||||
L.Pop(1)
|
||||
push(L, []int{})
|
||||
L.SetGlobal("empty", L.Get(-1))
|
||||
L.Pop(1)
|
||||
if err := L.DoString(`assert(type(empty) == "userdata" and #empty == 0)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadOnlySlicePusher(t *testing.T) {
|
||||
L := glua.NewState()
|
||||
defer L.Close()
|
||||
values := []int{3, 5}
|
||||
NewReadOnlySlicePusher[int](L)(L, values)
|
||||
L.SetGlobal("values", L.Get(-1))
|
||||
L.Pop(1)
|
||||
if err := L.DoString(`
|
||||
assert(#values == 2 and values[1] == 3 and values[2] == 5)
|
||||
assert(not pcall(function() values[1] = 7 end))
|
||||
assert(not pcall(function() return values + 7 end))
|
||||
@@ -36,17 +69,6 @@ assert(sum == 8)
|
||||
if &got[0] != &values[0] || values[0] != 3 || values[1] != 5 {
|
||||
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) {
|
||||
@@ -208,23 +230,23 @@ assert(not pcall(function() return nested + nested end))
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadOnlySlicePusherMetatablePerState(t *testing.T) {
|
||||
func TestSlicePusherMetatablePerState(t *testing.T) {
|
||||
first := glua.NewState()
|
||||
defer first.Close()
|
||||
second := glua.NewState()
|
||||
defer second.Close()
|
||||
NewReadOnlySlicePusher[int](first)(first, []int{1})
|
||||
NewReadOnlySlicePusher[int](second)(second, []int{1})
|
||||
NewSlicePusher[int](first)(first, []int{1})
|
||||
NewSlicePusher[int](second)(second, []int{1})
|
||||
if first.Get(-1).(*glua.LUserData).Metatable == second.Get(-1).(*glua.LUserData).Metatable {
|
||||
t.Fatal("independent states share a slice metatable")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkReadOnlySlicePusher(b *testing.B) {
|
||||
func BenchmarkSlicePusher(b *testing.B) {
|
||||
L := glua.NewState()
|
||||
defer L.Close()
|
||||
ips := []net.IP{net.ParseIP("127.0.0.1")}
|
||||
pushIPs := NewReadOnlySlicePusher[net.IP](L)
|
||||
pushIPs := NewSlicePusher[net.IP](L)
|
||||
for _, benchmark := range []struct {
|
||||
name string
|
||||
push func(*glua.LState, []net.IP)
|
||||
|
||||
@@ -671,7 +671,7 @@ string.__tostring = nil
|
||||
L.SetGlobal("testNativeError", L.Get(-1))
|
||||
L.Pop(1)
|
||||
L.SetGlobal("testGoStruct", luar.New(L, &struct{ Value string }{"readable field"}))
|
||||
NewReadOnlySlicePusher[net.IP](L)(L, []net.IP{net.ParseIP("192.0.2.1")})
|
||||
NewSlicePusher[net.IP](L)(L, []net.IP{net.ParseIP("192.0.2.1")})
|
||||
L.SetGlobal("testIPs", L.Get(-1))
|
||||
L.Pop(1)
|
||||
userdata := L.NewUserData()
|
||||
@@ -865,7 +865,9 @@ assert(not ok and a == "{<address> <address>}")
|
||||
PushUserData(L, struct{ Pointer *int }{&target})
|
||||
L.SetGlobal("testObject", L.Get(-1))
|
||||
L.Pop(1)
|
||||
L.SetGlobal("testValues", luar.New(L, []int{1}))
|
||||
NewSlicePusher[int](L)(L, []int{1})
|
||||
L.SetGlobal("testValues", L.Get(-1))
|
||||
L.Pop(1)
|
||||
L.SetGlobal("testPanic", L.NewFunction(func(L *glua.LState) int {
|
||||
panic(struct{ First, Second *int }{&target, &target})
|
||||
}))
|
||||
|
||||
@@ -1,420 +0,0 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"context"
|
||||
goerrors "errors"
|
||||
"io"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/signal/done"
|
||||
"github.com/xtls/xray-core/common/task"
|
||||
"github.com/xtls/xray-core/common/xudp"
|
||||
"github.com/xtls/xray-core/proxy"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
type ClientManager struct {
|
||||
Enabled bool // whether mux is enabled from user config
|
||||
Picker WorkerPicker
|
||||
}
|
||||
|
||||
func (m *ClientManager) Dispatch(ctx context.Context, link *transport.Link) error {
|
||||
for i := 0; i < 16; i++ {
|
||||
worker, err := m.Picker.PickAvailable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if worker.Dispatch(ctx, link) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return errors.New("unable to find an available mux client")
|
||||
}
|
||||
|
||||
type WorkerPicker interface {
|
||||
PickAvailable() (*ClientWorker, error)
|
||||
}
|
||||
|
||||
type IncrementalWorkerPicker struct {
|
||||
Factory ClientWorkerFactory
|
||||
|
||||
access sync.Mutex
|
||||
workers []*ClientWorker
|
||||
cleanupTask *task.Periodic
|
||||
}
|
||||
|
||||
func (p *IncrementalWorkerPicker) cleanupFunc() error {
|
||||
p.access.Lock()
|
||||
defer p.access.Unlock()
|
||||
|
||||
if len(p.workers) == 0 {
|
||||
return errors.New("no worker")
|
||||
}
|
||||
|
||||
p.cleanup()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *IncrementalWorkerPicker) cleanup() {
|
||||
var activeWorkers []*ClientWorker
|
||||
for _, w := range p.workers {
|
||||
if !w.Closed() {
|
||||
activeWorkers = append(activeWorkers, w)
|
||||
}
|
||||
}
|
||||
p.workers = activeWorkers
|
||||
}
|
||||
|
||||
func (p *IncrementalWorkerPicker) findAvailable() int {
|
||||
for idx, w := range p.workers {
|
||||
if !w.IsFull() {
|
||||
return idx
|
||||
}
|
||||
}
|
||||
|
||||
return -1
|
||||
}
|
||||
|
||||
func (p *IncrementalWorkerPicker) pickInternal() (*ClientWorker, bool, error) {
|
||||
p.access.Lock()
|
||||
defer p.access.Unlock()
|
||||
|
||||
idx := p.findAvailable()
|
||||
if idx >= 0 {
|
||||
n := len(p.workers)
|
||||
if n > 1 && idx != n-1 {
|
||||
p.workers[n-1], p.workers[idx] = p.workers[idx], p.workers[n-1]
|
||||
}
|
||||
return p.workers[idx], false, nil
|
||||
}
|
||||
|
||||
p.cleanup()
|
||||
|
||||
worker, err := p.Factory.Create()
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
p.workers = append(p.workers, worker)
|
||||
|
||||
if p.cleanupTask == nil {
|
||||
p.cleanupTask = &task.Periodic{
|
||||
Interval: time.Second * 30,
|
||||
Execute: p.cleanupFunc,
|
||||
}
|
||||
}
|
||||
|
||||
return worker, true, nil
|
||||
}
|
||||
|
||||
func (p *IncrementalWorkerPicker) PickAvailable() (*ClientWorker, error) {
|
||||
worker, start, err := p.pickInternal()
|
||||
if start {
|
||||
common.Must(p.cleanupTask.Start())
|
||||
}
|
||||
|
||||
return worker, err
|
||||
}
|
||||
|
||||
type ClientWorkerFactory interface {
|
||||
Create() (*ClientWorker, error)
|
||||
}
|
||||
|
||||
type DialingWorkerFactory struct {
|
||||
Proxy proxy.Outbound
|
||||
Dialer internet.Dialer
|
||||
Strategy ClientStrategy
|
||||
}
|
||||
|
||||
func (f *DialingWorkerFactory) Create() (*ClientWorker, error) {
|
||||
opts := []pipe.Option{pipe.WithSizeLimit(64 * 1024)}
|
||||
uplinkReader, upLinkWriter := pipe.New(opts...)
|
||||
downlinkReader, downlinkWriter := pipe.New(opts...)
|
||||
|
||||
c, err := NewClientWorker(transport.Link{
|
||||
Reader: downlinkReader,
|
||||
Writer: upLinkWriter,
|
||||
}, f.Strategy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
go func(p proxy.Outbound, d internet.Dialer, c common.Closable) {
|
||||
outbounds := []*session.Outbound{{
|
||||
Target: net.TCPDestination(muxCoolAddress, muxCoolPort),
|
||||
}}
|
||||
ctx := session.ContextWithOutbounds(context.Background(), outbounds)
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
|
||||
if errP := p.Process(ctx, &transport.Link{Reader: uplinkReader, Writer: downlinkWriter}, d); errP != nil {
|
||||
errC := errors.Cause(errP)
|
||||
if !(goerrors.Is(errC, io.EOF) || goerrors.Is(errC, io.ErrClosedPipe) || goerrors.Is(errC, context.Canceled)) {
|
||||
errors.LogInfoInner(ctx, errP, "failed to handler mux client connection")
|
||||
}
|
||||
}
|
||||
common.Must(c.Close())
|
||||
cancel()
|
||||
}(f.Proxy, f.Dialer, c.done)
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
type ClientStrategy struct {
|
||||
MaxConcurrency uint32
|
||||
MaxConnection uint32
|
||||
}
|
||||
|
||||
type ClientWorker struct {
|
||||
sessionManager *SessionManager
|
||||
link transport.Link
|
||||
done *done.Instance
|
||||
timer *time.Ticker
|
||||
strategy ClientStrategy
|
||||
}
|
||||
|
||||
var (
|
||||
muxCoolAddress = net.DomainAddress("v1.mux.cool")
|
||||
muxCoolPort = net.Port(9527)
|
||||
)
|
||||
|
||||
// NewClientWorker creates a new mux.Client.
|
||||
func NewClientWorker(stream transport.Link, s ClientStrategy) (*ClientWorker, error) {
|
||||
writer := buf.NewBufferedWriter(stream.Writer)
|
||||
writer.SetBuffered(false)
|
||||
stream.Writer = writer
|
||||
c := &ClientWorker{
|
||||
sessionManager: NewSessionManager(),
|
||||
link: stream,
|
||||
done: done.New(),
|
||||
timer: time.NewTicker(time.Second * 16),
|
||||
strategy: s,
|
||||
}
|
||||
|
||||
go c.fetchOutput()
|
||||
go c.monitor()
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (m *ClientWorker) TotalConnections() uint32 {
|
||||
return uint32(m.sessionManager.Count())
|
||||
}
|
||||
|
||||
func (m *ClientWorker) ActiveConnections() uint32 {
|
||||
return uint32(m.sessionManager.Size())
|
||||
}
|
||||
|
||||
// Closed returns true if this Client is closed.
|
||||
func (m *ClientWorker) Closed() bool {
|
||||
return m.done.Done()
|
||||
}
|
||||
|
||||
func (m *ClientWorker) WaitClosed() <-chan struct{} {
|
||||
return m.done.Wait()
|
||||
}
|
||||
|
||||
func (m *ClientWorker) Close() error {
|
||||
return m.done.Close()
|
||||
}
|
||||
|
||||
func (m *ClientWorker) monitor() {
|
||||
defer m.timer.Stop()
|
||||
|
||||
for {
|
||||
checkSize := m.sessionManager.Size()
|
||||
checkCount := m.sessionManager.Count()
|
||||
select {
|
||||
case <-m.done.Wait():
|
||||
m.sessionManager.Close()
|
||||
common.Interrupt(m.link.Writer)
|
||||
common.Interrupt(m.link.Reader)
|
||||
return
|
||||
case <-m.timer.C:
|
||||
if m.sessionManager.CloseIfNoSessionAndIdle(checkSize, checkCount) {
|
||||
common.Must(m.done.Close())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func writeFirstPayload(reader buf.Reader, writer *Writer) error {
|
||||
err := buf.CopyOnceTimeout(reader, writer, time.Millisecond*100)
|
||||
if err == buf.ErrNotTimeoutReader || err == buf.ErrReadTimeout {
|
||||
return writer.WriteMultiBuffer(buf.MultiBuffer{})
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func fetchInput(ctx context.Context, s *Session, output buf.Writer) {
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
ob := outbounds[len(outbounds)-1]
|
||||
transferType := protocol.TransferTypeStream
|
||||
if ob.Target.Network == net.Network_UDP {
|
||||
transferType = protocol.TransferTypePacket
|
||||
}
|
||||
s.transferType = transferType
|
||||
var inbound *session.Inbound
|
||||
if session.IsReverseMuxFromContext(ctx) {
|
||||
inbound = session.InboundFromContext(ctx)
|
||||
}
|
||||
writer := NewWriter(s.ID, ob.Target, output, transferType, xudp.GetGlobalID(ctx), inbound)
|
||||
defer s.Close(false)
|
||||
defer writer.Close()
|
||||
|
||||
errors.LogInfo(ctx, "dispatching request to ", ob.Target)
|
||||
if err := writeFirstPayload(s.input, writer); err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to write first payload")
|
||||
writer.hasError = true
|
||||
return
|
||||
}
|
||||
|
||||
if err := buf.Copy(s.input, writer); err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to fetch all input")
|
||||
writer.hasError = true
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (m *ClientWorker) IsClosing() bool {
|
||||
sm := m.sessionManager
|
||||
if m.strategy.MaxConnection > 0 && sm.Count() >= int(m.strategy.MaxConnection) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsFull returns true if this ClientWorker is unable to accept more connections.
|
||||
// it might be because it is closing, or the number of connections has reached the limit.
|
||||
func (m *ClientWorker) IsFull() bool {
|
||||
if m.IsClosing() || m.Closed() {
|
||||
return true
|
||||
}
|
||||
|
||||
sm := m.sessionManager
|
||||
if m.strategy.MaxConcurrency > 0 && sm.Size() >= int(m.strategy.MaxConcurrency) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (m *ClientWorker) Dispatch(ctx context.Context, link *transport.Link) bool {
|
||||
if m.IsFull() {
|
||||
return false
|
||||
}
|
||||
|
||||
sm := m.sessionManager
|
||||
s := sm.Allocate(&m.strategy, link.Reader, link.Writer)
|
||||
if s == nil {
|
||||
return false
|
||||
}
|
||||
go fetchInput(ctx, s, m.link.Writer)
|
||||
if _, ok := link.Reader.(*pipe.Reader); !ok {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-s.done.Wait():
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (m *ClientWorker) handleStatueKeepAlive(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if meta.Option.Has(OptionData) {
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *ClientWorker) handleStatusNew(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if meta.Option.Has(OptionData) {
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *ClientWorker) handleStatusKeep(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if !meta.Option.Has(OptionData) {
|
||||
return nil
|
||||
}
|
||||
|
||||
s, found := m.sessionManager.Get(meta.SessionID)
|
||||
if !found {
|
||||
// Notify remote peer to close this session.
|
||||
closingWriter := NewResponseWriter(meta.SessionID, m.link.Writer, protocol.TransferTypeStream)
|
||||
closingWriter.Close()
|
||||
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
|
||||
rr := s.NewReader(reader, &meta.Target)
|
||||
err := buf.Copy(rr, s.output)
|
||||
if err != nil && buf.IsWriteError(err) {
|
||||
errors.LogInfoInner(context.Background(), err, "failed to write to downstream. closing session ", s.ID)
|
||||
s.Close(false)
|
||||
return buf.Copy(rr, buf.Discard)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *ClientWorker) handleStatusEnd(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if s, found := m.sessionManager.Get(meta.SessionID); found {
|
||||
s.Close(false)
|
||||
}
|
||||
if meta.Option.Has(OptionData) {
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *ClientWorker) fetchOutput() {
|
||||
defer func() {
|
||||
common.Must(m.done.Close())
|
||||
}()
|
||||
|
||||
reader := &buf.BufferedReader{Reader: m.link.Reader}
|
||||
|
||||
var meta FrameMetadata
|
||||
for {
|
||||
err := meta.Unmarshal(reader, false)
|
||||
if err != nil {
|
||||
if errors.Cause(err) != io.EOF {
|
||||
errors.LogInfoInner(context.Background(), err, "failed to read metadata")
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
switch meta.SessionStatus {
|
||||
case SessionStatusKeepAlive:
|
||||
err = m.handleStatueKeepAlive(&meta, reader)
|
||||
case SessionStatusEnd:
|
||||
err = m.handleStatusEnd(&meta, reader)
|
||||
case SessionStatusNew:
|
||||
err = m.handleStatusNew(&meta, reader)
|
||||
case SessionStatusKeep:
|
||||
err = m.handleStatusKeep(&meta, reader)
|
||||
default:
|
||||
status := meta.SessionStatus
|
||||
errors.LogError(context.Background(), "unknown status: ", status)
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
errors.LogInfoInner(context.Background(), err, "failed to process data")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
package mux_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/mux"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/testing/mocks"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
func TestIncrementalPickerFailure(t *testing.T) {
|
||||
mockCtl := gomock.NewController(t)
|
||||
defer mockCtl.Finish()
|
||||
|
||||
mockWorkerFactory := mocks.NewMuxClientWorkerFactory(mockCtl)
|
||||
mockWorkerFactory.EXPECT().Create().Return(nil, errors.New("test"))
|
||||
|
||||
picker := mux.IncrementalWorkerPicker{
|
||||
Factory: mockWorkerFactory,
|
||||
}
|
||||
|
||||
_, err := picker.PickAvailable()
|
||||
if err == nil {
|
||||
t.Error("expected error, but nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientWorkerEOF(t *testing.T) {
|
||||
reader, writer := pipe.New(pipe.WithoutSizeLimit())
|
||||
common.Must(writer.Close())
|
||||
|
||||
worker, err := mux.NewClientWorker(transport.Link{Reader: reader, Writer: writer}, mux.ClientStrategy{})
|
||||
common.Must(err)
|
||||
|
||||
time.Sleep(time.Millisecond * 500)
|
||||
|
||||
f := worker.Dispatch(context.Background(), nil)
|
||||
if f {
|
||||
t.Error("expected failed dispatching, but actually not")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientWorkerClose(t *testing.T) {
|
||||
mockCtl := gomock.NewController(t)
|
||||
defer mockCtl.Finish()
|
||||
|
||||
r1, w1 := pipe.New(pipe.WithoutSizeLimit())
|
||||
worker1, err := mux.NewClientWorker(transport.Link{
|
||||
Reader: r1,
|
||||
Writer: w1,
|
||||
}, mux.ClientStrategy{
|
||||
MaxConcurrency: 4,
|
||||
MaxConnection: 4,
|
||||
})
|
||||
common.Must(err)
|
||||
|
||||
r2, w2 := pipe.New(pipe.WithoutSizeLimit())
|
||||
worker2, err := mux.NewClientWorker(transport.Link{
|
||||
Reader: r2,
|
||||
Writer: w2,
|
||||
}, mux.ClientStrategy{
|
||||
MaxConcurrency: 4,
|
||||
MaxConnection: 4,
|
||||
})
|
||||
common.Must(err)
|
||||
|
||||
factory := mocks.NewMuxClientWorkerFactory(mockCtl)
|
||||
gomock.InOrder(
|
||||
factory.EXPECT().Create().Return(worker1, nil),
|
||||
factory.EXPECT().Create().Return(worker2, nil),
|
||||
)
|
||||
|
||||
picker := &mux.IncrementalWorkerPicker{
|
||||
Factory: factory,
|
||||
}
|
||||
manager := &mux.ClientManager{
|
||||
Picker: picker,
|
||||
}
|
||||
|
||||
tr1, tw1 := pipe.New(pipe.WithoutSizeLimit())
|
||||
ctx1 := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
|
||||
Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80),
|
||||
}})
|
||||
common.Must(manager.Dispatch(ctx1, &transport.Link{
|
||||
Reader: tr1,
|
||||
Writer: tw1,
|
||||
}))
|
||||
defer tw1.Close()
|
||||
|
||||
common.Must(w1.Close())
|
||||
|
||||
time.Sleep(time.Millisecond * 500)
|
||||
if !worker1.Closed() {
|
||||
t.Error("worker1 is not finished")
|
||||
}
|
||||
|
||||
tr2, tw2 := pipe.New(pipe.WithoutSizeLimit())
|
||||
ctx2 := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
|
||||
Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80),
|
||||
}})
|
||||
common.Must(manager.Dispatch(ctx2, &transport.Link{
|
||||
Reader: tr2,
|
||||
Writer: tw2,
|
||||
}))
|
||||
defer tw2.Close()
|
||||
|
||||
common.Must(w2.Close())
|
||||
}
|
||||
|
||||
func TestClientWorkerUDPSource(t *testing.T) {
|
||||
downR, downW := pipe.New(pipe.WithoutSizeLimit())
|
||||
upR, upW := pipe.New(pipe.WithoutSizeLimit())
|
||||
worker, err := mux.NewClientWorker(transport.Link{Reader: downR, Writer: upW}, mux.ClientStrategy{})
|
||||
common.Must(err)
|
||||
|
||||
inR, inW := pipe.New(pipe.WithoutSizeLimit())
|
||||
outR, outW := pipe.New(pipe.WithoutSizeLimit())
|
||||
ctx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
|
||||
Target: net.UDPDestination(net.ParseAddress("8.8.8.8"), 53),
|
||||
}})
|
||||
if !worker.Dispatch(ctx, &transport.Link{Reader: inR, Writer: outW}) {
|
||||
t.Fatal("failed to dispatch")
|
||||
}
|
||||
b := buf.New()
|
||||
b.WriteString("query")
|
||||
common.Must(inW.WriteMultiBuffer(buf.MultiBuffer{b}))
|
||||
mb, err := upR.ReadMultiBuffer() // New frame, the session is UDP from now on
|
||||
common.Must(err)
|
||||
buf.ReleaseMulti(mb)
|
||||
|
||||
srcs := []net.Destination{
|
||||
net.UDPDestination(net.ParseAddress("1.1.1.1"), 1111),
|
||||
net.UDPDestination(net.DomainAddress("example.com"), 2222),
|
||||
net.UDPDestination(net.ParseAddress("3.3.3.3"), 3333),
|
||||
}
|
||||
w := mux.NewResponseWriter(1, downW, protocol.TransferTypePacket)
|
||||
var got buf.MultiBuffer
|
||||
for i := range srcs {
|
||||
b := buf.New()
|
||||
b.WriteString("reply")
|
||||
b.UDP = &srcs[i]
|
||||
common.Must(w.WriteMultiBuffer(buf.MultiBuffer{b}))
|
||||
// keep earlier replies around while the next frame is parsed
|
||||
mb, err := outR.ReadMultiBuffer()
|
||||
common.Must(err)
|
||||
got = append(got, mb...)
|
||||
}
|
||||
for i, b := range got {
|
||||
if b.UDP == nil || *b.UDP != srcs[i] {
|
||||
t.Errorf("reply %d: source = %v, want %v", i, b.UDP, srcs[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package mux_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/mux"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
)
|
||||
|
||||
func BenchmarkFrameWrite(b *testing.B) {
|
||||
frame := mux.FrameMetadata{
|
||||
Target: net.TCPDestination(net.DomainAddress("www.example.com"), net.Port(80)),
|
||||
SessionID: 1,
|
||||
SessionStatus: mux.SessionStatusNew,
|
||||
}
|
||||
writer := buf.New()
|
||||
defer writer.Release()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
common.Must(frame.WriteTo(writer))
|
||||
writer.Clear()
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
package mux
|
||||
@@ -1,60 +0,0 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/crypto"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
)
|
||||
|
||||
// PacketReader is an io.Reader that reads whole chunk of Mux frames every time.
|
||||
type PacketReader struct {
|
||||
reader io.Reader
|
||||
eof bool
|
||||
dest net.Destination
|
||||
}
|
||||
|
||||
// NewPacketReader creates a new PacketReader.
|
||||
// dest is copied because the caller reuses it for the next frame.
|
||||
func NewPacketReader(reader io.Reader, dest *net.Destination) *PacketReader {
|
||||
return &PacketReader{
|
||||
reader: reader,
|
||||
eof: false,
|
||||
dest: *dest,
|
||||
}
|
||||
}
|
||||
|
||||
// ReadMultiBuffer implements buf.Reader.
|
||||
func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
if r.eof {
|
||||
return nil, io.EOF
|
||||
}
|
||||
|
||||
size, err := serial.ReadUint16(r.reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if size > buf.Size {
|
||||
return nil, errors.New("packet size too large: ", size)
|
||||
}
|
||||
|
||||
b := buf.New()
|
||||
if _, err := b.ReadFullFrom(r.reader, int32(size)); err != nil {
|
||||
b.Release()
|
||||
return nil, err
|
||||
}
|
||||
r.eof = true
|
||||
if r.dest.Network == net.Network_UDP {
|
||||
b.UDP = &r.dest // only one packet is read, so b owns r.dest
|
||||
}
|
||||
return buf.MultiBuffer{b}, nil
|
||||
}
|
||||
|
||||
// NewStreamReader creates a new StreamReader.
|
||||
func NewStreamReader(reader *buf.BufferedReader) buf.Reader {
|
||||
return crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, reader, 1)
|
||||
}
|
||||
@@ -1,386 +0,0 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/log"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/signal/done"
|
||||
"github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
dispatcher routing.Dispatcher
|
||||
}
|
||||
|
||||
// NewServer creates a new mux.Server.
|
||||
func NewServer(ctx context.Context) *Server {
|
||||
s := &Server{}
|
||||
core.RequireFeatures(ctx, func(d routing.Dispatcher) {
|
||||
s.dispatcher = d
|
||||
})
|
||||
return s
|
||||
}
|
||||
|
||||
// Type implements common.HasType.
|
||||
func (s *Server) Type() interface{} {
|
||||
return s.dispatcher.Type()
|
||||
}
|
||||
|
||||
// Dispatch implements routing.Dispatcher
|
||||
func (s *Server) Dispatch(ctx context.Context, dest net.Destination) (*transport.Link, error) {
|
||||
if dest.Address != muxCoolAddress {
|
||||
return s.dispatcher.Dispatch(ctx, dest)
|
||||
}
|
||||
|
||||
opts := pipe.OptionsFromContext(ctx)
|
||||
uplinkReader, uplinkWriter := pipe.New(opts...)
|
||||
downlinkReader, downlinkWriter := pipe.New(opts...)
|
||||
|
||||
_, err := NewServerWorker(ctx, s.dispatcher, &transport.Link{
|
||||
Reader: uplinkReader,
|
||||
Writer: downlinkWriter,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &transport.Link{Reader: downlinkReader, Writer: uplinkWriter}, nil
|
||||
}
|
||||
|
||||
// DispatchLink implements routing.Dispatcher
|
||||
func (s *Server) DispatchLink(ctx context.Context, dest net.Destination, link *transport.Link) error {
|
||||
if dest.Address != muxCoolAddress {
|
||||
return s.dispatcher.DispatchLink(ctx, dest, link)
|
||||
}
|
||||
worker, err := NewServerWorker(ctx, s.dispatcher, link)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-worker.done.Wait():
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Start implements common.Runnable.
|
||||
func (s *Server) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close implements common.Closable.
|
||||
func (s *Server) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type ServerWorker struct {
|
||||
dispatcher routing.Dispatcher
|
||||
link *transport.Link
|
||||
sessionManager *SessionManager
|
||||
done *done.Instance
|
||||
timer *time.Ticker
|
||||
}
|
||||
|
||||
func NewServerWorker(ctx context.Context, d routing.Dispatcher, link *transport.Link) (*ServerWorker, error) {
|
||||
writer := buf.NewBufferedWriter(link.Writer)
|
||||
writer.SetBuffered(false)
|
||||
worker := &ServerWorker{
|
||||
dispatcher: d,
|
||||
link: &transport.Link{Reader: link.Reader, Writer: writer},
|
||||
sessionManager: NewSessionManager(),
|
||||
done: done.New(),
|
||||
timer: time.NewTicker(60 * time.Second),
|
||||
}
|
||||
if inbound := session.InboundFromContext(ctx); inbound != nil {
|
||||
inbound.CanSpliceCopy = 3
|
||||
}
|
||||
go worker.run(ctx)
|
||||
go worker.monitor()
|
||||
return worker, nil
|
||||
}
|
||||
|
||||
func handle(ctx context.Context, s *Session, output buf.Writer) {
|
||||
writer := NewResponseWriter(s.ID, output, s.transferType)
|
||||
if err := buf.Copy(s.input, writer); err != nil {
|
||||
errors.LogInfoInner(ctx, err, "session ", s.ID, " ends.")
|
||||
writer.hasError = true
|
||||
}
|
||||
|
||||
writer.Close()
|
||||
s.Close(false)
|
||||
}
|
||||
|
||||
func (w *ServerWorker) monitor() {
|
||||
defer w.timer.Stop()
|
||||
|
||||
for {
|
||||
checkSize := w.sessionManager.Size()
|
||||
checkCount := w.sessionManager.Count()
|
||||
select {
|
||||
case <-w.done.Wait():
|
||||
w.sessionManager.Close()
|
||||
common.Interrupt(w.link.Writer)
|
||||
common.Interrupt(w.link.Reader)
|
||||
return
|
||||
case <-w.timer.C:
|
||||
if w.sessionManager.CloseIfNoSessionAndIdle(checkSize, checkCount) {
|
||||
common.Must(w.done.Close())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *ServerWorker) ActiveConnections() uint32 {
|
||||
return uint32(w.sessionManager.Size())
|
||||
}
|
||||
|
||||
func (w *ServerWorker) Closed() bool {
|
||||
return w.done.Done()
|
||||
}
|
||||
|
||||
func (w *ServerWorker) WaitClosed() <-chan struct{} {
|
||||
return w.done.Wait()
|
||||
}
|
||||
|
||||
func (w *ServerWorker) Close() error {
|
||||
return w.done.Close()
|
||||
}
|
||||
|
||||
func (w *ServerWorker) handleStatusKeepAlive(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if meta.Option.Has(OptionData) {
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
ctx = session.SubContextFromMuxInbound(ctx)
|
||||
if meta.Inbound != nil && meta.Inbound.Source.IsValid() && meta.Inbound.Local.IsValid() {
|
||||
if inbound := session.InboundFromContext(ctx); inbound != nil {
|
||||
newInbound := *inbound
|
||||
newInbound.Source = meta.Inbound.Source
|
||||
newInbound.Local = meta.Inbound.Local
|
||||
ctx = session.ContextWithInbound(ctx, &newInbound)
|
||||
}
|
||||
}
|
||||
errors.LogInfo(ctx, "received request for ", meta.Target)
|
||||
{
|
||||
msg := &log.AccessMessage{
|
||||
To: meta.Target,
|
||||
Status: log.AccessAccepted,
|
||||
Reason: "",
|
||||
}
|
||||
if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.IsValid() {
|
||||
msg.From = inbound.Source
|
||||
msg.Email = inbound.User.Email
|
||||
}
|
||||
ctx = log.ContextWithAccessMessage(ctx, msg)
|
||||
}
|
||||
|
||||
if network := session.AllowedNetworkFromContext(ctx); network != net.Network_Unknown {
|
||||
if meta.Target.Network != network {
|
||||
return errors.New("unexpected network ", meta.Target.Network) // it will break the whole Mux connection
|
||||
}
|
||||
}
|
||||
|
||||
if meta.GlobalID != [8]byte{} { // MUST ignore empty Global ID
|
||||
mb, err := NewPacketReader(reader, &meta.Target).ReadMultiBuffer()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
XUDPManager.Lock()
|
||||
x := XUDPManager.Map[meta.GlobalID]
|
||||
if x == nil {
|
||||
x = &XUDP{GlobalID: meta.GlobalID}
|
||||
XUDPManager.Map[meta.GlobalID] = x
|
||||
XUDPManager.Unlock()
|
||||
} else {
|
||||
if x.Status == Initializing { // nearly impossible
|
||||
XUDPManager.Unlock()
|
||||
errors.LogWarningInner(ctx, errors.New("conflict"), "XUDP hit ", meta.GlobalID)
|
||||
// It's not a good idea to return an err here, so just let client wait.
|
||||
// Client will receive an End frame after sending a Keep frame.
|
||||
return nil
|
||||
}
|
||||
x.Status = Initializing
|
||||
XUDPManager.Unlock()
|
||||
x.Mux.Close(false) // detach from previous Mux
|
||||
b := buf.New()
|
||||
b.Write(mb[0].Bytes())
|
||||
b.UDP = mb[0].UDP
|
||||
if err = x.Mux.output.WriteMultiBuffer(mb); err != nil {
|
||||
x.Interrupt()
|
||||
mb = buf.MultiBuffer{b}
|
||||
} else {
|
||||
b.Release()
|
||||
mb = nil
|
||||
}
|
||||
errors.LogInfoInner(ctx, err, "XUDP hit ", meta.GlobalID)
|
||||
}
|
||||
if mb != nil {
|
||||
ctx = session.ContextWithTimeoutOnly(ctx, true)
|
||||
// Actually, it won't return an error in Xray-core's implementations.
|
||||
link, err := w.dispatcher.Dispatch(ctx, meta.Target)
|
||||
if err != nil {
|
||||
XUDPManager.Lock()
|
||||
delete(XUDPManager.Map, x.GlobalID)
|
||||
XUDPManager.Unlock()
|
||||
err = errors.New("XUDP new ", meta.GlobalID).Base(errors.New("failed to dispatch request to ", meta.Target).Base(err))
|
||||
return err // it will break the whole Mux connection
|
||||
}
|
||||
link.Writer.WriteMultiBuffer(mb) // it's meaningless to test a new pipe
|
||||
x.Mux = &Session{
|
||||
input: link.Reader,
|
||||
output: link.Writer,
|
||||
}
|
||||
errors.LogInfoInner(ctx, err, "XUDP new ", meta.GlobalID)
|
||||
}
|
||||
x.Mux = &Session{
|
||||
input: x.Mux.input,
|
||||
output: x.Mux.output,
|
||||
parent: w.sessionManager,
|
||||
ID: meta.SessionID,
|
||||
transferType: protocol.TransferTypePacket,
|
||||
XUDP: x,
|
||||
}
|
||||
x.Status = Active
|
||||
if !w.sessionManager.Add(x.Mux) {
|
||||
x.Mux.Close(false)
|
||||
return errors.New("failed to add new session")
|
||||
}
|
||||
go handle(ctx, x.Mux, w.link.Writer)
|
||||
return nil
|
||||
}
|
||||
|
||||
link, err := w.dispatcher.Dispatch(ctx, meta.Target)
|
||||
if err != nil {
|
||||
if meta.Option.Has(OptionData) {
|
||||
buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
return errors.New("failed to dispatch request.").Base(err)
|
||||
}
|
||||
s := &Session{
|
||||
input: link.Reader,
|
||||
output: link.Writer,
|
||||
parent: w.sessionManager,
|
||||
ID: meta.SessionID,
|
||||
transferType: protocol.TransferTypeStream,
|
||||
}
|
||||
if meta.Target.Network == net.Network_UDP {
|
||||
s.transferType = protocol.TransferTypePacket
|
||||
}
|
||||
if !w.sessionManager.Add(s) {
|
||||
s.Close(false)
|
||||
return errors.New("failed to add new session")
|
||||
}
|
||||
go handle(ctx, s, w.link.Writer)
|
||||
if !meta.Option.Has(OptionData) {
|
||||
return nil
|
||||
}
|
||||
|
||||
rr := s.NewReader(reader, &meta.Target)
|
||||
err = buf.Copy(rr, s.output)
|
||||
|
||||
if err != nil && buf.IsWriteError(err) {
|
||||
s.Close(false)
|
||||
return buf.Copy(rr, buf.Discard)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (w *ServerWorker) handleStatusKeep(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if !meta.Option.Has(OptionData) {
|
||||
return nil
|
||||
}
|
||||
|
||||
s, found := w.sessionManager.Get(meta.SessionID)
|
||||
if !found {
|
||||
// Notify remote peer to close this session.
|
||||
closingWriter := NewResponseWriter(meta.SessionID, w.link.Writer, protocol.TransferTypeStream)
|
||||
closingWriter.Close()
|
||||
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
|
||||
rr := s.NewReader(reader, &meta.Target)
|
||||
err := buf.Copy(rr, s.output)
|
||||
|
||||
if err != nil && buf.IsWriteError(err) {
|
||||
errors.LogInfoInner(context.Background(), err, "failed to write to downstream writer. closing session ", s.ID)
|
||||
s.Close(false)
|
||||
return buf.Copy(rr, buf.Discard)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (w *ServerWorker) handleStatusEnd(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if s, found := w.sessionManager.Get(meta.SessionID); found {
|
||||
s.Close(false)
|
||||
}
|
||||
if meta.Option.Has(OptionData) {
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *ServerWorker) handleFrame(ctx context.Context, reader *buf.BufferedReader) error {
|
||||
var meta FrameMetadata
|
||||
err := meta.Unmarshal(reader, session.IsReverseMuxFromContext(ctx))
|
||||
if err != nil {
|
||||
return errors.New("failed to read metadata").Base(err)
|
||||
}
|
||||
|
||||
switch meta.SessionStatus {
|
||||
case SessionStatusKeepAlive:
|
||||
err = w.handleStatusKeepAlive(&meta, reader)
|
||||
case SessionStatusEnd:
|
||||
err = w.handleStatusEnd(&meta, reader)
|
||||
case SessionStatusNew:
|
||||
err = w.handleStatusNew(session.ContextWithIsReverseMux(ctx, false), &meta, reader)
|
||||
case SessionStatusKeep:
|
||||
err = w.handleStatusKeep(&meta, reader)
|
||||
default:
|
||||
status := meta.SessionStatus
|
||||
return errors.New("unknown status: ", status)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return errors.New("failed to process data").Base(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *ServerWorker) run(ctx context.Context) {
|
||||
defer func() {
|
||||
common.Must(w.done.Close())
|
||||
}()
|
||||
|
||||
reader := &buf.BufferedReader{Reader: w.link.Reader}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
err := w.handleFrame(ctx, reader)
|
||||
if err != nil {
|
||||
if errors.Cause(err) != io.EOF {
|
||||
errors.LogInfoInner(ctx, err, "unexpected EOF")
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,254 +0,0 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/signal/done"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
type SessionManager struct {
|
||||
sync.RWMutex
|
||||
sessions map[uint16]*Session
|
||||
count uint16
|
||||
closed bool
|
||||
}
|
||||
|
||||
func NewSessionManager() *SessionManager {
|
||||
return &SessionManager{
|
||||
count: 0,
|
||||
sessions: make(map[uint16]*Session, 16),
|
||||
}
|
||||
}
|
||||
|
||||
func (m *SessionManager) Closed() bool {
|
||||
m.RLock()
|
||||
defer m.RUnlock()
|
||||
|
||||
return m.closed
|
||||
}
|
||||
|
||||
func (m *SessionManager) Size() int {
|
||||
m.RLock()
|
||||
defer m.RUnlock()
|
||||
|
||||
return len(m.sessions)
|
||||
}
|
||||
|
||||
func (m *SessionManager) Count() int {
|
||||
m.RLock()
|
||||
defer m.RUnlock()
|
||||
|
||||
return int(m.count)
|
||||
}
|
||||
|
||||
func (m *SessionManager) Allocate(Strategy *ClientStrategy, input buf.Reader, output buf.Writer) *Session {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
MaxConcurrency := int(Strategy.MaxConcurrency)
|
||||
MaxConnection := uint16(Strategy.MaxConnection)
|
||||
|
||||
if m.closed || (MaxConcurrency > 0 && len(m.sessions) >= MaxConcurrency) || (MaxConnection > 0 && m.count >= MaxConnection) {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.count++
|
||||
s := &Session{
|
||||
input: input,
|
||||
output: output,
|
||||
ID: m.count,
|
||||
parent: m,
|
||||
done: done.New(),
|
||||
}
|
||||
m.sessions[s.ID] = s
|
||||
return s
|
||||
}
|
||||
|
||||
func (m *SessionManager) Add(s *Session) bool {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
if m.closed {
|
||||
return false
|
||||
}
|
||||
|
||||
m.count++
|
||||
m.sessions[s.ID] = s
|
||||
return true
|
||||
}
|
||||
|
||||
func (m *SessionManager) Remove(locked bool, id uint16) {
|
||||
if !locked {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
}
|
||||
locked = true
|
||||
|
||||
if m.closed {
|
||||
return
|
||||
}
|
||||
|
||||
delete(m.sessions, id)
|
||||
|
||||
/*
|
||||
if len(m.sessions) == 0 {
|
||||
m.sessions = make(map[uint16]*Session, 16)
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
func (m *SessionManager) Get(id uint16) (*Session, bool) {
|
||||
m.RLock()
|
||||
defer m.RUnlock()
|
||||
|
||||
if m.closed {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
s, found := m.sessions[id]
|
||||
return s, found
|
||||
}
|
||||
|
||||
func (m *SessionManager) CloseIfNoSessionAndIdle(checkSize int, checkCount int) bool {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
if m.closed {
|
||||
return true
|
||||
}
|
||||
|
||||
if len(m.sessions) != 0 || checkSize != 0 || checkCount != int(m.count) {
|
||||
return false
|
||||
}
|
||||
|
||||
m.closed = true
|
||||
|
||||
m.sessions = nil
|
||||
return true
|
||||
}
|
||||
|
||||
func (m *SessionManager) Close() error {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
if m.closed {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.closed = true
|
||||
|
||||
for _, s := range m.sessions {
|
||||
s.Close(true)
|
||||
}
|
||||
|
||||
m.sessions = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// Session represents a client connection in a Mux connection.
|
||||
type Session struct {
|
||||
input buf.Reader
|
||||
output buf.Writer
|
||||
parent *SessionManager
|
||||
ID uint16
|
||||
transferType protocol.TransferType
|
||||
closed bool
|
||||
done *done.Instance
|
||||
XUDP *XUDP
|
||||
}
|
||||
|
||||
// Close closes all resources associated with this session.
|
||||
func (s *Session) Close(locked bool) error {
|
||||
if !locked {
|
||||
s.parent.Lock()
|
||||
defer s.parent.Unlock()
|
||||
}
|
||||
locked = true
|
||||
if s.closed {
|
||||
return nil
|
||||
}
|
||||
s.closed = true
|
||||
if s.done != nil {
|
||||
s.done.Close()
|
||||
}
|
||||
if s.XUDP == nil {
|
||||
common.Interrupt(s.input)
|
||||
common.Close(s.output)
|
||||
} else {
|
||||
// Stop existing handle(), then trigger writer.Close().
|
||||
// Note that s.output may be dispatcher.SizeStatWriter.
|
||||
s.input.(*pipe.Reader).ReturnAnError(io.EOF)
|
||||
runtime.Gosched()
|
||||
// If the error set by ReturnAnError still exists, clear it.
|
||||
s.input.(*pipe.Reader).Recover()
|
||||
XUDPManager.Lock()
|
||||
if s.XUDP.Status == Active {
|
||||
s.XUDP.Expire = time.Now().Add(time.Minute)
|
||||
s.XUDP.Status = Expiring
|
||||
errors.LogDebug(context.Background(), "XUDP put ", s.XUDP.GlobalID)
|
||||
}
|
||||
XUDPManager.Unlock()
|
||||
}
|
||||
s.parent.Remove(locked, s.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewReader creates a buf.Reader based on the transfer type of this Session.
|
||||
func (s *Session) NewReader(reader *buf.BufferedReader, dest *net.Destination) buf.Reader {
|
||||
if s.transferType == protocol.TransferTypeStream {
|
||||
return NewStreamReader(reader)
|
||||
}
|
||||
return NewPacketReader(reader, dest)
|
||||
}
|
||||
|
||||
const (
|
||||
Initializing = 0
|
||||
Active = 1
|
||||
Expiring = 2
|
||||
)
|
||||
|
||||
type XUDP struct {
|
||||
GlobalID [8]byte
|
||||
Status uint64
|
||||
Expire time.Time
|
||||
Mux *Session
|
||||
}
|
||||
|
||||
func (x *XUDP) Interrupt() {
|
||||
common.Interrupt(x.Mux.input)
|
||||
common.Close(x.Mux.output)
|
||||
}
|
||||
|
||||
var XUDPManager struct {
|
||||
sync.Mutex
|
||||
Map map[[8]byte]*XUDP
|
||||
}
|
||||
|
||||
func init() {
|
||||
XUDPManager.Map = make(map[[8]byte]*XUDP)
|
||||
go func() {
|
||||
for {
|
||||
time.Sleep(time.Minute)
|
||||
now := time.Now()
|
||||
XUDPManager.Lock()
|
||||
for id, x := range XUDPManager.Map {
|
||||
if x.Status == Expiring && now.After(x.Expire) {
|
||||
x.Interrupt()
|
||||
delete(XUDPManager.Map, id)
|
||||
errors.LogDebug(context.Background(), "XUDP del ", id)
|
||||
}
|
||||
}
|
||||
XUDPManager.Unlock()
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package mux_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "github.com/xtls/xray-core/common/mux"
|
||||
)
|
||||
|
||||
func TestSessionManagerAdd(t *testing.T) {
|
||||
m := NewSessionManager()
|
||||
|
||||
s := m.Allocate(&ClientStrategy{}, nil, nil)
|
||||
if s.ID != 1 {
|
||||
t.Error("id: ", s.ID)
|
||||
}
|
||||
if m.Size() != 1 {
|
||||
t.Error("size: ", m.Size())
|
||||
}
|
||||
|
||||
s = m.Allocate(&ClientStrategy{}, nil, nil)
|
||||
if s.ID != 2 {
|
||||
t.Error("id: ", s.ID)
|
||||
}
|
||||
if m.Size() != 2 {
|
||||
t.Error("size: ", m.Size())
|
||||
}
|
||||
|
||||
s = &Session{
|
||||
ID: 4,
|
||||
}
|
||||
m.Add(s)
|
||||
if s.ID != 4 {
|
||||
t.Error("id: ", s.ID)
|
||||
}
|
||||
if m.Size() != 3 {
|
||||
t.Error("size: ", m.Size())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionManagerClose(t *testing.T) {
|
||||
m := NewSessionManager()
|
||||
s := m.Allocate(&ClientStrategy{}, nil, nil)
|
||||
|
||||
if m.CloseIfNoSessionAndIdle(m.Size(), m.Count()) {
|
||||
t.Error("able to close")
|
||||
}
|
||||
m.Remove(false, s.ID)
|
||||
if !m.CloseIfNoSessionAndIdle(m.Size(), m.Count()) {
|
||||
t.Error("not able to close")
|
||||
}
|
||||
}
|
||||
@@ -1,136 +0,0 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
)
|
||||
|
||||
type Writer struct {
|
||||
dest net.Destination
|
||||
writer buf.Writer
|
||||
id uint16
|
||||
followup bool
|
||||
hasError bool
|
||||
transferType protocol.TransferType
|
||||
globalID [8]byte
|
||||
inbound *session.Inbound
|
||||
}
|
||||
|
||||
func NewWriter(id uint16, dest net.Destination, writer buf.Writer, transferType protocol.TransferType, globalID [8]byte, inbound *session.Inbound) *Writer {
|
||||
return &Writer{
|
||||
id: id,
|
||||
dest: dest,
|
||||
writer: writer,
|
||||
followup: false,
|
||||
transferType: transferType,
|
||||
globalID: globalID,
|
||||
inbound: inbound,
|
||||
}
|
||||
}
|
||||
|
||||
func NewResponseWriter(id uint16, writer buf.Writer, transferType protocol.TransferType) *Writer {
|
||||
return &Writer{
|
||||
id: id,
|
||||
writer: writer,
|
||||
followup: true,
|
||||
transferType: transferType,
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Writer) getNextFrameMeta() FrameMetadata {
|
||||
meta := FrameMetadata{
|
||||
SessionID: w.id,
|
||||
Target: w.dest,
|
||||
GlobalID: w.globalID,
|
||||
Inbound: w.inbound,
|
||||
}
|
||||
|
||||
if w.followup {
|
||||
meta.SessionStatus = SessionStatusKeep
|
||||
} else {
|
||||
w.followup = true
|
||||
meta.SessionStatus = SessionStatusNew
|
||||
}
|
||||
|
||||
return meta
|
||||
}
|
||||
|
||||
func (w *Writer) writeMetaOnly() error {
|
||||
meta := w.getNextFrameMeta()
|
||||
b := buf.New()
|
||||
if err := meta.WriteTo(b); err != nil {
|
||||
return err
|
||||
}
|
||||
return w.writer.WriteMultiBuffer(buf.MultiBuffer{b})
|
||||
}
|
||||
|
||||
func writeMetaWithFrame(writer buf.Writer, meta FrameMetadata, data buf.MultiBuffer) error {
|
||||
frame := buf.New()
|
||||
if len(data) == 1 {
|
||||
frame.UDP = data[0].UDP
|
||||
}
|
||||
if err := meta.WriteTo(frame); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := serial.WriteUint16(frame, uint16(data.Len())); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
mb2 := make(buf.MultiBuffer, 0, len(data)+1)
|
||||
mb2 = append(mb2, frame)
|
||||
mb2 = append(mb2, data...)
|
||||
return writer.WriteMultiBuffer(mb2)
|
||||
}
|
||||
|
||||
func (w *Writer) writeData(mb buf.MultiBuffer) error {
|
||||
meta := w.getNextFrameMeta()
|
||||
meta.Option.Set(OptionData)
|
||||
|
||||
return writeMetaWithFrame(w.writer, meta, mb)
|
||||
}
|
||||
|
||||
// WriteMultiBuffer implements buf.Writer.
|
||||
func (w *Writer) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
defer buf.ReleaseMulti(mb)
|
||||
|
||||
if mb.IsEmpty() {
|
||||
return w.writeMetaOnly()
|
||||
}
|
||||
|
||||
for !mb.IsEmpty() {
|
||||
var chunk buf.MultiBuffer
|
||||
if w.transferType == protocol.TransferTypeStream {
|
||||
mb, chunk = buf.SplitSize(mb, 8*1024)
|
||||
} else {
|
||||
mb2, b := buf.SplitFirst(mb)
|
||||
mb = mb2
|
||||
chunk = buf.MultiBuffer{b}
|
||||
}
|
||||
if err := w.writeData(chunk); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close implements common.Closable.
|
||||
func (w *Writer) Close() error {
|
||||
meta := FrameMetadata{
|
||||
SessionID: w.id,
|
||||
SessionStatus: SessionStatusEnd,
|
||||
}
|
||||
if w.hasError {
|
||||
meta.Option.Set(OptionError)
|
||||
}
|
||||
|
||||
frame := buf.New()
|
||||
common.Must(meta.WriteTo(frame))
|
||||
|
||||
w.writer.WriteMultiBuffer(buf.MultiBuffer{frame})
|
||||
return nil
|
||||
}
|
||||
@@ -128,6 +128,7 @@ func (w *UDPWriter) WriteMessage(b *buf.Buffer) error {
|
||||
|
||||
type TCPWriter struct {
|
||||
buf.Writer
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
func (w *TCPWriter) WriteMessage(b *buf.Buffer) error {
|
||||
@@ -140,5 +141,7 @@ func (w *TCPWriter) WriteMessage(b *buf.Buffer) error {
|
||||
size := buf.New()
|
||||
binary.BigEndian.PutUint16(size.Extend(2), uint16(b.Len()))
|
||||
mb = append(mb, size, b)
|
||||
w.Lock()
|
||||
defer w.Unlock()
|
||||
return w.WriteMultiBuffer(mb)
|
||||
}
|
||||
|
||||
@@ -77,6 +77,11 @@ func ContentFromContext(ctx context.Context) *Content {
|
||||
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 {
|
||||
return context.WithValue(ctx, isReverseMuxKey, isReverseMux)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package core
|
||||
|
||||
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/io.go -mock_names Reader=Reader,Writer=Writer io Reader,Writer
|
||||
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/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/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
|
||||
|
||||
@@ -23,12 +23,12 @@ require (
|
||||
github.com/xtls/reality v0.0.0-20261108101329-4bb46b2afd8b
|
||||
github.com/yuin/gopher-lua v1.1.2
|
||||
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba
|
||||
golang.org/x/crypto v0.58.0
|
||||
golang.org/x/crypto v0.59.0
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20261020153306-9f2b28d4331a
|
||||
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842
|
||||
golang.org/x/net v0.62.0
|
||||
golang.org/x/sync v0.24.0
|
||||
golang.org/x/sys v0.49.0
|
||||
golang.org/x/net v0.63.0
|
||||
golang.org/x/sync v0.25.0
|
||||
golang.org/x/sys v0.50.0
|
||||
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2
|
||||
golang.zx2c4.com/wireguard v0.0.0-20250521234502-f333402bd9cb
|
||||
golang.zx2c4.com/wireguard/windows v1.1.1
|
||||
@@ -36,7 +36,7 @@ require (
|
||||
google.golang.org/protobuf v1.36.12
|
||||
h12.io/socks v1.0.3
|
||||
layeh.com/gopher-luar v1.0.11
|
||||
lukechampine.com/blake3 v1.4.1
|
||||
lukechampine.com/blake3 v1.5.1
|
||||
mvdan.cc/gofumpt v0.12.0
|
||||
)
|
||||
|
||||
@@ -56,8 +56,8 @@ require (
|
||||
github.com/vishvananda/netns v0.0.5 // indirect
|
||||
github.com/wlynxg/anet v0.0.5 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
golang.org/x/text v0.43.0 // indirect
|
||||
golang.org/x/tools v0.51.0 // indirect
|
||||
golang.org/x/text v0.44.0 // indirect
|
||||
golang.org/x/tools v0.52.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260817212433-ac3dfec99bb1 // indirect
|
||||
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.6.2 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
|
||||
@@ -31,8 +31,6 @@ github.com/jackpal/go-nat-pmp v1.0.2 h1:KzKSgb7qkJvOUTqYl9/Hg/me3pWgBmERKrTGD7Bd
|
||||
github.com/jackpal/go-nat-pmp v1.0.2/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc=
|
||||
github.com/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/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/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/klauspost/cpuid/v2 v2.4.2 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ=
|
||||
@@ -97,8 +95,8 @@ go4.org/netipx v0.0.0-20231129151722-fdeea329fbba h1:0b9z3AuHCjxk0x/opv64kcgZLBs
|
||||
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y=
|
||||
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.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
|
||||
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20261020153306-9f2b28d4331a h1:V5oicZXS0oqZx30gY/apgSVD7YvNBfrIOdcMnlelJY4=
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20261020153306-9f2b28d4331a/go.mod h1:HPze8vhfG6fO06AM+VSvxRm4E3+5Yk375mgrJ5M2z1E=
|
||||
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 h1:vr/HnozRka3pE4EsMEg1lgkXJkTFJCVUX+S/ZT6wYzM=
|
||||
@@ -109,12 +107,12 @@ golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-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.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
|
||||
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
|
||||
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
|
||||
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
||||
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
@@ -123,22 +121,22 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w
|
||||
golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
|
||||
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/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.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
|
||||
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
|
||||
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
|
||||
golang.org/x/time v0.14.0/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-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.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU=
|
||||
golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI=
|
||||
golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA=
|
||||
golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
|
||||
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
@@ -170,7 +168,7 @@ h12.io/socks v1.0.3 h1:Ka3qaQewws4j4/eDQnOdpr4wXsC//dXtWvftlIcCQUo=
|
||||
h12.io/socks v1.0.3/go.mod h1:AIhxy1jOId/XCz9BO+EIgNL2rQiPTBNnOfnVnQ+3Eck=
|
||||
layeh.com/gopher-luar v1.0.11 h1:8zJudpKI6HWkoh9eyyNFaTM79PY6CAPcIr6X/KTiliw=
|
||||
layeh.com/gopher-luar v1.0.11/go.mod h1:TPnIVCZ2RJBndm7ohXyaqfhzjlZ+OA2SZR/YwL8tECk=
|
||||
lukechampine.com/blake3 v1.4.1 h1:I3Smz7gso8w4/TunLKec6K2fn+kyKtDxr/xcQEN84Wg=
|
||||
lukechampine.com/blake3 v1.4.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo=
|
||||
lukechampine.com/blake3 v1.5.1 h1:ITRyxe0LlLZcPUWOZ3Taz8mbug/ptn7jbbeeij5ZiPo=
|
||||
lukechampine.com/blake3 v1.5.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo=
|
||||
mvdan.cc/gofumpt v0.12.0 h1:1Lbudkz2kpM9Cjz2pL4M19u7q+GaEhCTNf7N9mfpcho=
|
||||
mvdan.cc/gofumpt v0.12.0/go.mod h1:SmBHHrljiZu/uoypeKup3rFzP6eoC9UwCp2iH5E3jZA=
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"github.com/xtls/xray-core/app/reverse"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
type BridgeConfig struct {
|
||||
Tag string `json:"tag"`
|
||||
Domain string `json:"domain"`
|
||||
}
|
||||
|
||||
func (c *BridgeConfig) Build() (*reverse.BridgeConfig, error) {
|
||||
return &reverse.BridgeConfig{
|
||||
Tag: c.Tag,
|
||||
Domain: c.Domain,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type PortalConfig struct {
|
||||
Tag string `json:"tag"`
|
||||
Domain string `json:"domain"`
|
||||
}
|
||||
|
||||
func (c *PortalConfig) Build() (*reverse.PortalConfig, error) {
|
||||
return &reverse.PortalConfig{
|
||||
Tag: c.Tag,
|
||||
Domain: c.Domain,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type ReverseConfig struct {
|
||||
Bridges []BridgeConfig `json:"bridges"`
|
||||
Portals []PortalConfig `json:"portals"`
|
||||
}
|
||||
|
||||
func (c *ReverseConfig) Build() (proto.Message, error) {
|
||||
config := &reverse.Config{}
|
||||
for _, bconfig := range c.Bridges {
|
||||
b, err := bconfig.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config.BridgeConfig = append(config.BridgeConfig, b)
|
||||
}
|
||||
|
||||
for _, pconfig := range c.Portals {
|
||||
p, err := pconfig.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config.PortalConfig = append(config.PortalConfig, p)
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package conf_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/app/reverse"
|
||||
"github.com/xtls/xray-core/infra/conf"
|
||||
)
|
||||
|
||||
func TestReverseConfig(t *testing.T) {
|
||||
creator := func() conf.Buildable {
|
||||
return new(conf.ReverseConfig)
|
||||
}
|
||||
|
||||
runMultiTestCase(t, []TestCase{
|
||||
{
|
||||
Input: `{
|
||||
"bridges": [{
|
||||
"tag": "test",
|
||||
"domain": "test.example.com"
|
||||
}]
|
||||
}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &reverse.Config{
|
||||
BridgeConfig: []*reverse.BridgeConfig{
|
||||
{Tag: "test", Domain: "test.example.com"},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Input: `{
|
||||
"portals": [{
|
||||
"tag": "test",
|
||||
"domain": "test.example.com"
|
||||
}]
|
||||
}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &reverse.Config{
|
||||
PortalConfig: []*reverse.PortalConfig{
|
||||
{Tag: "test", Domain: "test.example.com"},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package conf
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
@@ -865,6 +867,7 @@ type XDNSDomain struct {
|
||||
LabelLimit int32 `json:"labelLimit"`
|
||||
Types []int32 `json:"types"`
|
||||
Edns0 int32 `json:"edns0"`
|
||||
Alphabet string `json:"alphabet"`
|
||||
}
|
||||
|
||||
type XDNSResolver struct {
|
||||
@@ -891,7 +894,7 @@ func (c *XDNS) Build() (proto.Message, error) {
|
||||
c.Domains[i].LabelLimit = 63
|
||||
}
|
||||
for j := range c.Domains[i].Names {
|
||||
domain, err := xdns.NewDomain(c.Domains[i].Names[j], int(c.Domains[i].LenLimit), int(c.Domains[i].LabelLimit), []uint16{1, 5, 16, 28}, uint16(c.Domains[i].Edns0))
|
||||
domain, err := xdns.NewDomain(c.Domains[i].Names[j], int(c.Domains[i].LenLimit), int(c.Domains[i].LabelLimit), []uint16{1, 5, 16, 28}, uint16(c.Domains[i].Edns0), c.Domains[i].Alphabet)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -902,6 +905,7 @@ func (c *XDNS) Build() (proto.Message, error) {
|
||||
LabelLimit: c.Domains[i].LabelLimit,
|
||||
Types: c.Domains[i].Types,
|
||||
Edns0: c.Domains[i].Edns0,
|
||||
Alphabet: c.Domains[i].Alphabet,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -961,10 +965,11 @@ func (c *XDNS) Build() (proto.Message, error) {
|
||||
}
|
||||
|
||||
type XMC struct {
|
||||
Hostname string `json:"hostname"`
|
||||
Profiles []XMCProfile `json:"profiles"`
|
||||
Password string `json:"password"`
|
||||
Paddings []XMCPaddingTurn `json:"paddings,omitempty"`
|
||||
Hostname string `json:"hostname"`
|
||||
Profiles []XMCProfile `json:"profiles"`
|
||||
Password string `json:"password"`
|
||||
Paddings []XMCPaddingTurn `json:"paddings,omitempty"`
|
||||
Yggdrasil *XMCYggdrasil `json:"yggdrasil,omitempty"`
|
||||
// A configured list is the complete padding schedule and replaces the
|
||||
// built-in preset entirely, including the preset's Play-state join tail.
|
||||
// NoPadding disables padding. An explicit empty "paddings" array means the
|
||||
@@ -982,6 +987,19 @@ type XMCPaddingTurn struct {
|
||||
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 {
|
||||
// Resolve the UUID by username, then request the session profile with
|
||||
// unsigned=false. Client and server must use the same signed profile.
|
||||
@@ -1015,16 +1033,6 @@ func (c *XMCProfile) Build() (*xmc.Profile, error) {
|
||||
}
|
||||
|
||||
func (c *XMC) Build() (proto.Message, error) {
|
||||
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
|
||||
// Paddings nil when it is absent, so the user can turn padding off without
|
||||
// a second switch.
|
||||
@@ -1032,7 +1040,7 @@ func (c *XMC) Build() (proto.Message, error) {
|
||||
if noPadding && len(c.Paddings) > 0 {
|
||||
return nil, fmt.Errorf("minecraft padding: noPadding and paddings are exclusive")
|
||||
}
|
||||
config := &xmc.Config{Password: c.Password, Hostname: c.Hostname, NoPadding: noPadding}
|
||||
config := &xmc.Config{Hostname: c.Hostname, NoPadding: noPadding}
|
||||
for i, turn := range c.Paddings {
|
||||
minimum, maximum, err := ParseRangeString(turn.Length)
|
||||
if err != nil {
|
||||
@@ -1065,9 +1073,75 @@ func (c *XMC) Build() (proto.Message, error) {
|
||||
return nil, fmt.Errorf("minecraft padding: %w", err)
|
||||
}
|
||||
|
||||
rsaPrivateKey, err := xmc.DeriveRSAKey(c.Password)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("derive minecraft rsa key: %w", err)
|
||||
var yggdrasil *xmc.Yggdrasil
|
||||
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 {
|
||||
return nil, fmt.Errorf("derive minecraft rsa key: %w", err)
|
||||
}
|
||||
rsaPrivateKey = derived
|
||||
password = c.Password
|
||||
}
|
||||
|
||||
rsaPublicKey, err := x509.MarshalPKIXPublicKey(&rsaPrivateKey.PublicKey)
|
||||
@@ -1084,9 +1158,11 @@ func (c *XMC) Build() (proto.Message, error) {
|
||||
profiles = append(profiles, profile)
|
||||
}
|
||||
|
||||
config.Password = password
|
||||
config.RsaPrivateKey = x509.MarshalPKCS1PrivateKey(rsaPrivateKey)
|
||||
config.RsaPublicKey = rsaPublicKey
|
||||
config.Profiles = profiles
|
||||
config.Yggdrasil = yggdrasil
|
||||
return config, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -113,6 +114,96 @@ func TestXMCBuildRejectsLongPassword(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMCBuildYggdrasil(t *testing.T) {
|
||||
built, err := (&XMC{
|
||||
Password: "test-password",
|
||||
Yggdrasil: &XMCYggdrasil{
|
||||
API: "https://skin.example.com/api/yggdrasil/",
|
||||
Username: "user@example.com",
|
||||
Password: "login-password",
|
||||
Player: "TestUser",
|
||||
},
|
||||
}).Build()
|
||||
if err != nil {
|
||||
t.Fatalf("build XMC config: %v", err)
|
||||
}
|
||||
|
||||
config := built.(*xmc.Config)
|
||||
if config.Yggdrasil == nil {
|
||||
t.Fatal("yggdrasil config is missing")
|
||||
}
|
||||
if config.Yggdrasil.Api != "https://skin.example.com/api/yggdrasil" {
|
||||
t.Fatalf("yggdrasil api = %q", config.Yggdrasil.Api)
|
||||
}
|
||||
if config.Yggdrasil.Username != "user@example.com" || config.Yggdrasil.Password != "login-password" || config.Yggdrasil.Player != "TestUser" {
|
||||
t.Fatalf("unexpected yggdrasil config: %+v", config.Yggdrasil)
|
||||
}
|
||||
if config.Password != "" {
|
||||
t.Fatalf("password must not be used in yggdrasil mode: %q", config.Password)
|
||||
}
|
||||
if len(config.RsaPrivateKey) == 0 || len(config.RsaPublicKey) == 0 {
|
||||
t.Fatal("yggdrasil mode must build a random rsa key pair")
|
||||
}
|
||||
privateKey, err := x509.ParsePKCS1PrivateKey(config.RsaPrivateKey)
|
||||
if err != nil {
|
||||
t.Fatalf("parse generated rsa private key: %v", err)
|
||||
}
|
||||
publicKey, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal generated rsa public key: %v", err)
|
||||
}
|
||||
if string(publicKey) != string(config.RsaPublicKey) {
|
||||
t.Fatal("generated rsa key pair does not match")
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMCBuildYggdrasilServerWithoutCredentials(t *testing.T) {
|
||||
built, err := (&XMC{
|
||||
Yggdrasil: &XMCYggdrasil{
|
||||
API: "https://skin.example.com/api/yggdrasil",
|
||||
},
|
||||
}).Build()
|
||||
if err != nil {
|
||||
t.Fatalf("build server-side XMC config: %v", err)
|
||||
}
|
||||
if built.(*xmc.Config).Yggdrasil == nil {
|
||||
t.Fatal("yggdrasil config is missing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMCBuildRejectsInvalidYggdrasil(t *testing.T) {
|
||||
cases := []*XMCYggdrasil{
|
||||
{API: ""},
|
||||
{API: "ftp://skin.example.com/api/yggdrasil"},
|
||||
{API: "https://skin.example.com/api/yggdrasil?foo=bar"},
|
||||
{API: "https://skin.example.com/api/yggdrasil", Username: "user@example.com"},
|
||||
{API: "https://skin.example.com/api/yggdrasil", Password: "login-password"},
|
||||
{API: "https://skin.example.com/api/yggdrasil", Player: "bad name"},
|
||||
}
|
||||
for i, yggdrasil := range cases {
|
||||
_, err := (&XMC{Yggdrasil: yggdrasil}).Build()
|
||||
if err == nil {
|
||||
t.Fatalf("case %d was accepted: %+v", i, yggdrasil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMCBuildRequiresPasswordInLegacyMode(t *testing.T) {
|
||||
_, err := (&XMC{
|
||||
Profiles: []XMCProfile{
|
||||
{
|
||||
Username: "TestUser",
|
||||
UUID: "00112233-4455-6677-8899-aabbccddeeff",
|
||||
TexturesValue: "textures-value",
|
||||
TexturesSignature: "textures-signature",
|
||||
},
|
||||
},
|
||||
}).Build()
|
||||
if err == nil || !strings.Contains(err.Error(), "empty password") {
|
||||
t.Fatalf("expected empty password error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMCBuildDisablesPadding(t *testing.T) {
|
||||
profile := XMCProfile{
|
||||
Username: "TestUser", UUID: "00112233-4455-6677-8899-aabbccddeeff",
|
||||
|
||||
@@ -529,26 +529,25 @@ func TestXDriveOutboundConfig(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, input := range []string{
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`,
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": 0, "xudpConcurrency": 8, "xudpProxyUDP443": "allow"}}`,
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8, "xudpConcurrency": 8, "xudpProxyUDP443": "allow"}}, ` + xdriveStream + `}`,
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "reverse": {"tag": "r"}}, ` + xdriveStream + `}`,
|
||||
`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `}]}]}, ` + xdriveStream + `, "mux": {"enabled": true}}`,
|
||||
`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `}]}], "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
|
||||
} {
|
||||
if err := build(input); err != nil {
|
||||
t.Errorf("%s: %v", input, err)
|
||||
}
|
||||
}
|
||||
for _, c := range []struct{ input, err string }{
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, "encryption": "none"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"encryption"`},
|
||||
{`{"protocol": "vless", "settings": {"address": "example.com", "port": 443, ` + xdriveID + `, "encryption": "none"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"encryption"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `}`, `"mux"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": false}}`, `"mux"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": -1}}`, `"mux"`},
|
||||
{`{"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": "vless", "settings": {` + xdriveServer + `, "encryption": "none", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"encryption"`},
|
||||
{`{"protocol": "vless", "settings": {"address": "example.com", "port": 443, ` + xdriveID + `, "encryption": "none", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"encryption"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `}`, `"settings.multiplex.concurrency"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"settings.multiplex.concurrency"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"xudpConcurrency": 8}}, ` + xdriveStream + `}`, `"settings.multiplex.concurrency"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8, "xudpProxyUDP443": "skip"}}, ` + xdriveStream + `}`, `"settings.multiplex.concurrency"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
|
||||
{`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision"}]}], "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "testpre": 1, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"testpre"`},
|
||||
{`{"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": "freedom", ` + xdriveStream + `}`, "VLESS"},
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/proxy/tun"
|
||||
@@ -16,6 +17,7 @@ import (
|
||||
type TunConfig struct {
|
||||
Name string `json:"name"`
|
||||
Desc string `json:"desc"`
|
||||
GUID string `json:"guid"`
|
||||
MTU uint32 `json:"mtu"`
|
||||
Gateway []string `json:"gateway"`
|
||||
DNS []string `json:"dns"`
|
||||
@@ -37,6 +39,13 @@ func (v *TunConfig) Build() (proto.Message, error) {
|
||||
AutoSystemRoutingTable: v.AutoSystemRoutingTable,
|
||||
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)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -124,3 +124,49 @@ func TestTunConfigAutoSystemWfpBlockLeakUnknown(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestTunConfigGUID checks that a guid is read, written back in the canonical
|
||||
// form, and rejected unless it is one, on every system, even though only
|
||||
// Windows gives the TUN a GUID.
|
||||
func TestTunConfigGUID(t *testing.T) {
|
||||
build := func(guid string) (*tun.Config, error) {
|
||||
config := new(TunConfig)
|
||||
if err := json.Unmarshal([]byte(`{"name": "xray0", "guid": "`+guid+`"}`), config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
message, err := config.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return message.(*tun.Config), nil
|
||||
}
|
||||
|
||||
if config, err := build("6ba7b810-9dad-11d1-80b4-00c04fd430c8"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if config.GUID != "6ba7b810-9dad-11d1-80b4-00c04fd430c8" {
|
||||
t.Errorf("guid = %q, want it kept", config.GUID)
|
||||
}
|
||||
if config, err := build("6BA7B810-9DAD-11D1-80B4-00C04FD430C8"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if config.GUID != "6ba7b810-9dad-11d1-80b4-00c04fd430c8" {
|
||||
t.Errorf("guid = %q, want it lowercased", config.GUID)
|
||||
}
|
||||
if config, err := build(""); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if config.GUID != "" {
|
||||
t.Errorf("guid = %q, want it empty, as the adapter GUID is derived from the name then", config.GUID)
|
||||
}
|
||||
for _, guid := range []string{
|
||||
"xray0",
|
||||
"6ba7b810-9dad-11d1-80b4-00c04fd430c",
|
||||
"6ba7b8109-dad-11d1-80b4-00c04fd430c8", // the right length, a hyphen out of place
|
||||
"6ba7b8109dad11d180b400c04fd430c8",
|
||||
"{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
|
||||
"urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8",
|
||||
"6ba7b810-9dad-11d1-80b4-00c04fd430cg",
|
||||
} {
|
||||
if _, err := build(guid); err == nil {
|
||||
t.Errorf("guid %q was accepted", guid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+27
-1
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/xtls/xray-core/common/uuid"
|
||||
"github.com/xtls/xray-core/proxy/vless"
|
||||
"github.com/xtls/xray-core/proxy/vless/inbound"
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
"github.com/xtls/xray-core/proxy/vless/outbound"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
@@ -236,6 +237,25 @@ func (c *VLessReverseConfig) Build() (*vless.Reverse, error) {
|
||||
return r, nil
|
||||
}
|
||||
|
||||
type MultiplexConfig struct {
|
||||
Concurrency int16 `json:"concurrency"`
|
||||
XudpConcurrency int16 `json:"xudpConcurrency"`
|
||||
XudpProxyUDP443 string `json:"xudpProxyUDP443"`
|
||||
}
|
||||
|
||||
func (c *MultiplexConfig) Build() (*vless.Multiplex, error) {
|
||||
if c == nil {
|
||||
return nil, nil
|
||||
}
|
||||
udp443 := c.XudpProxyUDP443
|
||||
if udp443 == "" {
|
||||
udp443 = "reject"
|
||||
}
|
||||
return multiplex.NormalizeConfig(&vless.Multiplex{
|
||||
Concurrency: int32(c.Concurrency), XudpConcurrency: int32(c.XudpConcurrency), XudpProxyUDP443: udp443,
|
||||
})
|
||||
}
|
||||
|
||||
type VLessOutboundVnext struct {
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
@@ -251,6 +271,7 @@ type VLessOutboundConfig struct {
|
||||
Flow string `json:"flow"`
|
||||
Seed string `json:"seed"`
|
||||
Encryption string `json:"encryption"`
|
||||
Multiplex *MultiplexConfig `json:"multiplex"`
|
||||
Reverse *VLessReverseConfig `json:"reverse"`
|
||||
Testpre uint32 `json:"testpre"`
|
||||
Testseed []uint32 `json:"testseed"`
|
||||
@@ -259,7 +280,12 @@ type VLessOutboundConfig struct {
|
||||
|
||||
// Build implements Buildable
|
||||
func (c *VLessOutboundConfig) Build() (proto.Message, error) {
|
||||
config := new(outbound.Config)
|
||||
multiplex, err := c.Multiplex.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config := &outbound.Config{Multiplex: multiplex}
|
||||
|
||||
if c.Address != nil {
|
||||
c.Vnext = []*VLessOutboundVnext{
|
||||
{
|
||||
|
||||
+6
-1
@@ -117,13 +117,18 @@ type VMessOutboundConfig struct {
|
||||
Security string `json:"security"`
|
||||
Experiments string `json:"experiments"`
|
||||
Receivers []*VMessOutboundTarget `json:"vnext"`
|
||||
Multiplex *MultiplexConfig `json:"multiplex"`
|
||||
}
|
||||
|
||||
// Build implements Buildable
|
||||
func (c *VMessOutboundConfig) Build() (proto.Message, error) {
|
||||
errors.PrintNonRemovalDeprecatedFeatureWarning("VMess (with no Forward Secrecy, etc.)", "VLESS Encryption")
|
||||
|
||||
config := new(outbound.Config)
|
||||
multiplex, err := c.Multiplex.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config := &outbound.Config{Multiplex: multiplex}
|
||||
if c.Address != nil {
|
||||
c.Receivers = []*VMessOutboundTarget{
|
||||
{
|
||||
|
||||
+13
-46
@@ -107,30 +107,6 @@ func (c *SniffingConfig) Build() (*proxyman.SniffingConfig, error) {
|
||||
}, 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 {
|
||||
Protocol string `json:"protocol"`
|
||||
PortList *PortList `json:"port"`
|
||||
@@ -213,7 +189,7 @@ func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
|
||||
if _, ok := ts.(*masque.ServerConfig); !ok && receiverSettings.StreamSettings != nil && receiverSettings.StreamSettings.ProtocolName == "masque" {
|
||||
return nil, errors.New("the masque transport can only be used by the masque inbound")
|
||||
}
|
||||
if err := validateXDrive(ts, receiverSettings.StreamSettings, nil, receiverSettings.PortList); err != nil {
|
||||
if err := validateXDrive(ts, receiverSettings.StreamSettings, receiverSettings.PortList); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -231,7 +207,7 @@ type OutboundDetourConfig struct {
|
||||
Settings *json.RawMessage `json:"settings"`
|
||||
StreamSetting *StreamConfig `json:"streamSettings"`
|
||||
ProxySettings *json.RawMessage `json:"proxySettings"`
|
||||
MuxSettings *MuxConfig `json:"mux"`
|
||||
LegacyMux json.RawMessage `json:"mux,omitempty"`
|
||||
TargetStrategy string `json:"targetStrategy"`
|
||||
}
|
||||
|
||||
@@ -270,8 +246,8 @@ func validateOutboundTransportSecurity(rawConfig interface{}, senderSettings *pr
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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, ms *proxyman.MultiplexingConfig, pl *net.PortList) error {
|
||||
// validateXDrive allows only encrypted VLESS on xdrive, with native multiplex on every client connection.
|
||||
func validateXDrive(ts proto.Message, ss *internet.StreamConfig, pl *net.PortList) error {
|
||||
if ss == nil || ss.ProtocolName != "xdrive" {
|
||||
return nil
|
||||
}
|
||||
@@ -288,9 +264,9 @@ func validateXDrive(ts proto.Message, ss *internet.StreamConfig, ms *proxyman.Mu
|
||||
if account.Encryption == "none" {
|
||||
return errors.New(`the xdrive transport needs VLESS "encryption", run "xray vlessenc" to get one`)
|
||||
}
|
||||
// reverse opens its own mux
|
||||
if account.Reverse == nil && (ms == nil || !ms.Enabled || ms.Concurrency < 0 || ms.XudpConcurrency < 0 || ms.XudpProxyUDP443 == "skip") {
|
||||
return errors.New(`the xdrive transport needs "mux" enabled, with no negative "concurrency" or "xudpConcurrency" and no "xudpProxyUDP443":"skip"`)
|
||||
// Reverse opens its own multiplexed connection.
|
||||
if account.Reverse == nil && (c.Multiplex.GetConcurrency() == 0 || c.Multiplex.GetXudpProxyUDP443() == "skip") {
|
||||
return errors.New(`the xdrive transport needs positive "settings.multiplex.concurrency" and does not support "xudpProxyUDP443":"skip"`)
|
||||
}
|
||||
if account.Testpre != 0 {
|
||||
return errors.New(`the xdrive transport doesn't support VLESS "testpre"`)
|
||||
@@ -376,14 +352,6 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
|
||||
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("{}")
|
||||
if c.Settings != nil {
|
||||
settings = ([]byte)(*c.Settings)
|
||||
@@ -392,13 +360,17 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
|
||||
if err != nil {
|
||||
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()
|
||||
if err != nil {
|
||||
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 err := validateXDrive(ts, senderSettings.StreamSettings, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := validateOutboundTransportSecurity(rawConfig, senderSettings); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -478,7 +450,7 @@ type Config struct {
|
||||
API *APIConfig `json:"api"`
|
||||
Metrics *MetricsConfig `json:"metrics"`
|
||||
Stats *StatsConfig `json:"stats"`
|
||||
Reverse *ReverseConfig `json:"reverse"`
|
||||
Reverse *json.RawMessage `json:"reverse"`
|
||||
FakeDNS *FakeDNSConfig `json:"fakeDns"`
|
||||
Observatory *ObservatoryConfig `json:"observatory"`
|
||||
BurstObservatory *BurstObservatoryConfig `json:"burstObservatory"`
|
||||
@@ -680,11 +652,6 @@ func (c *Config) Build() (*core.Config, error) {
|
||||
|
||||
if c.Reverse != nil {
|
||||
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 {
|
||||
|
||||
+101
-37
@@ -1,6 +1,7 @@
|
||||
package conf_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
@@ -10,7 +11,6 @@ import (
|
||||
"github.com/xtls/xray-core/app/log"
|
||||
"github.com/xtls/xray-core/app/proxyman"
|
||||
"github.com/xtls/xray-core/app/router"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
clog "github.com/xtls/xray-core/common/log"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
core "github.com/xtls/xray-core/core"
|
||||
. "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/inbound"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
@@ -225,49 +226,112 @@ func TestSniffingConfig_Build(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMuxConfig_Build(t *testing.T) {
|
||||
tests := []struct {
|
||||
func TestMultiplexConfig_Build(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
fields string
|
||||
want *proxyman.MultiplexingConfig
|
||||
want *vless.Multiplex
|
||||
bad bool
|
||||
}{
|
||||
{"default", `{"enabled": true, "concurrency": 16}`, &proxyman.MultiplexingConfig{
|
||||
Enabled: true,
|
||||
Concurrency: 16,
|
||||
XudpConcurrency: 0,
|
||||
XudpProxyUDP443: "reject",
|
||||
}},
|
||||
{"empty def", `{}`, &proxyman.MultiplexingConfig{
|
||||
Enabled: false,
|
||||
Concurrency: 0,
|
||||
XudpConcurrency: 0,
|
||||
XudpProxyUDP443: "reject",
|
||||
}},
|
||||
{"not enable", `{"enabled": false, "concurrency": 4}`, &proxyman.MultiplexingConfig{
|
||||
Enabled: false,
|
||||
Concurrency: 4,
|
||||
XudpConcurrency: 0,
|
||||
XudpProxyUDP443: "reject",
|
||||
}},
|
||||
{"forbidden", `{"enabled": false, "concurrency": -1}`, &proxyman.MultiplexingConfig{
|
||||
Enabled: false,
|
||||
Concurrency: -1,
|
||||
XudpConcurrency: 0,
|
||||
XudpProxyUDP443: "reject",
|
||||
}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
m := &MuxConfig{}
|
||||
common.Must(json.Unmarshal([]byte(tt.fields), m))
|
||||
if got, _ := m.Build(); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("MuxConfig.Build() = %v, want %v", got, tt.want)
|
||||
{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 {
|
||||
name string
|
||||
legacy string
|
||||
native string
|
||||
want *vless.Multiplex
|
||||
}{
|
||||
{name: "absent"},
|
||||
{name: "legacy enabled", legacy: `{"enabled":true,"concurrency":16}`},
|
||||
{name: "legacy disabled", legacy: `{"enabled":false}`},
|
||||
{name: "legacy null", legacy: `null`},
|
||||
{name: "legacy empty", legacy: `{}`},
|
||||
{name: "legacy values are not decoded", legacy: `{"enabled":"ignored","concurrency":"ignored"}`},
|
||||
{name: "empty native object", native: `{}`},
|
||||
{name: "enabled flag alone does not create a pool", native: `{"enabled":true}`},
|
||||
{
|
||||
name: "positive concurrency with old enabled flag", native: `{"concurrency":4,"enabled":false}`,
|
||||
want: &vless.Multiplex{Concurrency: 4, XudpProxyUDP443: "reject"},
|
||||
},
|
||||
{
|
||||
name: "native XUDP only", native: `{"xudpConcurrency":8}`,
|
||||
want: &vless.Multiplex{XudpConcurrency: 8, XudpProxyUDP443: "reject"},
|
||||
},
|
||||
{
|
||||
name: "native options override legacy", legacy: `{"enabled":true,"concurrency":16}`,
|
||||
native: `{"concurrency":4,"xudpConcurrency":8,"xudpProxyUDP443":"allow"}`,
|
||||
want: &vless.Multiplex{Concurrency: 4, XudpConcurrency: 8, XudpProxyUDP443: "allow"},
|
||||
},
|
||||
{name: "empty native with legacy enabled", legacy: `{"enabled":true}`, native: `{}`},
|
||||
}
|
||||
for _, protoName := range []string{"vless", "vmess"} {
|
||||
for _, tc := range tests {
|
||||
t.Run(protoName+"/"+tc.name, func(t *testing.T) {
|
||||
settings := `"address":"127.0.0.1","port":443,"id":"d19768cb-2891-4c3c-b45d-863f8fd64b6d"`
|
||||
if protoName == "vless" {
|
||||
settings += `,"encryption":"none"`
|
||||
}
|
||||
if tc.native != "" {
|
||||
settings += `,"multiplex":` + tc.native
|
||||
}
|
||||
input := `{"protocol":"` + protoName + `","settings":{` + settings + `}`
|
||||
if tc.legacy != "" {
|
||||
input += `,"mux":` + tc.legacy
|
||||
}
|
||||
|
||||
var config OutboundDetourConfig
|
||||
if err := json.Unmarshal([]byte(input+"}"), &config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := string(config.LegacyMux); got != tc.legacy {
|
||||
t.Errorf("legacy mux marker = %q, want %q", got, tc.legacy)
|
||||
}
|
||||
serialized, err := json.Marshal(config)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if hasMux := bytes.Contains(serialized, []byte(`"mux":`)); hasMux != (tc.legacy != "") {
|
||||
t.Errorf("serialized config changed legacy mux presence: %s", serialized)
|
||||
}
|
||||
built, err := config.Build()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
proxyConfig, err := built.ProxySettings.GetInstance()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := proxyConfig.(interface{ GetMultiplex() *vless.Multiplex }).GetMultiplex()
|
||||
if !proto.Equal(got, tc.want) {
|
||||
t.Errorf("multiplex = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfig_Override(t *testing.T) {
|
||||
legacyReverse := json.RawMessage(`{}`)
|
||||
tests := []struct {
|
||||
name string
|
||||
orig *Config
|
||||
@@ -285,7 +349,7 @@ func TestConfig_Override(t *testing.T) {
|
||||
Policy: &PolicyConfig{},
|
||||
API: &APIConfig{},
|
||||
Stats: &StatsConfig{},
|
||||
Reverse: &ReverseConfig{},
|
||||
Reverse: &legacyReverse,
|
||||
},
|
||||
"",
|
||||
&Config{
|
||||
@@ -295,7 +359,7 @@ func TestConfig_Override(t *testing.T) {
|
||||
Policy: &PolicyConfig{},
|
||||
API: &APIConfig{},
|
||||
Stats: &StatsConfig{},
|
||||
Reverse: &ReverseConfig{},
|
||||
Reverse: &legacyReverse,
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -24,7 +24,6 @@ import (
|
||||
_ "github.com/xtls/xray-core/app/log"
|
||||
_ "github.com/xtls/xray-core/app/metrics"
|
||||
_ "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/stats"
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math/rand/v2"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/signal"
|
||||
)
|
||||
|
||||
// wait to drain all the possible incoming UDP data
|
||||
// because re-established QUIC UDP may bypass the sniffer
|
||||
func DropUDP(ctx context.Context, reader buf.Reader) {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
timer := signal.CancelAfterInactivity(ctx, func() {
|
||||
cancel()
|
||||
}, time.Duration(30+rand.N(60))*time.Second)
|
||||
context.AfterFunc(ctx, func() {
|
||||
common.Interrupt(reader)
|
||||
})
|
||||
buf.Copy(reader, buf.Discard, buf.UpdateActivity(timer))
|
||||
}
|
||||
@@ -318,6 +318,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
}
|
||||
ob.Name = "freedom"
|
||||
ob.CanSpliceCopy = 1
|
||||
|
||||
if !h.usesDialerProxy && len(h.firewall) > 0 {
|
||||
rule := h.firewall[0]
|
||||
if rule.action == RuleAction_Block && rule.network == allNetworks && len(rule.port) == 0 && rule.ip == nil {
|
||||
@@ -350,6 +351,10 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
}
|
||||
}
|
||||
|
||||
if h.resolveStrategy.HasStrategy() && session.SkipDNSResolveFromContext(ctx) {
|
||||
errors.LogInfo(ctx, "DNS-origin connection to ", destination, " may recursively resolve with sockopt.domainStrategy ", h.resolveStrategy)
|
||||
}
|
||||
|
||||
input := link.Reader
|
||||
output := link.Writer
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ func (l *Loopback) Process(ctx context.Context, link *transport.Link, _ internet
|
||||
|
||||
errors.LogInfo(ctx, "opening connection to ", destination)
|
||||
content := new(session.Content)
|
||||
content.SkipDNSResolve = true
|
||||
content.SkipDNSResolve = session.SkipDNSResolveFromContext(ctx)
|
||||
content.SniffingRequest = l.sniffingRequest
|
||||
|
||||
ctx = session.ContextWithContent(ctx, content)
|
||||
|
||||
@@ -223,6 +223,8 @@ To make it start, wintun.dll specific for your Windows/arch must be present next
|
||||
|
||||
After the start network adapter with the name you chose in the config will be created in the system, and exist while Xray is running. A Wintun adapter that already has that name is reused.
|
||||
|
||||
`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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
)
|
||||
|
||||
@@ -49,3 +50,18 @@ func (updater *InterfaceUpdater) Update() {
|
||||
updater.iface = got
|
||||
errors.LogInfo(context.Background(), "[tun] update interface ", got.Name, " ", got.Index)
|
||||
}
|
||||
|
||||
// ParseGUID parses a canonical textual GUID, as in
|
||||
// "00000000-0000-0000-0000-000000000000", into the 16 bytes it denotes.
|
||||
// The form is all that is accepted, not the other ones uuid.Parse takes,
|
||||
// such as one without hyphens; the length check is what rules those out.
|
||||
func ParseGUID(s string) ([16]byte, error) {
|
||||
if len(s) != 36 {
|
||||
return [16]byte{}, errors.New("invalid guid: ", s, ", want xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
|
||||
}
|
||||
id, err := uuid.Parse(s)
|
||||
if err != nil {
|
||||
return [16]byte{}, errors.New("invalid guid: ", s, ", want xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").Base(err)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
+11
-2
@@ -33,6 +33,7 @@ type Config struct {
|
||||
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"`
|
||||
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
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -137,11 +138,18 @@ func (x *Config) GetAutoSystemWfpBlockLeak() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Config) GetGUID() string {
|
||||
if x != nil {
|
||||
return x.GUID
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var File_proxy_tun_config_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_proxy_tun_config_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"\x16proxy/tun/config.proto\x12\x0exray.proxy.tun\"\xfa\x02\n" +
|
||||
"\x16proxy/tun/config.proto\x12\x0exray.proxy.tun\"\x8e\x03\n" +
|
||||
"\x06Config\x12\x12\n" +
|
||||
"\x04name\x18\x01 \x01(\tR\x04name\x12\x10\n" +
|
||||
"\x03MTU\x18\x02 \x01(\rR\x03MTU\x12\x18\n" +
|
||||
@@ -154,7 +162,8 @@ const file_proxy_tun_config_proto_rawDesc = "" +
|
||||
"\x04desc\x18\b \x01(\tR\x04desc\x12:\n" +
|
||||
"\x1aauto_system_dns_to_gateway\x18\t \x01(\bR\x16autoSystemDnsToGateway\x12:\n" +
|
||||
"\x1aauto_system_wfp_block_leak\x18\n" +
|
||||
" \x03(\tR\x16autoSystemWfpBlockLeakBL\n" +
|
||||
" \x03(\tR\x16autoSystemWfpBlockLeak\x12\x12\n" +
|
||||
"\x04GUID\x18\v \x01(\tR\x04GUIDBL\n" +
|
||||
"\x12com.xray.proxy.tunP\x01Z#github.com/xtls/xray-core/proxy/tun\xaa\x02\x0eXray.Proxy.Tunb\x06proto3"
|
||||
|
||||
var (
|
||||
|
||||
@@ -17,4 +17,5 @@ message Config {
|
||||
string desc = 8;
|
||||
bool auto_system_dns_to_gateway = 9;
|
||||
repeated string auto_system_wfp_block_leak = 10;
|
||||
string GUID = 11;
|
||||
}
|
||||
|
||||
@@ -1,390 +0,0 @@
|
||||
//go:build freebsd
|
||||
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type probeCall struct {
|
||||
inboundTag string
|
||||
source string
|
||||
address string
|
||||
}
|
||||
|
||||
// stubDNSRouting replaces the routing probe for the duration of a test and
|
||||
// records how it was called, so tests can assert the probe is representative.
|
||||
func stubDNSRouting(t *testing.T, err error) *[]probeCall {
|
||||
t.Helper()
|
||||
original := verifyDNSRouting
|
||||
calls := []probeCall{}
|
||||
verifyDNSRouting = func(_ context.Context, inboundTag, source, address string) error {
|
||||
calls = append(calls, probeCall{inboundTag, source, address})
|
||||
return err
|
||||
}
|
||||
t.Cleanup(func() { verifyDNSRouting = original })
|
||||
return &calls
|
||||
}
|
||||
|
||||
// recorder installs a resolvconf stub for the duration of a test and returns
|
||||
// the captured invocations, each as the arguments followed by the stdin in
|
||||
// angle brackets when there was one. An empty failOn succeeds every call;
|
||||
// otherwise the named subcommand fails.
|
||||
func recorder(t *testing.T, failOn string) *[]string {
|
||||
t.Helper()
|
||||
original := resolvconfRunner
|
||||
calls := []string{}
|
||||
resolvconfRunner = func(stdin string, args ...string) ([]byte, error) {
|
||||
call := strings.Join(args, " ")
|
||||
if stdin != "" {
|
||||
call += " <" + stdin + ">"
|
||||
}
|
||||
calls = append(calls, call)
|
||||
if failOn != "" && len(args) > 0 && args[0] == failOn {
|
||||
return nil, errors.New("boom")
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
t.Cleanup(func() { resolvconfRunner = original })
|
||||
return &calls
|
||||
}
|
||||
|
||||
// files replaces the resolver files read by the applied check for the
|
||||
// duration of a test. A path not in the map does not exist.
|
||||
func files(t *testing.T, contents map[string]string) {
|
||||
t.Helper()
|
||||
original := readResolverFile
|
||||
readResolverFile = func(path string) ([]byte, error) {
|
||||
if data, ok := contents[path]; ok {
|
||||
return []byte(data), nil
|
||||
}
|
||||
return nil, fs.ErrNotExist
|
||||
}
|
||||
t.Cleanup(func() { readResolverFile = original })
|
||||
}
|
||||
|
||||
// takenOver is what the libc subscriber writes once the TUN's nameserver is
|
||||
// the exclusive one.
|
||||
const takenOver = "# Generated by resolvconf\nnameserver 192.168.100.1\n"
|
||||
|
||||
// untouched is the DHCP-supplied resolv.conf that resolvconf=NO leaves in
|
||||
// place.
|
||||
const untouched = "# Generated by resolvconf\nnameserver 10.0.0.1\n"
|
||||
|
||||
func optedInTun() *FreeBSDTun {
|
||||
return &FreeBSDTun{
|
||||
options: &Config{
|
||||
Name: "tun7",
|
||||
Gateway: []string{"192.168.100.1/30"},
|
||||
AutoSystemDnsToGateway: true,
|
||||
},
|
||||
name: "tun7",
|
||||
gateway: netip.MustParsePrefix("192.168.100.1/30"),
|
||||
local: netip.MustParseAddr("192.168.100.2"),
|
||||
}
|
||||
}
|
||||
|
||||
func joined(calls []string) string {
|
||||
return strings.Join(calls, " | ")
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSDisabledByDefault(t *testing.T) {
|
||||
probes := stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.options.AutoSystemDnsToGateway = false
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*calls) != 0 || len(*probes) != 0 {
|
||||
t.Errorf("nothing may run when the option is off, got %q and %d probes", joined(*calls), len(*probes))
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the option is off")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSLeavesOSDNSWhenNoRoute(t *testing.T) {
|
||||
stubDNSRouting(t, errors.New("no route"))
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the probe fails")
|
||||
}
|
||||
if len(*calls) != 0 {
|
||||
t.Errorf("resolvconf must not run when the probe fails, got %q", joined(*calls))
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the probe fails")
|
||||
}
|
||||
}
|
||||
|
||||
// On FreeBSD the addresses are the other way round from Linux: the local
|
||||
// address is the one after the gateway, and the gateway itself has no owner,
|
||||
// so a packet to it is routed into the TUN. The probe has to carry that pair,
|
||||
// and the resolver has to be pointed at the gateway.
|
||||
func TestConfigureSystemDNSProbeCarriesFreeBSDPair(t *testing.T) {
|
||||
probes := stubDNSRouting(t, nil)
|
||||
recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*probes) != 1 {
|
||||
t.Fatalf("expected one probe, got %d", len(*probes))
|
||||
}
|
||||
want := probeCall{"tun", "192.168.100.2", "192.168.100.1"}
|
||||
if (*probes)[0] != want {
|
||||
t.Errorf("probe = %+v, want %+v", (*probes)[0], want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSAppliesResolvconf(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !t1.systemDNSSet {
|
||||
t.Fatal("systemDNSSet should be true after a successful takeover")
|
||||
}
|
||||
|
||||
want := "-a tun7 -x <nameserver 192.168.100.1\n>"
|
||||
if got := joined(*calls); got != want {
|
||||
t.Errorf("resolvconf calls = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// resolvconf exits 0 with resolvconf=NO in resolvconf.conf, and still records
|
||||
// the entry for the interface, but runs no subscriber, so success has to be
|
||||
// confirmed in what the subscribers wrote.
|
||||
func TestConfigureSystemDNSRefusesWhenResolvconfDidNotApply(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the nameserver did not reach a resolver")
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the takeover did not take")
|
||||
}
|
||||
if !strings.HasSuffix(joined(*calls), "-d tun7") {
|
||||
t.Errorf("expected a removal after the failed check, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSIdempotent(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
before := len(*calls)
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*calls) != before {
|
||||
t.Errorf("second call must be a no-op, calls went %d -> %d", before, len(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSAddFailureIsNotDirty(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "-a")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when resolvconf -a fails")
|
||||
}
|
||||
if t1.systemDNSSet || t1.systemDNSDirty {
|
||||
t.Error("a failed add leaves nothing to clean up")
|
||||
}
|
||||
if len(*calls) != 1 {
|
||||
t.Errorf("nothing else may run after a failed add, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
// If the removal after a failed check fails too, the entry may still be
|
||||
// installed, so the state has to be remembered rather than silently dropped.
|
||||
func TestConfigureSystemDNSRollbackFailureKeepsDirty(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
recorder(t, "-d")
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the check fails")
|
||||
}
|
||||
if !t1.systemDNSDirty {
|
||||
t.Error("a failed removal must leave the resolver marked dirty")
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the takeover did not complete")
|
||||
}
|
||||
}
|
||||
|
||||
// A dirty resolver is retried before anything new is applied.
|
||||
func TestConfigureSystemDNSRetriesDirtyBeforeApplying(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.systemDNSDirty = true
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
got := joined(*calls)
|
||||
if !strings.HasPrefix(got, "-d tun7 | -a tun7") {
|
||||
t.Errorf("expected the stale removal first, got %q", got)
|
||||
}
|
||||
if t1.systemDNSDirty {
|
||||
t.Error("a successful retry should clear the dirty flag")
|
||||
}
|
||||
if !t1.systemDNSSet {
|
||||
t.Error("the takeover should proceed once the retry succeeds")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsetSystemDNSRemoves(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("setup failed: %v", err)
|
||||
}
|
||||
*calls = nil
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet should be false after unset")
|
||||
}
|
||||
if got := joined(*calls); got != "-d tun7" {
|
||||
t.Errorf("unset calls = %q, want %q", got, "-d tun7")
|
||||
}
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if len(*calls) != 1 {
|
||||
t.Errorf("unsetSystemDNS must be idempotent, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsetSystemDNSKeepsDirtyWhenRemoveFails(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "-d")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.systemDNSSet = true
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if !t1.systemDNSDirty {
|
||||
t.Error("a failed removal during unset must be remembered")
|
||||
}
|
||||
if got := joined(*calls); got != "-d tun7" {
|
||||
t.Errorf("expected a removal attempt, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedLibc(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("resolv.conf listing the nameserver must count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedNotWhenUntouched(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || ok {
|
||||
t.Errorf("an unchanged resolv.conf and no resolvconf.conf must not count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
// With inclusive_interfaces in resolvconf.conf the exclusive marking is
|
||||
// ignored and the DHCP nameservers stay listed, so the system falls back to
|
||||
// them; that is the leak the option exists to close, and it must not pass.
|
||||
func TestResolvconfAppliedNotWhenOthersRemain(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.1\nnameserver 10.0.0.1\n"})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("another nameserver alongside the TUN's must not count as applied")
|
||||
}
|
||||
}
|
||||
|
||||
// A loopback nameserver alongside is a local resolver that resolvconf feeds
|
||||
// (local_unbound with the libc subscriber left on), not a leak.
|
||||
func TestResolvconfAppliedWithLoopbackAlongside(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 127.0.0.1\nnameserver 192.168.100.1\n"})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("a loopback nameserver alongside must still count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedIgnoresPrefixMatches(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.10\n"})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("192.168.100.10 must not match 192.168.100.1")
|
||||
}
|
||||
}
|
||||
|
||||
// local-unbound-setup turns the libc subscriber off and has resolvconf write
|
||||
// unbound's forwarders instead; resolv.conf then stays pointed at loopback.
|
||||
func TestResolvconfAppliedUnbound(t *testing.T) {
|
||||
files(t, map[string]string{
|
||||
"/etc/resolv.conf": "# Generated by resolvconf\nnameserver 127.0.0.1\noptions edns0\n",
|
||||
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
|
||||
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 192.168.100.1\n",
|
||||
})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("the nameserver in unbound's forwarders must count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedNotWhenUnboundUntouched(t *testing.T) {
|
||||
files(t, map[string]string{
|
||||
"/etc/resolv.conf": "nameserver 127.0.0.1\n",
|
||||
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
|
||||
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 10.0.0.1\n",
|
||||
})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("unbound still forwarding to the old server must not count as applied")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedReportsUnreadableResolvConf(t *testing.T) {
|
||||
files(t, map[string]string{})
|
||||
if _, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err == nil {
|
||||
t.Error("a missing resolv.conf is an error, not a verdict")
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,11 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/net/route"
|
||||
@@ -148,3 +152,381 @@ func TestDefaultRouteFamilyRejectsShortAddrs(t *testing.T) {
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,204 +0,0 @@
|
||||
//go:build linux && !android
|
||||
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/app/dispatcher"
|
||||
appdns "github.com/xtls/xray-core/app/dns"
|
||||
"github.com/xtls/xray-core/app/proxyman"
|
||||
_ "github.com/xtls/xray-core/app/proxyman/inbound"
|
||||
_ "github.com/xtls/xray-core/app/proxyman/outbound"
|
||||
"github.com/xtls/xray-core/app/router"
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/core"
|
||||
proxydns "github.com/xtls/xray-core/proxy/dns"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
)
|
||||
|
||||
const (
|
||||
routeTestInboundTag = "tun"
|
||||
routeTestSource = "192.168.100.1"
|
||||
routeTestDNSAddress = "192.168.100.2"
|
||||
)
|
||||
|
||||
// port53Rule sends DNS queries arriving from the interface to the dns outbound.
|
||||
func port53Rule() *router.RoutingRule {
|
||||
return &router.RoutingRule{
|
||||
InboundTag: []string{routeTestInboundTag},
|
||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(53)}},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "dns"},
|
||||
}
|
||||
}
|
||||
|
||||
// sourceBlockRule diverts traffic from one address, which is the shape of a rule
|
||||
// that only matches because the real request carries a source.
|
||||
func sourceBlockRule(ip []byte) *router.RoutingRule {
|
||||
return &router.RoutingRule{
|
||||
SourceIp: []*geodata.IPRule{{
|
||||
Value: &geodata.IPRule_Custom{
|
||||
Custom: &geodata.CIDRRule{
|
||||
Cidr: &geodata.CIDR{Ip: ip, Prefix: 32},
|
||||
},
|
||||
},
|
||||
}},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "block"},
|
||||
}
|
||||
}
|
||||
|
||||
// newRouteTestContext builds a real but unstarted instance: no TUN device, no
|
||||
// running resolver. The instance is placed in the context through the key core
|
||||
// exports for tests.
|
||||
func newRouteTestContext(t *testing.T, withDNSApp bool, nameServers []*appdns.NameServer, rules []*router.RoutingRule) context.Context {
|
||||
t.Helper()
|
||||
|
||||
apps := []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&dispatcher.Config{}),
|
||||
serial.ToTypedMessage(&proxyman.InboundConfig{}),
|
||||
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
|
||||
serial.ToTypedMessage(&router.Config{Rule: rules}),
|
||||
}
|
||||
if withDNSApp {
|
||||
apps = append(apps, serial.ToTypedMessage(&appdns.Config{NameServer: nameServers}))
|
||||
}
|
||||
|
||||
instance, err := core.New(&core.Config{
|
||||
App: apps,
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})},
|
||||
{Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})},
|
||||
{Tag: "block", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("core.New: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = instance.Close() })
|
||||
|
||||
return context.WithValue(context.Background(), core.XrayKey(1), instance)
|
||||
}
|
||||
|
||||
func udpNameServer(ip []byte) []*appdns.NameServer {
|
||||
return []*appdns.NameServer{{
|
||||
Address: &net.Endpoint{
|
||||
Network: net.Network_UDP,
|
||||
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Ip{Ip: ip}},
|
||||
Port: 53,
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
// localNameServer is a name server pointed at "localhost", which app/dns
|
||||
// resolves through the system resolver.
|
||||
func localNameServer() *appdns.NameServer {
|
||||
return &appdns.NameServer{
|
||||
Address: &net.Endpoint{
|
||||
Network: net.Network_UDP,
|
||||
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Domain{Domain: "localhost"}},
|
||||
Port: 53,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// These drive the real feature lookup and the real router. verifyDNSRouting is
|
||||
// the same function ConfigureSystemDNS calls, so a false positive here is a
|
||||
// false positive in the takeover decision itself, which is what assertions on
|
||||
// the resolvectl arguments could never catch.
|
||||
func TestVerifyDNSRoutingDecisions(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
withDNSApp bool
|
||||
nameServers []*appdns.NameServer
|
||||
rules []*router.RoutingRule
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "independent upstream reaches the dns outbound",
|
||||
withDNSApp: true,
|
||||
nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "no dns section falls back to the system resolver",
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
name: "dns section without name servers falls back too",
|
||||
withDNSApp: true,
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
// An independent upstream is not enough on its own: name servers are
|
||||
// selected per domain, so a local one can still be the one chosen.
|
||||
// The refusal is deliberately domain-agnostic for that reason.
|
||||
name: "a local name server alongside an independent one",
|
||||
withDNSApp: true,
|
||||
nameServers: append(udpNameServer([]byte{9, 9, 9, 9}), localNameServer()),
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
name: "a rule on the interface address diverts the real query",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{
|
||||
sourceBlockRule([]byte{192, 168, 100, 1}),
|
||||
port53Rule(),
|
||||
},
|
||||
wantErr: "does not handle DNS",
|
||||
},
|
||||
{
|
||||
name: "a rule on another address does not match it",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{
|
||||
sourceBlockRule([]byte{10, 0, 0, 1}),
|
||||
port53Rule(),
|
||||
},
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "no rule matches the query",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
wantErr: "no route",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := newRouteTestContext(t, tt.withDNSApp, tt.nameServers, tt.rules)
|
||||
err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, routeTestDNSAddress)
|
||||
|
||||
if tt.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("expected the takeover to be accepted, got: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatalf("expected the takeover to be refused with %q, got nil", tt.wantErr)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Errorf("error = %q, want it to contain %q", err.Error(), tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Without an IPv4 gateway, the takeover uses the first IPv6 one, and the probe
|
||||
// carries IPv6 addresses.
|
||||
func TestVerifyDNSRoutingIPv6(t *testing.T) {
|
||||
ctx := newRouteTestContext(t, true, udpNameServer([]byte{9, 9, 9, 9}), []*router.RoutingRule{port53Rule()})
|
||||
if err := verifyDNSRouting(ctx, routeTestInboundTag, "fc00::1", "fc00::2"); err != nil {
|
||||
t.Fatalf("expected the takeover to be accepted, got: %v", err)
|
||||
}
|
||||
if err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, "fc00::2"); err == nil {
|
||||
t.Fatal("expected mixed IPv4 and IPv6 addresses to be refused")
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,18 @@ import (
|
||||
"testing"
|
||||
|
||||
"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
|
||||
@@ -443,3 +455,185 @@ func TestBuildResolvectlArgs(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
routeTestInboundTag = "tun"
|
||||
routeTestSource = "192.168.100.1"
|
||||
routeTestDNSAddress = "192.168.100.2"
|
||||
)
|
||||
|
||||
// port53Rule sends DNS queries arriving from the interface to the dns outbound.
|
||||
func port53Rule() *router.RoutingRule {
|
||||
return &router.RoutingRule{
|
||||
InboundTag: []string{routeTestInboundTag},
|
||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(53)}},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "dns"},
|
||||
}
|
||||
}
|
||||
|
||||
// sourceBlockRule diverts traffic from one address, which is the shape of a rule
|
||||
// that only matches because the real request carries a source.
|
||||
func sourceBlockRule(ip []byte) *router.RoutingRule {
|
||||
return &router.RoutingRule{
|
||||
SourceIp: []*geodata.IPRule{{
|
||||
Value: &geodata.IPRule_Custom{
|
||||
Custom: &geodata.CIDRRule{
|
||||
Cidr: &geodata.CIDR{Ip: ip, Prefix: 32},
|
||||
},
|
||||
},
|
||||
}},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "block"},
|
||||
}
|
||||
}
|
||||
|
||||
// newRouteTestContext builds a real but unstarted instance: no TUN device, no
|
||||
// running resolver. The instance is placed in the context through the key core
|
||||
// exports for tests.
|
||||
func newRouteTestContext(t *testing.T, withDNSApp bool, nameServers []*appdns.NameServer, rules []*router.RoutingRule) context.Context {
|
||||
t.Helper()
|
||||
|
||||
apps := []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&dispatcher.Config{}),
|
||||
serial.ToTypedMessage(&proxyman.InboundConfig{}),
|
||||
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
|
||||
serial.ToTypedMessage(&router.Config{Rule: rules}),
|
||||
}
|
||||
if withDNSApp {
|
||||
apps = append(apps, serial.ToTypedMessage(&appdns.Config{NameServer: nameServers}))
|
||||
}
|
||||
|
||||
instance, err := core.New(&core.Config{
|
||||
App: apps,
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})},
|
||||
{Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})},
|
||||
{Tag: "block", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("core.New: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = instance.Close() })
|
||||
|
||||
return context.WithValue(context.Background(), core.XrayKey(1), instance)
|
||||
}
|
||||
|
||||
func udpNameServer(ip []byte) []*appdns.NameServer {
|
||||
return []*appdns.NameServer{{
|
||||
Address: &net.Endpoint{
|
||||
Network: net.Network_UDP,
|
||||
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Ip{Ip: ip}},
|
||||
Port: 53,
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
// localNameServer is a name server pointed at "localhost", which app/dns
|
||||
// resolves through the system resolver.
|
||||
func localNameServer() *appdns.NameServer {
|
||||
return &appdns.NameServer{
|
||||
Address: &net.Endpoint{
|
||||
Network: net.Network_UDP,
|
||||
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Domain{Domain: "localhost"}},
|
||||
Port: 53,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// These drive the real feature lookup and the real router. verifyDNSRouting is
|
||||
// the same function ConfigureSystemDNS calls, so a false positive here is a
|
||||
// false positive in the takeover decision itself, which is what assertions on
|
||||
// the resolvectl arguments could never catch.
|
||||
func TestVerifyDNSRoutingDecisions(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
withDNSApp bool
|
||||
nameServers []*appdns.NameServer
|
||||
rules []*router.RoutingRule
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "independent upstream reaches the dns outbound",
|
||||
withDNSApp: true,
|
||||
nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "no dns section falls back to the system resolver",
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
name: "dns section without name servers falls back too",
|
||||
withDNSApp: true,
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
// An independent upstream is not enough on its own: name servers are
|
||||
// selected per domain, so a local one can still be the one chosen.
|
||||
// The refusal is deliberately domain-agnostic for that reason.
|
||||
name: "a local name server alongside an independent one",
|
||||
withDNSApp: true,
|
||||
nameServers: append(udpNameServer([]byte{9, 9, 9, 9}), localNameServer()),
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
name: "a rule on the interface address diverts the real query",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{
|
||||
sourceBlockRule([]byte{192, 168, 100, 1}),
|
||||
port53Rule(),
|
||||
},
|
||||
wantErr: "does not handle DNS",
|
||||
},
|
||||
{
|
||||
name: "a rule on another address does not match it",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{
|
||||
sourceBlockRule([]byte{10, 0, 0, 1}),
|
||||
port53Rule(),
|
||||
},
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "no rule matches the query",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
wantErr: "no route",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := newRouteTestContext(t, tt.withDNSApp, tt.nameServers, tt.rules)
|
||||
err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, routeTestDNSAddress)
|
||||
|
||||
if tt.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("expected the takeover to be accepted, got: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatalf("expected the takeover to be refused with %q, got nil", tt.wantErr)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Errorf("error = %q, want it to contain %q", err.Error(), tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Without an IPv4 gateway, the takeover uses the first IPv6 one, and the probe
|
||||
// carries IPv6 addresses.
|
||||
func TestVerifyDNSRoutingIPv6(t *testing.T) {
|
||||
ctx := newRouteTestContext(t, true, udpNameServer([]byte{9, 9, 9, 9}), []*router.RoutingRule{port53Rule()})
|
||||
if err := verifyDNSRouting(ctx, routeTestInboundTag, "fc00::1", "fc00::2"); err != nil {
|
||||
t.Fatalf("expected the takeover to be accepted, got: %v", err)
|
||||
}
|
||||
if err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, "fc00::2"); err == nil {
|
||||
t.Fatal("expected mixed IPv4 and IPv6 addresses to be refused")
|
||||
}
|
||||
}
|
||||
+134
-5
@@ -59,7 +59,7 @@ var _ Tun = (*WindowsTun)(nil)
|
||||
// interface with the same name exist, it tried to be reused.
|
||||
func NewTun(options *Config) (Tun, error) {
|
||||
// instantiate wintun adapter
|
||||
adapter, err := open(options.Name, options.Desc)
|
||||
adapter, err := open(options.Name, options.Desc, options.GUID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -82,10 +82,11 @@ func NewTun(options *Config) (Tun, error) {
|
||||
return tun, nil
|
||||
}
|
||||
|
||||
func open(name, desc string) (*wintun.Adapter, error) {
|
||||
// generate a deterministic GUID from the adapter name
|
||||
id := md5.Sum([]byte(name))
|
||||
guid := (*windows.GUID)(unsafe.Pointer(&id[0]))
|
||||
func open(name, desc, id string) (*wintun.Adapter, error) {
|
||||
guid, err := adapterGUID(name, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// try to open existing adapter by name
|
||||
adapter, err := wintun.OpenAdapter(name)
|
||||
if err == nil {
|
||||
@@ -99,6 +100,28 @@ func open(name, desc string) (*wintun.Adapter, error) {
|
||||
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
|
||||
// interfaces (0x10, as 0xFF does), the TUN among them. Windows applies it at
|
||||
// boot only.
|
||||
@@ -687,3 +710,109 @@ func findOutboundInterface(tunIndex int, fixedName string) (*net.Interface, erro
|
||||
}
|
||||
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"
|
||||
}
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
//go:build windows
|
||||
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"golang.org/x/sys/windows"
|
||||
"golang.zx2c4.com/wireguard/windows/tunnel/winipcfg"
|
||||
)
|
||||
|
||||
// outboundGuard keeps Windows to the binding of autoOutboundsInterface, which
|
||||
// keeps Xray's own connections out of the TUN. With weak host send or
|
||||
// forwarding on for an IP version on the bound interface, Windows sends them
|
||||
// where the routes lead, into the TUN, from that interface's address, and
|
||||
// drops what comes back to that address through the TUN, so they stall.
|
||||
//
|
||||
// For the IP versions routed to the TUN, weak host send is turned off on the
|
||||
// bound interface while the TUN runs, and turned on again when the TUN stops
|
||||
// or another interface takes over. Forwarding is what Mobile Hotspot and
|
||||
// Internet Connection Sharing need, so it is only reported.
|
||||
type outboundGuard struct {
|
||||
sync.Mutex
|
||||
families []winipcfg.AddressFamily
|
||||
luid winipcfg.LUID // of the interface last checked
|
||||
name string // of that interface
|
||||
turnedOff []winipcfg.AddressFamily // where weak host send was turned off on it
|
||||
forwarding bool // whether forwarding was on there
|
||||
stopped bool
|
||||
}
|
||||
|
||||
// check turns weak host send off on the bound interface, and warns when
|
||||
// forwarding comes on there, but not again while it stays on.
|
||||
func (g *outboundGuard) check() {
|
||||
g.Lock()
|
||||
defer g.Unlock()
|
||||
if g.stopped {
|
||||
return
|
||||
}
|
||||
var luid winipcfg.LUID
|
||||
var name string
|
||||
if iface := updater.Get(); iface != nil {
|
||||
luid, _ = winipcfg.LUIDFromIndex(uint32(iface.Index))
|
||||
name = iface.Name
|
||||
}
|
||||
if luid != g.luid {
|
||||
g.restoreLocked()
|
||||
g.luid, g.name = luid, name
|
||||
g.forwarding = false // to warn about the new interface as well
|
||||
}
|
||||
if luid == 0 {
|
||||
return
|
||||
}
|
||||
var forwarding []string
|
||||
for _, family := range g.families {
|
||||
row, err := luid.IPInterface(family)
|
||||
if err != nil {
|
||||
continue // the interface lacks that IP version
|
||||
}
|
||||
if row.ForwardingEnabled {
|
||||
forwarding = append(forwarding, familyName(family))
|
||||
}
|
||||
if !row.WeakHostSend {
|
||||
continue
|
||||
}
|
||||
if err := setWeakHostSend(row, false); err != nil {
|
||||
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send off for ", familyName(family), " on ", name)
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(g.turnedOff, family) {
|
||||
g.turnedOff = append(g.turnedOff, family)
|
||||
errors.LogInfo(context.Background(), "[tun] weak host send turned off for ", familyName(family), " on ", name, " while the TUN runs, as Windows would ignore autoOutboundsInterface")
|
||||
}
|
||||
}
|
||||
wasOn := g.forwarding
|
||||
g.forwarding = len(forwarding) > 0
|
||||
if g.forwarding && !wasOn {
|
||||
errors.LogWarning(context.Background(), "[tun] forwarding is on for ", strings.Join(forwarding, " and "), " on ", name, " (Mobile Hotspot and Internet Connection Sharing turn it on), so Windows ignores autoOutboundsInterface there, and Xray's own connections go into the TUN and stall: turn the hotspot off, or have it share the TUN instead of ", name)
|
||||
}
|
||||
}
|
||||
|
||||
// restore turns weak host send on again where check turned it off, for good.
|
||||
func (g *outboundGuard) restore() {
|
||||
g.Lock()
|
||||
defer g.Unlock()
|
||||
g.restoreLocked()
|
||||
g.stopped = true
|
||||
}
|
||||
|
||||
func (g *outboundGuard) restoreLocked() {
|
||||
for _, family := range g.turnedOff {
|
||||
row, err := g.luid.IPInterface(family)
|
||||
if err == nil {
|
||||
err = setWeakHostSend(row, true)
|
||||
}
|
||||
if err != nil {
|
||||
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send on again for ", familyName(family), " on ", g.name)
|
||||
}
|
||||
}
|
||||
g.turnedOff = nil
|
||||
}
|
||||
|
||||
func setWeakHostSend(row *winipcfg.MibIPInterfaceRow, on bool) error {
|
||||
row.WeakHostSend = on
|
||||
if row.Family == windows.AF_INET {
|
||||
row.SitePrefixLength = 0 // as SetIpInterfaceEntry requires for IPv4
|
||||
}
|
||||
return row.Set()
|
||||
}
|
||||
|
||||
func familyName(family winipcfg.AddressFamily) string {
|
||||
if family == windows.AF_INET {
|
||||
return "IPv4"
|
||||
}
|
||||
return "IPv6"
|
||||
}
|
||||
@@ -4,6 +4,7 @@ package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
go_errors "errors"
|
||||
"net"
|
||||
"net/netip"
|
||||
@@ -340,3 +341,46 @@ func TestFlushDNSCache(t *testing.T) {
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -8,20 +8,6 @@ import (
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
)
|
||||
|
||||
// BenchmarkUDPNewSession measures what one new UDP flow costs the
|
||||
// inbound while it stays open: QUIC and DNS open many short flows, and each
|
||||
// one lives until the connection idle timeout.
|
||||
func BenchmarkUDPNewSession(b *testing.B) {
|
||||
u := newUdpConnectionHandler(func(conn net.Conn, dest net.Destination) {}, nil)
|
||||
dst := net.UDPDestination(net.ParseAddress("1.1.1.1"), 443)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
src := net.UDPDestination(net.IPAddress([]byte{10, byte(i >> 16), byte(i >> 8), byte(i)}), net.Port(1024+i%60000))
|
||||
u.HandlePacket(src, dst, &buf.Buffer{})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPacketQueueOrderAndClose(t *testing.T) {
|
||||
q := newPacketQueue(udpQueueLimit)
|
||||
for i := 0; i < 3; i++ {
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
)
|
||||
|
||||
const benchBatch = 64
|
||||
|
||||
// Raw cost of queueing and draining a small burst, as one flow's reader does.
|
||||
func BenchmarkQueueBurstChan(b *testing.B) {
|
||||
ch := make(chan *buf.Buffer, udpQueueLimit)
|
||||
p := &buf.Buffer{}
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
for j := 0; j < benchBatch; j++ {
|
||||
ch <- p
|
||||
}
|
||||
for j := 0; j < benchBatch; j++ {
|
||||
<-ch
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkQueueBurstPacketQueue(b *testing.B) {
|
||||
q := newPacketQueue(udpQueueLimit)
|
||||
p := &buf.Buffer{}
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
for j := 0; j < benchBatch; j++ {
|
||||
q.push(p)
|
||||
}
|
||||
for j := 0; j < benchBatch; j++ {
|
||||
q.pop()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Producer and consumer on different goroutines; the producer yields when the
|
||||
// queue is full instead of spinning, like a blocking channel send would.
|
||||
func BenchmarkQueueStreamChan(b *testing.B) {
|
||||
ch := make(chan *buf.Buffer, udpQueueLimit)
|
||||
p := &buf.Buffer{}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
for range ch {
|
||||
}
|
||||
close(done)
|
||||
}()
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
ch <- p
|
||||
}
|
||||
close(ch)
|
||||
<-done
|
||||
}
|
||||
|
||||
func BenchmarkQueueStreamPacketQueue(b *testing.B) {
|
||||
q := newPacketQueue(udpQueueLimit)
|
||||
p := &buf.Buffer{}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
for {
|
||||
if _, ok := q.pop(); !ok {
|
||||
break
|
||||
}
|
||||
}
|
||||
close(done)
|
||||
}()
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
for !q.push(p) {
|
||||
runtime.Gosched()
|
||||
}
|
||||
}
|
||||
q.close()
|
||||
<-done
|
||||
}
|
||||
@@ -80,43 +80,3 @@ func TestExpandWfpBlockLeak(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLeakCovers(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
value string
|
||||
protocol string
|
||||
port uint16
|
||||
covers bool
|
||||
}{
|
||||
{"tcp", "tcp", 1, true},
|
||||
{"tcp", "udp", 53, false},
|
||||
{"udp/53", "udp", 53, true},
|
||||
{"udp/53", "udp", 54, false},
|
||||
{"tcp/10-20", "tcp", 10, true},
|
||||
{"tcp/10-20", "tcp", 20, true},
|
||||
{"tcp/10-20", "tcp", 21, false},
|
||||
{"tcp/10-20", "tcp", 9, false},
|
||||
{"53", "udp", 53, true},
|
||||
{"53", "tcp", 53, true},
|
||||
{"10-20", "tcp", 15, true},
|
||||
{"10-20", "udp", 21, false},
|
||||
{"1.1.1.0/24:udp/53", "udp", 53, true},
|
||||
{"[::/0]:tcp", "tcp", 443, true},
|
||||
{"[2001:db8::/32]:53", "tcp", 53, true},
|
||||
{"0.0.0.0/0:icmp", "udp", 53, false},
|
||||
{"all", "udp", 53, true},
|
||||
{"1.1.1.1/32:all", "tcp", 1, true},
|
||||
{"allexceptlan", "udp", 53, false},
|
||||
{"misconfigtun", "udp", 53, false},
|
||||
{"windnsclient", "udp", 53, false},
|
||||
} {
|
||||
l, ok := parseLeak(c.value)
|
||||
if !ok {
|
||||
t.Errorf("%q was not parsed", c.value)
|
||||
continue
|
||||
}
|
||||
if got := l.covers(c.protocol, c.port); got != c.covers {
|
||||
t.Errorf("%q covers %s/%d = %v", c.value, c.protocol, c.port, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -184,6 +184,66 @@ func (x *Account) GetTestseed() []uint32 {
|
||||
return nil
|
||||
}
|
||||
|
||||
type Multiplex struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Concurrency int32 `protobuf:"varint,1,opt,name=concurrency,proto3" json:"concurrency,omitempty"`
|
||||
XudpConcurrency int32 `protobuf:"varint,2,opt,name=xudpConcurrency,proto3" json:"xudpConcurrency,omitempty"`
|
||||
XudpProxyUDP443 string `protobuf:"bytes,3,opt,name=xudpProxyUDP443,proto3" json:"xudpProxyUDP443,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Multiplex) Reset() {
|
||||
*x = Multiplex{}
|
||||
mi := &file_proxy_vless_account_proto_msgTypes[2]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *Multiplex) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Multiplex) ProtoMessage() {}
|
||||
|
||||
func (x *Multiplex) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_proxy_vless_account_proto_msgTypes[2]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Multiplex.ProtoReflect.Descriptor instead.
|
||||
func (*Multiplex) Descriptor() ([]byte, []int) {
|
||||
return file_proxy_vless_account_proto_rawDescGZIP(), []int{2}
|
||||
}
|
||||
|
||||
func (x *Multiplex) GetConcurrency() int32 {
|
||||
if x != nil {
|
||||
return x.Concurrency
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Multiplex) GetXudpConcurrency() int32 {
|
||||
if x != nil {
|
||||
return x.XudpConcurrency
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Multiplex) GetXudpProxyUDP443() string {
|
||||
if x != nil {
|
||||
return x.XudpProxyUDP443
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var File_proxy_vless_account_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_proxy_vless_account_proto_rawDesc = "" +
|
||||
@@ -203,7 +263,11 @@ const file_proxy_vless_account_proto_rawDesc = "" +
|
||||
"\apadding\x18\x06 \x01(\tR\apadding\x123\n" +
|
||||
"\areverse\x18\a \x01(\v2\x19.xray.proxy.vless.ReverseR\areverse\x12\x18\n" +
|
||||
"\atestpre\x18\b \x01(\rR\atestpre\x12\x1a\n" +
|
||||
"\btestseed\x18\t \x03(\rR\btestseedBR\n" +
|
||||
"\btestseed\x18\t \x03(\rR\btestseed\"\x81\x01\n" +
|
||||
"\tMultiplex\x12 \n" +
|
||||
"\vconcurrency\x18\x01 \x01(\x05R\vconcurrency\x12(\n" +
|
||||
"\x0fxudpConcurrency\x18\x02 \x01(\x05R\x0fxudpConcurrency\x12(\n" +
|
||||
"\x0fxudpProxyUDP443\x18\x03 \x01(\tR\x0fxudpProxyUDP443BR\n" +
|
||||
"\x14com.xray.proxy.vlessP\x01Z%github.com/xtls/xray-core/proxy/vless\xaa\x02\x10Xray.Proxy.Vlessb\x06proto3"
|
||||
|
||||
var (
|
||||
@@ -218,14 +282,15 @@ func file_proxy_vless_account_proto_rawDescGZIP() []byte {
|
||||
return file_proxy_vless_account_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_proxy_vless_account_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
|
||||
var file_proxy_vless_account_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
|
||||
var file_proxy_vless_account_proto_goTypes = []any{
|
||||
(*Reverse)(nil), // 0: xray.proxy.vless.Reverse
|
||||
(*Account)(nil), // 1: xray.proxy.vless.Account
|
||||
(*proxyman.SniffingConfig)(nil), // 2: xray.app.proxyman.SniffingConfig
|
||||
(*Multiplex)(nil), // 2: xray.proxy.vless.Multiplex
|
||||
(*proxyman.SniffingConfig)(nil), // 3: xray.app.proxyman.SniffingConfig
|
||||
}
|
||||
var file_proxy_vless_account_proto_depIdxs = []int32{
|
||||
2, // 0: xray.proxy.vless.Reverse.sniffing:type_name -> xray.app.proxyman.SniffingConfig
|
||||
3, // 0: xray.proxy.vless.Reverse.sniffing:type_name -> xray.app.proxyman.SniffingConfig
|
||||
0, // 1: xray.proxy.vless.Account.reverse:type_name -> xray.proxy.vless.Reverse
|
||||
2, // [2:2] is the sub-list for method output_type
|
||||
2, // [2:2] is the sub-list for method input_type
|
||||
@@ -245,7 +310,7 @@ func file_proxy_vless_account_proto_init() {
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_vless_account_proto_rawDesc), len(file_proxy_vless_account_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 2,
|
||||
NumMessages: 3,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
|
||||
@@ -29,3 +29,9 @@ message Account {
|
||||
uint32 testpre = 8;
|
||||
repeated uint32 testseed = 9;
|
||||
}
|
||||
|
||||
message Multiplex {
|
||||
int32 concurrency = 1;
|
||||
int32 xudpConcurrency = 2;
|
||||
string xudpProxyUDP443 = 3;
|
||||
}
|
||||
|
||||
@@ -11,16 +11,13 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/app/dispatcher"
|
||||
"github.com/xtls/xray-core/app/reverse"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/log"
|
||||
"github.com/xtls/xray-core/common/mux"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/retry"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/signal"
|
||||
"github.com/xtls/xray-core/common/task"
|
||||
@@ -28,7 +25,6 @@ import (
|
||||
"github.com/xtls/xray-core/features"
|
||||
"github.com/xtls/xray-core/features/dns"
|
||||
"github.com/xtls/xray-core/features/extension"
|
||||
feature_inbound "github.com/xtls/xray-core/features/inbound"
|
||||
"github.com/xtls/xray-core/features/outbound"
|
||||
"github.com/xtls/xray-core/features/policy"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
@@ -37,6 +33,8 @@ import (
|
||||
"github.com/xtls/xray-core/proxy/vless"
|
||||
"github.com/xtls/xray-core/proxy/vless/encoding"
|
||||
"github.com/xtls/xray-core/proxy/vless/encryption"
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
"github.com/xtls/xray-core/proxy/vless/reverse"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/internet/reality"
|
||||
"github.com/xtls/xray-core/transport/internet/stat"
|
||||
@@ -72,14 +70,12 @@ func init() {
|
||||
|
||||
// Handler is an inbound connection handler that handles messages in VLess protocol.
|
||||
type Handler struct {
|
||||
inboundHandlerManager feature_inbound.Manager
|
||||
policyManager policy.Manager
|
||||
stats stats.Manager
|
||||
validator vless.Validator
|
||||
decryption *encryption.ServerInstance
|
||||
outboundHandlerManager outbound.Manager
|
||||
observer features.Feature
|
||||
defaultDispatcher routing.Dispatcher
|
||||
ctx context.Context
|
||||
fallbacks map[string]map[string]map[string]*Fallback // or nil
|
||||
// regexps map[string]*regexp.Regexp // or nil
|
||||
@@ -89,13 +85,11 @@ type Handler struct {
|
||||
func New(ctx context.Context, config *Config, dc dns.Client, validator vless.Validator) (*Handler, error) {
|
||||
v := core.MustFromContext(ctx)
|
||||
handler := &Handler{
|
||||
inboundHandlerManager: v.GetFeature(feature_inbound.ManagerType()).(feature_inbound.Manager),
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
stats: v.GetFeature(stats.ManagerType()).(stats.Manager),
|
||||
validator: validator,
|
||||
outboundHandlerManager: v.GetFeature(outbound.ManagerType()).(outbound.Manager),
|
||||
observer: v.GetFeature(extension.ObservatoryType()),
|
||||
defaultDispatcher: v.GetFeature(routing.DispatcherType()).(routing.Dispatcher),
|
||||
ctx: ctx,
|
||||
}
|
||||
|
||||
@@ -188,7 +182,7 @@ func isMuxAndNotXUDP(request *protocol.RequestHeader, first *buf.Buffer) bool {
|
||||
firstBytes[6] == 2) // Network type: UDP
|
||||
}
|
||||
|
||||
func (h *Handler) GetReverse(a *vless.MemoryAccount) (*Reverse, error) {
|
||||
func (h *Handler) GetReverse(a *vless.MemoryAccount) (*reverse.PublicEndpoint, error) {
|
||||
u := h.validator.Get(a.ID.UUID())
|
||||
if u == nil {
|
||||
return nil, errors.New("reverse: user " + a.ID.String() + " doesn't exist anymore")
|
||||
@@ -199,25 +193,28 @@ func (h *Handler) GetReverse(a *vless.MemoryAccount) (*Reverse, error) {
|
||||
}
|
||||
r := h.outboundHandlerManager.GetHandler(a.Reverse.Tag)
|
||||
if r == nil {
|
||||
picker, _ := reverse.NewStaticMuxPicker()
|
||||
r = &Reverse{tag: a.Reverse.Tag, picker: picker, client: &mux.ClientManager{Picker: picker}}
|
||||
r = reverse.NewPublicEndpoint(a.Reverse.Tag, h.observer)
|
||||
for len(h.outboundHandlerManager.ListHandlers(h.ctx)) == 0 {
|
||||
time.Sleep(time.Second) // prevents this outbound from becoming the default outbound
|
||||
}
|
||||
if err := h.outboundHandlerManager.AddHandler(h.ctx, r); err != nil {
|
||||
r.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if r, ok := r.(*Reverse); ok {
|
||||
if r, ok := r.(*reverse.PublicEndpoint); ok {
|
||||
return r, nil
|
||||
}
|
||||
return nil, errors.New("reverse: outbound " + a.Reverse.Tag + " is not type Reverse")
|
||||
return nil, errors.New("reverse: outbound " + a.Reverse.Tag + " is not type PublicEndpoint")
|
||||
}
|
||||
|
||||
func (h *Handler) RemoveReverse(u *protocol.MemoryUser) {
|
||||
if u != nil {
|
||||
a := u.Account.(*vless.MemoryAccount)
|
||||
if a.Reverse != nil && a.Reverse.Tag != "" {
|
||||
if publicEndpoint, ok := h.outboundHandlerManager.GetHandler(a.Reverse.Tag).(*reverse.PublicEndpoint); ok {
|
||||
publicEndpoint.Close()
|
||||
}
|
||||
h.outboundHandlerManager.RemoveHandler(h.ctx, a.Reverse.Tag)
|
||||
}
|
||||
}
|
||||
@@ -541,10 +538,6 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
|
||||
return errors.New("for safety reasons, user " + account.ID.String() + " is not allowed to use forward proxy")
|
||||
}
|
||||
|
||||
responseAddons := &encoding.Addons{
|
||||
// Flow: requestAddons.Flow,
|
||||
}
|
||||
|
||||
var input *bytes.Reader
|
||||
var rawInput **bytes.Buffer
|
||||
switch requestAddons.Flow {
|
||||
@@ -607,85 +600,29 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
|
||||
}
|
||||
|
||||
bufferWriter := buf.NewBufferedWriter(buf.NewWriter(connection))
|
||||
if err := encoding.EncodeResponseHeader(bufferWriter, request, responseAddons); err != nil {
|
||||
if err := encoding.EncodeResponseHeader(bufferWriter, request, &encoding.Addons{}); err != nil {
|
||||
return errors.New("failed to encode response header").Base(err)
|
||||
}
|
||||
clientWriter := encoding.EncodeBodyAddons(bufferWriter, request, requestAddons, trafficState, false, ctx, connection, nil)
|
||||
bufferWriter.SetFlushNext()
|
||||
link := &transport.Link{Reader: clientReader, Writer: clientWriter}
|
||||
|
||||
if request.Command == protocol.RequestCommandRvs {
|
||||
r, err := h.GetReverse(account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return r.NewMux(ctx, dispatcher.WrapLink(ctx, h.policyManager, h.stats, &transport.Link{Reader: clientReader, Writer: clientWriter}), h.observer)
|
||||
return r.Accept(ctx, dispatcher.WrapLink(ctx, h.policyManager, h.stats, link))
|
||||
}
|
||||
|
||||
if err := dispatch.DispatchLink(
|
||||
ctx, request.Destination(), &transport.Link{
|
||||
Reader: clientReader,
|
||||
Writer: clientWriter,
|
||||
},
|
||||
); err != nil {
|
||||
if request.Command == protocol.RequestCommandMux {
|
||||
worker := multiplex.NewServerWorker(ctx, dispatch.DispatchLink, link)
|
||||
<-worker.WaitClosed()
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := dispatch.DispatchLink(ctx, request.Destination(), link); err != nil {
|
||||
return errors.New("failed to dispatch request").Base(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Reverse struct {
|
||||
tag string
|
||||
picker *reverse.StaticMuxPicker
|
||||
client *mux.ClientManager
|
||||
}
|
||||
|
||||
func (r *Reverse) Tag() string {
|
||||
return r.tag
|
||||
}
|
||||
|
||||
func (r *Reverse) NewMux(ctx context.Context, link *transport.Link, observer features.Feature) error {
|
||||
muxClient, err := mux.NewClientWorker(*link, mux.ClientStrategy{})
|
||||
if err != nil {
|
||||
return errors.New("failed to create mux client worker").Base(err)
|
||||
}
|
||||
worker, err := reverse.NewPortalWorker(muxClient)
|
||||
if err != nil {
|
||||
return errors.New("failed to create portal worker").Base(err)
|
||||
}
|
||||
r.picker.AddWorker(worker)
|
||||
if burstObs, ok := observer.(extension.BurstObservatory); ok {
|
||||
go burstObs.Check([]string{r.Tag()})
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-muxClient.WaitClosed():
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Reverse) Dispatch(ctx context.Context, link *transport.Link) {
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
ob := outbounds[len(outbounds)-1]
|
||||
if ob != nil {
|
||||
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
|
||||
link.Reader = &buf.EndpointOverrideReader{Reader: link.Reader, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
|
||||
link.Writer = &buf.EndpointOverrideWriter{Writer: link.Writer, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
|
||||
}
|
||||
r.client.Dispatch(session.ContextWithIsReverseMux(ctx, true), link)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Reverse) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Reverse) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Reverse) SenderSettings() *serial.TypedMessage {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Reverse) ProxySettings() *serial.TypedMessage {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
)
|
||||
|
||||
// Control intents carry no encoded DATA or caller payload.
|
||||
type carrier struct {
|
||||
sync.RWMutex
|
||||
sessions map[uint16]*Session
|
||||
|
||||
ready map[uint16]*Session // nil is a bounded END for an unknown wire ID
|
||||
unknown int
|
||||
count uint16
|
||||
active int
|
||||
client bool
|
||||
link transport.Link
|
||||
writeMutex sync.Mutex
|
||||
control *sync.Cond
|
||||
ctx context.Context
|
||||
cancel context.CancelCauseFunc
|
||||
timer *time.Timer
|
||||
}
|
||||
|
||||
func newCarrier(parent context.Context, link transport.Link, idle time.Duration, client bool) *carrier {
|
||||
ctx, cancel := context.WithCancelCause(parent)
|
||||
c := &carrier{
|
||||
sessions: make(map[uint16]*Session, 16), link: link, ctx: ctx, cancel: cancel,
|
||||
client: client,
|
||||
}
|
||||
c.control = sync.NewCond(&c.RWMutex)
|
||||
c.ready = make(map[uint16]*Session)
|
||||
context.AfterFunc(c.ctx, func() { common.Interrupt(c.link.Reader) })
|
||||
c.Lock()
|
||||
checkSize, checkCount := c.active, c.count
|
||||
c.timer = time.AfterFunc(idle, func() {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
if c.Closed() {
|
||||
return
|
||||
}
|
||||
if c.active == 0 && checkSize == 0 && c.count == checkCount {
|
||||
c.cancel(nil)
|
||||
return
|
||||
}
|
||||
checkSize, checkCount = c.active, c.count
|
||||
c.timer.Reset(idle)
|
||||
})
|
||||
c.Unlock()
|
||||
context.AfterFunc(c.ctx, c.shutdown)
|
||||
go c.controlLoop()
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *carrier) admitLocked(s *Session) bool {
|
||||
if c.Closed() || s.phase != outputOpen || c.sessions[s.ID] != nil {
|
||||
return false
|
||||
}
|
||||
c.count++
|
||||
c.active++
|
||||
c.invalidateUnknownLocked(s.ID)
|
||||
c.sessions[s.ID] = s
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *carrier) queueReadyLocked(s *Session) {
|
||||
if c.ready[s.ID] != s {
|
||||
c.ready[s.ID] = s
|
||||
c.control.Broadcast()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *carrier) scheduleLocked(s *Session) {
|
||||
if !c.Closed() && c.sessions[s.ID] == s && (s.phase == outputDone || s.packetReady()) {
|
||||
c.queueReadyLocked(s)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *carrier) invalidateUnknownLocked(id uint16) bool {
|
||||
if s, ok := c.ready[id]; ok && s == nil {
|
||||
delete(c.ready, id)
|
||||
c.unknown--
|
||||
c.control.Broadcast()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *carrier) unknownEnd(id uint16) {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
for !c.Closed() {
|
||||
if _, queued := c.ready[id]; queued || c.sessions[id] != nil {
|
||||
return
|
||||
}
|
||||
if c.unknown < 16 {
|
||||
c.ready[id] = nil
|
||||
c.unknown++
|
||||
c.control.Broadcast()
|
||||
return
|
||||
}
|
||||
c.control.Wait()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *carrier) controlLoop() {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
for !c.Closed() {
|
||||
if len(c.ready) == 0 {
|
||||
c.control.Wait()
|
||||
continue
|
||||
}
|
||||
// Advance the iterator under the lock. Physical sends never hold it.
|
||||
for id, selected := range c.ready {
|
||||
c.Unlock()
|
||||
c.writeMutex.Lock()
|
||||
var frames buf.MultiBuffer
|
||||
var err error
|
||||
raw, terminal := c.responseTurn(id, selected)
|
||||
if terminal {
|
||||
frames = endFrame(id, selected != nil && selected.endFailed)
|
||||
} else if len(raw) != 0 {
|
||||
frames, err = selected.encodeBatch(&raw)
|
||||
buf.ReleaseMulti(raw)
|
||||
}
|
||||
err = c.writeAndUnlock(frames, err)
|
||||
c.Lock()
|
||||
if err != nil || c.Closed() {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// No logical lock spans physical I/O or a codec/address callback.
|
||||
func (c *carrier) writeAndUnlock(frames buf.MultiBuffer, err error) error {
|
||||
if err != nil || c.Closed() {
|
||||
buf.ReleaseMulti(frames)
|
||||
} else if len(frames) != 0 {
|
||||
if r, ok := c.link.Reader.(*responseReader); ok {
|
||||
r.activity.Update()
|
||||
}
|
||||
err = c.link.Writer.WriteMultiBuffer(frames)
|
||||
}
|
||||
if err != nil {
|
||||
c.cancel(err)
|
||||
}
|
||||
c.writeMutex.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *carrier) ActiveConnections() uint32 {
|
||||
c.RLock()
|
||||
defer c.RUnlock()
|
||||
return uint32(c.active)
|
||||
}
|
||||
func (c *carrier) Closed() bool { return c.ctx.Err() != nil }
|
||||
func (c *carrier) WaitClosed() <-chan struct{} { return c.ctx.Done() }
|
||||
|
||||
// Err reports the first close cause, excluding normal cancellation.
|
||||
func (c *carrier) Err() error {
|
||||
err := context.Cause(c.ctx)
|
||||
if err == context.Canceled {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *carrier) Close() error {
|
||||
c.cancel(nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *carrier) shutdown() {
|
||||
c.Lock()
|
||||
c.timer.Stop()
|
||||
c.ready = nil
|
||||
c.control.Broadcast()
|
||||
sessions := c.sessions
|
||||
c.sessions, c.active = nil, 0
|
||||
c.Unlock()
|
||||
for _, s := range sessions {
|
||||
s.abort()
|
||||
}
|
||||
common.Interrupt(c.link.Writer)
|
||||
}
|
||||
|
||||
func (c *carrier) readFrame(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader, accept func(context.Context, *FrameMetadata, *buf.BufferedReader) error) error {
|
||||
var target *Session
|
||||
data := meta.Option.Has(OptionData)
|
||||
switch meta.SessionStatus {
|
||||
case SessionStatusNew:
|
||||
if accept != nil {
|
||||
return accept(session.ContextWithIsReverseMux(ctx, false), meta, reader)
|
||||
}
|
||||
case SessionStatusKeep:
|
||||
if !data {
|
||||
return nil
|
||||
}
|
||||
c.RLock()
|
||||
s, found := c.sessions[meta.SessionID]
|
||||
if found && s.phase == outputOpen {
|
||||
target = s
|
||||
}
|
||||
c.RUnlock()
|
||||
if !found && !c.client {
|
||||
c.unknownEnd(meta.SessionID)
|
||||
}
|
||||
case SessionStatusEnd:
|
||||
c.RLock()
|
||||
s := c.sessions[meta.SessionID]
|
||||
c.RUnlock()
|
||||
if s != nil {
|
||||
s.abort()
|
||||
}
|
||||
case SessionStatusKeepAlive:
|
||||
default:
|
||||
return errors.New("unknown status: ", meta.SessionStatus)
|
||||
}
|
||||
if data {
|
||||
return copyFramePayload(reader, target, meta.Target)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *carrier) run(ctx context.Context, accept func(context.Context, *FrameMetadata, *buf.BufferedReader) error) {
|
||||
var err error
|
||||
defer func() { c.cancel(err) }()
|
||||
reader := &buf.BufferedReader{Reader: c.link.Reader}
|
||||
defer func() { buf.ReleaseMulti(reader.Buffer) }()
|
||||
for !c.Closed() {
|
||||
var meta FrameMetadata
|
||||
err = meta.Unmarshal(reader, session.IsReverseMuxFromContext(ctx))
|
||||
if errors.Cause(err) == io.EOF {
|
||||
err = nil // clean EOF before the next metadata prefix
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
err = frameReadError(c.readFrame(ctx, &meta, reader, accept))
|
||||
}
|
||||
if err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to process multiplex frame")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/proxy"
|
||||
"github.com/xtls/xray-core/proxy/vless"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
)
|
||||
|
||||
// NormalizeConfig validates the pool settings and returns nil when both pools are off.
|
||||
func NormalizeConfig(config *vless.Multiplex) (*vless.Multiplex, error) {
|
||||
if config.GetConcurrency() < 0 || config.GetXudpConcurrency() < 0 {
|
||||
return nil, errors.New(`multiplex "concurrency" and "xudpConcurrency" must be non-negative`)
|
||||
}
|
||||
switch config.GetXudpProxyUDP443() {
|
||||
case "", "reject", "allow", "skip":
|
||||
default:
|
||||
return nil, errors.New(`unknown "xudpProxyUDP443": `, config.GetXudpProxyUDP443())
|
||||
}
|
||||
if config.GetConcurrency() == 0 && config.GetXudpConcurrency() == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// Client owns the logical stream pools.
|
||||
type Client struct {
|
||||
config *vless.Multiplex
|
||||
tcp *Pool
|
||||
udp *Pool
|
||||
}
|
||||
|
||||
func NewClient(ctx context.Context, config *vless.Multiplex, network string, open func(context.Context) (context.Context, *transport.Link, error)) *Client {
|
||||
c := &Client{config: config}
|
||||
pool := func(concurrency int32) *Pool {
|
||||
return NewPool(ctx, ClientStrategy{MaxConcurrency: uint32(concurrency), MaxConnection: 1024}, open)
|
||||
}
|
||||
if concurrency := config.GetConcurrency(); concurrency > 0 {
|
||||
if network == "xdrive" {
|
||||
concurrency = max(concurrency, 128)
|
||||
}
|
||||
c.tcp = pool(concurrency)
|
||||
}
|
||||
if concurrency := config.GetXudpConcurrency(); concurrency > 0 {
|
||||
c.udp = pool(concurrency)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *Client) Dispatch(ctx context.Context, link *transport.Link) (bool, error) {
|
||||
if c == nil {
|
||||
return false, nil
|
||||
}
|
||||
pool := c.tcp
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
target := outbounds[len(outbounds)-1].Target
|
||||
if target.Network == net.Network_UDP && c.udp != nil {
|
||||
pool = c.udp
|
||||
}
|
||||
if pool == nil {
|
||||
return false, nil
|
||||
}
|
||||
if target.Network == net.Network_UDP && target.Port == 443 {
|
||||
switch c.config.GetXudpProxyUDP443() {
|
||||
case "reject", "":
|
||||
proxy.DropUDP(ctx, link.Reader)
|
||||
return true, errors.New("XUDP rejected UDP/443 traffic")
|
||||
case "skip":
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
return true, Dispatch(ctx, link, pool.Admit)
|
||||
}
|
||||
|
||||
type deferredWriterClose struct{}
|
||||
|
||||
func (deferredWriterClose) Error() string { return "defer link writer close" }
|
||||
func (deferredWriterClose) DeferWriterClose() bool { return true }
|
||||
|
||||
// Dispatch runs a logical child. The caller owns the application endpoints.
|
||||
func Dispatch(ctx context.Context, link *transport.Link, admit func(context.Context, *Session) error, finish ...func(context.Context)) error {
|
||||
s := NewSession(ctx, link)
|
||||
if err := admit(ctx, s); err != nil {
|
||||
return err
|
||||
}
|
||||
go fetchInput(ctx, s)
|
||||
callerDone := ctx.Done()
|
||||
if session.TimeoutOnlyFromContext(ctx) {
|
||||
callerDone = nil
|
||||
}
|
||||
select {
|
||||
case <-callerDone:
|
||||
s.Close()
|
||||
case <-s.WaitClosed():
|
||||
}
|
||||
// The session is sealed. Only a response write already in progress can
|
||||
// still hold the application writer.
|
||||
writingResponse := s.writingResponse.Load()
|
||||
if len(finish) != 0 {
|
||||
if writingResponse {
|
||||
go finish[0](s.parent.ctx)
|
||||
} else {
|
||||
finish[0](s.parent.ctx)
|
||||
}
|
||||
} else if writingResponse {
|
||||
return deferredWriterClose{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Pool serializes unpublished opening with cancelable admission.
|
||||
type Pool struct {
|
||||
ctx context.Context
|
||||
access sync.Mutex
|
||||
opening chan struct{}
|
||||
workers []*ClientWorker
|
||||
strategy ClientStrategy
|
||||
open func(context.Context) (context.Context, *transport.Link, error)
|
||||
}
|
||||
|
||||
// NewPool borrows ctx; open must return a context derived from its input context.
|
||||
func NewPool(ctx context.Context, strategy ClientStrategy, open func(context.Context) (context.Context, *transport.Link, error)) *Pool {
|
||||
return &Pool{ctx: ctx, strategy: strategy, open: open}
|
||||
}
|
||||
|
||||
func (p *Pool) Admit(ctx context.Context, s *Session) error {
|
||||
p.access.Lock()
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
p.access.Unlock()
|
||||
return err
|
||||
}
|
||||
if p.ctx.Err() != nil {
|
||||
p.access.Unlock()
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
for _, worker := range p.workers {
|
||||
if worker.TryAdmit(ctx, s) {
|
||||
p.access.Unlock()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if p.opening == nil {
|
||||
p.opening = make(chan struct{})
|
||||
break
|
||||
}
|
||||
wait := p.opening
|
||||
p.access.Unlock()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-p.ctx.Done():
|
||||
return io.ErrClosedPipe
|
||||
case <-wait:
|
||||
}
|
||||
p.access.Lock()
|
||||
}
|
||||
p.access.Unlock()
|
||||
opening, cancel := context.WithCancel(p.ctx)
|
||||
stopCaller := context.AfterFunc(ctx, cancel)
|
||||
physicalCtx, physicalLink, err := p.open(opening)
|
||||
if !stopCaller() && err == nil {
|
||||
err = context.Canceled
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
err = ctx.Err()
|
||||
}
|
||||
if p.ctx.Err() != nil {
|
||||
err = io.ErrClosedPipe
|
||||
}
|
||||
p.access.Lock()
|
||||
close(p.opening)
|
||||
p.opening = nil
|
||||
var worker *ClientWorker
|
||||
if err == nil {
|
||||
worker = NewClientWorker(physicalCtx, *physicalLink, p.strategy)
|
||||
if !worker.TryAdmit(ctx, s) {
|
||||
err = ctx.Err()
|
||||
if err == nil {
|
||||
err = errors.New("unable to admit multiplex child")
|
||||
}
|
||||
} else {
|
||||
p.workers = append(p.workers, worker)
|
||||
}
|
||||
}
|
||||
p.access.Unlock()
|
||||
if err != nil {
|
||||
cancel()
|
||||
if physicalLink != nil {
|
||||
common.Interrupt(physicalLink.Reader)
|
||||
common.Interrupt(physicalLink.Writer)
|
||||
}
|
||||
return err
|
||||
}
|
||||
context.AfterFunc(worker.ctx, func() {
|
||||
cancel()
|
||||
p.access.Lock()
|
||||
p.workers = slices.DeleteFunc(p.workers, func(current *ClientWorker) bool { return current == worker })
|
||||
p.access.Unlock()
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
type ClientStrategy struct {
|
||||
MaxConcurrency uint32
|
||||
MaxConnection uint32
|
||||
}
|
||||
|
||||
type ClientWorker struct {
|
||||
*carrier
|
||||
strategy ClientStrategy
|
||||
}
|
||||
|
||||
func NewClientWorker(ctx context.Context, stream transport.Link, strategy ClientStrategy) *ClientWorker {
|
||||
c := &ClientWorker{carrier: newCarrier(ctx, stream, 16*time.Second, true), strategy: strategy}
|
||||
go c.run(context.Background(), nil)
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *ClientWorker) TotalConnections() uint32 {
|
||||
c.RLock()
|
||||
defer c.RUnlock()
|
||||
return uint32(c.count)
|
||||
}
|
||||
|
||||
func writeFirstPayload(s *Session) error {
|
||||
err := buf.CopyOnceTimeout(s.input, s, time.Millisecond*100)
|
||||
if err == buf.ErrNotTimeoutReader || err == buf.ErrReadTimeout {
|
||||
return s.WriteMultiBuffer(nil)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func fetchInput(ctx context.Context, s *Session) {
|
||||
var err error
|
||||
defer func() { s.CloseWithError(err) }()
|
||||
errors.LogInfo(ctx, "dispatching request to ", s.target)
|
||||
if err = writeFirstPayload(s); err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to write first payload")
|
||||
return
|
||||
}
|
||||
if err = buf.Copy(s.input, s); err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to fetch all input")
|
||||
}
|
||||
}
|
||||
|
||||
// TryAdmit publishes this prepared child without input or foreign cleanup.
|
||||
func (m *ClientWorker) TryAdmit(ctx context.Context, s *Session) bool {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
if ctx.Err() != nil || m.Closed() || m.count == 65535 ||
|
||||
(m.strategy.MaxConcurrency > 0 && m.active >= int(m.strategy.MaxConcurrency)) ||
|
||||
(m.strategy.MaxConnection > 0 && uint32(m.count) >= m.strategy.MaxConnection) {
|
||||
return false
|
||||
}
|
||||
s.parent, s.ID, s.phase, s.done = m.carrier, m.count+1, outputOpen, make(chan struct{})
|
||||
return m.admitLocked(s)
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/proxy/vless"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
func TestClientUDP443Policy(t *testing.T) {
|
||||
ctx := session.ContextWithOutbounds(t.Context(), []*session.Outbound{{
|
||||
Target: net.UDPDestination(net.LocalHostIP, 443),
|
||||
}})
|
||||
for _, policy := range []string{"reject", "skip"} {
|
||||
t.Run(policy, func(t *testing.T) {
|
||||
opened := false
|
||||
client := NewClient(ctx, &vless.Multiplex{Concurrency: 1, XudpProxyUDP443: policy}, "", func(context.Context) (context.Context, *transport.Link, error) {
|
||||
opened = true
|
||||
return nil, nil, context.Canceled
|
||||
})
|
||||
r, w := pipe.New()
|
||||
common.Close(w)
|
||||
handled, err := client.Dispatch(ctx, &transport.Link{Reader: r})
|
||||
wantRejected := policy == "reject"
|
||||
if opened || handled != wantRejected || (err != nil) != wantRejected {
|
||||
t.Fatalf("Dispatch() = (%t, %v), opened carrier = %t, want rejected = %t without opening a carrier", handled, err, opened, wantRejected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientWithoutPoolLeavesUDP443ToOutbound(t *testing.T) {
|
||||
ctx := session.ContextWithOutbounds(t.Context(), []*session.Outbound{{
|
||||
Target: net.UDPDestination(net.LocalHostIP, 443),
|
||||
}})
|
||||
client := NewClient(ctx, &vless.Multiplex{XudpProxyUDP443: "reject"}, "", nil)
|
||||
if handled, err := client.Dispatch(ctx, &transport.Link{}); handled || err != nil {
|
||||
t.Fatalf("Dispatch without a pool = (%t, %v), want fallback", handled, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolFailure(t *testing.T) {
|
||||
calls := 0
|
||||
owner, stop := context.WithCancel(context.Background())
|
||||
defer stop()
|
||||
pool := NewPool(owner, ClientStrategy{}, func(context.Context) (context.Context, *transport.Link, error) {
|
||||
calls++
|
||||
return nil, nil, errors.New("test")
|
||||
})
|
||||
ctx := testOutboundContext()
|
||||
s := NewSession(ctx, &transport.Link{Writer: buf.Discard})
|
||||
if err := pool.Admit(ctx, s); err == nil || calls != 1 {
|
||||
t.Fatalf("expected one failed opening, got %d calls and %v", calls, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientWorkerEOF(t *testing.T) {
|
||||
reader, writer := pipe.New(pipe.WithoutSizeLimit())
|
||||
common.Must(writer.Close())
|
||||
|
||||
worker := NewClientWorker(context.Background(), transport.Link{Reader: reader, Writer: writer}, ClientStrategy{})
|
||||
|
||||
select {
|
||||
case <-worker.WaitClosed():
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("worker did not close after EOF")
|
||||
}
|
||||
|
||||
ctx := testOutboundContext()
|
||||
f := worker.TryAdmit(ctx, NewSession(ctx, &transport.Link{Writer: buf.Discard}))
|
||||
if f {
|
||||
t.Error("expected failed dispatching, but actually not")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientWorkerClose(t *testing.T) {
|
||||
r1, w1 := pipe.New(pipe.WithoutSizeLimit())
|
||||
r2, w2 := pipe.New(pipe.WithoutSizeLimit())
|
||||
links := []*transport.Link{{Reader: r1, Writer: w1}, {Reader: r2, Writer: w2}}
|
||||
owner, stop := context.WithCancel(context.Background())
|
||||
defer stop()
|
||||
pool := NewPool(owner, ClientStrategy{MaxConcurrency: 4, MaxConnection: 4}, func(ctx context.Context) (context.Context, *transport.Link, error) {
|
||||
if len(links) == 0 {
|
||||
return nil, nil, errors.New("unexpected opening")
|
||||
}
|
||||
link := links[0]
|
||||
links = links[1:]
|
||||
return ctx, link, nil
|
||||
})
|
||||
ctx := testOutboundContext()
|
||||
worker1 := NewSession(ctx, &transport.Link{Writer: buf.Discard})
|
||||
common.Must(pool.Admit(ctx, worker1))
|
||||
tr1, tw1 := pipe.New(pipe.WithoutSizeLimit())
|
||||
ctx1 := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80)}})
|
||||
child1 := NewSession(ctx1, &transport.Link{Reader: tr1, Writer: tw1})
|
||||
common.Must(pool.Admit(ctx1, child1))
|
||||
go fetchInput(ctx1, child1)
|
||||
defer tw1.Close()
|
||||
common.Must(w1.Close())
|
||||
select {
|
||||
case <-worker1.parent.WaitClosed():
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("first worker did not close")
|
||||
}
|
||||
tr2, tw2 := pipe.New(pipe.WithoutSizeLimit())
|
||||
ctx2 := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80)}})
|
||||
child2 := NewSession(ctx2, &transport.Link{Reader: tr2, Writer: tw2})
|
||||
common.Must(pool.Admit(ctx2, child2))
|
||||
go fetchInput(ctx2, child2)
|
||||
defer tw2.Close()
|
||||
common.Must(w2.Close())
|
||||
}
|
||||
|
||||
func TestClientWorkerUDPSource(t *testing.T) {
|
||||
downR, downW := pipe.New(pipe.WithoutSizeLimit())
|
||||
upR, upW := pipe.New(pipe.WithoutSizeLimit())
|
||||
worker := NewClientWorker(context.Background(), transport.Link{Reader: downR, Writer: upW}, ClientStrategy{})
|
||||
t.Cleanup(func() {
|
||||
worker.Close()
|
||||
downW.Close()
|
||||
upR.Interrupt()
|
||||
})
|
||||
|
||||
inR, inW := pipe.New(pipe.WithoutSizeLimit())
|
||||
outR, outW := pipe.New(pipe.WithoutSizeLimit())
|
||||
t.Cleanup(func() {
|
||||
inW.Close()
|
||||
outR.Interrupt()
|
||||
})
|
||||
ctx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
|
||||
Target: net.UDPDestination(net.ParseAddress("8.8.8.8"), 53),
|
||||
}})
|
||||
child := NewSession(ctx, &transport.Link{Reader: inR, Writer: outW})
|
||||
if !worker.TryAdmit(ctx, child) {
|
||||
t.Fatal("failed to dispatch")
|
||||
}
|
||||
go fetchInput(ctx, child)
|
||||
b := buf.New()
|
||||
b.WriteString("query")
|
||||
common.Must(inW.WriteMultiBuffer(buf.MultiBuffer{b}))
|
||||
mb, err := upR.ReadMultiBuffer() // New frame, the session is UDP from now on
|
||||
common.Must(err)
|
||||
buf.ReleaseMulti(mb)
|
||||
|
||||
srcs := []net.Destination{
|
||||
net.UDPDestination(net.ParseAddress("1.1.1.1"), 1111),
|
||||
net.UDPDestination(net.DomainAddress("example.com"), 2222),
|
||||
net.UDPDestination(net.ParseAddress("3.3.3.3"), 3333),
|
||||
}
|
||||
response := &Session{ID: 1, target: net.Destination{Network: net.Network_UDP}}
|
||||
var got buf.MultiBuffer
|
||||
defer func() { buf.ReleaseMulti(got) }()
|
||||
for i := range srcs {
|
||||
b := buf.New()
|
||||
b.WriteString("reply")
|
||||
b.UDP = &srcs[i]
|
||||
data := buf.MultiBuffer{b}
|
||||
frames, err := response.encodeBatch(&data)
|
||||
buf.ReleaseMulti(data)
|
||||
if err != nil {
|
||||
buf.ReleaseMulti(frames)
|
||||
t.Fatal(err)
|
||||
}
|
||||
common.Must(downW.WriteMultiBuffer(frames))
|
||||
// keep earlier replies around while the next frame is parsed
|
||||
mb, err := outR.ReadMultiBuffer()
|
||||
common.Must(err)
|
||||
got = append(got, mb...)
|
||||
}
|
||||
if len(got) != len(srcs) {
|
||||
t.Fatalf("received %d replies, want %d", len(got), len(srcs))
|
||||
}
|
||||
for i, b := range got {
|
||||
if string(b.Bytes()) != "reply" {
|
||||
t.Errorf("reply %d: payload = %q", i, b.Bytes())
|
||||
}
|
||||
if b.UDP == nil || *b.UDP != srcs[i] {
|
||||
t.Errorf("reply %d: source = %v, want %v", i, b.UDP, srcs[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testOutboundContext() context.Context {
|
||||
return session.ContextWithOutbounds(context.Background(), []*session.Outbound{{Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80)}})
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/signal"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
)
|
||||
|
||||
type responseReader struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
activity *signal.ActivityTimer
|
||||
open func() (buf.Reader, error)
|
||||
body buf.Reader
|
||||
terminal error
|
||||
}
|
||||
|
||||
func (r *responseReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if r.open != nil {
|
||||
r.body, r.terminal = r.open()
|
||||
r.open = nil
|
||||
}
|
||||
for r.terminal == nil {
|
||||
data, err := r.body.ReadMultiBuffer()
|
||||
r.terminal = err
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
buf.ReleaseMulti(data)
|
||||
return nil, err
|
||||
}
|
||||
if !data.IsEmpty() {
|
||||
r.activity.Update()
|
||||
return data, nil
|
||||
}
|
||||
buf.ReleaseMulti(data)
|
||||
}
|
||||
return nil, r.terminal
|
||||
}
|
||||
|
||||
func (r *responseReader) Interrupt() {
|
||||
r.cancel()
|
||||
r.activity.SetTimeout(0)
|
||||
}
|
||||
|
||||
func OpenLink(ctx context.Context, cancel context.CancelFunc, writer buf.Writer, activity *signal.ActivityTimer, openResponse func() (buf.Reader, error)) (*transport.Link, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
cancel()
|
||||
activity.SetTimeout(0)
|
||||
return nil, err
|
||||
}
|
||||
return &transport.Link{Reader: &responseReader{ctx: ctx, cancel: cancel, activity: activity, open: openResponse}, Writer: writer}, nil
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package mux
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
@@ -9,9 +9,8 @@ import (
|
||||
"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/serial"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/xudp"
|
||||
)
|
||||
|
||||
type SessionStatus byte
|
||||
@@ -35,12 +34,7 @@ const (
|
||||
TargetNetworkUDP TargetNetwork = 0x02
|
||||
)
|
||||
|
||||
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(),
|
||||
)
|
||||
var addrParser = xudp.AddrParser
|
||||
|
||||
/*
|
||||
Frame format
|
||||
@@ -85,16 +79,13 @@ func (f FrameMetadata) WriteTo(b *buf.Buffer) error {
|
||||
return err
|
||||
}
|
||||
if f.Inbound != nil {
|
||||
if f.Inbound.Source.Network == net.Network_TCP || f.Inbound.Source.Network == net.Network_UDP {
|
||||
common.Must(b.WriteByte(byte(f.Inbound.Source.Network - 1)))
|
||||
if err := addrParser.WriteAddressPort(b, f.Inbound.Source.Address, f.Inbound.Source.Port); err != nil {
|
||||
return err
|
||||
for _, dst := range [...]net.Destination{f.Inbound.Source, f.Inbound.Local} {
|
||||
if dst.Network != net.Network_TCP && dst.Network != net.Network_UDP {
|
||||
break
|
||||
}
|
||||
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
|
||||
}
|
||||
common.Must(b.WriteByte(byte(dst.Network - 1)))
|
||||
if err := addrParser.WriteAddressPort(b, dst.Address, dst.Port); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else if b.UDP != nil { // make sure it's user's proxy request
|
||||
@@ -112,21 +103,12 @@ func (f FrameMetadata) WriteTo(b *buf.Buffer) error {
|
||||
|
||||
// Unmarshal reads FrameMetadata from the given reader.
|
||||
func (f *FrameMetadata) Unmarshal(reader io.Reader, readSourceAndLocal bool) error {
|
||||
metaLen, err := serial.ReadUint16(reader)
|
||||
b, err := readBlock(reader, 512, "invalid metalen ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if metaLen > 512 {
|
||||
return errors.New("invalid metalen ", metaLen)
|
||||
}
|
||||
|
||||
b := buf.New()
|
||||
defer b.Release()
|
||||
|
||||
if _, err := b.ReadFullFrom(reader, int32(metaLen)); err != nil {
|
||||
return err
|
||||
}
|
||||
return f.UnmarshalFromBuffer(b, readSourceAndLocal)
|
||||
return frameReadError(f.UnmarshalFromBuffer(b, readSourceAndLocal))
|
||||
}
|
||||
|
||||
// UnmarshalFromBuffer reads a FrameMetadata from the given buffer.
|
||||
@@ -146,73 +128,29 @@ func (f *FrameMetadata) UnmarshalFromBuffer(b *buf.Buffer, readSourceAndLocal bo
|
||||
if b.Len() < 8 {
|
||||
return errors.New("insufficient buffer: ", b.Len())
|
||||
}
|
||||
network := TargetNetwork(b.Byte(4))
|
||||
b.Advance(5)
|
||||
|
||||
addr, port, err := addrParser.ReadAddressPort(nil, b)
|
||||
b.Advance(4)
|
||||
target, err := readDestination(b, "")
|
||||
if err != nil {
|
||||
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)
|
||||
return err
|
||||
}
|
||||
f.Target = target
|
||||
}
|
||||
|
||||
if f.SessionStatus == SessionStatusNew && readSourceAndLocal {
|
||||
f.Inbound = &session.Inbound{}
|
||||
|
||||
if b.Len() == 0 {
|
||||
return nil // for heartbeat, etc.
|
||||
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
|
||||
break
|
||||
}
|
||||
parsed, err := readDestination(b, [...]string{"reading source: ", "reading local: "}[i])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*dst = parsed
|
||||
}
|
||||
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 {
|
||||
return errors.New("reading source: failed to parse address and port").Base(err)
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
// Application data is essential, to test whether the pipe is closed.
|
||||
if f.SessionStatus == SessionStatusNew && f.Option.Has(OptionData) &&
|
||||
f.Target.Network == net.Network_UDP && b.Len() >= 8 {
|
||||
copy(f.GlobalID[:], b.Bytes())
|
||||
@@ -220,3 +158,20 @@ func (f *FrameMetadata) UnmarshalFromBuffer(b *buf.Buffer, readSourceAndLocal bo
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package multiplex_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"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/session"
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
)
|
||||
|
||||
func TestFrameEndpoints(t *testing.T) {
|
||||
target := net.TCPDestination(net.DomainAddress("example.test"), 443)
|
||||
src := net.TCPDestination(net.LocalHostIP, 2053)
|
||||
local := net.UDPDestination(net.ParseAddress("::1"), 5060)
|
||||
// Wire bytes from the codec before consolidating its endpoint decoder.
|
||||
const targetBytes = "000701000101bb020c6578616d706c652e74657374"
|
||||
const sourceBytes = "010805017f000001"
|
||||
const localBytes = "0213c40300000000000000000000000000000001"
|
||||
for _, tc := range []struct {
|
||||
name, wire string
|
||||
input session.Inbound
|
||||
}{
|
||||
{"heartbeat", "0015" + targetBytes, session.Inbound{}},
|
||||
{"source-only", "001d" + targetBytes + sourceBytes, session.Inbound{Source: src}},
|
||||
{"both", "0031" + targetBytes + sourceBytes + localBytes, session.Inbound{Source: src, Local: local}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
frame := multiplex.FrameMetadata{
|
||||
Target: target, SessionID: 7, SessionStatus: multiplex.SessionStatusNew, Inbound: &tc.input,
|
||||
}
|
||||
wire := buf.New()
|
||||
defer wire.Release()
|
||||
if err := frame.WriteTo(wire); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := hex.EncodeToString(wire.Bytes()); got != tc.wire {
|
||||
t.Fatalf("metadata = %s, want %s", got, tc.wire)
|
||||
}
|
||||
reader := io.MultiReader(bytes.NewReader(wire.Bytes()), bytes.NewReader([]byte("payload")))
|
||||
var decoded multiplex.FrameMetadata
|
||||
if err := decoded.Unmarshal(reader, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if decoded.Inbound == nil || decoded.Target != target ||
|
||||
decoded.Inbound.Source != tc.input.Source || decoded.Inbound.Local != tc.input.Local {
|
||||
t.Fatalf("unexpected endpoint metadata: %+v", decoded)
|
||||
}
|
||||
if rest, err := io.ReadAll(reader); err != nil || string(rest) != "payload" {
|
||||
t.Fatalf("payload was consumed with metadata: %q, err = %v", rest, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkFrameWrite(b *testing.B) {
|
||||
frame := multiplex.FrameMetadata{
|
||||
Target: net.TCPDestination(net.DomainAddress("www.example.com"), net.Port(80)),
|
||||
SessionID: 1,
|
||||
SessionStatus: multiplex.SessionStatusNew,
|
||||
}
|
||||
writer := buf.New()
|
||||
defer writer.Release()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
common.Must(frame.WriteTo(writer))
|
||||
writer.Clear()
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package mux_test
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"io"
|
||||
@@ -7,9 +7,8 @@ import (
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"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/crypto"
|
||||
"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/transport/pipe"
|
||||
)
|
||||
@@ -33,31 +32,38 @@ func TestReaderWriter(t *testing.T) {
|
||||
pReader, pWriter := pipe.New(pipe.WithSizeLimit(1024))
|
||||
|
||||
dest := net.TCPDestination(net.DomainAddress("example.com"), 80)
|
||||
writer := NewWriter(1, dest, pWriter, protocol.TransferTypeStream, [8]byte{}, &session.Inbound{})
|
||||
s1 := &Session{ID: 1, target: dest, inbound: &session.Inbound{}, first: true}
|
||||
|
||||
dest2 := net.TCPDestination(net.LocalHostIP, 443)
|
||||
writer2 := NewWriter(2, dest2, pWriter, protocol.TransferTypeStream, [8]byte{}, &session.Inbound{})
|
||||
s2 := &Session{ID: 2, target: dest2, inbound: &session.Inbound{}, first: true}
|
||||
|
||||
dest3 := net.TCPDestination(net.LocalHostIPv6, 18374)
|
||||
writer3 := NewWriter(3, dest3, pWriter, protocol.TransferTypeStream, [8]byte{}, &session.Inbound{})
|
||||
s3 := &Session{ID: 3, target: dest3, inbound: &session.Inbound{}, first: true}
|
||||
|
||||
writePayload := func(writer *Writer, payload ...byte) error {
|
||||
writePayload := func(s *Session, payload ...byte) error {
|
||||
b := buf.New()
|
||||
b.Write(payload)
|
||||
return writer.WriteMultiBuffer(buf.MultiBuffer{b})
|
||||
data := 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(writer, 'a', 'b', 'c', 'd'))
|
||||
common.Must(writePayload(writer2))
|
||||
common.Must(writePayload(s1, 'a', 'b', 'c', 'd'))
|
||||
common.Must(writePayload(s2))
|
||||
|
||||
common.Must(writePayload(writer, 'e', 'f', 'g', 'h'))
|
||||
common.Must(writePayload(writer3, 'x'))
|
||||
common.Must(writePayload(s1, 'e', 'f', 'g', 'h'))
|
||||
common.Must(writePayload(s3, 'x'))
|
||||
|
||||
writer.Close()
|
||||
writer3.Close()
|
||||
common.Must(pWriter.WriteMultiBuffer(endFrame(s1.ID, false)))
|
||||
common.Must(pWriter.WriteMultiBuffer(endFrame(s3.ID, false)))
|
||||
|
||||
common.Must(writePayload(writer2, 'y'))
|
||||
writer2.Close()
|
||||
common.Must(writePayload(s2, 'y'))
|
||||
common.Must(pWriter.WriteMultiBuffer(endFrame(s2.ID, false)))
|
||||
|
||||
bytesReader := &buf.BufferedReader{Reader: pReader}
|
||||
|
||||
@@ -73,7 +79,7 @@ func TestReaderWriter(t *testing.T) {
|
||||
t.Error("metadata: ", r)
|
||||
}
|
||||
|
||||
data, err := readAll(NewStreamReader(bytesReader))
|
||||
data, err := readAll(crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, bytesReader, 1))
|
||||
common.Must(err)
|
||||
if s := data.String(); s != "abcd" {
|
||||
t.Error("data: ", s)
|
||||
@@ -104,7 +110,7 @@ func TestReaderWriter(t *testing.T) {
|
||||
t.Error("meta: ", r)
|
||||
}
|
||||
|
||||
data, err := readAll(NewStreamReader(bytesReader))
|
||||
data, err := readAll(crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, bytesReader, 1))
|
||||
common.Must(err)
|
||||
if s := data.String(); s != "efgh" {
|
||||
t.Error("data: ", s)
|
||||
@@ -123,7 +129,7 @@ func TestReaderWriter(t *testing.T) {
|
||||
t.Error("meta: ", r)
|
||||
}
|
||||
|
||||
data, err := readAll(NewStreamReader(bytesReader))
|
||||
data, err := readAll(crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, bytesReader, 1))
|
||||
common.Must(err)
|
||||
if s := data.String(); s != "x" {
|
||||
t.Error("data: ", s)
|
||||
@@ -165,7 +171,7 @@ func TestReaderWriter(t *testing.T) {
|
||||
t.Error("meta: ", r)
|
||||
}
|
||||
|
||||
data, err := readAll(NewStreamReader(bytesReader))
|
||||
data, err := readAll(crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, bytesReader, 1))
|
||||
common.Must(err)
|
||||
if s := data.String(); s != "y" {
|
||||
t.Error("data: ", s)
|
||||
@@ -0,0 +1,87 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"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/serial"
|
||||
)
|
||||
|
||||
// frameReadError distinguishes truncation inside a frame from EOF between frames.
|
||||
func frameReadError(err error) error {
|
||||
if errors.Cause(err) == io.EOF {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// readBlock reads one length-prefixed frame component without retaining a partial buffer.
|
||||
func readBlock(reader io.Reader, limit uint16, oversized string) (*buf.Buffer, error) {
|
||||
size, err := serial.ReadUint16(reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if size > limit {
|
||||
return nil, errors.New(oversized, size)
|
||||
}
|
||||
b := buf.New()
|
||||
if _, err := b.ReadFullFrom(reader, int32(size)); err != nil {
|
||||
b.Release()
|
||||
return nil, frameReadError(err)
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// readPacket reads one complete packet; its destination belongs to the buffer.
|
||||
func readPacket(reader io.Reader, dest net.Destination) (buf.MultiBuffer, error) {
|
||||
b, err := readBlock(reader, buf.Size, "packet size too large: ")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if dest.Network == net.Network_UDP {
|
||||
b.UDP = &dest
|
||||
}
|
||||
return buf.MultiBuffer{b}, nil
|
||||
}
|
||||
|
||||
// copyFramePayload publishes stream data as it arrives and keeps packets whole.
|
||||
// A closed child discards the remainder without crossing the frame boundary.
|
||||
func copyFramePayload(reader *buf.BufferedReader, s *Session, dest net.Destination) (err error) {
|
||||
packet := s != nil && s.target.Network == net.Network_UDP
|
||||
var left int32
|
||||
if !packet {
|
||||
size, sizeErr := serial.ReadUint16(reader)
|
||||
if sizeErr != nil {
|
||||
return sizeErr
|
||||
}
|
||||
left = int32(size)
|
||||
}
|
||||
for packet || left > 0 {
|
||||
var mb buf.MultiBuffer
|
||||
if packet {
|
||||
mb, err = readPacket(reader, dest)
|
||||
} else {
|
||||
mb, err = reader.ReadAtMost(left)
|
||||
left -= mb.Len()
|
||||
// Coalesce cached pieces without reading more from the transport.
|
||||
for s != nil && left > 0 && reader.BufferedBytes() > 0 {
|
||||
var part buf.MultiBuffer
|
||||
part, err = reader.ReadAtMost(left)
|
||||
left -= part.Len()
|
||||
mb = append(mb, part...)
|
||||
}
|
||||
}
|
||||
if s == nil || mb.IsEmpty() {
|
||||
buf.ReleaseMulti(mb)
|
||||
} else if werr := s.writePayload(mb); werr != nil {
|
||||
s.Interrupt()
|
||||
s = nil
|
||||
}
|
||||
if packet || err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"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/session"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
)
|
||||
|
||||
type ServerWorker struct {
|
||||
*carrier
|
||||
dispatch func(context.Context, net.Destination, *transport.Link) error
|
||||
}
|
||||
|
||||
func NewServerWorker(ctx context.Context, dispatch func(context.Context, net.Destination, *transport.Link) error, link *transport.Link) *ServerWorker {
|
||||
w := &ServerWorker{carrier: newCarrier(ctx, *link, 60*time.Second, false), dispatch: dispatch}
|
||||
go w.run(ctx, w.handleStatusNew)
|
||||
return w
|
||||
}
|
||||
|
||||
// A non-nil dispatch return rejects admission; accepted backend failures use the link.
|
||||
func (w *ServerWorker) dispatchFlow(ctx context.Context, dest net.Destination, flow *inboundFlow, output buf.Writer) {
|
||||
if err := w.dispatch(ctx, dest, &transport.Link{Reader: flow, Writer: output}); err != nil {
|
||||
if flow.GlobalID != [8]byte{} {
|
||||
XUDPManager.Lock()
|
||||
if XUDPManager.Map[flow.GlobalID] == flow {
|
||||
delete(XUDPManager.Map, flow.GlobalID)
|
||||
}
|
||||
XUDPManager.Unlock()
|
||||
}
|
||||
w.cancel(err)
|
||||
flow.Interrupt()
|
||||
flow.finish(true)
|
||||
errors.LogInfoInner(ctx, err, "failed to dispatch request to ", dest)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
w.RLock()
|
||||
previous := w.sessions[meta.SessionID]
|
||||
w.RUnlock()
|
||||
if previous != nil {
|
||||
previous.abort()
|
||||
}
|
||||
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,
|
||||
}
|
||||
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 && meta.Target.Network != network {
|
||||
return errors.New("unexpected network ", meta.Target.Network)
|
||||
}
|
||||
|
||||
if meta.GlobalID != [8]byte{} {
|
||||
return w.bindXUDP(ctx, meta, reader)
|
||||
}
|
||||
|
||||
s := &Session{
|
||||
parent: w.carrier, phase: outputOpen,
|
||||
ID: meta.SessionID, target: net.Destination{Network: meta.Target.Network},
|
||||
}
|
||||
s.flow = newInboundFlow(ctx, [8]byte{})
|
||||
s.flow.binding = s
|
||||
w.Lock()
|
||||
admitted := w.admitLocked(s)
|
||||
w.Unlock()
|
||||
if !admitted {
|
||||
s.flow.Interrupt()
|
||||
return errors.New("failed to add new session")
|
||||
}
|
||||
var output buf.Writer = s
|
||||
if meta.Target.Network == net.Network_UDP {
|
||||
output = &flowOutput{s.flow}
|
||||
}
|
||||
go w.dispatchFlow(ctx, meta.Target, s.flow, output)
|
||||
if !meta.Option.Has(OptionData) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return copyFramePayload(reader, s, meta.Target)
|
||||
}
|
||||
@@ -1,15 +1,16 @@
|
||||
package mux_test
|
||||
package multiplex_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"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"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
"github.com/xtls/xray-core/common/task"
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
@@ -32,66 +33,51 @@ func newLinkPair() (*transport.Link, *transport.Link) {
|
||||
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) {
|
||||
originalOutbounds := []*session.Outbound{{}}
|
||||
serverCtx := session.ContextWithOutbounds(context.Background(), originalOutbounds)
|
||||
|
||||
websiteUplink, websiteDownlink := newLinkPair()
|
||||
|
||||
dispatcher := TestDispatcher{
|
||||
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.Target = dest
|
||||
return websiteDownlink, nil
|
||||
},
|
||||
dispatch := func(ctx context.Context, dest net.Destination, link *transport.Link) error {
|
||||
// Emulate DefaultDispatcher's context mutation while forwarding real data.
|
||||
ob := session.OutboundsFromContext(ctx)[0]
|
||||
ob.Target = dest
|
||||
return task.Run(ctx,
|
||||
func() error { return buf.Copy(link.Reader, websiteDownlink.Writer) },
|
||||
func() error { return buf.Copy(websiteDownlink.Reader, link.Writer) })
|
||||
}
|
||||
|
||||
muxServerUplink, muxServerDownlink := newLinkPair()
|
||||
_, err := mux.NewServerWorker(serverCtx, &dispatcher, muxServerUplink)
|
||||
common.Must(err)
|
||||
multiplexServerUplink, multiplexServerDownlink := newLinkPair()
|
||||
multiplex.NewServerWorker(serverCtx, dispatch, multiplexServerUplink)
|
||||
|
||||
client, err := mux.NewClientWorker(*muxServerDownlink, mux.ClientStrategy{})
|
||||
common.Must(err)
|
||||
client := multiplex.NewClientWorker(context.Background(), *multiplexServerDownlink, multiplex.ClientStrategy{})
|
||||
|
||||
clientCtx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
|
||||
Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80),
|
||||
}})
|
||||
|
||||
muxClientUplink, muxClientDownlink := newLinkPair()
|
||||
multiplexClientUplink, multiplexClientDownlink := newLinkPair()
|
||||
|
||||
ok := client.Dispatch(clientCtx, muxClientUplink)
|
||||
if !ok {
|
||||
t.Error("failed to dispatch")
|
||||
}
|
||||
dispatched := make(chan error, 1)
|
||||
go func() {
|
||||
dispatched <- multiplex.Dispatch(clientCtx, multiplexClientUplink, func(ctx context.Context, s *multiplex.Session) error {
|
||||
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"))
|
||||
common.Must(muxClientDownlink.Writer.WriteMultiBuffer(buf.MultiBuffer{b}))
|
||||
common.Must(multiplexClientDownlink.Writer.WriteMultiBuffer(buf.MultiBuffer{b}))
|
||||
}
|
||||
|
||||
resMb, err := websiteUplink.Reader.ReadMultiBuffer()
|
||||
@@ -106,7 +92,7 @@ func TestRegressionOutboundLeak(t *testing.T) {
|
||||
common.Must(websiteUplink.Writer.WriteMultiBuffer(buf.MultiBuffer{b}))
|
||||
}
|
||||
|
||||
resMb, err = muxClientDownlink.Reader.ReadMultiBuffer()
|
||||
resMb, err = multiplexClientDownlink.Reader.ReadMultiBuffer()
|
||||
common.Must(err)
|
||||
res = resMb.String()
|
||||
if res != "world" {
|
||||
@@ -0,0 +1,220 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/xudp"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
)
|
||||
|
||||
// Session has one physical owner. Parent guards phase and registry identity;
|
||||
// Flow is immutable after publication; its retained route can outlive this ID.
|
||||
type Session struct {
|
||||
input buf.Reader
|
||||
output buf.Writer
|
||||
parent *carrier
|
||||
ID uint16
|
||||
target net.Destination
|
||||
globalID [8]byte
|
||||
inbound *session.Inbound
|
||||
first bool
|
||||
endFailed bool // immutable after the first local terminal transition
|
||||
phase byte
|
||||
done chan struct{}
|
||||
flow *inboundFlow
|
||||
producer sync.Mutex
|
||||
|
||||
writingResponse atomic.Bool
|
||||
}
|
||||
|
||||
const (
|
||||
outputStarting = iota
|
||||
outputOpen
|
||||
outputDone
|
||||
)
|
||||
|
||||
// NewSession prepares initiating metadata before any physical admission lock.
|
||||
func NewSession(ctx context.Context, link *transport.Link) *Session {
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
target := outbounds[len(outbounds)-1].Target
|
||||
s := &Session{
|
||||
input: link.Reader, output: link.Writer, target: target,
|
||||
globalID: xudp.GetGlobalID(ctx), first: true,
|
||||
}
|
||||
if session.IsReverseMuxFromContext(ctx) {
|
||||
s.inbound = session.InboundFromContext(ctx)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Initiating input is serial; native server callbacks are serialized per offer.
|
||||
// Existing producers own DATA through direct physical admission.
|
||||
func (s *Session) WriteMultiBuffer(raw buf.MultiBuffer) error {
|
||||
c := s.parent
|
||||
c.RLock()
|
||||
live := !c.Closed() && s.phase == outputOpen && c.sessions[s.ID] == s
|
||||
c.RUnlock()
|
||||
if !live {
|
||||
buf.ReleaseMulti(raw)
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
if !c.client {
|
||||
s.producer.Lock()
|
||||
defer s.producer.Unlock()
|
||||
}
|
||||
defer func() { buf.ReleaseMulti(raw) }()
|
||||
for {
|
||||
c.writeMutex.Lock()
|
||||
c.RLock()
|
||||
live := !c.Closed() && s.phase == outputOpen && c.sessions[s.ID] == s
|
||||
c.RUnlock()
|
||||
var frames buf.MultiBuffer
|
||||
var err error
|
||||
if live {
|
||||
frames, err = s.encodeBatch(&raw)
|
||||
}
|
||||
if err = c.writeAndUnlock(frames, err); err != nil {
|
||||
return err
|
||||
}
|
||||
if !live || c.Closed() {
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
if len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Session) writePayload(data buf.MultiBuffer) error {
|
||||
// The flow validates server admission for this immutable binding.
|
||||
x := s.flow
|
||||
if x == nil {
|
||||
s.parent.RLock()
|
||||
live := s.phase == outputOpen || s.phase == outputStarting
|
||||
if live {
|
||||
s.writingResponse.Store(true)
|
||||
}
|
||||
s.parent.RUnlock()
|
||||
if !live {
|
||||
buf.ReleaseMulti(data)
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
defer s.writingResponse.Store(false)
|
||||
return s.output.WriteMultiBuffer(data)
|
||||
}
|
||||
err := x.accept(data, s)
|
||||
if err != nil {
|
||||
buf.ReleaseMulti(data)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Session) Close() error {
|
||||
if s.parent.client {
|
||||
s.close(true)
|
||||
return nil
|
||||
}
|
||||
s.producer.Lock()
|
||||
defer s.producer.Unlock()
|
||||
s.close(false)
|
||||
return nil
|
||||
}
|
||||
func (s *Session) Interrupt() { s.close(true) }
|
||||
func (s *Session) WaitClosed() <-chan struct{} { return s.done }
|
||||
|
||||
func (s *Session) CloseWithError(err error) { s.close(err != nil) }
|
||||
|
||||
func (s *Session) close(failed bool) { s.seal(failed, true) }
|
||||
func (s *Session) abort() { s.seal(false, false) }
|
||||
|
||||
func (s *Session) seal(failed, local bool) {
|
||||
c, x := s.parent, s.flow
|
||||
if x != nil {
|
||||
x.access.Lock()
|
||||
defer x.access.Unlock()
|
||||
}
|
||||
c.Lock()
|
||||
s.closeLocked(x, failed, local)
|
||||
c.Unlock()
|
||||
}
|
||||
|
||||
// closeLocked seals the logical route under flow/carrier ownership. The role's
|
||||
// producer or carrier sender owns END; the first local failure flag is immutable.
|
||||
func (s *Session) closeLocked(x *inboundFlow, failed, local bool) {
|
||||
c := s.parent
|
||||
first := s.phase != outputDone
|
||||
// A borrowed peer pointer must not rewrite a client's first terminal state.
|
||||
if !first && (local || c.client) {
|
||||
return
|
||||
}
|
||||
registered := c.sessions[s.ID] == s
|
||||
if s.phase == outputOpen && registered {
|
||||
c.active--
|
||||
}
|
||||
s.phase = outputDone
|
||||
// A terminal row retained in the registry owns a pending END.
|
||||
if registered && local && !c.Closed() {
|
||||
s.endFailed = failed
|
||||
c.queueReadyLocked(s)
|
||||
} else if registered {
|
||||
delete(c.ready, s.ID)
|
||||
delete(c.sessions, s.ID)
|
||||
}
|
||||
if first {
|
||||
if s.done != nil {
|
||||
close(s.done)
|
||||
}
|
||||
if x != nil && x.binding == s {
|
||||
x.binding = nil
|
||||
if x.GlobalID == [8]byte{} {
|
||||
if x.requestErr == nil {
|
||||
x.requestErr = io.EOF
|
||||
}
|
||||
x.responseErr = io.ErrClosedPipe
|
||||
x.response = buf.ReleaseMulti(x.response)
|
||||
x.responseWake.Broadcast()
|
||||
} else {
|
||||
x.Expire = time.Now().Add(time.Minute)
|
||||
}
|
||||
x.requestWake.Broadcast()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var XUDPManager = struct {
|
||||
sync.Mutex
|
||||
Map map[[8]byte]*inboundFlow
|
||||
}{Map: make(map[[8]byte]*inboundFlow)}
|
||||
|
||||
func init() { time.AfterFunc(time.Minute, scheduleXUDPSweep) }
|
||||
|
||||
func scheduleXUDPSweep() {
|
||||
sweepXUDP(time.Now())
|
||||
time.AfterFunc(time.Minute, scheduleXUDPSweep)
|
||||
}
|
||||
|
||||
func sweepXUDP(now time.Time) {
|
||||
var expired []*inboundFlow
|
||||
XUDPManager.Lock()
|
||||
for id, x := range XUDPManager.Map {
|
||||
x.access.Lock()
|
||||
if x.binding == nil && !x.Expire.IsZero() && now.After(x.Expire) {
|
||||
expired = append(expired, x)
|
||||
delete(XUDPManager.Map, id)
|
||||
}
|
||||
x.access.Unlock()
|
||||
}
|
||||
XUDPManager.Unlock()
|
||||
for _, x := range expired {
|
||||
errors.LogDebug(context.Background(), "XUDP del ", x.GlobalID)
|
||||
x.expire()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
func TestCarrierAdmission(t *testing.T) {
|
||||
reader, writer := pipe.New(pipe.WithoutSizeLimit())
|
||||
worker := NewClientWorker(context.Background(), transport.Link{Reader: reader, Writer: buf.Discard}, ClientStrategy{})
|
||||
t.Cleanup(func() { worker.Close(); writer.Close() })
|
||||
for id := uint16(1); id <= 2; id++ {
|
||||
ctx := testOutboundContext()
|
||||
s := NewSession(ctx, &transport.Link{Writer: buf.Discard})
|
||||
if !worker.TryAdmit(ctx, s) || s.ID != id {
|
||||
t.Fatalf("id%d: %v", id, s)
|
||||
}
|
||||
if worker.ActiveConnections() != uint32(id) {
|
||||
t.Fatalf("active: %d", worker.ActiveConnections())
|
||||
}
|
||||
}
|
||||
// Preserve the original explicit-ID publication assertion, with a fully
|
||||
// initialized real physical owner instead of a standalone manager facade.
|
||||
s := &Session{ID: 4, parent: worker.carrier, output: buf.Discard, done: make(chan struct{}), phase: outputOpen}
|
||||
worker.Lock()
|
||||
admitted := worker.admitLocked(s)
|
||||
indexed := worker.sessions[4] == s
|
||||
worker.Unlock()
|
||||
if !admitted || !indexed || s.ID != 4 || worker.ActiveConnections() != 3 {
|
||||
t.Fatal("explicit wire identity not admitted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCarrierIdleRetirement(t *testing.T) {
|
||||
reader, writer := pipe.New(pipe.WithoutSizeLimit())
|
||||
worker := &ClientWorker{carrier: newCarrier(context.Background(), transport.Link{Reader: reader, Writer: buf.Discard}, 20*time.Millisecond, true)}
|
||||
go worker.run(context.Background(), nil)
|
||||
t.Cleanup(func() { worker.Close(); writer.Close() })
|
||||
ctx := testOutboundContext()
|
||||
s := NewSession(ctx, &transport.Link{Writer: buf.Discard})
|
||||
if !worker.TryAdmit(ctx, s) {
|
||||
t.Fatal("session not admitted")
|
||||
}
|
||||
select {
|
||||
case <-worker.WaitClosed():
|
||||
t.Fatal("active carrier retired")
|
||||
case <-time.After(65 * time.Millisecond):
|
||||
}
|
||||
s.Close()
|
||||
select {
|
||||
case <-worker.WaitClosed():
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("empty carrier did not retire")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package multiplex
|
||||
|
||||
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/serial"
|
||||
)
|
||||
|
||||
// encodeBatch moves up to four complete wire frames from raw caller custody.
|
||||
// An offer without buffers contains metadata only.
|
||||
func (s *Session) encodeBatch(mb *buf.MultiBuffer) (frames buf.MultiBuffer, err error) {
|
||||
stream := s.target.Network != net.Network_UDP
|
||||
if stream && (*mb).IsEmpty() {
|
||||
*mb = buf.ReleaseMulti(*mb)
|
||||
}
|
||||
for n := 0; n < 4 && (s.first || len(*mb) != 0); n++ {
|
||||
frame := buf.NewWithSize(1024)
|
||||
frames = append(frames, frame)
|
||||
meta := FrameMetadata{
|
||||
SessionID: s.ID, Target: s.target, GlobalID: s.globalID,
|
||||
Inbound: s.inbound, SessionStatus: SessionStatusKeep,
|
||||
}
|
||||
if s.first {
|
||||
s.first = false
|
||||
meta.SessionStatus = SessionStatusNew
|
||||
}
|
||||
if len(*mb) == 0 {
|
||||
return frames, meta.WriteTo(frame)
|
||||
}
|
||||
var chunk buf.MultiBuffer
|
||||
if stream {
|
||||
*mb, chunk = buf.SplitSize(*mb, 8*1024)
|
||||
} else {
|
||||
mb2, b := buf.SplitFirst(*mb)
|
||||
*mb = mb2
|
||||
chunk = buf.MultiBuffer{b}
|
||||
}
|
||||
if len(chunk) == 1 {
|
||||
frame.UDP = chunk[0].UDP
|
||||
}
|
||||
frames = append(frames, chunk...)
|
||||
meta.Option.Set(OptionData)
|
||||
if err := meta.WriteTo(frame); err != nil {
|
||||
return frames, err
|
||||
}
|
||||
if _, err := serial.WriteUint16(frame, uint16(chunk.Len())); err != nil {
|
||||
return frames, err
|
||||
}
|
||||
}
|
||||
return frames, nil
|
||||
}
|
||||
|
||||
func endFrame(id uint16, failed bool) buf.MultiBuffer {
|
||||
meta := FrameMetadata{SessionID: id, SessionStatus: SessionStatusEnd}
|
||||
if failed {
|
||||
meta.Option.Set(OptionError)
|
||||
}
|
||||
frame := buf.NewWithSize(1024)
|
||||
common.Must(meta.WriteTo(frame))
|
||||
return buf.MultiBuffer{frame}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/features/policy"
|
||||
"github.com/xtls/xray-core/features/stats"
|
||||
)
|
||||
|
||||
// inboundFlow owns native route input and persistent binding state. Its response
|
||||
// packet response mailbox retains native bytes until the physical sender claims them.
|
||||
// Locks nest association map -> flow -> one carrier; I/O is outside them.
|
||||
type inboundFlow struct {
|
||||
access sync.Mutex
|
||||
|
||||
requestWake, responseWake sync.Cond
|
||||
request, response buf.MultiBuffer
|
||||
requestErr, responseErr error
|
||||
uplinkCounter stats.Counter
|
||||
uplinkPending int64
|
||||
uplinkBound bool
|
||||
limit int32
|
||||
binding *Session
|
||||
GlobalID [8]byte
|
||||
Expire time.Time
|
||||
}
|
||||
|
||||
func newInboundFlow(ctx context.Context, id [8]byte) *inboundFlow {
|
||||
x := &inboundFlow{limit: policy.BufferPolicyFromContext(ctx).PerConnection, GlobalID: id}
|
||||
x.requestWake.L, x.responseWake.L = &x.access, &x.access
|
||||
return x
|
||||
}
|
||||
|
||||
// SetUplinkCounter binds attempted-input accounting once, including disabled stats.
|
||||
func (x *inboundFlow) SetUplinkCounter(counter stats.Counter) {
|
||||
x.access.Lock()
|
||||
if x.uplinkBound {
|
||||
x.access.Unlock()
|
||||
return
|
||||
}
|
||||
x.uplinkCounter, x.uplinkBound = counter, true
|
||||
pending := x.uplinkPending
|
||||
x.uplinkPending = 0
|
||||
x.access.Unlock()
|
||||
if counter != nil && pending != 0 {
|
||||
counter.Add(pending)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *inboundFlow) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
x.access.Lock()
|
||||
defer x.access.Unlock()
|
||||
return x.readLocked(nil)
|
||||
}
|
||||
|
||||
func (x *inboundFlow) ReadMultiBufferTimeout(duration time.Duration) (buf.MultiBuffer, error) {
|
||||
x.access.Lock()
|
||||
defer x.access.Unlock()
|
||||
if len(x.request) > 0 || x.requestErr != nil {
|
||||
return x.readLocked(nil)
|
||||
}
|
||||
timedOut := false
|
||||
timer := time.AfterFunc(duration, func() {
|
||||
x.access.Lock()
|
||||
timedOut = true
|
||||
x.requestWake.Broadcast()
|
||||
x.access.Unlock()
|
||||
})
|
||||
defer timer.Stop()
|
||||
return x.readLocked(&timedOut)
|
||||
}
|
||||
|
||||
// readLocked has no timeout closure or escaping flag on ordinary native reads.
|
||||
func (x *inboundFlow) readLocked(timedOut *bool) (buf.MultiBuffer, error) {
|
||||
for len(x.request) == 0 && x.requestErr == nil && (timedOut == nil || !*timedOut) {
|
||||
x.requestWake.Wait()
|
||||
}
|
||||
if len(x.request) > 0 {
|
||||
data := x.request
|
||||
x.request = nil
|
||||
x.requestWake.Broadcast()
|
||||
return data, nil
|
||||
}
|
||||
if x.requestErr != nil {
|
||||
return nil, x.requestErr
|
||||
}
|
||||
return nil, buf.ErrReadTimeout
|
||||
}
|
||||
|
||||
// accept leaves rejected data with the parser so a failed retained route can
|
||||
// restart with the very same first packet and destination.
|
||||
func (x *inboundFlow) accept(data buf.MultiBuffer, binding *Session) error {
|
||||
x.access.Lock()
|
||||
if !x.uplinkBound {
|
||||
x.uplinkPending += int64(data.Len())
|
||||
} else if counter := x.uplinkCounter; counter != nil {
|
||||
x.access.Unlock()
|
||||
counter.Add(int64(data.Len()))
|
||||
x.access.Lock()
|
||||
}
|
||||
defer x.access.Unlock()
|
||||
for {
|
||||
if x.requestErr != nil || x.binding != binding || binding.parent.Closed() {
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
if x.limit < 0 || x.request.Len() <= x.limit {
|
||||
if len(x.request) == 0 {
|
||||
x.request = data
|
||||
} else {
|
||||
x.request, _ = buf.MergeMulti(x.request, data)
|
||||
}
|
||||
x.requestWake.Broadcast()
|
||||
return nil
|
||||
}
|
||||
x.requestWake.Wait()
|
||||
}
|
||||
}
|
||||
|
||||
// Interrupt is native request abort. Ordinary wire EOF instead seals this
|
||||
// input in Session.close, preserving payload already accepted from the parser.
|
||||
func (x *inboundFlow) Interrupt() {
|
||||
x.access.Lock()
|
||||
x.requestErr = io.ErrClosedPipe
|
||||
x.request = buf.ReleaseMulti(x.request)
|
||||
x.requestWake.Broadcast()
|
||||
x.access.Unlock()
|
||||
}
|
||||
|
||||
type flowOutput struct{ *inboundFlow }
|
||||
|
||||
func (w *flowOutput) Interrupt() { w.finish(true) }
|
||||
func (w *flowOutput) Close() error { w.finish(false); return nil }
|
||||
func (x *inboundFlow) finish(abort bool) {
|
||||
x.access.Lock()
|
||||
if abort {
|
||||
x.responseErr = io.ErrClosedPipe
|
||||
x.response = buf.ReleaseMulti(x.response)
|
||||
} else if x.responseErr == nil {
|
||||
x.responseErr = io.EOF
|
||||
}
|
||||
if s := x.binding; s != nil {
|
||||
c := s.parent
|
||||
c.Lock()
|
||||
if abort && s.phase == outputOpen {
|
||||
s.closeLocked(x, true, true)
|
||||
} else {
|
||||
c.scheduleLocked(s)
|
||||
}
|
||||
c.Unlock()
|
||||
}
|
||||
x.responseWake.Broadcast()
|
||||
x.access.Unlock()
|
||||
}
|
||||
|
||||
func (x *inboundFlow) expire() {
|
||||
x.access.Lock()
|
||||
if x.requestErr == nil {
|
||||
x.requestErr = io.EOF
|
||||
x.requestWake.Broadcast()
|
||||
}
|
||||
x.access.Unlock()
|
||||
x.finish(true)
|
||||
}
|
||||
|
||||
// WriteMultiBuffer admits the whole raw offer under the original soft policy.
|
||||
// Response-capacity waiters are separate from request readers.
|
||||
func (w *flowOutput) WriteMultiBuffer(data buf.MultiBuffer) error {
|
||||
x := w.inboundFlow
|
||||
x.access.Lock()
|
||||
defer x.access.Unlock()
|
||||
for x.responseErr == nil && x.limit >= 0 && x.response.Len() > x.limit {
|
||||
x.responseWake.Wait()
|
||||
}
|
||||
if x.responseErr != nil {
|
||||
buf.ReleaseMulti(data)
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
if data.IsEmpty() {
|
||||
buf.ReleaseMulti(data)
|
||||
return nil
|
||||
}
|
||||
if len(x.response) == 0 {
|
||||
x.response = data
|
||||
} else {
|
||||
x.response, _ = buf.MergeMulti(x.response, data)
|
||||
}
|
||||
if s := x.binding; s != nil {
|
||||
s.parent.Lock()
|
||||
s.parent.scheduleLocked(s)
|
||||
s.parent.Unlock()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// packetReady is checked with the flow and carrier locked.
|
||||
func (s *Session) packetReady() bool {
|
||||
x := s.flow
|
||||
return x != nil && x.binding == s &&
|
||||
(s.phase == outputOpen && (len(x.response) != 0 || x.responseErr != nil) ||
|
||||
s.phase == outputStarting && x.requestErr == nil && len(x.response) != 0)
|
||||
}
|
||||
|
||||
// One gated actor claims packet data or retires one exact terminal identity.
|
||||
// It returns custody only; the sender encodes after both logical locks release.
|
||||
func (c *carrier) responseTurn(id uint16, s *Session) (buf.MultiBuffer, bool) {
|
||||
if s != nil && s.flow != nil {
|
||||
s.flow.access.Lock()
|
||||
defer s.flow.access.Unlock()
|
||||
}
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
if c.Closed() {
|
||||
return nil, false
|
||||
}
|
||||
if s == nil {
|
||||
return nil, c.invalidateUnknownLocked(id)
|
||||
}
|
||||
if c.sessions[id] != s {
|
||||
return nil, false
|
||||
}
|
||||
x := s.flow
|
||||
ready := s.packetReady()
|
||||
if ready && len(x.response) == 0 {
|
||||
s.closeLocked(x, x.responseErr == io.ErrClosedPipe, true)
|
||||
}
|
||||
if s.phase == outputDone {
|
||||
delete(c.ready, s.ID)
|
||||
delete(c.sessions, s.ID)
|
||||
return nil, true
|
||||
}
|
||||
if !ready {
|
||||
delete(c.ready, s.ID)
|
||||
return nil, false
|
||||
}
|
||||
n := min(4, len(x.response))
|
||||
data := x.response[:n:n]
|
||||
x.response = x.response[n:]
|
||||
if len(x.response) == 0 {
|
||||
x.response = nil
|
||||
}
|
||||
x.responseWake.Broadcast()
|
||||
// A terminal follow-up cannot run until this DATA turn completes physically.
|
||||
if !s.packetReady() {
|
||||
delete(c.ready, s.ID)
|
||||
}
|
||||
return data, false
|
||||
}
|
||||
|
||||
func (w *ServerWorker) bindXUDP(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
data, err := readPacket(reader, meta.Target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx = session.ContextWithTimeoutOnly(ctx, true)
|
||||
XUDPManager.Lock()
|
||||
for {
|
||||
x := XUDPManager.Map[meta.GlobalID]
|
||||
fresh := x == nil
|
||||
if fresh {
|
||||
x = newInboundFlow(ctx, meta.GlobalID)
|
||||
}
|
||||
x.access.Lock()
|
||||
if previous := x.binding; previous != nil {
|
||||
previous.parent.Lock()
|
||||
if previous.phase == outputStarting {
|
||||
previous.parent.Unlock()
|
||||
x.access.Unlock()
|
||||
XUDPManager.Unlock()
|
||||
buf.ReleaseMulti(data)
|
||||
errors.LogWarningInner(ctx, errors.New("conflict"), "XUDP hit ", meta.GlobalID)
|
||||
return nil
|
||||
}
|
||||
previous.closeLocked(x, true, true)
|
||||
previous.parent.Unlock()
|
||||
}
|
||||
w.Lock()
|
||||
if w.Closed() || w.sessions[meta.SessionID] != nil {
|
||||
w.Unlock()
|
||||
x.access.Unlock()
|
||||
XUDPManager.Unlock()
|
||||
buf.ReleaseMulti(data)
|
||||
return errors.New("failed to add new session")
|
||||
}
|
||||
s := &Session{
|
||||
parent: w.carrier, ID: meta.SessionID, phase: outputStarting,
|
||||
target: net.Destination{Network: net.Network_UDP}, flow: x,
|
||||
}
|
||||
w.invalidateUnknownLocked(s.ID)
|
||||
w.sessions[s.ID] = s
|
||||
XUDPManager.Map[meta.GlobalID] = x
|
||||
x.binding, x.Expire = s, time.Time{}
|
||||
w.scheduleLocked(s)
|
||||
w.Unlock()
|
||||
x.access.Unlock()
|
||||
XUDPManager.Unlock()
|
||||
if fresh {
|
||||
go w.dispatchFlow(ctx, meta.Target, x, &flowOutput{x})
|
||||
}
|
||||
err = x.accept(data, s)
|
||||
|
||||
XUDPManager.Lock()
|
||||
x.access.Lock()
|
||||
w.Lock()
|
||||
live := !w.Closed() && w.sessions[s.ID] == s && x.binding == s && s.phase == outputStarting
|
||||
current := XUDPManager.Map[meta.GlobalID]
|
||||
restart := err != nil && !fresh
|
||||
retry := restart && live && (current == x || current == nil)
|
||||
admitted := live && current == x
|
||||
if restart {
|
||||
s.closeLocked(x, false, false)
|
||||
if retry {
|
||||
x.responseErr = io.ErrClosedPipe
|
||||
x.response = buf.ReleaseMulti(x.response)
|
||||
x.responseWake.Broadcast()
|
||||
delete(XUDPManager.Map, meta.GlobalID)
|
||||
}
|
||||
} else if admitted {
|
||||
w.count++
|
||||
if x.responseErr == nil || len(x.response) != 0 {
|
||||
s.phase = outputOpen
|
||||
w.active++
|
||||
} else {
|
||||
s.closeLocked(x, x.responseErr == io.ErrClosedPipe, true)
|
||||
}
|
||||
w.scheduleLocked(s)
|
||||
}
|
||||
w.Unlock()
|
||||
x.access.Unlock()
|
||||
if retry {
|
||||
// Keep the manager lock until the replacement is registered.
|
||||
continue
|
||||
}
|
||||
XUDPManager.Unlock()
|
||||
if err != nil {
|
||||
buf.ReleaseMulti(data)
|
||||
}
|
||||
if restart {
|
||||
if !live {
|
||||
return nil
|
||||
}
|
||||
x.expire()
|
||||
}
|
||||
if restart || !admitted {
|
||||
s.abort()
|
||||
return errors.New("failed to add new session")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ package outbound
|
||||
|
||||
import (
|
||||
protocol "github.com/xtls/xray-core/common/protocol"
|
||||
vless "github.com/xtls/xray-core/proxy/vless"
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
@@ -25,6 +26,7 @@ const (
|
||||
type Config struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Vnext *protocol.ServerEndpoint `protobuf:"bytes,1,opt,name=vnext,proto3" json:"vnext,omitempty"`
|
||||
Multiplex *vless.Multiplex `protobuf:"bytes,2,opt,name=multiplex,proto3" json:"multiplex,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -66,13 +68,21 @@ func (x *Config) GetVnext() *protocol.ServerEndpoint {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Config) GetMultiplex() *vless.Multiplex {
|
||||
if x != nil {
|
||||
return x.Multiplex
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_proxy_vless_outbound_config_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_proxy_vless_outbound_config_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"!proxy/vless/outbound/config.proto\x12\x19xray.proxy.vless.outbound\x1a!common/protocol/server_spec.proto\"D\n" +
|
||||
"!proxy/vless/outbound/config.proto\x12\x19xray.proxy.vless.outbound\x1a!common/protocol/server_spec.proto\x1a\x19proxy/vless/account.proto\"\x7f\n" +
|
||||
"\x06Config\x12:\n" +
|
||||
"\x05vnext\x18\x01 \x01(\v2$.xray.common.protocol.ServerEndpointR\x05vnextBm\n" +
|
||||
"\x05vnext\x18\x01 \x01(\v2$.xray.common.protocol.ServerEndpointR\x05vnext\x129\n" +
|
||||
"\tmultiplex\x18\x02 \x01(\v2\x1b.xray.proxy.vless.MultiplexR\tmultiplexBm\n" +
|
||||
"\x1dcom.xray.proxy.vless.outboundP\x01Z.github.com/xtls/xray-core/proxy/vless/outbound\xaa\x02\x19Xray.Proxy.Vless.Outboundb\x06proto3"
|
||||
|
||||
var (
|
||||
@@ -91,14 +101,16 @@ var file_proxy_vless_outbound_config_proto_msgTypes = make([]protoimpl.MessageIn
|
||||
var file_proxy_vless_outbound_config_proto_goTypes = []any{
|
||||
(*Config)(nil), // 0: xray.proxy.vless.outbound.Config
|
||||
(*protocol.ServerEndpoint)(nil), // 1: xray.common.protocol.ServerEndpoint
|
||||
(*vless.Multiplex)(nil), // 2: xray.proxy.vless.Multiplex
|
||||
}
|
||||
var file_proxy_vless_outbound_config_proto_depIdxs = []int32{
|
||||
1, // 0: xray.proxy.vless.outbound.Config.vnext:type_name -> xray.common.protocol.ServerEndpoint
|
||||
1, // [1:1] is the sub-list for method output_type
|
||||
1, // [1:1] is the sub-list for method input_type
|
||||
1, // [1:1] is the sub-list for extension type_name
|
||||
1, // [1:1] is the sub-list for extension extendee
|
||||
0, // [0:1] is the sub-list for field type_name
|
||||
2, // 1: xray.proxy.vless.outbound.Config.multiplex:type_name -> xray.proxy.vless.Multiplex
|
||||
2, // [2:2] is the sub-list for method output_type
|
||||
2, // [2:2] is the sub-list for method input_type
|
||||
2, // [2:2] is the sub-list for extension type_name
|
||||
2, // [2:2] is the sub-list for extension extendee
|
||||
0, // [0:2] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_proxy_vless_outbound_config_proto_init() }
|
||||
|
||||
@@ -7,7 +7,9 @@ option java_package = "com.xray.proxy.vless.outbound";
|
||||
option java_multiple_files = true;
|
||||
|
||||
import "common/protocol/server_spec.proto";
|
||||
import "proxy/vless/account.proto";
|
||||
|
||||
message Config {
|
||||
xray.common.protocol.ServerEndpoint vnext = 1;
|
||||
xray.proxy.vless.Multiplex multiplex = 2;
|
||||
}
|
||||
|
||||
+188
-189
@@ -9,15 +9,11 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
utls "github.com/refraction-networking/utls"
|
||||
proxymanConfig "github.com/xtls/xray-core/app/proxyman"
|
||||
proxyman "github.com/xtls/xray-core/app/proxyman/outbound"
|
||||
"github.com/xtls/xray-core/app/reverse"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
xctx "github.com/xtls/xray-core/common/ctx"
|
||||
"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/retry"
|
||||
@@ -32,12 +28,13 @@ import (
|
||||
"github.com/xtls/xray-core/proxy/vless"
|
||||
"github.com/xtls/xray-core/proxy/vless/encoding"
|
||||
"github.com/xtls/xray-core/proxy/vless/encryption"
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
"github.com/xtls/xray-core/proxy/vless/reverse"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"github.com/xtls/xray-core/transport/internet/reality"
|
||||
"github.com/xtls/xray-core/transport/internet/stat"
|
||||
"github.com/xtls/xray-core/transport/internet/tls"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -51,7 +48,10 @@ type Handler struct {
|
||||
server *protocol.ServerSpec
|
||||
policyManager policy.Manager
|
||||
encryption *encryption.ClientInstance
|
||||
reverse *Reverse
|
||||
closeReverse func()
|
||||
ctx context.Context
|
||||
stop context.CancelFunc
|
||||
multiplex *multiplex.Client
|
||||
|
||||
testpre uint32
|
||||
initpre sync.Once
|
||||
@@ -73,13 +73,24 @@ func New(ctx context.Context, config *Config) (*Handler, error) {
|
||||
return nil, errors.New("failed to get server spec").Base(err)
|
||||
}
|
||||
|
||||
muxConfig, err := multiplex.NormalizeConfig(config.Multiplex)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a := server.User.Account.(*vless.MemoryAccount)
|
||||
dialer, _ := session.FullHandlerFromContext(ctx).(internet.Dialer)
|
||||
if dialer == nil && (a.Reverse != nil || muxConfig != nil) {
|
||||
return nil, errors.New("VLESS Reverse or multiplex requires an outbound dialer")
|
||||
}
|
||||
|
||||
v := core.MustFromContext(ctx)
|
||||
handler := &Handler{
|
||||
server: server,
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
}
|
||||
|
||||
a := handler.server.User.Account.(*vless.MemoryAccount)
|
||||
handler.ctx, handler.stop = context.WithCancel(context.Background())
|
||||
|
||||
if a.Encryption != "" && a.Encryption != "none" {
|
||||
s := strings.Split(a.Encryption, ".")
|
||||
var nfsPKeysBytes [][]byte
|
||||
@@ -93,11 +104,14 @@ func New(ctx context.Context, config *Config) (*Handler, error) {
|
||||
}
|
||||
}
|
||||
|
||||
if a.Reverse != nil {
|
||||
if a.Reverse == nil {
|
||||
handler.testpre = a.Testpre
|
||||
} else {
|
||||
rvsCtx := session.ContextWithInbound(ctx, &session.Inbound{
|
||||
Tag: a.Reverse.Tag,
|
||||
Name: "vless-reverse",
|
||||
User: handler.server.User, // TODO: email
|
||||
Tag: a.Reverse.Tag,
|
||||
Name: "vless-reverse",
|
||||
User: handler.server.User, // TODO: email
|
||||
CanSpliceCopy: 3,
|
||||
})
|
||||
if sc := a.Reverse.Sniffing; sc != nil && sc.Enabled {
|
||||
request, err := proxymanConfig.BuildSniffingRequest(sc)
|
||||
@@ -108,73 +122,113 @@ func New(ctx context.Context, config *Config) (*Handler, error) {
|
||||
SniffingRequest: request,
|
||||
})
|
||||
}
|
||||
handler.reverse = &Reverse{
|
||||
tag: a.Reverse.Tag,
|
||||
dispatcher: v.GetFeature(routing.DispatcherType()).(routing.Dispatcher),
|
||||
ctx: rvsCtx,
|
||||
handler: handler,
|
||||
}
|
||||
handler.reverse.monitorTask = &task.Periodic{
|
||||
Execute: handler.reverse.monitor,
|
||||
Interval: time.Second * 2,
|
||||
}
|
||||
go func() {
|
||||
time.Sleep(2 * time.Second)
|
||||
handler.reverse.Start()
|
||||
}()
|
||||
handler.closeReverse = reverse.StartIntranet(rvsCtx,
|
||||
v.GetFeature(routing.DispatcherType()).(routing.Dispatcher).DispatchLink,
|
||||
func(ctx context.Context) (context.Context, *transport.Link, error) {
|
||||
return handler.process(ctx, nil, dialer, protocol.RequestCommandRvs)
|
||||
})
|
||||
}
|
||||
|
||||
handler.testpre = a.Testpre
|
||||
if muxConfig != nil {
|
||||
network := ""
|
||||
if settings, ok := session.StreamSettingsFromContext(ctx).(*internet.MemoryStreamConfig); ok {
|
||||
network = settings.ProtocolName
|
||||
}
|
||||
handler.multiplex = multiplex.NewClient(handler.ctx, muxConfig, network,
|
||||
func(ctx context.Context) (context.Context, *transport.Link, error) {
|
||||
return handler.process(ctx, nil, dialer, protocol.RequestCommandMux)
|
||||
})
|
||||
}
|
||||
|
||||
return handler, nil
|
||||
}
|
||||
|
||||
// Close implements common.Closable.Close().
|
||||
func (h *Handler) Close() error {
|
||||
if h.preConns != nil {
|
||||
close(h.preConns)
|
||||
}
|
||||
if h.reverse != nil {
|
||||
return h.reverse.Close()
|
||||
h.stop()
|
||||
if h.closeReverse != nil {
|
||||
h.closeReverse()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Process implements proxy.Outbound.Process().
|
||||
func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
|
||||
if handled, err := h.multiplex.Dispatch(ctx, link); handled {
|
||||
return err
|
||||
}
|
||||
_, _, err := h.process(ctx, link, dialer, 0)
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *Handler) process(ctx context.Context, link *transport.Link, dialer internet.Dialer, command protocol.RequestCommand) (nativeCtx context.Context, nativeLink *transport.Link, err error) {
|
||||
native := command != 0
|
||||
if native {
|
||||
ctx = session.ContextWithOutbounds(ctx, []*session.Outbound{{Target: h.server.Destination}})
|
||||
}
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
var rawConn stat.Connection
|
||||
var timer *signal.ActivityTimer
|
||||
defer func() {
|
||||
if !native || err != nil {
|
||||
if timer != nil {
|
||||
timer.SetTimeout(0)
|
||||
}
|
||||
cancel()
|
||||
if rawConn != nil {
|
||||
rawConn.Close()
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
ob := outbounds[len(outbounds)-1]
|
||||
if !ob.Target.IsValid() && ob.Target.Address.String() != "v1.rvs.cool" {
|
||||
return errors.New("target not specified")
|
||||
if !ob.Target.IsValid() {
|
||||
return nil, nil, errors.New("target not specified")
|
||||
}
|
||||
ob.Name = "vless"
|
||||
|
||||
rec := h.server
|
||||
var conn stat.Connection
|
||||
|
||||
if h.testpre > 0 && h.reverse == nil {
|
||||
account := rec.User.Account.(*vless.MemoryAccount)
|
||||
|
||||
if !native && ob.Target.Network == net.Network_UDP && ob.Target.Port == 443 && account.Flow == vless.XRV {
|
||||
proxy.DropUDP(ctx, link.Reader)
|
||||
return nil, nil, errors.New("XTLS rejected UDP/443 traffic")
|
||||
}
|
||||
|
||||
if h.testpre > 0 {
|
||||
h.initpre.Do(func() {
|
||||
h.preConns = make(chan *ConnExpire)
|
||||
for range h.testpre { // TODO: randomize
|
||||
go func() {
|
||||
defer func() { recover() }()
|
||||
ctx := xctx.ContextWithID(context.Background(), session.NewID())
|
||||
for {
|
||||
ctx := xctx.ContextWithID(h.ctx, session.NewID())
|
||||
for ctx.Err() == nil {
|
||||
conn, err := dialer.Dial(ctx, rec.Destination)
|
||||
if err != nil {
|
||||
errors.LogWarningInner(ctx, err, "pre-connect failed")
|
||||
continue
|
||||
}
|
||||
h.preConns <- &ConnExpire{Conn: conn, Expire: time.Now().Add(time.Minute * 2)} // TODO: customize & randomize
|
||||
time.Sleep(time.Millisecond * 200) // TODO: customize & randomize
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
conn.Close()
|
||||
return
|
||||
case h.preConns <- &ConnExpire{Conn: conn, Expire: time.Now().Add(time.Minute * 2)}:
|
||||
}
|
||||
time.Sleep(time.Millisecond * 200) // TODO: customize & randomize
|
||||
}
|
||||
}()
|
||||
}
|
||||
})
|
||||
for {
|
||||
connTime := <-h.preConns
|
||||
if connTime == nil {
|
||||
return errors.New("closed handler")
|
||||
var connTime *ConnExpire
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, nil, ctx.Err()
|
||||
case <-h.ctx.Done():
|
||||
return nil, nil, h.ctx.Err()
|
||||
case connTime = <-h.preConns:
|
||||
}
|
||||
if time.Now().Before(connTime.Expire) {
|
||||
conn = connTime.Conn
|
||||
@@ -193,10 +247,13 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.New("failed to find an available destination").Base(err)
|
||||
return nil, nil, errors.New("failed to find an available destination").Base(err)
|
||||
}
|
||||
}
|
||||
defer conn.Close()
|
||||
rawConn = conn
|
||||
if native {
|
||||
context.AfterFunc(ctx, func() { common.Interrupt(stat.TryUnwrapStatsConn(rawConn)) })
|
||||
}
|
||||
|
||||
iConn := stat.TryUnwrapStatsConn(conn)
|
||||
target := ob.Target
|
||||
@@ -205,23 +262,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
if h.encryption != nil {
|
||||
var err error
|
||||
if conn, err = h.encryption.Handshake(conn); err != nil {
|
||||
return errors.New("ML-KEM-768 handshake failed").Base(err)
|
||||
}
|
||||
}
|
||||
|
||||
command := protocol.RequestCommandTCP
|
||||
if target.Network == net.Network_UDP {
|
||||
command = protocol.RequestCommandUDP
|
||||
}
|
||||
if target.Address.Family().IsDomain() {
|
||||
switch target.Address.Domain() {
|
||||
case "v1.mux.cool":
|
||||
command = protocol.RequestCommandMux
|
||||
case "v1.rvs.cool":
|
||||
if target.Network != net.Network_Unknown {
|
||||
return errors.New("nice try baby")
|
||||
}
|
||||
command = protocol.RequestCommandRvs
|
||||
return nil, nil, errors.New("ML-KEM-768 handshake failed").Base(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,11 +270,14 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
Version: encoding.Version,
|
||||
User: rec.User,
|
||||
Command: command,
|
||||
Address: target.Address,
|
||||
Port: target.Port,
|
||||
}
|
||||
|
||||
account := request.User.Account.(*vless.MemoryAccount)
|
||||
if !native {
|
||||
request.Command = protocol.RequestCommandTCP
|
||||
if target.Network == net.Network_UDP {
|
||||
request.Command = protocol.RequestCommandUDP
|
||||
}
|
||||
request.Address, request.Port = target.Address, target.Port
|
||||
}
|
||||
|
||||
requestAddons := &encoding.Addons{
|
||||
Flow: account.Flow,
|
||||
@@ -241,22 +285,15 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
|
||||
var input *bytes.Reader
|
||||
var rawInput **bytes.Buffer
|
||||
allowUDP443 := false
|
||||
switch requestAddons.Flow {
|
||||
case vless.XRV + "-udp443":
|
||||
allowUDP443 = true
|
||||
requestAddons.Flow = requestAddons.Flow[:16]
|
||||
fallthrough
|
||||
case vless.XRV:
|
||||
ob.CanSpliceCopy = 2
|
||||
switch request.Command {
|
||||
case protocol.RequestCommandUDP:
|
||||
if !allowUDP443 && request.Port == 443 {
|
||||
return errors.New("XTLS rejected UDP/443 traffic")
|
||||
}
|
||||
case protocol.RequestCommandMux:
|
||||
fallthrough // let server break Mux connections that contain TCP requests
|
||||
case protocol.RequestCommandTCP, protocol.RequestCommandRvs:
|
||||
case protocol.RequestCommandTCP, protocol.RequestCommandMux, protocol.RequestCommandRvs:
|
||||
var target net.Conn
|
||||
if commonConn, ok := conn.(*encryption.CommonConn); ok {
|
||||
if _, ok := commonConn.Conn.(*encryption.XorConn); ok || !proxy.IsRAWTransportWithoutSecurity(iConn) {
|
||||
@@ -270,7 +307,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
} else if realityConn, ok := iConn.(*reality.UConn); ok {
|
||||
target = realityConn.Conn
|
||||
} else {
|
||||
return errors.New("XTLS only supports TLS and REALITY directly for now.")
|
||||
return nil, nil, errors.New("XTLS only supports TLS and REALITY directly for now.")
|
||||
}
|
||||
input, rawInput = vless.AccessTLSBuffers(target)
|
||||
default:
|
||||
@@ -282,41 +319,95 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
|
||||
var newCtx context.Context
|
||||
var newCancel context.CancelFunc
|
||||
if session.TimeoutOnlyFromContext(ctx) {
|
||||
if !native && session.TimeoutOnlyFromContext(ctx) {
|
||||
newCtx, newCancel = context.WithCancel(context.Background())
|
||||
}
|
||||
|
||||
sessionPolicy := h.policyManager.ForLevel(request.User.Level)
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
timer := signal.CancelAfterInactivity(ctx, func() {
|
||||
timer = signal.CancelAfterInactivity(ctx, func() {
|
||||
cancel()
|
||||
if newCancel != nil {
|
||||
newCancel()
|
||||
}
|
||||
}, sessionPolicy.Timeouts.ConnectionIdle)
|
||||
|
||||
clientReader := link.Reader // .(*pipe.Reader)
|
||||
clientWriter := link.Writer // .(*pipe.Writer)
|
||||
if requestAddons.Flow == vless.XRV {
|
||||
if outerTLS, ok := iConn.(interface {
|
||||
tls.Interface
|
||||
ConnectionState() gotls.ConnectionState
|
||||
}); ok {
|
||||
if err := outerTLS.HandshakeContext(ctx); err != nil {
|
||||
return nil, nil, errors.New("failed outer TLS handshake for Vision").Base(err)
|
||||
}
|
||||
if version := outerTLS.ConnectionState().Version; version != gotls.VersionTLS13 {
|
||||
return nil, nil, errors.New("failed to use "+requestAddons.Flow+", found outer tls version ", version)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
trafficState := proxy.NewTrafficState(account.ID.Bytes())
|
||||
if request.Command == protocol.RequestCommandUDP && (requestAddons.Flow == vless.XRV || (request.Port != 53 && request.Port != 443)) {
|
||||
singleXUDP := request.Command == protocol.RequestCommandUDP && (requestAddons.Flow == vless.XRV || request.Port != 53 && request.Port != 443)
|
||||
if singleXUDP {
|
||||
request.Command = protocol.RequestCommandMux
|
||||
request.Address = net.DomainAddress("v1.mux.cool")
|
||||
request.Port = net.Port(666)
|
||||
}
|
||||
|
||||
bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
|
||||
if err := encoding.EncodeRequestHeader(bufferWriter, request, requestAddons); err != nil {
|
||||
return nil, nil, errors.New("failed to encode request header").Base(err)
|
||||
}
|
||||
|
||||
// default: serverWriter := bufferWriter
|
||||
serverWriter := encoding.EncodeBodyAddons(bufferWriter, request, requestAddons, trafficState, true, ctx, conn, ob)
|
||||
if singleXUDP {
|
||||
serverWriter = xudp.NewPacketWriter(serverWriter, target, xudp.GetGlobalID(ctx))
|
||||
}
|
||||
|
||||
openResponse := func() (buf.Reader, error) {
|
||||
responseAddons, err := encoding.DecodeResponseHeader(conn, request)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to decode response header").Base(err)
|
||||
}
|
||||
|
||||
// default: serverReader := buf.NewReader(conn)
|
||||
serverReader := encoding.DecodeBodyAddons(conn, request, responseAddons)
|
||||
if requestAddons.Flow == vless.XRV {
|
||||
serverReader = proxy.NewVisionReader(serverReader, trafficState, false, ctx, conn, input, rawInput, ob)
|
||||
}
|
||||
if singleXUDP {
|
||||
if requestAddons.Flow == vless.XRV {
|
||||
serverReader = xudp.NewPacketReader(&buf.BufferedReader{Reader: serverReader})
|
||||
} else {
|
||||
serverReader = xudp.NewPacketReader(conn)
|
||||
}
|
||||
}
|
||||
|
||||
return serverReader, nil
|
||||
}
|
||||
|
||||
if native {
|
||||
bufferWriter.SetFlushNext()
|
||||
if request.Command == protocol.RequestCommandRvs {
|
||||
timer.Update()
|
||||
if requestAddons.Flow == vless.XRV {
|
||||
if err := serverWriter.WriteMultiBuffer(buf.MultiBuffer{nil}); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
if err := bufferWriter.SetBuffered(false); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
directLink, openErr := multiplex.OpenLink(ctx, cancel, serverWriter, timer, openResponse)
|
||||
if openErr != nil {
|
||||
return nil, nil, openErr
|
||||
}
|
||||
return ctx, directLink, nil
|
||||
}
|
||||
|
||||
postRequest := func() error {
|
||||
clientReader := link.Reader
|
||||
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
|
||||
|
||||
bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
|
||||
if err := encoding.EncodeRequestHeader(bufferWriter, request, requestAddons); err != nil {
|
||||
return errors.New("failed to encode request header").Base(err)
|
||||
}
|
||||
|
||||
// default: serverWriter := bufferWriter
|
||||
serverWriter := encoding.EncodeBodyAddons(bufferWriter, request, requestAddons, trafficState, true, ctx, conn, ob)
|
||||
if request.Command == protocol.RequestCommandMux && request.Port == 666 {
|
||||
serverWriter = xudp.NewPacketWriter(serverWriter, target, xudp.GetGlobalID(ctx))
|
||||
}
|
||||
timeoutReader, ok := clientReader.(buf.TimeoutReader)
|
||||
if ok {
|
||||
multiBuffer, err1 := timeoutReader.ReadMultiBufferTimeout(time.Millisecond * 500)
|
||||
@@ -341,48 +432,20 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
return errors.New("failed to write A request payload").Base(err)
|
||||
}
|
||||
|
||||
if requestAddons.Flow == vless.XRV {
|
||||
if tlsConn, ok := iConn.(*tls.Conn); ok {
|
||||
if tlsConn.ConnectionState().Version != gotls.VersionTLS13 {
|
||||
return errors.New(`failed to use `+requestAddons.Flow+`, found outer tls version `, tlsConn.ConnectionState().Version)
|
||||
}
|
||||
} else if utlsConn, ok := iConn.(*tls.UConn); ok {
|
||||
if utlsConn.ConnectionState().Version != utls.VersionTLS13 {
|
||||
return errors.New(`failed to use `+requestAddons.Flow+`, found outer tls version `, utlsConn.ConnectionState().Version)
|
||||
}
|
||||
}
|
||||
}
|
||||
err := buf.Copy(clientReader, serverWriter, buf.UpdateActivity(timer))
|
||||
if err != nil {
|
||||
return errors.New("failed to transfer request payload").Base(err)
|
||||
}
|
||||
|
||||
// Indicates the end of request payload.
|
||||
switch requestAddons.Flow {
|
||||
default:
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
clientWriter := link.Writer
|
||||
getResponse := func() error {
|
||||
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
|
||||
|
||||
responseAddons, err := encoding.DecodeResponseHeader(conn, request)
|
||||
serverReader, err := openResponse()
|
||||
if err != nil {
|
||||
return errors.New("failed to decode response header").Base(err)
|
||||
}
|
||||
|
||||
// default: serverReader := buf.NewReader(conn)
|
||||
serverReader := encoding.DecodeBodyAddons(conn, request, responseAddons)
|
||||
if requestAddons.Flow == vless.XRV {
|
||||
serverReader = proxy.NewVisionReader(serverReader, trafficState, false, ctx, conn, input, rawInput, ob)
|
||||
}
|
||||
if request.Command == protocol.RequestCommandMux && request.Port == 666 {
|
||||
if requestAddons.Flow == vless.XRV {
|
||||
serverReader = xudp.NewPacketReader(&buf.BufferedReader{Reader: serverReader})
|
||||
} else {
|
||||
serverReader = xudp.NewPacketReader(conn)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if requestAddons.Flow == vless.XRV {
|
||||
@@ -404,72 +467,8 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
}
|
||||
|
||||
if err := task.Run(ctx, postRequest, task.OnSuccess(getResponse, task.Close(clientWriter))); err != nil {
|
||||
return errors.New("connection ends").Base(err)
|
||||
return nil, nil, errors.New("connection ends").Base(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type Reverse struct {
|
||||
tag string
|
||||
dispatcher routing.Dispatcher
|
||||
ctx context.Context
|
||||
handler *Handler
|
||||
workers []*reverse.BridgeWorker
|
||||
monitorTask *task.Periodic
|
||||
}
|
||||
|
||||
func (r *Reverse) monitor() error {
|
||||
var activeWorkers []*reverse.BridgeWorker
|
||||
for _, w := range r.workers {
|
||||
if w.IsActive() {
|
||||
activeWorkers = append(activeWorkers, w)
|
||||
}
|
||||
}
|
||||
if len(activeWorkers) != len(r.workers) {
|
||||
r.workers = activeWorkers
|
||||
}
|
||||
|
||||
var numConnections uint32
|
||||
var numWorker uint32
|
||||
for _, w := range r.workers {
|
||||
if w.IsActive() {
|
||||
numConnections += w.Connections()
|
||||
numWorker++
|
||||
}
|
||||
}
|
||||
if numWorker == 0 || numConnections/numWorker > 16 {
|
||||
reader1, writer1 := pipe.New(pipe.WithSizeLimit(2 * buf.Size))
|
||||
reader2, writer2 := pipe.New(pipe.WithSizeLimit(2 * buf.Size))
|
||||
link1 := &transport.Link{Reader: reader1, Writer: writer2}
|
||||
link2 := &transport.Link{Reader: reader2, Writer: writer1}
|
||||
w := &reverse.BridgeWorker{
|
||||
Tag: r.tag,
|
||||
Dispatcher: r.dispatcher,
|
||||
}
|
||||
worker, err := mux.NewServerWorker(session.ContextWithIsReverseMux(r.ctx, true), w, link1)
|
||||
if err != nil {
|
||||
errors.LogWarningInner(r.ctx, err, "failed to create mux server worker")
|
||||
return nil
|
||||
}
|
||||
w.Worker = worker
|
||||
r.workers = append(r.workers, w)
|
||||
go func() {
|
||||
ctx := session.ContextWithOutbounds(r.ctx, []*session.Outbound{{
|
||||
Target: net.Destination{Address: net.DomainAddress("v1.rvs.cool")},
|
||||
}})
|
||||
r.handler.Process(ctx, link2, session.FullHandlerFromContext(ctx).(*proxyman.Handler))
|
||||
common.Interrupt(reader1)
|
||||
common.Interrupt(reader2)
|
||||
}()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Reverse) Start() error {
|
||||
return r.monitorTask.Start()
|
||||
}
|
||||
|
||||
func (r *Reverse) Close() error {
|
||||
return r.monitorTask.Close()
|
||||
return nil, nil, nil
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"io"
|
||||
|
||||
"github.com/xtls/xray-core/common/dice"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
)
|
||||
|
||||
func (c *Control) FillInRandom() {
|
||||
@@ -13,3 +14,9 @@ func (c *Control) FillInRandom() {
|
||||
c.Random = make([]byte, randomLength)
|
||||
io.ReadFull(rand.Reader, c.Random)
|
||||
}
|
||||
|
||||
const internalDomain = "reverse"
|
||||
|
||||
func isInternalDomain(dest net.Destination) bool {
|
||||
return dest.Address.Family().IsDomain() && dest.Address.Domain() == internalDomain
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.12
|
||||
// protoc (unknown)
|
||||
// source: proxy/vless/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_proxy_vless_reverse_config_proto_enumTypes[0].Descriptor()
|
||||
}
|
||||
|
||||
func (Control_State) Type() protoreflect.EnumType {
|
||||
return &file_proxy_vless_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_proxy_vless_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_proxy_vless_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_proxy_vless_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_proxy_vless_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
|
||||
}
|
||||
|
||||
var File_proxy_vless_reverse_config_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_proxy_vless_reverse_config_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
" proxy/vless/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\x01B^\n" +
|
||||
"\x16com.xray.proxy.reverseP\x01Z-github.com/xtls/xray-core/proxy/vless/reverse\xaa\x02\x12Xray.Proxy.Reverseb\x06proto3"
|
||||
|
||||
var (
|
||||
file_proxy_vless_reverse_config_proto_rawDescOnce sync.Once
|
||||
file_proxy_vless_reverse_config_proto_rawDescData []byte
|
||||
)
|
||||
|
||||
func file_proxy_vless_reverse_config_proto_rawDescGZIP() []byte {
|
||||
file_proxy_vless_reverse_config_proto_rawDescOnce.Do(func() {
|
||||
file_proxy_vless_reverse_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_vless_reverse_config_proto_rawDesc), len(file_proxy_vless_reverse_config_proto_rawDesc)))
|
||||
})
|
||||
return file_proxy_vless_reverse_config_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_proxy_vless_reverse_config_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
|
||||
var file_proxy_vless_reverse_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
|
||||
var file_proxy_vless_reverse_config_proto_goTypes = []any{
|
||||
(Control_State)(0), // 0: xray.app.reverse.Control.State
|
||||
(*Control)(nil), // 1: xray.app.reverse.Control
|
||||
}
|
||||
var file_proxy_vless_reverse_config_proto_depIdxs = []int32{
|
||||
0, // 0: xray.app.reverse.Control.state:type_name -> xray.app.reverse.Control.State
|
||||
1, // [1:1] is the sub-list for method output_type
|
||||
1, // [1:1] is the sub-list for method input_type
|
||||
1, // [1:1] is the sub-list for extension type_name
|
||||
1, // [1:1] is the sub-list for extension extendee
|
||||
0, // [0:1] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_proxy_vless_reverse_config_proto_init() }
|
||||
func file_proxy_vless_reverse_config_proto_init() {
|
||||
if File_proxy_vless_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_proxy_vless_reverse_config_proto_rawDesc), len(file_proxy_vless_reverse_config_proto_rawDesc)),
|
||||
NumEnums: 1,
|
||||
NumMessages: 1,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
GoTypes: file_proxy_vless_reverse_config_proto_goTypes,
|
||||
DependencyIndexes: file_proxy_vless_reverse_config_proto_depIdxs,
|
||||
EnumInfos: file_proxy_vless_reverse_config_proto_enumTypes,
|
||||
MessageInfos: file_proxy_vless_reverse_config_proto_msgTypes,
|
||||
}.Build()
|
||||
File_proxy_vless_reverse_config_proto = out.File
|
||||
file_proxy_vless_reverse_config_proto_goTypes = nil
|
||||
file_proxy_vless_reverse_config_proto_depIdxs = nil
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package xray.app.reverse;
|
||||
option csharp_namespace = "Xray.Proxy.Reverse";
|
||||
option go_package = "github.com/xtls/xray-core/proxy/vless/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;
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package reverse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// StartIntranet maintains Reverse carriers until the returned cancellation function is called.
|
||||
// The opener derives each physical connection's context from the supplied context.
|
||||
func StartIntranet(ctx context.Context, dispatch func(context.Context, net.Destination, *transport.Link) error, open func(context.Context) (context.Context, *transport.Link, error)) func() {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
go func() {
|
||||
const interval = 2 * time.Second
|
||||
timer := time.NewTimer(interval)
|
||||
defer timer.Stop()
|
||||
var workers []*intranetWorker
|
||||
for ; ; timer.Reset(interval) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-timer.C:
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
var connections uint32
|
||||
active := workers[:0]
|
||||
for _, w := range workers {
|
||||
if w.state.Load() == int32(Control_ACTIVE) && !w.worker.Closed() {
|
||||
active = append(active, w)
|
||||
connections += w.worker.ActiveConnections()
|
||||
}
|
||||
}
|
||||
clear(workers[len(active):])
|
||||
workers = active
|
||||
if len(workers) != 0 && connections/uint32(len(workers)) <= 16 {
|
||||
continue
|
||||
}
|
||||
physical, link, err := open(ctx)
|
||||
if err != nil {
|
||||
errors.LogWarningInner(ctx, err, "failed to create intranet worker")
|
||||
continue
|
||||
}
|
||||
w := &intranetWorker{dispatch: dispatch}
|
||||
w.worker = multiplex.NewServerWorker(session.ContextWithIsReverseMux(physical, true), w.handle, link)
|
||||
workers = append(workers, w)
|
||||
}
|
||||
}()
|
||||
return cancel
|
||||
}
|
||||
|
||||
type intranetWorker struct {
|
||||
worker *multiplex.ServerWorker
|
||||
dispatch func(context.Context, net.Destination, *transport.Link) error
|
||||
state atomic.Int32
|
||||
}
|
||||
|
||||
// handle forwards user traffic or consumes the native Reverse control stream.
|
||||
func (w *intranetWorker) handle(ctx context.Context, dest net.Destination, link *transport.Link) error {
|
||||
if !isInternalDomain(dest) {
|
||||
return w.dispatch(ctx, dest, link)
|
||||
}
|
||||
defer common.Close(link.Writer)
|
||||
defer common.Interrupt(link.Reader)
|
||||
for {
|
||||
mb, readErr := link.Reader.ReadMultiBuffer()
|
||||
for _, b := range mb {
|
||||
var ctl Control
|
||||
if err := proto.Unmarshal(b.Bytes(), &ctl); err != nil {
|
||||
buf.ReleaseMulti(mb)
|
||||
errors.LogInfoInner(ctx, err, "failed to parse proto message")
|
||||
return nil
|
||||
}
|
||||
w.state.Store(int32(ctl.State))
|
||||
}
|
||||
buf.ReleaseMulti(mb)
|
||||
if readErr != nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package reverse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/signal"
|
||||
"github.com/xtls/xray-core/features"
|
||||
"github.com/xtls/xray-core/features/extension"
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
type PublicEndpoint struct {
|
||||
observer features.Feature
|
||||
tag string
|
||||
closed bool
|
||||
access sync.Mutex
|
||||
workers []*PublicWorker
|
||||
}
|
||||
|
||||
func NewPublicEndpoint(tag string, observer features.Feature) *PublicEndpoint {
|
||||
return &PublicEndpoint{tag: tag, observer: observer}
|
||||
}
|
||||
|
||||
func (p *PublicEndpoint) Tag() string { return p.tag }
|
||||
func (p *PublicEndpoint) SenderSettings() *serial.TypedMessage { return nil }
|
||||
func (p *PublicEndpoint) ProxySettings() *serial.TypedMessage { return nil }
|
||||
func (p *PublicEndpoint) Dispatch(ctx context.Context, link *transport.Link) {
|
||||
reader, writer := link.Reader, link.Writer
|
||||
if err := p.HandleConnection(ctx, link); err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to process reverse connection")
|
||||
common.Interrupt(writer)
|
||||
common.Interrupt(reader)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *PublicEndpoint) Accept(ctx context.Context, link *transport.Link) error {
|
||||
client := multiplex.NewClientWorker(ctx, *link, multiplex.ClientStrategy{})
|
||||
target := net.UDPDestination(net.DomainAddress(internalDomain), 0)
|
||||
controlCtx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{Target: target}})
|
||||
s := multiplex.NewSession(controlCtx, &transport.Link{Writer: buf.Discard})
|
||||
if !client.TryAdmit(controlCtx, s) {
|
||||
client.Close()
|
||||
return errors.New("failed to admit reverse control session")
|
||||
}
|
||||
worker := &PublicWorker{
|
||||
client: client,
|
||||
timer: signal.CancelAfterInactivity(context.Background(), func() { client.Close() }, 24*time.Hour),
|
||||
}
|
||||
defer func() {
|
||||
worker.Close()
|
||||
p.access.Lock()
|
||||
p.workers = slices.DeleteFunc(p.workers, func(current *PublicWorker) bool { return current == worker })
|
||||
p.access.Unlock()
|
||||
}()
|
||||
p.access.Lock()
|
||||
if p.closed || ctx.Err() != nil || client.Closed() {
|
||||
p.access.Unlock()
|
||||
return client.Err()
|
||||
}
|
||||
p.workers = append(p.workers, worker)
|
||||
p.access.Unlock()
|
||||
if observer, ok := p.observer.(extension.BurstObservatory); ok {
|
||||
go observer.Check([]string{p.tag})
|
||||
}
|
||||
go p.heartbeat(worker, s)
|
||||
<-client.WaitClosed()
|
||||
return client.Err()
|
||||
}
|
||||
|
||||
func (p *PublicEndpoint) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *PublicEndpoint) Close() error {
|
||||
p.access.Lock()
|
||||
p.closed = true
|
||||
workers := p.workers
|
||||
p.workers = nil
|
||||
p.access.Unlock()
|
||||
for _, worker := range workers {
|
||||
worker.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *PublicEndpoint) 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")
|
||||
}
|
||||
|
||||
reader, writer := link.Reader, link.Writer
|
||||
ctx = session.ContextWithIsReverseMux(ctx, true)
|
||||
|
||||
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 multiplex.Dispatch(ctx, link, p.Admit, func(physical context.Context) {
|
||||
stop := context.AfterFunc(physical, func() {
|
||||
common.Interrupt(writer)
|
||||
common.Interrupt(reader)
|
||||
})
|
||||
defer stop()
|
||||
common.Close(writer)
|
||||
common.Interrupt(reader)
|
||||
})
|
||||
}
|
||||
|
||||
func (p *PublicEndpoint) Admit(ctx context.Context, s *multiplex.Session) error {
|
||||
p.access.Lock()
|
||||
defer p.access.Unlock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.closed || len(p.workers) == 0 {
|
||||
return errors.New("empty worker list")
|
||||
}
|
||||
|
||||
// Failed reservations move out of this admission's candidate prefix.
|
||||
for remaining := len(p.workers); remaining > 0; {
|
||||
best, state := -1, Control_DRAIN
|
||||
var active uint32
|
||||
for i := 0; i < remaining; i++ {
|
||||
w := p.workers[i]
|
||||
a := w.client.ActiveConnections()
|
||||
if best == -1 || w.state < state || (w.state == state && a < active) {
|
||||
best, state, active = i, w.state, a
|
||||
}
|
||||
}
|
||||
if p.workers[best].client.TryAdmit(ctx, s) {
|
||||
return nil
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
remaining--
|
||||
p.workers[best], p.workers[remaining] = p.workers[remaining], p.workers[best]
|
||||
}
|
||||
|
||||
return errors.New("no mux client worker available")
|
||||
}
|
||||
|
||||
type PublicWorker struct {
|
||||
client *multiplex.ClientWorker
|
||||
state Control_State // guarded by PublicEndpoint.access; zero is ACTIVE
|
||||
timer *signal.ActivityTimer
|
||||
}
|
||||
|
||||
func (w *PublicWorker) Close() {
|
||||
w.client.Close()
|
||||
w.timer.SetTimeout(0)
|
||||
}
|
||||
|
||||
func (p *PublicEndpoint) heartbeat(w *PublicWorker, s *multiplex.Session) {
|
||||
var err error
|
||||
defer func() { s.CloseWithError(err) }()
|
||||
err = w.writeControl(s, Control_ACTIVE)
|
||||
if err != nil {
|
||||
w.client.Close()
|
||||
return
|
||||
}
|
||||
timer := time.NewTimer(2 * time.Second)
|
||||
defer timer.Stop()
|
||||
counter := uint32(1)
|
||||
for {
|
||||
select {
|
||||
case <-timer.C:
|
||||
case <-s.WaitClosed():
|
||||
err = io.ErrClosedPipe
|
||||
return
|
||||
case <-w.client.WaitClosed():
|
||||
err = io.ErrClosedPipe
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-s.WaitClosed():
|
||||
err = io.ErrClosedPipe
|
||||
return
|
||||
default:
|
||||
}
|
||||
if w.client.Closed() {
|
||||
err = io.ErrClosedPipe
|
||||
return
|
||||
}
|
||||
counter = (counter + 1) % 5
|
||||
if w.client.TotalConnections() > 256 {
|
||||
p.access.Lock()
|
||||
w.state = Control_DRAIN
|
||||
p.access.Unlock()
|
||||
err = w.writeControl(s, Control_DRAIN)
|
||||
return
|
||||
}
|
||||
if counter == 1 {
|
||||
if err = w.writeControl(s, Control_ACTIVE); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
timer.Reset(2 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *PublicWorker) writeControl(s *multiplex.Session, state Control_State) error {
|
||||
msg := &Control{State: state}
|
||||
msg.FillInRandom()
|
||||
b, err := proto.Marshal(msg)
|
||||
common.Must(err)
|
||||
w.timer.Update()
|
||||
return s.WriteMultiBuffer(buf.MergeBytes(nil, b))
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
feature_inbound "github.com/xtls/xray-core/features/inbound"
|
||||
"github.com/xtls/xray-core/features/policy"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
"github.com/xtls/xray-core/proxy/vmess"
|
||||
"github.com/xtls/xray-core/proxy/vmess/encoding"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
@@ -238,7 +239,6 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
|
||||
if err != nil {
|
||||
return errors.New("failed to start decoding").Base(err)
|
||||
}
|
||||
|
||||
writer := buf.NewBufferedWriter(buf.NewWriter(connection))
|
||||
response := &protocol.ResponseHeader{
|
||||
Command: h.generateCommand(ctx, request),
|
||||
@@ -249,12 +249,14 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
|
||||
return errors.New("failed to start decoding response").Base(err)
|
||||
}
|
||||
writer.SetFlushNext()
|
||||
link := &transport.Link{Reader: bodyReader, Writer: bodyWriter}
|
||||
|
||||
if err := dispatcher.DispatchLink(ctx, request.Destination(), &transport.Link{
|
||||
Reader: bodyReader,
|
||||
Writer: bodyWriter,
|
||||
},
|
||||
); err != nil {
|
||||
if request.Command == protocol.RequestCommandMux {
|
||||
worker := multiplex.NewServerWorker(ctx, dispatcher.DispatchLink, link)
|
||||
<-worker.WaitClosed()
|
||||
return worker.Err()
|
||||
}
|
||||
if err := dispatcher.DispatchLink(ctx, request.Destination(), link); err != nil {
|
||||
return errors.New("failed to dispatch request").Base(err)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
)
|
||||
|
||||
// As a stub command consumer.
|
||||
func (h *Handler) handleCommand(dest net.Destination, cmd protocol.ResponseCommand) {
|
||||
switch cmd.(type) {
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ package outbound
|
||||
|
||||
import (
|
||||
protocol "github.com/xtls/xray-core/common/protocol"
|
||||
vless "github.com/xtls/xray-core/proxy/vless"
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
@@ -25,6 +26,7 @@ const (
|
||||
type Config struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Receiver *protocol.ServerEndpoint `protobuf:"bytes,1,opt,name=Receiver,proto3" json:"Receiver,omitempty"`
|
||||
Multiplex *vless.Multiplex `protobuf:"bytes,2,opt,name=multiplex,proto3" json:"multiplex,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -66,13 +68,21 @@ func (x *Config) GetReceiver() *protocol.ServerEndpoint {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Config) GetMultiplex() *vless.Multiplex {
|
||||
if x != nil {
|
||||
return x.Multiplex
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_proxy_vmess_outbound_config_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_proxy_vmess_outbound_config_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"!proxy/vmess/outbound/config.proto\x12\x19xray.proxy.vmess.outbound\x1a!common/protocol/server_spec.proto\"J\n" +
|
||||
"!proxy/vmess/outbound/config.proto\x12\x19xray.proxy.vmess.outbound\x1a!common/protocol/server_spec.proto\x1a\x19proxy/vless/account.proto\"\x85\x01\n" +
|
||||
"\x06Config\x12@\n" +
|
||||
"\bReceiver\x18\x01 \x01(\v2$.xray.common.protocol.ServerEndpointR\bReceiverBm\n" +
|
||||
"\bReceiver\x18\x01 \x01(\v2$.xray.common.protocol.ServerEndpointR\bReceiver\x129\n" +
|
||||
"\tmultiplex\x18\x02 \x01(\v2\x1b.xray.proxy.vless.MultiplexR\tmultiplexBm\n" +
|
||||
"\x1dcom.xray.proxy.vmess.outboundP\x01Z.github.com/xtls/xray-core/proxy/vmess/outbound\xaa\x02\x19Xray.Proxy.Vmess.Outboundb\x06proto3"
|
||||
|
||||
var (
|
||||
@@ -91,14 +101,16 @@ var file_proxy_vmess_outbound_config_proto_msgTypes = make([]protoimpl.MessageIn
|
||||
var file_proxy_vmess_outbound_config_proto_goTypes = []any{
|
||||
(*Config)(nil), // 0: xray.proxy.vmess.outbound.Config
|
||||
(*protocol.ServerEndpoint)(nil), // 1: xray.common.protocol.ServerEndpoint
|
||||
(*vless.Multiplex)(nil), // 2: xray.proxy.vless.Multiplex
|
||||
}
|
||||
var file_proxy_vmess_outbound_config_proto_depIdxs = []int32{
|
||||
1, // 0: xray.proxy.vmess.outbound.Config.Receiver:type_name -> xray.common.protocol.ServerEndpoint
|
||||
1, // [1:1] is the sub-list for method output_type
|
||||
1, // [1:1] is the sub-list for method input_type
|
||||
1, // [1:1] is the sub-list for extension type_name
|
||||
1, // [1:1] is the sub-list for extension extendee
|
||||
0, // [0:1] is the sub-list for field type_name
|
||||
2, // 1: xray.proxy.vmess.outbound.Config.multiplex:type_name -> xray.proxy.vless.Multiplex
|
||||
2, // [2:2] is the sub-list for method output_type
|
||||
2, // [2:2] is the sub-list for method input_type
|
||||
2, // [2:2] is the sub-list for extension type_name
|
||||
2, // [2:2] is the sub-list for extension extendee
|
||||
0, // [0:2] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_proxy_vmess_outbound_config_proto_init() }
|
||||
|
||||
@@ -7,7 +7,9 @@ option java_package = "com.xray.proxy.vmess.outbound";
|
||||
option java_multiple_files = true;
|
||||
|
||||
import "common/protocol/server_spec.proto";
|
||||
import "proxy/vless/account.proto";
|
||||
|
||||
message Config {
|
||||
xray.common.protocol.ServerEndpoint Receiver = 1;
|
||||
xray.proxy.vless.Multiplex multiplex = 2;
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"github.com/xtls/xray-core/common/xudp"
|
||||
core "github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/features/policy"
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
"github.com/xtls/xray-core/proxy/vmess"
|
||||
"github.com/xtls/xray-core/proxy/vmess/encoding"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
@@ -32,6 +33,8 @@ import (
|
||||
type Handler struct {
|
||||
server *protocol.ServerSpec
|
||||
policyManager policy.Manager
|
||||
multiplex *multiplex.Client
|
||||
stopMultiplex context.CancelFunc
|
||||
}
|
||||
|
||||
// New creates a new VMess outbound handler.
|
||||
@@ -44,21 +47,55 @@ func New(ctx context.Context, config *Config) (*Handler, error) {
|
||||
return nil, errors.New("failed to get server spec").Base(err)
|
||||
}
|
||||
|
||||
muxConfig, err := multiplex.NormalizeConfig(config.Multiplex)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v := core.MustFromContext(ctx)
|
||||
handler := &Handler{
|
||||
server: server,
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
}
|
||||
if muxConfig != nil {
|
||||
dialer, ok := session.FullHandlerFromContext(ctx).(internet.Dialer)
|
||||
if !ok {
|
||||
return nil, errors.New("VMess multiplex requires an outbound dialer")
|
||||
}
|
||||
poolCtx, stop := context.WithCancel(context.Background())
|
||||
handler.stopMultiplex = stop
|
||||
handler.multiplex = multiplex.NewClient(poolCtx, muxConfig, "", func(ctx context.Context) (context.Context, *transport.Link, error) {
|
||||
return handler.process(ctx, nil, dialer, protocol.RequestCommandMux)
|
||||
})
|
||||
}
|
||||
|
||||
return handler, nil
|
||||
}
|
||||
|
||||
func (h *Handler) Close() error {
|
||||
if h.stopMultiplex != nil {
|
||||
h.stopMultiplex()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Process implements proxy.Outbound.Process().
|
||||
func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
|
||||
if handled, err := h.multiplex.Dispatch(ctx, link); handled {
|
||||
return err
|
||||
}
|
||||
_, _, err := h.process(ctx, link, dialer, 0)
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *Handler) process(ctx context.Context, link *transport.Link, dialer internet.Dialer, command protocol.RequestCommand) (_ context.Context, _ *transport.Link, err error) {
|
||||
native := command == protocol.RequestCommandMux
|
||||
if native {
|
||||
ctx = session.ContextWithOutbounds(ctx, []*session.Outbound{{Target: h.server.Destination}})
|
||||
}
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
ob := outbounds[len(outbounds)-1]
|
||||
if !ob.Target.IsValid() {
|
||||
return errors.New("target not specified")
|
||||
return nil, nil, errors.New("target not specified")
|
||||
}
|
||||
ob.Name = "vmess"
|
||||
ob.CanSpliceCopy = 3
|
||||
@@ -66,7 +103,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
rec := h.server
|
||||
var conn stat.Connection
|
||||
|
||||
err := retry.ExponentialBackoff(5, 200).On(func() error {
|
||||
err = retry.ExponentialBackoff(5, 200).On(func() error {
|
||||
rawConn, err := dialer.Dial(ctx, rec.Destination)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -76,30 +113,30 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return errors.New("failed to find an available destination").Base(err)
|
||||
return nil, nil, errors.New("failed to find an available destination").Base(err)
|
||||
}
|
||||
if !native {
|
||||
defer conn.Close()
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
target := ob.Target
|
||||
errors.LogInfo(ctx, "tunneling request to ", target, " via ", rec.Destination.NetAddr())
|
||||
|
||||
command := protocol.RequestCommandTCP
|
||||
if target.Network == net.Network_UDP {
|
||||
command = protocol.RequestCommandUDP
|
||||
}
|
||||
if target.Address.Family().IsDomain() && target.Address.Domain() == "v1.mux.cool" {
|
||||
command = protocol.RequestCommandMux
|
||||
}
|
||||
|
||||
user := rec.User
|
||||
singleXUDP := target.Network == net.Network_UDP && target.Port != 53 && target.Port != 443
|
||||
request := &protocol.RequestHeader{
|
||||
Version: encoding.Version,
|
||||
User: user,
|
||||
Command: command,
|
||||
User: rec.User,
|
||||
Command: protocol.RequestCommandTCP,
|
||||
Address: target.Address,
|
||||
Port: target.Port,
|
||||
Option: protocol.RequestOptionChunkStream,
|
||||
}
|
||||
switch {
|
||||
case native || singleXUDP:
|
||||
request.Command = protocol.RequestCommandMux
|
||||
case target.Network == net.Network_UDP:
|
||||
request.Command = protocol.RequestCommandUDP
|
||||
}
|
||||
|
||||
account := request.User.Account.(*vmess.MemoryAccount)
|
||||
request.Security = account.Security
|
||||
@@ -107,7 +144,6 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
if request.Security == protocol.SecurityType_AES128_GCM || request.Security == protocol.SecurityType_CHACHA20_POLY1305 {
|
||||
request.Option.Set(protocol.RequestOptionChunkMasking)
|
||||
}
|
||||
|
||||
if shouldEnablePadding(request.Security) && request.Option.Has(protocol.RequestOptionChunkMasking) {
|
||||
request.Option.Set(protocol.RequestOptionGlobalPadding)
|
||||
}
|
||||
@@ -116,54 +152,60 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
request.Option.Set(protocol.RequestOptionAuthenticatedLength)
|
||||
}
|
||||
|
||||
input := link.Reader
|
||||
output := link.Writer
|
||||
|
||||
hashkdf := hmac.New(sha256.New, []byte("VMessBF"))
|
||||
hashkdf.Write(account.ID.Bytes())
|
||||
|
||||
behaviorSeed := crc64.Checksum(hashkdf.Sum(nil), crc64.MakeTable(crc64.ISO))
|
||||
|
||||
var newCtx context.Context
|
||||
var newCancel context.CancelFunc
|
||||
clientSession := encoding.NewClientSession(ctx, int64(behaviorSeed))
|
||||
sessionPolicy := h.policyManager.ForLevel(request.User.Level)
|
||||
if session.TimeoutOnlyFromContext(ctx) {
|
||||
newCtx, newCancel = context.WithCancel(context.Background())
|
||||
ctx = context.Background()
|
||||
}
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
|
||||
if native {
|
||||
context.AfterFunc(ctx, func() { common.Interrupt(stat.TryUnwrapStatsConn(conn)) })
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
timer.SetTimeout(0)
|
||||
}
|
||||
}()
|
||||
|
||||
writer := buf.NewBufferedWriter(buf.NewWriter(conn))
|
||||
if err := clientSession.EncodeRequestHeader(request, writer); err != nil {
|
||||
return nil, nil, errors.New("failed to encode request").Base(err)
|
||||
}
|
||||
|
||||
session := encoding.NewClientSession(ctx, int64(behaviorSeed))
|
||||
sessionPolicy := h.policyManager.ForLevel(request.User.Level)
|
||||
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
timer := signal.CancelAfterInactivity(ctx, func() {
|
||||
cancel()
|
||||
if newCancel != nil {
|
||||
newCancel()
|
||||
bodyWriter, err := clientSession.EncodeRequestBody(request, writer)
|
||||
if err != nil {
|
||||
return nil, nil, errors.New("failed to start encoding").Base(err)
|
||||
}
|
||||
openResponse := func() (buf.Reader, error) {
|
||||
reader := &buf.BufferedReader{Reader: buf.NewReader(conn)}
|
||||
if _, err := clientSession.DecodeResponseHeader(reader); err != nil {
|
||||
return nil, errors.New("failed to read header").Base(err)
|
||||
}
|
||||
}, sessionPolicy.Timeouts.ConnectionIdle)
|
||||
return clientSession.DecodeResponseBody(request, reader)
|
||||
}
|
||||
|
||||
if request.Command == protocol.RequestCommandUDP && request.Port != 53 && request.Port != 443 {
|
||||
request.Command = protocol.RequestCommandMux
|
||||
request.Address = net.DomainAddress("v1.mux.cool")
|
||||
request.Port = net.Port(666)
|
||||
if native {
|
||||
if err := writer.SetBuffered(false); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
physical, err := multiplex.OpenLink(ctx, cancel, bodyWriter, timer, openResponse)
|
||||
return ctx, physical, err
|
||||
}
|
||||
|
||||
requestDone := func() error {
|
||||
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
|
||||
|
||||
writer := buf.NewBufferedWriter(buf.NewWriter(conn))
|
||||
if err := session.EncodeRequestHeader(request, writer); err != nil {
|
||||
return errors.New("failed to encode request").Base(err)
|
||||
stream := bodyWriter
|
||||
if singleXUDP {
|
||||
stream = xudp.NewPacketWriter(bodyWriter, target, xudp.GetGlobalID(ctx))
|
||||
}
|
||||
|
||||
bodyWriter, err := session.EncodeRequestBody(request, writer)
|
||||
if err != nil {
|
||||
return errors.New("failed to start encoding").Base(err)
|
||||
}
|
||||
bodyWriter2 := bodyWriter
|
||||
if request.Command == protocol.RequestCommandMux && request.Port == 666 {
|
||||
bodyWriter = xudp.NewPacketWriter(bodyWriter, target, xudp.GetGlobalID(ctx))
|
||||
}
|
||||
if err := buf.CopyOnceTimeout(input, bodyWriter, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout {
|
||||
if err := buf.CopyOnceTimeout(link.Reader, stream, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout {
|
||||
return errors.New("failed to write first payload").Base(err)
|
||||
}
|
||||
|
||||
@@ -171,50 +213,33 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
return err
|
||||
}
|
||||
|
||||
if err := buf.Copy(input, bodyWriter, buf.UpdateActivity(timer)); err != nil {
|
||||
err := buf.Copy(link.Reader, stream, buf.UpdateActivity(timer))
|
||||
if err != nil || account.NoTerminationSignal {
|
||||
return err
|
||||
}
|
||||
|
||||
if request.Option.Has(protocol.RequestOptionChunkStream) && !account.NoTerminationSignal {
|
||||
if err := bodyWriter2.WriteMultiBuffer(buf.MultiBuffer{}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
return bodyWriter.WriteMultiBuffer(buf.MultiBuffer{})
|
||||
}
|
||||
|
||||
responseDone := func() error {
|
||||
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
|
||||
|
||||
reader := &buf.BufferedReader{Reader: buf.NewReader(conn)}
|
||||
header, err := session.DecodeResponseHeader(reader)
|
||||
bodyReader, err := openResponse()
|
||||
if err != nil {
|
||||
return errors.New("failed to read header").Base(err)
|
||||
return err
|
||||
}
|
||||
h.handleCommand(rec.Destination, header.Command)
|
||||
|
||||
bodyReader, err := session.DecodeResponseBody(request, reader)
|
||||
if err != nil {
|
||||
return errors.New("failed to start encoding response").Base(err)
|
||||
}
|
||||
if request.Command == protocol.RequestCommandMux && request.Port == 666 {
|
||||
if singleXUDP {
|
||||
bodyReader = xudp.NewPacketReader(&buf.BufferedReader{Reader: bodyReader})
|
||||
}
|
||||
|
||||
return buf.Copy(bodyReader, output, buf.UpdateActivity(timer))
|
||||
return buf.Copy(bodyReader, link.Writer, buf.UpdateActivity(timer))
|
||||
}
|
||||
|
||||
if newCtx != nil {
|
||||
ctx = newCtx
|
||||
}
|
||||
|
||||
responseDonePost := task.OnSuccess(responseDone, task.Close(output))
|
||||
responseDonePost := task.OnSuccess(responseDone, task.Close(link.Writer))
|
||||
if err := task.Run(ctx, requestDone, responseDonePost); err != nil {
|
||||
return errors.New("connection ends").Base(err)
|
||||
return nil, nil, errors.New("connection ends").Base(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
return nil, nil, nil
|
||||
}
|
||||
|
||||
var enablePadding atomic.Bool
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
// Code generated by MockGen. DO NOT EDIT.
|
||||
// Source: github.com/xtls/xray-core/common/mux (interfaces: ClientWorkerFactory)
|
||||
|
||||
// Package mocks is a generated GoMock package.
|
||||
package mocks
|
||||
|
||||
import (
|
||||
reflect "reflect"
|
||||
|
||||
gomock "github.com/golang/mock/gomock"
|
||||
mux "github.com/xtls/xray-core/common/mux"
|
||||
)
|
||||
|
||||
// MuxClientWorkerFactory is a mock of ClientWorkerFactory interface
|
||||
type MuxClientWorkerFactory struct {
|
||||
ctrl *gomock.Controller
|
||||
recorder *MuxClientWorkerFactoryMockRecorder
|
||||
}
|
||||
|
||||
// MuxClientWorkerFactoryMockRecorder is the mock recorder for MuxClientWorkerFactory
|
||||
type MuxClientWorkerFactoryMockRecorder struct {
|
||||
mock *MuxClientWorkerFactory
|
||||
}
|
||||
|
||||
// NewMuxClientWorkerFactory creates a new mock instance
|
||||
func NewMuxClientWorkerFactory(ctrl *gomock.Controller) *MuxClientWorkerFactory {
|
||||
mock := &MuxClientWorkerFactory{ctrl: ctrl}
|
||||
mock.recorder = &MuxClientWorkerFactoryMockRecorder{mock}
|
||||
return mock
|
||||
}
|
||||
|
||||
// EXPECT returns an object that allows the caller to indicate expected use
|
||||
func (m *MuxClientWorkerFactory) EXPECT() *MuxClientWorkerFactoryMockRecorder {
|
||||
return m.recorder
|
||||
}
|
||||
|
||||
// Create mocks base method
|
||||
func (m *MuxClientWorkerFactory) Create() (*mux.ClientWorker, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "Create")
|
||||
ret0, _ := ret[0].(*mux.ClientWorker)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// Create indicates an expected call of Create
|
||||
func (mr *MuxClientWorkerFactoryMockRecorder) Create() *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MuxClientWorkerFactory)(nil).Create))
|
||||
}
|
||||
@@ -4,24 +4,20 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/app/log"
|
||||
"github.com/xtls/xray-core/app/policy"
|
||||
"github.com/xtls/xray-core/app/proxyman"
|
||||
"github.com/xtls/xray-core/app/reverse"
|
||||
"github.com/xtls/xray-core/app/router"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
clog "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/retry"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/uuid"
|
||||
core "github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/proxy/dokodemo"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
"github.com/xtls/xray-core/proxy/vmess"
|
||||
"github.com/xtls/xray-core/proxy/vmess/inbound"
|
||||
"github.com/xtls/xray-core/proxy/vmess/outbound"
|
||||
"github.com/xtls/xray-core/proxy/vless"
|
||||
"github.com/xtls/xray-core/proxy/vless/inbound"
|
||||
"github.com/xtls/xray-core/proxy/vless/outbound"
|
||||
"github.com/xtls/xray-core/testing/servers/tcp"
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
@@ -41,24 +37,8 @@ func TestReverseProxy(t *testing.T) {
|
||||
|
||||
serverConfig := &core.Config{
|
||||
App: []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&reverse.Config{
|
||||
PortalConfig: []*reverse.PortalConfig{
|
||||
{
|
||||
Tag: "portal",
|
||||
Domain: "test.example.com",
|
||||
},
|
||||
},
|
||||
}),
|
||||
serial.ToTypedMessage(&router.Config{
|
||||
Rule: []*router.RoutingRule{
|
||||
{
|
||||
Domain: []*geodata.DomainRule{
|
||||
{Value: &geodata.DomainRule_Custom{Custom: &geodata.Domain{Type: geodata.Domain_Full, Value: "test.example.com"}}},
|
||||
},
|
||||
TargetTag: &router.RoutingRule_Tag{
|
||||
Tag: "portal",
|
||||
},
|
||||
},
|
||||
{
|
||||
InboundTag: []string{"external"},
|
||||
TargetTag: &router.RoutingRule_Tag{
|
||||
@@ -87,10 +67,11 @@ func TestReverseProxy(t *testing.T) {
|
||||
Listen: net.NewIPOrDomain(net.LocalHostIP),
|
||||
}),
|
||||
ProxySettings: serial.ToTypedMessage(&inbound.Config{
|
||||
User: []*protocol.User{
|
||||
Users: []*protocol.User{
|
||||
{
|
||||
Account: serial.ToTypedMessage(&vmess.Account{
|
||||
Id: userID.String(),
|
||||
Account: serial.ToTypedMessage(&vless.Account{
|
||||
Id: userID.String(),
|
||||
Reverse: &vless.Reverse{Tag: "portal"},
|
||||
}),
|
||||
},
|
||||
},
|
||||
@@ -107,24 +88,8 @@ func TestReverseProxy(t *testing.T) {
|
||||
clientPort := tcp.PickPort()
|
||||
clientConfig := &core.Config{
|
||||
App: []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&reverse.Config{
|
||||
BridgeConfig: []*reverse.BridgeConfig{
|
||||
{
|
||||
Tag: "bridge",
|
||||
Domain: "test.example.com",
|
||||
},
|
||||
},
|
||||
}),
|
||||
serial.ToTypedMessage(&router.Config{
|
||||
Rule: []*router.RoutingRule{
|
||||
{
|
||||
Domain: []*geodata.DomainRule{
|
||||
{Value: &geodata.DomainRule_Custom{Custom: &geodata.Domain{Type: geodata.Domain_Full, Value: "test.example.com"}}},
|
||||
},
|
||||
TargetTag: &router.RoutingRule_Tag{
|
||||
Tag: "reverse",
|
||||
},
|
||||
},
|
||||
{
|
||||
InboundTag: []string{"bridge"},
|
||||
TargetTag: &router.RoutingRule_Tag{
|
||||
@@ -155,15 +120,13 @@ func TestReverseProxy(t *testing.T) {
|
||||
{
|
||||
Tag: "reverse",
|
||||
ProxySettings: serial.ToTypedMessage(&outbound.Config{
|
||||
Receiver: &protocol.ServerEndpoint{
|
||||
Vnext: &protocol.ServerEndpoint{
|
||||
Address: net.NewIPOrDomain(net.LocalHostIP),
|
||||
Port: uint32(reversePort),
|
||||
User: &protocol.User{
|
||||
Account: serial.ToTypedMessage(&vmess.Account{
|
||||
Id: userID.String(),
|
||||
SecuritySettings: &protocol.SecurityConfig{
|
||||
Type: protocol.SecurityType_AES128_GCM,
|
||||
},
|
||||
Account: serial.ToTypedMessage(&vless.Account{
|
||||
Id: userID.String(),
|
||||
Reverse: &vless.Reverse{Tag: "bridge"},
|
||||
}),
|
||||
},
|
||||
},
|
||||
@@ -177,198 +140,16 @@ func TestReverseProxy(t *testing.T) {
|
||||
|
||||
defer CloseAllServers(servers)
|
||||
|
||||
if err := retry.Timed(20, 100).On(testTCPConn(externalPort, 1, time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var errg errgroup.Group
|
||||
for range 32 {
|
||||
errg.Go(testTCPConn(externalPort, 10240*1024, time.Second*40))
|
||||
for range 4 {
|
||||
errg.Go(testTCPConn(externalPort, 64*1024, time.Second*10))
|
||||
}
|
||||
|
||||
if err := errg.Wait(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReverseProxyLongRunning(t *testing.T) {
|
||||
tcpServer := tcp.Server{
|
||||
MsgProcessor: xor,
|
||||
}
|
||||
dest, err := tcpServer.Start()
|
||||
common.Must(err)
|
||||
|
||||
defer tcpServer.Close()
|
||||
|
||||
userID := protocol.NewID(uuid.New())
|
||||
externalPort := tcp.PickPort()
|
||||
reversePort := tcp.PickPort()
|
||||
|
||||
serverConfig := &core.Config{
|
||||
App: []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&log.Config{
|
||||
ErrorLogLevel: clog.Severity_Warning,
|
||||
ErrorLogType: log.LogType_Console,
|
||||
}),
|
||||
serial.ToTypedMessage(&policy.Config{
|
||||
Level: map[uint32]*policy.Policy{
|
||||
0: {
|
||||
Timeout: &policy.Policy_Timeout{
|
||||
UplinkOnly: &policy.Second{Value: 0},
|
||||
DownlinkOnly: &policy.Second{Value: 0},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
serial.ToTypedMessage(&reverse.Config{
|
||||
PortalConfig: []*reverse.PortalConfig{
|
||||
{
|
||||
Tag: "portal",
|
||||
Domain: "test.example.com",
|
||||
},
|
||||
},
|
||||
}),
|
||||
serial.ToTypedMessage(&router.Config{
|
||||
Rule: []*router.RoutingRule{
|
||||
{
|
||||
Domain: []*geodata.DomainRule{
|
||||
{Value: &geodata.DomainRule_Custom{Custom: &geodata.Domain{Type: geodata.Domain_Full, Value: "test.example.com"}}},
|
||||
},
|
||||
TargetTag: &router.RoutingRule_Tag{
|
||||
Tag: "portal",
|
||||
},
|
||||
},
|
||||
{
|
||||
InboundTag: []string{"external"},
|
||||
TargetTag: &router.RoutingRule_Tag{
|
||||
Tag: "portal",
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
Inbound: []*core.InboundHandlerConfig{
|
||||
{
|
||||
Tag: "external",
|
||||
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
|
||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(externalPort)}},
|
||||
Listen: net.NewIPOrDomain(net.LocalHostIP),
|
||||
}),
|
||||
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
|
||||
RewriteAddress: net.NewIPOrDomain(dest.Address),
|
||||
RewritePort: uint32(dest.Port),
|
||||
AllowedNetworks: []net.Network{net.Network_TCP},
|
||||
}),
|
||||
},
|
||||
{
|
||||
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
|
||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(reversePort)}},
|
||||
Listen: net.NewIPOrDomain(net.LocalHostIP),
|
||||
}),
|
||||
ProxySettings: serial.ToTypedMessage(&inbound.Config{
|
||||
User: []*protocol.User{
|
||||
{
|
||||
Account: serial.ToTypedMessage(&vmess.Account{
|
||||
Id: userID.String(),
|
||||
}),
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
clientPort := tcp.PickPort()
|
||||
clientConfig := &core.Config{
|
||||
App: []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&log.Config{
|
||||
ErrorLogLevel: clog.Severity_Warning,
|
||||
ErrorLogType: log.LogType_Console,
|
||||
}),
|
||||
serial.ToTypedMessage(&policy.Config{
|
||||
Level: map[uint32]*policy.Policy{
|
||||
0: {
|
||||
Timeout: &policy.Policy_Timeout{
|
||||
UplinkOnly: &policy.Second{Value: 0},
|
||||
DownlinkOnly: &policy.Second{Value: 0},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
serial.ToTypedMessage(&reverse.Config{
|
||||
BridgeConfig: []*reverse.BridgeConfig{
|
||||
{
|
||||
Tag: "bridge",
|
||||
Domain: "test.example.com",
|
||||
},
|
||||
},
|
||||
}),
|
||||
serial.ToTypedMessage(&router.Config{
|
||||
Rule: []*router.RoutingRule{
|
||||
{
|
||||
Domain: []*geodata.DomainRule{
|
||||
{Value: &geodata.DomainRule_Custom{Custom: &geodata.Domain{Type: geodata.Domain_Full, Value: "test.example.com"}}},
|
||||
},
|
||||
TargetTag: &router.RoutingRule_Tag{
|
||||
Tag: "reverse",
|
||||
},
|
||||
},
|
||||
{
|
||||
InboundTag: []string{"bridge"},
|
||||
TargetTag: &router.RoutingRule_Tag{
|
||||
Tag: "freedom",
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
Inbound: []*core.InboundHandlerConfig{
|
||||
{
|
||||
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
|
||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(clientPort)}},
|
||||
Listen: net.NewIPOrDomain(net.LocalHostIP),
|
||||
}),
|
||||
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
|
||||
RewriteAddress: net.NewIPOrDomain(dest.Address),
|
||||
RewritePort: uint32(dest.Port),
|
||||
AllowedNetworks: []net.Network{net.Network_TCP},
|
||||
}),
|
||||
},
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
Tag: "freedom",
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
|
||||
},
|
||||
{
|
||||
Tag: "reverse",
|
||||
ProxySettings: serial.ToTypedMessage(&outbound.Config{
|
||||
Receiver: &protocol.ServerEndpoint{
|
||||
Address: net.NewIPOrDomain(net.LocalHostIP),
|
||||
Port: uint32(reversePort),
|
||||
User: &protocol.User{
|
||||
Account: serial.ToTypedMessage(&vmess.Account{
|
||||
Id: userID.String(),
|
||||
SecuritySettings: &protocol.SecurityConfig{
|
||||
Type: protocol.SecurityType_AES128_GCM,
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
|
||||
common.Must(err)
|
||||
|
||||
defer CloseAllServers(servers)
|
||||
|
||||
for range 4096 {
|
||||
if err := testTCPConn(externalPort, 1024, time.Second*20)(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,103 +290,3 @@ func TestShadowsocksAES128GCMUDP(t *testing.T) {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShadowsocksAES128GCMUDPMux(t *testing.T) {
|
||||
udpServer := udp.Server{
|
||||
MsgProcessor: xor,
|
||||
}
|
||||
dest, err := udpServer.Start()
|
||||
common.Must(err)
|
||||
defer udpServer.Close()
|
||||
|
||||
account := serial.ToTypedMessage(&shadowsocks.Account{
|
||||
Password: "shadowsocks-password",
|
||||
CipherType: shadowsocks.CipherType_AES_128_GCM,
|
||||
})
|
||||
|
||||
serverPort := tcp.PickPort()
|
||||
serverConfig := &core.Config{
|
||||
App: []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&log.Config{
|
||||
ErrorLogLevel: clog.Severity_Debug,
|
||||
ErrorLogType: log.LogType_Console,
|
||||
}),
|
||||
},
|
||||
Inbound: []*core.InboundHandlerConfig{
|
||||
{
|
||||
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
|
||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(serverPort)}},
|
||||
Listen: net.NewIPOrDomain(net.LocalHostIP),
|
||||
}),
|
||||
ProxySettings: serial.ToTypedMessage(&shadowsocks.ServerConfig{
|
||||
Users: []*protocol.User{{
|
||||
Account: account,
|
||||
Level: 1,
|
||||
}},
|
||||
Network: []net.Network{net.Network_TCP},
|
||||
}),
|
||||
},
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
|
||||
}),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
clientPort := udp.PickPort()
|
||||
clientConfig := &core.Config{
|
||||
App: []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&log.Config{
|
||||
ErrorLogLevel: clog.Severity_Debug,
|
||||
ErrorLogType: log.LogType_Console,
|
||||
}),
|
||||
},
|
||||
Inbound: []*core.InboundHandlerConfig{
|
||||
{
|
||||
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
|
||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(clientPort)}},
|
||||
Listen: net.NewIPOrDomain(net.LocalHostIP),
|
||||
}),
|
||||
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
|
||||
RewriteAddress: net.NewIPOrDomain(dest.Address),
|
||||
RewritePort: uint32(dest.Port),
|
||||
AllowedNetworks: []net.Network{net.Network_UDP},
|
||||
}),
|
||||
},
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
|
||||
MultiplexSettings: &proxyman.MultiplexingConfig{
|
||||
Enabled: true,
|
||||
Concurrency: 8,
|
||||
},
|
||||
}),
|
||||
ProxySettings: serial.ToTypedMessage(&shadowsocks.ClientConfig{
|
||||
Server: &protocol.ServerEndpoint{
|
||||
Address: net.NewIPOrDomain(net.LocalHostIP),
|
||||
Port: uint32(serverPort),
|
||||
User: &protocol.User{
|
||||
Account: account,
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
|
||||
common.Must(err)
|
||||
defer CloseAllServers(servers)
|
||||
|
||||
var errGroup errgroup.Group
|
||||
for range 3 {
|
||||
errGroup.Go(testUDPConn(clientPort, 1024, time.Second*5))
|
||||
}
|
||||
if err := errGroup.Wait(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -33,7 +34,47 @@ import (
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
|
||||
func countTCPCarriers(t *testing.T, target net.Port) (net.Port, *atomic.Int32) {
|
||||
t.Helper()
|
||||
addr := &net.TCPAddr{IP: net.LocalHostIP.IP()}
|
||||
listener, err := net.ListenTCP("tcp", addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { listener.Close() })
|
||||
count := new(atomic.Int32)
|
||||
go func() {
|
||||
for {
|
||||
conn, err := listener.AcceptTCP()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
count.Add(1)
|
||||
go func() {
|
||||
defer conn.Close()
|
||||
server, err := net.DialTCP("tcp", nil, &net.TCPAddr{IP: addr.IP, Port: int(target)})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer server.Close()
|
||||
go func() {
|
||||
io.Copy(server, conn)
|
||||
server.CloseWrite()
|
||||
}()
|
||||
io.Copy(conn, server)
|
||||
}()
|
||||
}
|
||||
}()
|
||||
return net.Port(listener.Addr().(*net.TCPAddr).Port), count
|
||||
}
|
||||
|
||||
func TestVless(t *testing.T) {
|
||||
t.Run("direct", func(t *testing.T) { testVlessTCP(t, false) })
|
||||
t.Run("native-multiplex", func(t *testing.T) { testVlessTCP(t, true) })
|
||||
}
|
||||
|
||||
func testVlessTCP(t *testing.T, nativeMux bool) {
|
||||
t.Helper()
|
||||
tcpServer := tcp.Server{
|
||||
MsgProcessor: xor,
|
||||
}
|
||||
@@ -76,6 +117,14 @@ func TestVless(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
outboundPort := serverPort
|
||||
var carrierCount func() int32
|
||||
var multiplex *vless.Multiplex
|
||||
if nativeMux {
|
||||
port, count := countTCPCarriers(t, serverPort)
|
||||
outboundPort, carrierCount = port, count.Load
|
||||
multiplex = &vless.Multiplex{Concurrency: 4}
|
||||
}
|
||||
clientPort := tcp.PickPort()
|
||||
clientConfig := &core.Config{
|
||||
App: []*serial.TypedMessage{
|
||||
@@ -100,9 +149,10 @@ func TestVless(t *testing.T) {
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&outbound.Config{
|
||||
Multiplex: multiplex,
|
||||
Vnext: &protocol.ServerEndpoint{
|
||||
Address: net.NewIPOrDomain(net.LocalHostIP),
|
||||
Port: uint32(serverPort),
|
||||
Port: uint32(outboundPort),
|
||||
User: &protocol.User{
|
||||
Account: serial.ToTypedMessage(&vless.Account{
|
||||
Id: userID.String(),
|
||||
@@ -118,6 +168,11 @@ func TestVless(t *testing.T) {
|
||||
common.Must(err)
|
||||
defer CloseAllServers(servers)
|
||||
|
||||
if nativeMux {
|
||||
if err := testTCPConn(clientPort, 64*1024, time.Second*10)(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var errg errgroup.Group
|
||||
for range 3 {
|
||||
errg.Go(testTCPConn(clientPort, 1024*1024, time.Second*30))
|
||||
@@ -125,6 +180,11 @@ func TestVless(t *testing.T) {
|
||||
if err := errg.Wait(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if nativeMux {
|
||||
if got := carrierCount(); got != 1 {
|
||||
t.Errorf("connections used %d physical carriers, want 1", got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVlessTls(t *testing.T) {
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
core "github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/proxy/dokodemo"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
"github.com/xtls/xray-core/proxy/vless"
|
||||
"github.com/xtls/xray-core/proxy/vmess"
|
||||
"github.com/xtls/xray-core/proxy/vmess/inbound"
|
||||
"github.com/xtls/xray-core/proxy/vmess/outbound"
|
||||
@@ -680,6 +681,7 @@ func TestVMessGCMMux(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
carrierPort, carriers := countTCPCarriers(t, serverPort)
|
||||
clientPort := tcp.PickPort()
|
||||
clientConfig := &core.Config{
|
||||
App: []*serial.TypedMessage{
|
||||
@@ -703,16 +705,11 @@ func TestVMessGCMMux(t *testing.T) {
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
|
||||
MultiplexSettings: &proxyman.MultiplexingConfig{
|
||||
Enabled: true,
|
||||
Concurrency: 4,
|
||||
},
|
||||
}),
|
||||
ProxySettings: serial.ToTypedMessage(&outbound.Config{
|
||||
Multiplex: &vless.Multiplex{Concurrency: 4},
|
||||
Receiver: &protocol.ServerEndpoint{
|
||||
Address: net.NewIPOrDomain(net.LocalHostIP),
|
||||
Port: uint32(serverPort),
|
||||
Port: uint32(carrierPort),
|
||||
User: &protocol.User{
|
||||
Account: serial.ToTypedMessage(&vmess.Account{
|
||||
Id: userID.String(),
|
||||
@@ -731,7 +728,10 @@ func TestVMessGCMMux(t *testing.T) {
|
||||
common.Must(err)
|
||||
defer CloseAllServers(servers)
|
||||
|
||||
for range "abcd" {
|
||||
if err := testTCPConn(clientPort, 10240, 10*time.Second)(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for range 4 {
|
||||
var errg errgroup.Group
|
||||
for range 3 {
|
||||
errg.Go(testTCPConn(clientPort, 10240, time.Second*20))
|
||||
@@ -739,7 +739,9 @@ func TestVMessGCMMux(t *testing.T) {
|
||||
if err := errg.Wait(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
if got := carriers.Load(); got != 1 {
|
||||
t.Errorf("connections used %d physical carriers, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -793,6 +795,7 @@ func TestVMessGCMMuxUDP(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
carrierPort, carriers := countTCPCarriers(t, serverPort)
|
||||
clientPort := tcp.PickPort()
|
||||
clientUDPPort := udp.PickPort()
|
||||
clientConfig := &core.Config{
|
||||
@@ -828,16 +831,11 @@ func TestVMessGCMMuxUDP(t *testing.T) {
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
|
||||
MultiplexSettings: &proxyman.MultiplexingConfig{
|
||||
Enabled: true,
|
||||
Concurrency: 4,
|
||||
},
|
||||
}),
|
||||
ProxySettings: serial.ToTypedMessage(&outbound.Config{
|
||||
Multiplex: &vless.Multiplex{Concurrency: 16},
|
||||
Receiver: &protocol.ServerEndpoint{
|
||||
Address: net.NewIPOrDomain(net.LocalHostIP),
|
||||
Port: uint32(serverPort),
|
||||
Port: uint32(carrierPort),
|
||||
User: &protocol.User{
|
||||
Account: serial.ToTypedMessage(&vmess.Account{
|
||||
Id: userID.String(),
|
||||
@@ -867,6 +865,10 @@ func TestVMessGCMMuxUDP(t *testing.T) {
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
|
||||
if got := carriers.Load(); got != 1 {
|
||||
t.Errorf("TCP and UDP used %d physical carriers, want 1", got)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
<-time.After(5 * time.Second)
|
||||
CloseAllServers(servers)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user