Compare commits

..
8 Commits
Author SHA1 Message Date
Fangliding 75a9977537 format 2026-11-26 21:24:20 +08:00
Fangliding fcf0e2378a refine 2026-11-26 21:19:36 +08:00
Fangliding bd62d6ffcb Fix 2026-11-26 21:09:22 +08:00
Fangliding e04430d18f Refactor 2026-11-26 21:09:20 +08:00
Fangliding 2e9bac5648 simple clear 2026-11-26 21:09:18 +08:00
Fangliding 5d796c827a test 2026-11-26 21:09:16 +08:00
Roman RublevandFangliding ed6718a367 SS2022 inbound: Don't end a UDP session when its first source address expires
The relay session context was derived from the inbound connection of the
source address that created the session. After a client changes its source
address (NAT rebinding), the UDP worker of the old address is cleaned up after
~2 minutes of inactivity and cancels that context, which tears down the
dispatched outbound flow; the next packet then creates a brand-new session and
outbound flow (new local port on the server, reset replay window).

Sessions are routed by client session ID (SIP022 3.2.4), so detach the session
context from the originating connection's cancellation and let the session's
own inactivity timer govern its lifetime.
2026-11-26 21:09:14 +08:00
Roman RublevandFangliding 2ac088f627 SS2022 inbound: Fix data races and duplicate acceptance when decoding one UDP session concurrently
Packets of one client session can be processed by two inbound workers at
the same time (e.g. the client's old and new source address after a NAT
rebinding). The sliding window was checked and updated in two separate
critical sections, and clientBodyCipher and the session's User were read
without the lock, so the same packet ID could be accepted more than once
and go test -race reported data races.

Re-check the window and publish the cached body cipher in one critical
section after the packet is fully validated, and always initialize the
session's User under the lock.
2026-11-26 21:09:05 +08:00
51 changed files with 1716 additions and 1426 deletions
+4
View File
@@ -7,6 +7,7 @@ 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/net"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/core"
@@ -183,6 +184,9 @@ func NewHandler(ctx context.Context, config *core.InboundHandlerConfig) (inbound
Mark: streamSettings.SocketSettings.Mark,
})
}
if streamSettings != nil && (streamSettings.ProtocolName == "splithttp" || streamSettings.ProtocolName == "masque") {
ctx = session.ContextWithAllowedNetwork(ctx, net.Network_UDP)
}
return NewAlwaysOnInboundHandler(ctx, tag, receiverSettings, proxySettings)
}
+23 -3
View File
@@ -15,6 +15,8 @@ const (
var ErrBufferFull = errors.New("buffer is full")
var pool = bytespool.GetPool(Size)
// ownership represents the data owner of the buffer.
type ownership uint8
@@ -37,7 +39,16 @@ type Buffer struct {
// New creates a Buffer with 0 length and 8K capacity, managed.
func New() *Buffer {
return &Buffer{v: bytespool.Alloc(Size)}
buf := pool.Get().([]byte)
if cap(buf) >= Size {
buf = buf[:Size]
} else {
buf = make([]byte, Size)
}
return &Buffer{
v: buf,
}
}
// NewExisted creates a standard size Buffer with an existed bytearray, managed.
@@ -69,7 +80,16 @@ func FromBytes(b []byte) *Buffer {
// StackNew creates a new Buffer object on stack, managed.
// This method is for buffers that is released in the same function.
func StackNew() Buffer {
return Buffer{v: bytespool.Alloc(Size)}
buf := pool.Get().([]byte)
if cap(buf) >= Size {
buf = buf[:Size]
} else {
buf = make([]byte, Size)
}
return Buffer{
v: buf,
}
}
// NewWithSize creates a Buffer with 0 length and capacity with at least the given size, bytespool's.
@@ -93,7 +113,7 @@ func (b *Buffer) Release() {
switch b.ownership {
case managed:
if cap(p) == Size {
bytespool.Free(p)
pool.Put(p)
}
case bytespools:
bytespool.Free(p)
+55 -67
View File
@@ -1,84 +1,72 @@
package bytespool
import (
"math/bits"
"sync"
)
import "sync"
const (
minShift = 10 // 1KB
maxShift = 16 // 64KB
numPools = maxShift - minShift + 1
minSize = 1 << minShift
maxSize = 1 << maxShift
)
// pools hold array pointers (*[N]byte) to avoid interface boxing allocations on Put.
var pools = [numPools]sync.Pool{
{New: func() any { return new([1 << 10]byte) }},
{New: func() any { return new([1 << 11]byte) }},
{New: func() any { return new([1 << 12]byte) }},
{New: func() any { return new([1 << 13]byte) }},
{New: func() any { return new([1 << 14]byte) }},
{New: func() any { return new([1 << 15]byte) }},
{New: func() any { return new([1 << 16]byte) }},
func createAllocFunc(size int32) func() interface{} {
return func() interface{} {
return make([]byte, size)
}
}
// Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 1024.
// The following parameters controls the size of buffer pools.
// There are numPools pools. Starting from 2k size, the size of each pool is sizeMulti of the previous one.
// Package buf is guaranteed to not use buffers larger than the largest pool.
// Other packets may use larger buffers.
const (
numPools = 4
sizeMulti = 4
)
var (
pool [numPools]sync.Pool
poolSize [numPools]int32
)
func init() {
size := int32(2048)
for i := 0; i < numPools; i++ {
pool[i] = sync.Pool{
New: createAllocFunc(size),
}
poolSize[i] = size
size *= sizeMulti
}
}
// GetPool returns a sync.Pool that generates bytes array with at least the given size.
// It may return nil if no such pool exists.
//
// xray:api:stable
func GetPool(size int32) *sync.Pool {
for idx, ps := range poolSize {
if size <= ps {
return &pool[idx]
}
}
return nil
}
// Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 2048.
//
// xray:api:stable
func Alloc(size int32) []byte {
if size > maxSize {
return make([]byte, size)
}
index := 0
if size > minSize {
index = bits.Len32(uint32(size-1)) - minShift
}
p := pools[index].Get()
switch index {
case 0:
return p.(*[1 << 10]byte)[:]
case 1:
return p.(*[1 << 11]byte)[:]
case 2:
return p.(*[1 << 12]byte)[:]
case 3:
return p.(*[1 << 13]byte)[:]
case 4:
return p.(*[1 << 14]byte)[:]
case 5:
return p.(*[1 << 15]byte)[:]
case 6:
return p.(*[1 << 16]byte)[:]
default:
panic("invalid pool index")
pool := GetPool(size)
if pool != nil {
return pool.Get().([]byte)
}
return make([]byte, size)
}
// Free puts a byte slice into the internal pool.
//
// xray:api:stable
func Free(b []byte) {
c := cap(b)
if c < minSize || c > maxSize {
return
}
index := bits.Len(uint(c)) - 1 - minShift
switch index {
case 0:
pools[0].Put((*[1 << 10]byte)(b[:1<<10]))
case 1:
pools[1].Put((*[1 << 11]byte)(b[:1<<11]))
case 2:
pools[2].Put((*[1 << 12]byte)(b[:1<<12]))
case 3:
pools[3].Put((*[1 << 13]byte)(b[:1<<13]))
case 4:
pools[4].Put((*[1 << 14]byte)(b[:1<<14]))
case 5:
pools[5].Put((*[1 << 15]byte)(b[:1<<15]))
case 6:
pools[6].Put((*[1 << 16]byte)(b[:1<<16]))
size := int32(cap(b))
b = b[0:cap(b)]
for i := numPools - 1; i >= 0; i-- {
if size >= poolSize[i] {
pool[i].Put(b)
return
}
}
}
+12 -4
View File
@@ -191,10 +191,18 @@ func getConfig() string {
{
"protocol": "vless",
"settings": {
"address": "1.2.3.4",
"port": 1234,
"id": "4784f9b8-a879-4fec-9718-ebddefa47750",
"encryption": "none"
"vnext": [
{
"address": "1.2.3.4",
"port": 1234,
"users": [
{
"id": "4784f9b8-a879-4fec-9718-ebddefa47750",
"encryption": "none"
}
]
}
]
},
"tag": "XHTTP_IN",
"streamSettings": {
+1 -4
View File
@@ -70,11 +70,8 @@ func (t *ActivityTimer) SetTimeout(timeout time.Duration) {
Execute: t.check,
}
common.CloseIfExists(t.checkTask)
select {
case <-t.updated:
default:
}
t.checkTask = newCheckTask
t.Update()
common.Must(newCheckTask.Start())
}
+7 -3
View File
@@ -58,11 +58,15 @@ func (t *Periodic) Start() error {
return nil
}
t.running = true
t.timer = time.AfterFunc(t.Interval, func() {
t.checkedExecute()
})
t.access.Unlock()
if err := t.checkedExecute(); err != nil {
t.access.Lock()
t.running = false
t.access.Unlock()
return err
}
return nil
}
+6 -6
View File
@@ -20,17 +20,17 @@ func TestPeriodicTaskStop(t *testing.T) {
common.Must(task.Start())
time.Sleep(time.Second * 5)
common.Must(task.Close())
if value != 2 {
t.Fatal("expected 2, but got ", value)
if value != 3 {
t.Fatal("expected 3, but got ", value)
}
time.Sleep(time.Second * 4)
if value != 2 {
t.Fatal("expected 2, but got ", value)
if value != 3 {
t.Fatal("expected 3, but got ", value)
}
common.Must(task.Start())
time.Sleep(time.Second * 3)
if value != 3 {
t.Fatal("Expected 3, but ", value)
if value != 5 {
t.Fatal("Expected 5, but ", value)
}
common.Must(task.Close())
}
+1 -1
View File
@@ -3,7 +3,7 @@ module github.com/xtls/xray-core
go 1.27
require (
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c
github.com/bufbuild/protocompile v0.14.1
github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344
github.com/golang/mock v1.7.0-rc.1
+2 -2
View File
@@ -1,5 +1,5 @@
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a h1:uCIlOCbXUtBkFk47HxIkQieCkV+zKv5VCDawLtj3Pkc=
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a/go.mod h1:J7UZVOMF2M1LiE3iiUZWPuy8YCPAcLJOwVURrfJCvc0=
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c h1:cxK8qTA0YCsj68A7zLYDCfPgMTOyt3ePkHh+oXEmYU0=
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c/go.mod h1:J7UZVOMF2M1LiE3iiUZWPuy8YCPAcLJOwVURrfJCvc0=
github.com/bufbuild/protocompile v0.14.1 h1:iA73zAf/fyljNjQKwYzUHD6AD4R8KMasmwa/FBatYVw=
github.com/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU5DoEw9xY/FUi1c=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
+62 -23
View File
@@ -1,6 +1,9 @@
package conf
import (
"encoding/json"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/proxy/http"
@@ -46,37 +49,73 @@ func (c *HTTPServerConfig) Build() (proto.Message, error) {
return config, nil
}
type HTTPRemoteConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Users []json.RawMessage `json:"users"`
}
type HTTPClientConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level uint32 `json:"level"`
Email string `json:"email"`
Username string `json:"user"`
Password string `json:"pass"`
Headers map[string]string `json:"headers"`
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level uint32 `json:"level"`
Email string `json:"email"`
Username string `json:"user"`
Password string `json:"pass"`
Servers []*HTTPRemoteConfig `json:"servers"`
Headers map[string]string `json:"headers"`
}
func (v *HTTPClientConfig) Build() (proto.Message, error) {
config := new(http.ClientConfig)
server := &protocol.ServerEndpoint{
Address: v.Address.Build(),
Port: uint32(v.Port),
}
if len(v.Username) > 0 {
account := &HTTPAccount{
Username: v.Username,
Password: v.Password,
if v.Address != nil {
v.Servers = []*HTTPRemoteConfig{
{
Address: v.Address,
Port: v.Port,
},
}
user := &protocol.User{
Level: v.Level,
Email: v.Email,
Account: serial.ToTypedMessage(account.Build()),
if len(v.Username) > 0 {
v.Servers[0].Users = []json.RawMessage{{}}
}
server.User = user
}
config.Server = server
if len(v.Servers) != 1 {
return nil, errors.New(`HTTP settings: "servers" should have one and only one member. Multiple endpoints in "servers" should use multiple HTTP outbounds and routing balancer instead`)
}
for _, serverConfig := range v.Servers {
if len(serverConfig.Users) > 1 {
return nil, errors.New(`HTTP servers: "users" should have one member at most. Multiple members in "users" should use multiple HTTP outbounds and routing balancer instead`)
}
server := &protocol.ServerEndpoint{
Address: serverConfig.Address.Build(),
Port: uint32(serverConfig.Port),
}
for _, rawUser := range serverConfig.Users {
user := new(protocol.User)
if v.Address != nil {
user.Level = v.Level
user.Email = v.Email
} else {
if err := json.Unmarshal(rawUser, user); err != nil {
return nil, errors.New("failed to parse HTTP user").Base(err)
}
}
account := new(HTTPAccount)
if v.Address != nil {
account.Username = v.Username
account.Password = v.Password
} else {
if err := json.Unmarshal(rawUser, account); err != nil {
return nil, errors.New("failed to parse HTTP account").Base(err)
}
}
user.Account = serial.ToTypedMessage(account.Build())
server.User = user
break
}
config.Server = server
break
}
config.Header = make([]*http.Header, 0, 32)
for key, value := range v.Headers {
config.Header = append(config.Header, &http.Header{
+48 -22
View File
@@ -177,7 +177,7 @@ func buildShadowsocks2022(v *ShadowsocksServerConfig) (proto.Message, error) {
return config, nil
}
type ShadowsocksClientConfig struct {
type ShadowsocksServerTarget struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level byte `json:"level"`
@@ -186,43 +186,69 @@ type ShadowsocksClientConfig struct {
Password string `json:"password"`
}
type ShadowsocksClientConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level byte `json:"level"`
Email string `json:"email"`
Cipher string `json:"method"`
Password string `json:"password"`
Servers []*ShadowsocksServerTarget `json:"servers"`
}
func (v *ShadowsocksClientConfig) Build() (proto.Message, error) {
errors.PrintNonRemovalDeprecatedFeatureWarning("Shadowsocks (with no Forward Secrecy, etc.)", "VLESS Encryption")
if v.Address == nil {
if v.Address != nil {
v.Servers = []*ShadowsocksServerTarget{
{
Address: v.Address,
Port: v.Port,
Level: v.Level,
Email: v.Email,
Cipher: v.Cipher,
Password: v.Password,
},
}
}
if len(v.Servers) != 1 {
return nil, errors.New(`Shadowsocks settings: "servers" should have one and only one member. Multiple endpoints in "servers" should use multiple Shadowsocks outbounds and routing balancer instead`)
}
server := v.Servers[0]
if server.Address == nil {
return nil, errors.New("Shadowsocks server address is not set.")
}
if v.Port == 0 {
if server.Port == 0 {
return nil, errors.New("Invalid Shadowsocks port.")
}
if v.Password == "" {
if server.Password == "" {
return nil, errors.New("Shadowsocks password is not specified.")
}
if _, err := shadowsocks_2022.GetCipherMethod(v.Cipher); err == nil {
config := &shadowsocks_2022.ClientConfig{
Address: v.Address.Build(),
Port: uint32(v.Port),
Method: v.Cipher,
Key: v.Password,
}
if _, err := shadowsocks_2022.GetCipherMethod(server.Cipher); err == nil {
config := new(shadowsocks_2022.ClientConfig)
config.Address = server.Address.Build()
config.Port = uint32(server.Port)
config.Method = server.Cipher
config.Key = server.Password
return config, nil
}
config := new(shadowsocks.ClientConfig)
if cipherFromString(v.Cipher) == shadowsocks.CipherType_UNKNOWN {
return nil, errors.New("unknown cipher method: ", v.Cipher)
account := &shadowsocks.Account{
Password: server.Password,
}
account.CipherType = cipherFromString(server.Cipher)
if account.CipherType == shadowsocks.CipherType_UNKNOWN {
return nil, errors.New("unknown cipher method: ", server.Cipher)
}
ss := &protocol.ServerEndpoint{
Address: v.Address.Build(),
Port: uint32(v.Port),
Address: server.Address.Build(),
Port: uint32(server.Port),
User: &protocol.User{
Level: uint32(v.Level),
Email: v.Email,
Account: serial.ToTypedMessage(&shadowsocks.Account{
Password: v.Password,
CipherType: cipherFromString(v.Cipher),
}),
Level: uint32(server.Level),
Email: server.Email,
Account: serial.ToTypedMessage(account),
},
}
config.Server = ss
+61 -22
View File
@@ -1,6 +1,9 @@
package conf
import (
"encoding/json"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/proxy/socks"
@@ -64,35 +67,71 @@ func (v *SocksServerConfig) Build() (proto.Message, error) {
return config, nil
}
type SocksRemoteConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Users []json.RawMessage `json:"users"`
}
type SocksClientConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level uint32 `json:"level"`
Email string `json:"email"`
Username string `json:"user"`
Password string `json:"pass"`
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level uint32 `json:"level"`
Email string `json:"email"`
Username string `json:"user"`
Password string `json:"pass"`
Servers []*SocksRemoteConfig `json:"servers"`
}
func (v *SocksClientConfig) Build() (proto.Message, error) {
config := new(socks.ClientConfig)
server := &protocol.ServerEndpoint{
Address: v.Address.Build(),
Port: uint32(v.Port),
}
if len(v.Username) > 0 {
account := &SocksAccount{
Username: v.Username,
Password: v.Password,
if v.Address != nil {
v.Servers = []*SocksRemoteConfig{
{
Address: v.Address,
Port: v.Port,
},
}
user := &protocol.User{
Level: v.Level,
Email: v.Email,
Account: serial.ToTypedMessage(account.Build()),
if len(v.Username) > 0 {
v.Servers[0].Users = []json.RawMessage{{}}
}
server.User = user
}
config.Server = server
if len(v.Servers) != 1 {
return nil, errors.New(`SOCKS settings: "servers" should have one and only one member. Multiple endpoints in "servers" should use multiple SOCKS outbounds and routing balancer instead`)
}
for _, serverConfig := range v.Servers {
if len(serverConfig.Users) > 1 {
return nil, errors.New(`SOCKS servers: "users" should have one member at most. Multiple members in "users" should use multiple SOCKS outbounds and routing balancer instead`)
}
server := &protocol.ServerEndpoint{
Address: serverConfig.Address.Build(),
Port: uint32(serverConfig.Port),
}
for _, rawUser := range serverConfig.Users {
user := new(protocol.User)
if v.Address != nil {
user.Level = v.Level
user.Email = v.Email
} else {
if err := json.Unmarshal(rawUser, user); err != nil {
return nil, errors.New("failed to parse Socks user").Base(err)
}
}
account := new(SocksAccount)
if v.Address != nil {
account.Username = v.Username
account.Password = v.Password
} else {
if err := json.Unmarshal(rawUser, account); err != nil {
return nil, errors.New("failed to parse socks account").Base(err)
}
}
user.Account = serial.ToTypedMessage(account.Build())
server.User = user
break
}
config.Server = server
break
}
return config, nil
}
+29
View File
@@ -53,6 +53,35 @@ func TestSocksOutboundConfig(t *testing.T) {
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"servers": [{
"address": "127.0.0.1",
"port": 1234,
"users": [
{"user": "test user", "pass": "test pass", "email": "test@email.com"}
]
}]
}`,
Parser: loadJSON(creator),
Output: &socks.ClientConfig{
Server: &protocol.ServerEndpoint{
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: 1234,
User: &protocol.User{
Email: "test@email.com",
Account: serial.ToTypedMessage(&socks.Account{
Username: "test user",
Password: "test pass",
}),
},
},
},
},
{
Input: `{
"address": "127.0.0.1",
+6 -3
View File
@@ -532,7 +532,7 @@ func TestXDriveOutboundConfig(t *testing.T) {
`{"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": {"address": "127.0.0.1", "port": 443, ` + xdriveID + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `}]}], "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
} {
if err := build(input); err != nil {
t.Errorf("%s: %v", input, err)
@@ -541,9 +541,12 @@ func TestXDriveOutboundConfig(t *testing.T) {
for _, c := range []struct{ input, err string }{
{`{"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 + `, "multiplex": {"concurrency": 8, "xudpProxyUDP443": "skip"}}, ` + xdriveStream + `}`, `"xudpProxyUDP443":"skip"`},
{`{"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": {"address": "127.0.0.1", "port": 443, ` + xdriveID + `, ` + 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"},
+60 -21
View File
@@ -17,41 +17,76 @@ import (
"google.golang.org/protobuf/proto"
)
// TrojanClientConfig is configuration of trojan servers
type TrojanClientConfig struct {
// TrojanServerTarget is configuration of a single trojan server
type TrojanServerTarget struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level byte `json:"level"`
Email string `json:"email"`
Password string `json:"password"`
Flow string `json:"flow"`
}
// TrojanClientConfig is configuration of trojan servers
type TrojanClientConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level byte `json:"level"`
Email string `json:"email"`
Password string `json:"password"`
Flow string `json:"flow"`
Servers []*TrojanServerTarget `json:"servers"`
}
// Build implements Buildable
func (c *TrojanClientConfig) Build() (proto.Message, error) {
errors.PrintNonRemovalDeprecatedFeatureWarning("Trojan (with no Flow, etc.)", "VLESS with Flow & Seed")
if c.Address != nil {
c.Servers = []*TrojanServerTarget{
{
Address: c.Address,
Port: c.Port,
Level: c.Level,
Email: c.Email,
Password: c.Password,
Flow: c.Flow,
},
}
}
if len(c.Servers) != 1 {
return nil, errors.New(`Trojan settings: "servers" should have one and only one member. Multiple endpoints in "servers" should use multiple Trojan outbounds and routing balancer instead`)
}
config := &trojan.ClientConfig{}
if c.Address == nil {
return nil, errors.New("Trojan server address is not set.")
}
if c.Port == 0 {
return nil, errors.New("Invalid Trojan port.")
}
if c.Password == "" {
return nil, errors.New("Trojan password is not specified.")
}
for _, rec := range c.Servers {
if rec.Address == nil {
return nil, errors.New("Trojan server address is not set.")
}
if rec.Port == 0 {
return nil, errors.New("Invalid Trojan port.")
}
if rec.Password == "" {
return nil, errors.New("Trojan password is not specified.")
}
if rec.Flow != "" {
return nil, errors.PrintRemovedFeatureError(`Flow for Trojan`, ``)
}
config.Server = &protocol.ServerEndpoint{
Address: c.Address.Build(),
Port: uint32(c.Port),
User: &protocol.User{
Level: uint32(c.Level),
Email: c.Email,
Account: serial.ToTypedMessage(&trojan.Account{
Password: c.Password,
}),
},
config.Server = &protocol.ServerEndpoint{
Address: rec.Address.Build(),
Port: uint32(rec.Port),
User: &protocol.User{
Level: uint32(rec.Level),
Email: rec.Email,
Account: serial.ToTypedMessage(&trojan.Account{
Password: rec.Password,
}),
},
}
break
}
return config, nil
@@ -72,6 +107,7 @@ type TrojanUserConfig struct {
Password string `json:"password"`
Level byte `json:"level"`
Email string `json:"email"`
Flow string `json:"flow"`
}
// TrojanServerConfig is Inbound configuration
@@ -95,6 +131,9 @@ func (c *TrojanServerConfig) Build() (proto.Message, error) {
processClient := func(idx int) error {
rawUser := c.Users[idx]
if rawUser.Flow != "" {
return errors.PrintRemovedFeatureError(`Flow for Trojan`, ``)
}
config.Users[idx] = &protocol.User{
Level: uint32(rawUser.Level),
-1
View File
@@ -159,7 +159,6 @@ func TestTunConfigGUID(t *testing.T) {
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",
+134 -89
View File
@@ -256,19 +256,26 @@ func (c *MultiplexConfig) Build() (*vless.Multiplex, error) {
})
}
type VLessOutboundVnext struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Users []json.RawMessage `json:"users"`
}
type VLessOutboundConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level uint32 `json:"level"`
Email string `json:"email"`
Id string `json:"id"`
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"`
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level uint32 `json:"level"`
Email string `json:"email"`
Id string `json:"id"`
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"`
Vnext []*VLessOutboundVnext `json:"vnext"`
}
// Build implements Buildable
@@ -279,92 +286,130 @@ func (c *VLessOutboundConfig) Build() (proto.Message, error) {
}
config := &outbound.Config{Multiplex: multiplex}
if c.Address == nil {
return nil, errors.New(`VLESS: "address" is not set`)
}
uid, err := uuid.ParseString(c.Id)
if err != nil {
return nil, err
}
switch c.Flow {
case "":
case vless.XRV, vless.XRV + "-udp443":
default:
return nil, errors.New(`VLESS users: "flow" doesn't support "` + c.Flow + `" in this version`)
}
spec := &protocol.ServerEndpoint{
Address: c.Address.Build(),
Port: uint32(c.Port),
}
user := &protocol.User{
Level: c.Level,
Email: c.Email,
}
account := &vless.Account{
Id: uid.String(),
Flow: c.Flow,
// Seed: c.Seed,
Encryption: c.Encryption,
Testpre: c.Testpre,
Testseed: c.Testseed,
}
if c.Reverse != nil {
rvs, err := c.Reverse.Build()
if err != nil {
return nil, err
if c.Address != nil {
c.Vnext = []*VLessOutboundVnext{
{
Address: c.Address,
Port: c.Port,
Users: []json.RawMessage{{}},
},
}
account.Reverse = rvs
}
if !func() bool {
s := strings.Split(account.Encryption, ".")
if len(s) < 4 || s[0] != "mlkem768x25519plus" {
return false
if len(c.Vnext) != 1 {
return nil, errors.New(`VLESS settings: "vnext" should have one and only one member. Multiple endpoints in "vnext" should use multiple VLESS outbounds and routing balancer instead`)
}
for _, rec := range c.Vnext {
if rec.Address == nil {
return nil, errors.New(`VLESS vnext: "address" is not set`)
}
switch s[1] {
case "native":
case "xorpub":
account.XorMode = 1
case "random":
account.XorMode = 2
default:
return false
if len(rec.Users) != 1 {
return nil, errors.New(`VLESS vnext: "users" should have one and only one member. Multiple members in "users" should use multiple VLESS outbounds and routing balancer instead`)
}
switch s[2] {
case "1rtt":
case "0rtt":
account.Seconds = 1
default:
return false
spec := &protocol.ServerEndpoint{
Address: rec.Address.Build(),
Port: uint32(rec.Port),
}
padding := 0
for _, r := range s[3:] {
if len(r) < 20 {
padding += len(r) + 1
continue
for _, rawUser := range rec.Users {
user := new(protocol.User)
if c.Address != nil {
user.Level = c.Level
user.Email = c.Email
} else {
if err := json.Unmarshal(rawUser, user); err != nil {
return nil, errors.New(`VLESS users: invalid user`).Base(err)
}
}
if b, _ := base64.RawURLEncoding.DecodeString(r); len(b) != 32 && len(b) != 1184 {
return false
account := new(vless.Account)
if c.Address != nil {
account.Id = c.Id
account.Flow = c.Flow
//account.Seed = c.Seed
account.Encryption = c.Encryption
if c.Reverse != nil {
rvs, err := c.Reverse.Build()
if err != nil {
return nil, err
}
account.Reverse = rvs
}
account.Testpre = c.Testpre
account.Testseed = c.Testseed
} else {
if err := json.Unmarshal(rawUser, account); err != nil {
return nil, errors.New(`VLESS users: invalid user`).Base(err)
}
// validateOutboundTransportSecurity needs to see these
c.Encryption = account.Encryption
c.Address = rec.Address
if account.Reverse != nil { // may not be reached: error json unmarshal
return nil, errors.New(`VLESS users: please use simplified outbound's config style to use "reverse"`)
}
}
u, err := uuid.ParseString(account.Id)
if err != nil {
return nil, err
}
account.Id = u.String()
switch account.Flow {
case "":
case vless.XRV, vless.XRV + "-udp443":
default:
return nil, errors.New(`VLESS users: "flow" doesn't support "` + account.Flow + `" in this version`)
}
if !func() bool {
s := strings.Split(account.Encryption, ".")
if len(s) < 4 || s[0] != "mlkem768x25519plus" {
return false
}
switch s[1] {
case "native":
case "xorpub":
account.XorMode = 1
case "random":
account.XorMode = 2
default:
return false
}
switch s[2] {
case "1rtt":
case "0rtt":
account.Seconds = 1
default:
return false
}
padding := 0
for _, r := range s[3:] {
if len(r) < 20 {
padding += len(r) + 1
continue
}
if b, _ := base64.RawURLEncoding.DecodeString(r); len(b) != 32 && len(b) != 1184 {
return false
}
}
account.Encryption = account.Encryption[27+len(s[2]):]
if padding > 0 {
account.Padding = account.Encryption[:padding-1]
account.Encryption = account.Encryption[padding:]
}
return true
}() && account.Encryption != "none" {
if account.Encryption == "" {
return nil, errors.New(`VLESS users: please add/set "encryption":"none" for every user`)
}
return nil, errors.New(`VLESS users: unsupported "encryption": ` + account.Encryption)
}
user.Account = serial.ToTypedMessage(account)
spec.User = user
break
}
account.Encryption = account.Encryption[27+len(s[2]):]
if padding > 0 {
account.Padding = account.Encryption[:padding-1]
account.Encryption = account.Encryption[padding:]
}
return true
}() && account.Encryption != "none" {
if account.Encryption == "" {
return nil, errors.New(`VLESS users: please add/set "encryption":"none" for every user`)
}
return nil, errors.New(`VLESS users: unsupported "encryption": ` + account.Encryption)
config.Vnext = spec
break
}
user.Account = serial.ToTypedMessage(account)
spec.User = user
config.Vnext = spec
return config, nil
}
+35
View File
@@ -18,6 +18,41 @@ func TestVLessOutbound(t *testing.T) {
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"vnext": [{
"address": "example.com",
"port": 443,
"users": [
{
"id": "27848739-7e62-4138-9fd3-098a63964b6b",
"flow": "xtls-rprx-vision-udp443",
"encryption": "none",
"level": 0
}
]
}]
}`,
Parser: loadJSON(creator),
Output: &outbound.Config{
Vnext: &protocol.ServerEndpoint{
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Domain{
Domain: "example.com",
},
},
Port: 443,
User: &protocol.User{
Account: serial.ToTypedMessage(&vless.Account{
Id: "27848739-7e62-4138-9fd3-098a63964b6b",
Flow: "xtls-rprx-vision-udp443",
Encryption: "none",
}),
Level: 0,
},
},
},
},
{
Input: `{
"address": "example.com",
+69 -30
View File
@@ -102,15 +102,22 @@ func (c *VMessInboundConfig) Build() (proto.Message, error) {
return config, nil
}
type VMessOutboundTarget struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Users []json.RawMessage `json:"users"`
}
type VMessOutboundConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level uint32 `json:"level"`
Email string `json:"email"`
ID string `json:"id"`
Security string `json:"security"`
Experiments string `json:"experiments"`
Multiplex *MultiplexConfig `json:"multiplex"`
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level uint32 `json:"level"`
Email string `json:"email"`
ID string `json:"id"`
Security string `json:"security"`
Experiments string `json:"experiments"`
Receivers []*VMessOutboundTarget `json:"vnext"`
Multiplex *MultiplexConfig `json:"multiplex"`
}
// Build implements Buildable
@@ -122,30 +129,62 @@ func (c *VMessOutboundConfig) Build() (proto.Message, error) {
return nil, err
}
config := &outbound.Config{Multiplex: multiplex}
if c.Address != nil {
c.Receivers = []*VMessOutboundTarget{
{
Address: c.Address,
Port: c.Port,
Users: []json.RawMessage{{}},
},
}
}
if len(c.Receivers) != 1 {
return nil, errors.New(`VMess settings: "vnext" should have one and only one member. Multiple endpoints in "vnext" should use multiple VMess outbounds and routing balancer instead`)
}
for _, rec := range c.Receivers {
if len(rec.Users) != 1 {
return nil, errors.New(`VMess vnext: "users" should have one and only one member. Multiple members in "users" should use multiple VMess outbounds and routing balancer instead`)
}
if rec.Address == nil {
return nil, errors.New(`VMess vnext: "address" is not set`)
}
spec := &protocol.ServerEndpoint{
Address: rec.Address.Build(),
Port: uint32(rec.Port),
}
for _, rawUser := range rec.Users {
user := new(protocol.User)
if c.Address != nil {
user.Level = c.Level
user.Email = c.Email
} else {
if err := json.Unmarshal(rawUser, user); err != nil {
return nil, errors.New("invalid VMess user").Base(err)
}
}
account := new(VMessAccount)
if c.Address != nil {
account.ID = c.ID
account.Security = c.Security
account.Experiments = c.Experiments
} else {
if err := json.Unmarshal(rawUser, account); err != nil {
return nil, errors.New("invalid VMess user").Base(err)
}
}
if c.Address == nil {
return nil, errors.New(`VMess: "address" is not set`)
}
uid, err := uuid.ParseString(c.ID)
if err != nil {
return nil, err
}
u, err := uuid.ParseString(account.ID)
if err != nil {
return nil, err
}
account.ID = u.String()
account := &VMessAccount{
ID: uid.String(),
Security: c.Security,
Experiments: c.Experiments,
user.Account = serial.ToTypedMessage(account.Build())
spec.User = user
break
}
config.Receiver = spec
break
}
spec := &protocol.ServerEndpoint{
Address: c.Address.Build(),
Port: uint32(c.Port),
User: &protocol.User{
Level: c.Level,
Email: c.Email,
Account: serial.ToTypedMessage(account.Build()),
},
}
config.Receiver = spec
return config, nil
}
+36
View File
@@ -18,6 +18,42 @@ func TestVMessOutbound(t *testing.T) {
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"vnext": [{
"address": "127.0.0.1",
"port": 80,
"users": [
{
"id": "e641f5ad-9397-41e3-bf1a-e8740dfed019",
"email": "love@example.com",
"level": 255
}
]
}]
}`,
Parser: loadJSON(creator),
Output: &outbound.Config{
Receiver: &protocol.ServerEndpoint{
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: 80,
User: &protocol.User{
Email: "love@example.com",
Level: 255,
Account: serial.ToTypedMessage(&vmess.Account{
Id: "e641f5ad-9397-41e3-bf1a-e8740dfed019",
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AUTO,
},
}),
},
},
},
},
{
Input: `{
"address": "127.0.0.1",
+4 -14
View File
@@ -238,7 +238,7 @@ func validateOutboundTransportSecurity(rawConfig interface{}, senderSettings *pr
}
if tjCfg, ok := rawConfig.(*TrojanClientConfig); ok {
if requiresTransportSecurity(tjCfg.Address) {
if requiresTransportSecurity(tjCfg.Servers[0].Address) {
return errors.New("trojan without TLS is prohibited unless the server address is a private IP or domain")
}
}
@@ -265,13 +265,8 @@ func validateXDrive(ts proto.Message, ss *internet.StreamConfig, pl *net.PortLis
return errors.New(`the xdrive transport needs VLESS "encryption", run "xray vlessenc" to get one`)
}
// Reverse opens its own multiplexed connection.
if account.Reverse == nil {
if c.Multiplex == nil {
c.Multiplex = &vless.Multiplex{Concurrency: 128}
}
if c.Multiplex.XudpProxyUDP443 == "skip" {
return errors.New(`the xdrive transport does not support "xudpProxyUDP443":"skip"`)
}
if account.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"`)
@@ -372,15 +367,10 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
if err != nil {
return nil, errors.New("failed to build outbound handler for protocol ", c.Protocol).Base(err)
}
if senderSettings.StreamSettings != nil && senderSettings.StreamSettings.ProtocolName == "splithttp" {
if v, ok := ts.(*outbound.Config); ok && v.Multiplex != nil && v.Multiplex.Concurrency != 0 {
errors.LogWarning(context.Background(), `ATTENTION: Using VLESS Multiplex over XHTTP XMUX`)
}
}
if err := validateXDrive(ts, senderSettings.StreamSettings, nil); err != nil {
return nil, err
}
if err := validateOutboundTransportSecurity(rawConfig, senderSettings); err != nil {
return nil, err
}
-24
View File
@@ -1,24 +0,0 @@
package proxy
import (
"context"
"math/rand/v2"
"time"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/signal"
)
// wait to drain all the possible incoming UDP data
// because re-established QUIC UDP may bypass the sniffer
func DropUDP(ctx context.Context, reader buf.Reader) {
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, func() {
cancel()
}, time.Duration(30+rand.N(60))*time.Second)
context.AfterFunc(ctx, func() {
common.Interrupt(reader)
})
buf.Copy(reader, buf.Discard, buf.UpdateActivity(timer))
}
+14 -39
View File
@@ -5,7 +5,6 @@ import (
go_errors "errors"
"io"
"math/rand"
"slices"
"github.com/apernet/quic-go"
"github.com/xtls/xray-core/common"
@@ -175,15 +174,10 @@ func init() {
}))
}
// UDPWriter is not safe for concurrent writes.
type UDPWriter struct {
writer io.Writer
addr string
buf [buf.Size]byte
// Last b.UDP and its NetAddr, which allocates on every call.
lastUDP net.Destination
lastUDPAddr string
}
func (w *UDPWriter) SendMessage(msg *UDPMessage) error {
@@ -199,21 +193,21 @@ func (w *UDPWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
for i, b := range mb {
addr := w.addr
if b.UDP != nil {
if *b.UDP != w.lastUDP {
w.lastUDP = *b.UDP
w.lastUDPAddr = b.UDP.NetAddr()
}
addr = w.lastUDPAddr
addr = b.UDP.NetAddr()
}
msg := &UDPMessage{
SessionID: 0,
PacketID: 0,
FragID: 0,
FragCount: 1,
Addr: addr,
Data: b.Bytes(),
}
err := w.SendMessage(msg)
if errTooLarge, ok := go_errors.AsType[*quic.DatagramTooLargeError](err); ok {
var errTooLarge *quic.DatagramTooLargeError
if go_errors.As(err, &errTooLarge) {
msg.PacketID = uint16(rand.Intn(0xFFFF)) + 1
fMsgs := FragUDPMessage(msg, int(errTooLarge.MaxDatagramPayloadSize))
for _, fMsg := range fMsgs {
@@ -234,59 +228,40 @@ func (w *UDPWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
return nil
}
// UDPReader is not safe for concurrent reads.
type UDPReader struct {
reader io.Reader
df *Defragger
firstBuf *buf.Buffer
// Last message address and its parsed destination.
lastAddr string
lastDest net.Destination
packet [1500]byte
msg UDPMessage
}
func (r *UDPReader) ReadFrom(p []byte) (n int, addr *net.Destination, err error) {
for {
n, err := r.reader.Read(r.packet[:])
var packet [1500]byte
n, err := r.reader.Read(packet[:])
if err != nil {
return 0, nil, err
}
if err := parseUDPMessage(r.packet[:n], r.lastAddr, &r.msg); err != nil {
msg, err := ParseUDPMessage(packet[:n])
if err != nil {
continue
}
msg := &r.msg
if msg.FragCount > 1 {
// The defragger keeps fragments between calls, so they must not alias packet.
frag := *msg
frag.Data = slices.Clone(msg.Data)
msg = &frag
}
dfMsg := r.df.Feed(msg)
if dfMsg == nil {
continue
}
if dfMsg.Addr != r.lastAddr {
dest, err := net.ParseDestination("udp:" + dfMsg.Addr)
if err != nil {
continue
}
r.lastAddr = dfMsg.Addr
r.lastDest = dest
dest, err := net.ParseDestination("udp:" + dfMsg.Addr)
if err != nil {
continue
}
if len(p) < len(dfMsg.Data) {
continue
}
// Callers can rewrite the packet destination in place.
dest := r.lastDest
return copy(p, dfMsg.Data), &dest, nil
}
}
-147
View File
@@ -1,147 +0,0 @@
package hysteria
import (
"bytes"
"io"
"testing"
"github.com/apernet/quic-go"
"github.com/xtls/xray-core/common/buf"
xnet "github.com/xtls/xray-core/common/net"
)
// datagramReader returns one datagram per Read, like a QUIC datagram stream.
type datagramReader struct {
msgs [][]byte
}
func (r *datagramReader) Read(p []byte) (int, error) {
if len(r.msgs) == 0 {
return 0, io.EOF
}
n := copy(p, r.msgs[0])
r.msgs = r.msgs[1:]
return n, nil
}
func newTestReader(msgs []UDPMessage) *UDPReader {
datagrams := make([][]byte, len(msgs))
for i := range msgs {
datagrams[i] = make([]byte, msgs[i].Size())
msgs[i].Serialize(datagrams[i])
}
return &UDPReader{reader: &datagramReader{msgs: datagrams}, df: &Defragger{}}
}
func TestUDPReaderFragments(t *testing.T) {
want := &UDPMessage{PacketID: 1, Addr: "example.com:443", Data: bytes.Repeat([]byte("0123456789"), 20)}
frags := FragUDPMessage(want, 100)
if len(frags) < 2 {
t.Fatalf("got %d fragments, want at least 2", len(frags))
}
p := make([]byte, buf.Size)
n, dest, err := newTestReader(frags).ReadFrom(p)
if err != nil {
t.Fatal(err)
}
if dest.NetAddr() != want.Addr || !bytes.Equal(p[:n], want.Data) {
t.Errorf("got %q to %v, want %q to %s", p[:n], dest, want.Data, want.Addr)
}
}
func TestUDPReaderDestinations(t *testing.T) {
msgs := []UDPMessage{
{Addr: "203.0.113.1:53", Data: []byte("first")},
{Addr: "203.0.113.1:53", Data: []byte("second")},
{Addr: "203.0.113.2:53", Data: []byte("third")},
}
r := newTestReader(msgs)
p := make([]byte, buf.Size)
for i, want := range msgs {
n, dest, err := r.ReadFrom(p)
if err != nil {
t.Fatal(err)
}
if dest.NetAddr() != want.Addr || !bytes.Equal(p[:n], want.Data) {
t.Errorf("packet %d: got %q to %v, want %q to %s", i, p[:n], dest, want.Data, want.Addr)
}
// Callers rewrite the destination in place, the next packet must not see it.
dest.Port = 5353
}
}
type captureWriter struct {
writes [][]byte
}
func (w *captureWriter) Write(p []byte) (int, error) {
w.writes = append(w.writes, bytes.Clone(p))
return len(p), nil
}
func TestUDPWriterAddress(t *testing.T) {
ip := xnet.UDPDestination(xnet.ParseAddress("203.0.113.1"), 53)
domain := xnet.UDPDestination(xnet.DomainAddress("example.com"), 53)
cw := &captureWriter{}
w := &UDPWriter{writer: cw, addr: "198.51.100.1:1"}
for _, tc := range []struct {
udp *xnet.Destination
want string
}{
{&ip, "203.0.113.1:53"},
{&domain, "example.com:53"},
{nil, "198.51.100.1:1"},
{&ip, "203.0.113.1:53"},
} {
b := buf.FromBytes([]byte("data"))
b.UDP = tc.udp
if err := w.WriteMultiBuffer(buf.MultiBuffer{b}); err != nil {
t.Fatal(err)
}
msg, err := ParseUDPMessage(cw.writes[len(cw.writes)-1])
if err != nil {
t.Fatal(err)
}
if msg.Addr != tc.want {
t.Errorf("address = %q, want %q", msg.Addr, tc.want)
}
}
}
// fragmentingWriter rejects datagrams larger than max, like a QUIC connection.
type fragmentingWriter struct {
max int
writes [][]byte
}
func (w *fragmentingWriter) Write(p []byte) (int, error) {
if len(p) > w.max {
return 0, &quic.DatagramTooLargeError{MaxDatagramPayloadSize: int64(w.max)}
}
w.writes = append(w.writes, bytes.Clone(p))
return len(p), nil
}
func TestUDPWriterFragmentation(t *testing.T) {
data := bytes.Repeat([]byte("0123456789"), 20)
fw := &fragmentingWriter{max: 100}
w := &UDPWriter{writer: fw, addr: "example.com:443"}
if err := w.WriteMultiBuffer(buf.MultiBuffer{buf.FromBytes(data)}); err != nil {
t.Fatal(err)
}
if len(fw.writes) < 2 {
t.Fatalf("got %d datagrams, want at least 2", len(fw.writes))
}
r := &UDPReader{reader: &datagramReader{msgs: fw.writes}, df: &Defragger{}}
p := make([]byte, buf.Size)
n, dest, err := r.ReadFrom(p)
if err != nil {
t.Fatal(err)
}
if dest.NetAddr() != w.addr || !bytes.Equal(p[:n], data) {
t.Errorf("got %q to %v, want %q to %s", p[:n], dest, data, w.addr)
}
}
+20 -28
View File
@@ -1,6 +1,7 @@
package hysteria
import (
"bytes"
"encoding/binary"
"fmt"
"io"
@@ -182,44 +183,35 @@ func (m *UDPMessage) Serialize(buf []byte) int {
}
func ParseUDPMessage(msg []byte) (*UDPMessage, error) {
m := new(UDPMessage)
if err := parseUDPMessage(msg, "", m); err != nil {
m := &UDPMessage{}
buf := bytes.NewBuffer(msg)
if err := binary.Read(buf, binary.BigEndian, &m.SessionID); err != nil {
return nil, err
}
return m, nil
}
// parseUDPMessage parses msg into m. m.Data aliases msg; m.Addr is lastAddr
// when they are equal, so an unchanged address is not allocated again.
func parseUDPMessage(msg []byte, lastAddr string, m *UDPMessage) error {
if len(msg) < 8 {
return io.ErrUnexpectedEOF
if err := binary.Read(buf, binary.BigEndian, &m.PacketID); err != nil {
return nil, err
}
lAddr, n, err := quicvarint.Parse(msg[8:])
if err := binary.Read(buf, binary.BigEndian, &m.FragID); err != nil {
return nil, err
}
if err := binary.Read(buf, binary.BigEndian, &m.FragCount); err != nil {
return nil, err
}
lAddr, err := quicvarint.Read(buf)
if err != nil {
return err
return nil, err
}
if lAddr == 0 || lAddr > MaxMessageLength {
return errors.New("invalid address length")
return nil, errors.New("invalid address length")
}
bs := msg[8+n:]
bs := buf.Bytes()
if len(bs) <= int(lAddr) {
// We use <= instead of < here as we expect at least one byte of data after the address
return errors.New("invalid message length")
return nil, errors.New("invalid message length")
}
*m = UDPMessage{
SessionID: binary.BigEndian.Uint32(msg),
PacketID: binary.BigEndian.Uint16(msg[4:]),
FragID: msg[6],
FragCount: msg[7],
Data: bs[lAddr:],
}
if string(bs[:lAddr]) == lastAddr {
m.Addr = lastAddr
} else {
m.Addr = string(bs[:lAddr])
}
return nil
m.Addr = string(bs[:lAddr])
m.Data = bs[lAddr:]
return m, nil
}
// varintPut is like quicvarint.Append, but instead of appending to a slice,
-49
View File
@@ -1,49 +0,0 @@
package hysteria
import (
"bytes"
"reflect"
"testing"
)
func TestParseUDPMessage(t *testing.T) {
want := &UDPMessage{PacketID: 1, FragID: 2, FragCount: 3, Addr: "example.com:443", Data: []byte("hello")}
msg := make([]byte, want.Size())
want.Serialize(msg)
for _, lastAddr := range []string{"", want.Addr, "other:1"} {
got := new(UDPMessage)
if err := parseUDPMessage(msg, lastAddr, got); err != nil {
t.Fatalf("lastAddr %q: %v", lastAddr, err)
}
if !reflect.DeepEqual(got, want) {
t.Errorf("lastAddr %q: got %+v, want %+v", lastAddr, got, want)
}
}
}
func TestParseUDPMessageInvalid(t *testing.T) {
msg := &UDPMessage{Addr: "example.com:443", Data: []byte("hello")}
buf := make([]byte, msg.Size())
msg.Serialize(buf)
zeroAddrLen := bytes.Clone(buf)
zeroAddrLen[8] = 0 // Address length varint follows the 8-byte header
noData := &UDPMessage{Addr: msg.Addr}
noDataBuf := make([]byte, noData.Size())
noData.Serialize(noDataBuf)
for _, tc := range []struct {
name string
msg []byte
}{
{"short header", buf[:7]},
{"zero address length", zeroAddrLen},
{"no data after address", noDataBuf},
} {
if _, err := ParseUDPMessage(tc.msg); err == nil {
t.Errorf("%s: expected error", tc.name)
}
}
}
-16
View File
@@ -5,7 +5,6 @@ import (
"net"
"sync"
"github.com/google/uuid"
"github.com/xtls/xray-core/common/errors"
)
@@ -50,18 +49,3 @@ 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
}
+21
View File
@@ -0,0 +1,21 @@
package tun
import (
"github.com/google/uuid"
"github.com/xtls/xray-core/common/errors"
)
// 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
}
+54
View File
@@ -0,0 +1,54 @@
package tun_test
import (
"testing"
"github.com/xtls/xray-core/proxy/tun"
)
func TestParseGUID(t *testing.T) {
for _, c := range []struct {
guid string
raw [16]byte
}{
{"00000000-0000-0000-0000-000000000000", [16]byte{}},
{"00010203-0405-0607-0809-0a0b0c0d0e0f", [16]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}},
{"6ba7b810-9dad-11d1-80b4-00c04fd430c8", [16]byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}},
{"6BA7B810-9DAD-11D1-80B4-00C04FD430C8", [16]byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}},
{"ffffffff-ffff-ffff-ffff-ffffffffffff", [16]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
} {
raw, err := tun.ParseGUID(c.guid)
if err != nil {
t.Errorf("ParseGUID(%q) failed: %v", c.guid, err)
continue
}
if raw != c.raw {
t.Errorf("ParseGUID(%q) = %x, want %x", c.guid, raw, c.raw)
}
}
}
func TestParseGUIDInvalid(t *testing.T) {
for _, guid := range []string{
"",
" ",
"xray0",
// right characters, wrong places of the hyphens
"6ba7b8109-dad-11d1-80b4-00c04fd430c8",
"6ba7b810-9dad-11d1-80b4-00c04fd430c",
"6ba7b810-9dad-11d1-80b4-00c04fd430c88",
"6ba7b810-9dad-11d1-80b4_00c04fd430c8",
// not hexadecimal
"6ba7b81g-9dad-11d1-80b4-00c04fd430c8",
"6ba7b810-9dad-11d1-80b4-00c04fd430cg",
// forms other than the canonical one
"6ba7b8109dad11d180b400c04fd430c8",
"{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
"urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8",
"6ba7b810-9dad-11d1-80b4-00c04fd430c8 ",
} {
if raw, err := tun.ParseGUID(guid); err == nil {
t.Errorf("ParseGUID(%q) = %x, want an error", guid, raw)
}
}
}
+54
View File
@@ -0,0 +1,54 @@
//go:build windows
package tun
import (
"crypto/md5"
"testing"
"unsafe"
"golang.org/x/sys/windows"
)
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")
}
}
+390
View File
@@ -0,0 +1,390 @@
//go:build freebsd
package tun
import (
"context"
"errors"
"io/fs"
"net/netip"
"strings"
"testing"
)
type probeCall struct {
inboundTag string
source string
address string
}
// stubDNSRouting replaces the routing probe for the duration of a test and
// records how it was called, so tests can assert the probe is representative.
func stubDNSRouting(t *testing.T, err error) *[]probeCall {
t.Helper()
original := verifyDNSRouting
calls := []probeCall{}
verifyDNSRouting = func(_ context.Context, inboundTag, source, address string) error {
calls = append(calls, probeCall{inboundTag, source, address})
return err
}
t.Cleanup(func() { verifyDNSRouting = original })
return &calls
}
// recorder installs a resolvconf stub for the duration of a test and returns
// the captured invocations, each as the arguments followed by the stdin in
// angle brackets when there was one. An empty failOn succeeds every call;
// otherwise the named subcommand fails.
func recorder(t *testing.T, failOn string) *[]string {
t.Helper()
original := resolvconfRunner
calls := []string{}
resolvconfRunner = func(stdin string, args ...string) ([]byte, error) {
call := strings.Join(args, " ")
if stdin != "" {
call += " <" + stdin + ">"
}
calls = append(calls, call)
if failOn != "" && len(args) > 0 && args[0] == failOn {
return nil, errors.New("boom")
}
return nil, nil
}
t.Cleanup(func() { resolvconfRunner = original })
return &calls
}
// files replaces the resolver files read by the applied check for the
// duration of a test. A path not in the map does not exist.
func files(t *testing.T, contents map[string]string) {
t.Helper()
original := readResolverFile
readResolverFile = func(path string) ([]byte, error) {
if data, ok := contents[path]; ok {
return []byte(data), nil
}
return nil, fs.ErrNotExist
}
t.Cleanup(func() { readResolverFile = original })
}
// takenOver is what the libc subscriber writes once the TUN's nameserver is
// the exclusive one.
const takenOver = "# Generated by resolvconf\nnameserver 192.168.100.1\n"
// untouched is the DHCP-supplied resolv.conf that resolvconf=NO leaves in
// place.
const untouched = "# Generated by resolvconf\nnameserver 10.0.0.1\n"
func optedInTun() *FreeBSDTun {
return &FreeBSDTun{
options: &Config{
Name: "tun7",
Gateway: []string{"192.168.100.1/30"},
AutoSystemDnsToGateway: true,
},
name: "tun7",
gateway: netip.MustParsePrefix("192.168.100.1/30"),
local: netip.MustParseAddr("192.168.100.2"),
}
}
func joined(calls []string) string {
return strings.Join(calls, " | ")
}
func TestConfigureSystemDNSDisabledByDefault(t *testing.T) {
probes := stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
t1.options.AutoSystemDnsToGateway = false
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(*calls) != 0 || len(*probes) != 0 {
t.Errorf("nothing may run when the option is off, got %q and %d probes", joined(*calls), len(*probes))
}
if t1.systemDNSSet {
t.Error("systemDNSSet must stay false when the option is off")
}
}
func TestConfigureSystemDNSLeavesOSDNSWhenNoRoute(t *testing.T) {
stubDNSRouting(t, errors.New("no route"))
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
t.Fatal("expected an error when the probe fails")
}
if len(*calls) != 0 {
t.Errorf("resolvconf must not run when the probe fails, got %q", joined(*calls))
}
if t1.systemDNSSet {
t.Error("systemDNSSet must stay false when the probe fails")
}
}
// On FreeBSD the addresses are the other way round from Linux: the local
// address is the one after the gateway, and the gateway itself has no owner,
// so a packet to it is routed into the TUN. The probe has to carry that pair,
// and the resolver has to be pointed at the gateway.
func TestConfigureSystemDNSProbeCarriesFreeBSDPair(t *testing.T) {
probes := stubDNSRouting(t, nil)
recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(*probes) != 1 {
t.Fatalf("expected one probe, got %d", len(*probes))
}
want := probeCall{"tun", "192.168.100.2", "192.168.100.1"}
if (*probes)[0] != want {
t.Errorf("probe = %+v, want %+v", (*probes)[0], want)
}
}
func TestConfigureSystemDNSAppliesResolvconf(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !t1.systemDNSSet {
t.Fatal("systemDNSSet should be true after a successful takeover")
}
want := "-a tun7 -x <nameserver 192.168.100.1\n>"
if got := joined(*calls); got != want {
t.Errorf("resolvconf calls = %q, want %q", got, want)
}
}
// resolvconf exits 0 with resolvconf=NO in resolvconf.conf, and still records
// the entry for the interface, but runs no subscriber, so success has to be
// confirmed in what the subscribers wrote.
func TestConfigureSystemDNSRefusesWhenResolvconfDidNotApply(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": untouched})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
t.Fatal("expected an error when the nameserver did not reach a resolver")
}
if t1.systemDNSSet {
t.Error("systemDNSSet must stay false when the takeover did not take")
}
if !strings.HasSuffix(joined(*calls), "-d tun7") {
t.Errorf("expected a removal after the failed check, got %q", joined(*calls))
}
}
func TestConfigureSystemDNSIdempotent(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
before := len(*calls)
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(*calls) != before {
t.Errorf("second call must be a no-op, calls went %d -> %d", before, len(*calls))
}
}
func TestConfigureSystemDNSAddFailureIsNotDirty(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "-a")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
t.Fatal("expected an error when resolvconf -a fails")
}
if t1.systemDNSSet || t1.systemDNSDirty {
t.Error("a failed add leaves nothing to clean up")
}
if len(*calls) != 1 {
t.Errorf("nothing else may run after a failed add, got %q", joined(*calls))
}
}
// If the removal after a failed check fails too, the entry may still be
// installed, so the state has to be remembered rather than silently dropped.
func TestConfigureSystemDNSRollbackFailureKeepsDirty(t *testing.T) {
stubDNSRouting(t, nil)
recorder(t, "-d")
files(t, map[string]string{"/etc/resolv.conf": untouched})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
t.Fatal("expected an error when the check fails")
}
if !t1.systemDNSDirty {
t.Error("a failed removal must leave the resolver marked dirty")
}
if t1.systemDNSSet {
t.Error("systemDNSSet must stay false when the takeover did not complete")
}
}
// A dirty resolver is retried before anything new is applied.
func TestConfigureSystemDNSRetriesDirtyBeforeApplying(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
t1.systemDNSDirty = true
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
got := joined(*calls)
if !strings.HasPrefix(got, "-d tun7 | -a tun7") {
t.Errorf("expected the stale removal first, got %q", got)
}
if t1.systemDNSDirty {
t.Error("a successful retry should clear the dirty flag")
}
if !t1.systemDNSSet {
t.Error("the takeover should proceed once the retry succeeds")
}
}
func TestUnsetSystemDNSRemoves(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("setup failed: %v", err)
}
*calls = nil
t1.unsetSystemDNS()
if t1.systemDNSSet {
t.Error("systemDNSSet should be false after unset")
}
if got := joined(*calls); got != "-d tun7" {
t.Errorf("unset calls = %q, want %q", got, "-d tun7")
}
t1.unsetSystemDNS()
if len(*calls) != 1 {
t.Errorf("unsetSystemDNS must be idempotent, got %q", joined(*calls))
}
}
func TestUnsetSystemDNSKeepsDirtyWhenRemoveFails(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "-d")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
t1.systemDNSSet = true
t1.unsetSystemDNS()
if !t1.systemDNSDirty {
t.Error("a failed removal during unset must be remembered")
}
if got := joined(*calls); got != "-d tun7" {
t.Errorf("expected a removal attempt, got %q", got)
}
}
func TestResolvconfAppliedLibc(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": takenOver})
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
t.Errorf("resolv.conf listing the nameserver must count as applied, got %v, %v", ok, err)
}
}
func TestResolvconfAppliedNotWhenUntouched(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": untouched})
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || ok {
t.Errorf("an unchanged resolv.conf and no resolvconf.conf must not count as applied, got %v, %v", ok, err)
}
}
// With inclusive_interfaces in resolvconf.conf the exclusive marking is
// ignored and the DHCP nameservers stay listed, so the system falls back to
// them; that is the leak the option exists to close, and it must not pass.
func TestResolvconfAppliedNotWhenOthersRemain(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.1\nnameserver 10.0.0.1\n"})
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
t.Error("another nameserver alongside the TUN's must not count as applied")
}
}
// A loopback nameserver alongside is a local resolver that resolvconf feeds
// (local_unbound with the libc subscriber left on), not a leak.
func TestResolvconfAppliedWithLoopbackAlongside(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": "nameserver 127.0.0.1\nnameserver 192.168.100.1\n"})
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
t.Errorf("a loopback nameserver alongside must still count as applied, got %v, %v", ok, err)
}
}
func TestResolvconfAppliedIgnoresPrefixMatches(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.10\n"})
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
t.Error("192.168.100.10 must not match 192.168.100.1")
}
}
// local-unbound-setup turns the libc subscriber off and has resolvconf write
// unbound's forwarders instead; resolv.conf then stays pointed at loopback.
func TestResolvconfAppliedUnbound(t *testing.T) {
files(t, map[string]string{
"/etc/resolv.conf": "# Generated by resolvconf\nnameserver 127.0.0.1\noptions edns0\n",
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 192.168.100.1\n",
})
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
t.Errorf("the nameserver in unbound's forwarders must count as applied, got %v, %v", ok, err)
}
}
func TestResolvconfAppliedNotWhenUnboundUntouched(t *testing.T) {
files(t, map[string]string{
"/etc/resolv.conf": "nameserver 127.0.0.1\n",
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 10.0.0.1\n",
})
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
t.Error("unbound still forwarding to the old server must not count as applied")
}
}
func TestResolvconfAppliedReportsUnreadableResolvConf(t *testing.T) {
files(t, map[string]string{})
if _, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err == nil {
t.Error("a missing resolv.conf is an error, not a verdict")
}
}
-382
View File
@@ -3,11 +3,7 @@
package tun
import (
"context"
"errors"
"io/fs"
"net/netip"
"strings"
"testing"
"golang.org/x/net/route"
@@ -152,381 +148,3 @@ 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")
}
}
+204
View File
@@ -0,0 +1,204 @@
//go:build linux && !android
package tun
import (
"context"
"strings"
"testing"
"github.com/xtls/xray-core/app/dispatcher"
appdns "github.com/xtls/xray-core/app/dns"
"github.com/xtls/xray-core/app/proxyman"
_ "github.com/xtls/xray-core/app/proxyman/inbound"
_ "github.com/xtls/xray-core/app/proxyman/outbound"
"github.com/xtls/xray-core/app/router"
"github.com/xtls/xray-core/common/geodata"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/core"
proxydns "github.com/xtls/xray-core/proxy/dns"
"github.com/xtls/xray-core/proxy/freedom"
)
const (
routeTestInboundTag = "tun"
routeTestSource = "192.168.100.1"
routeTestDNSAddress = "192.168.100.2"
)
// port53Rule sends DNS queries arriving from the interface to the dns outbound.
func port53Rule() *router.RoutingRule {
return &router.RoutingRule{
InboundTag: []string{routeTestInboundTag},
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(53)}},
TargetTag: &router.RoutingRule_Tag{Tag: "dns"},
}
}
// sourceBlockRule diverts traffic from one address, which is the shape of a rule
// that only matches because the real request carries a source.
func sourceBlockRule(ip []byte) *router.RoutingRule {
return &router.RoutingRule{
SourceIp: []*geodata.IPRule{{
Value: &geodata.IPRule_Custom{
Custom: &geodata.CIDRRule{
Cidr: &geodata.CIDR{Ip: ip, Prefix: 32},
},
},
}},
TargetTag: &router.RoutingRule_Tag{Tag: "block"},
}
}
// newRouteTestContext builds a real but unstarted instance: no TUN device, no
// running resolver. The instance is placed in the context through the key core
// exports for tests.
func newRouteTestContext(t *testing.T, withDNSApp bool, nameServers []*appdns.NameServer, rules []*router.RoutingRule) context.Context {
t.Helper()
apps := []*serial.TypedMessage{
serial.ToTypedMessage(&dispatcher.Config{}),
serial.ToTypedMessage(&proxyman.InboundConfig{}),
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
serial.ToTypedMessage(&router.Config{Rule: rules}),
}
if withDNSApp {
apps = append(apps, serial.ToTypedMessage(&appdns.Config{NameServer: nameServers}))
}
instance, err := core.New(&core.Config{
App: apps,
Outbound: []*core.OutboundHandlerConfig{
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})},
{Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})},
{Tag: "block", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
},
})
if err != nil {
t.Fatalf("core.New: %v", err)
}
t.Cleanup(func() { _ = instance.Close() })
return context.WithValue(context.Background(), core.XrayKey(1), instance)
}
func udpNameServer(ip []byte) []*appdns.NameServer {
return []*appdns.NameServer{{
Address: &net.Endpoint{
Network: net.Network_UDP,
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Ip{Ip: ip}},
Port: 53,
},
}}
}
// localNameServer is a name server pointed at "localhost", which app/dns
// resolves through the system resolver.
func localNameServer() *appdns.NameServer {
return &appdns.NameServer{
Address: &net.Endpoint{
Network: net.Network_UDP,
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Domain{Domain: "localhost"}},
Port: 53,
},
}
}
// These drive the real feature lookup and the real router. verifyDNSRouting is
// the same function ConfigureSystemDNS calls, so a false positive here is a
// false positive in the takeover decision itself, which is what assertions on
// the resolvectl arguments could never catch.
func TestVerifyDNSRoutingDecisions(t *testing.T) {
tests := []struct {
name string
withDNSApp bool
nameServers []*appdns.NameServer
rules []*router.RoutingRule
wantErr string
}{
{
name: "independent upstream reaches the dns outbound",
withDNSApp: true,
nameServers: udpNameServer([]byte{9, 9, 9, 9}),
rules: []*router.RoutingRule{port53Rule()},
wantErr: "",
},
{
name: "no dns section falls back to the system resolver",
rules: []*router.RoutingRule{port53Rule()},
wantErr: "system resolver",
},
{
name: "dns section without name servers falls back too",
withDNSApp: true,
rules: []*router.RoutingRule{port53Rule()},
wantErr: "system resolver",
},
{
// An independent upstream is not enough on its own: name servers are
// selected per domain, so a local one can still be the one chosen.
// The refusal is deliberately domain-agnostic for that reason.
name: "a local name server alongside an independent one",
withDNSApp: true,
nameServers: append(udpNameServer([]byte{9, 9, 9, 9}), localNameServer()),
rules: []*router.RoutingRule{port53Rule()},
wantErr: "system resolver",
},
{
name: "a rule on the interface address diverts the real query",
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
rules: []*router.RoutingRule{
sourceBlockRule([]byte{192, 168, 100, 1}),
port53Rule(),
},
wantErr: "does not handle DNS",
},
{
name: "a rule on another address does not match it",
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
rules: []*router.RoutingRule{
sourceBlockRule([]byte{10, 0, 0, 1}),
port53Rule(),
},
wantErr: "",
},
{
name: "no rule matches the query",
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
wantErr: "no route",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := newRouteTestContext(t, tt.withDNSApp, tt.nameServers, tt.rules)
err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, routeTestDNSAddress)
if tt.wantErr == "" {
if err != nil {
t.Fatalf("expected the takeover to be accepted, got: %v", err)
}
return
}
if err == nil {
t.Fatalf("expected the takeover to be refused with %q, got nil", tt.wantErr)
}
if !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("error = %q, want it to contain %q", err.Error(), tt.wantErr)
}
})
}
}
// Without an IPv4 gateway, the takeover uses the first IPv6 one, and the probe
// carries IPv6 addresses.
func TestVerifyDNSRoutingIPv6(t *testing.T) {
ctx := newRouteTestContext(t, true, udpNameServer([]byte{9, 9, 9, 9}), []*router.RoutingRule{port53Rule()})
if err := verifyDNSRouting(ctx, routeTestInboundTag, "fc00::1", "fc00::2"); err != nil {
t.Fatalf("expected the takeover to be accepted, got: %v", err)
}
if err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, "fc00::2"); err == nil {
t.Fatal("expected mixed IPv4 and IPv6 addresses to be refused")
}
}
@@ -9,18 +9,6 @@ import (
"testing"
"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
@@ -455,185 +443,3 @@ func TestBuildResolvectlArgs(t *testing.T) {
})
}
}
const (
routeTestInboundTag = "tun"
routeTestSource = "192.168.100.1"
routeTestDNSAddress = "192.168.100.2"
)
// port53Rule sends DNS queries arriving from the interface to the dns outbound.
func port53Rule() *router.RoutingRule {
return &router.RoutingRule{
InboundTag: []string{routeTestInboundTag},
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(53)}},
TargetTag: &router.RoutingRule_Tag{Tag: "dns"},
}
}
// sourceBlockRule diverts traffic from one address, which is the shape of a rule
// that only matches because the real request carries a source.
func sourceBlockRule(ip []byte) *router.RoutingRule {
return &router.RoutingRule{
SourceIp: []*geodata.IPRule{{
Value: &geodata.IPRule_Custom{
Custom: &geodata.CIDRRule{
Cidr: &geodata.CIDR{Ip: ip, Prefix: 32},
},
},
}},
TargetTag: &router.RoutingRule_Tag{Tag: "block"},
}
}
// newRouteTestContext builds a real but unstarted instance: no TUN device, no
// running resolver. The instance is placed in the context through the key core
// exports for tests.
func newRouteTestContext(t *testing.T, withDNSApp bool, nameServers []*appdns.NameServer, rules []*router.RoutingRule) context.Context {
t.Helper()
apps := []*serial.TypedMessage{
serial.ToTypedMessage(&dispatcher.Config{}),
serial.ToTypedMessage(&proxyman.InboundConfig{}),
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
serial.ToTypedMessage(&router.Config{Rule: rules}),
}
if withDNSApp {
apps = append(apps, serial.ToTypedMessage(&appdns.Config{NameServer: nameServers}))
}
instance, err := core.New(&core.Config{
App: apps,
Outbound: []*core.OutboundHandlerConfig{
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})},
{Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})},
{Tag: "block", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
},
})
if err != nil {
t.Fatalf("core.New: %v", err)
}
t.Cleanup(func() { _ = instance.Close() })
return context.WithValue(context.Background(), core.XrayKey(1), instance)
}
func udpNameServer(ip []byte) []*appdns.NameServer {
return []*appdns.NameServer{{
Address: &net.Endpoint{
Network: net.Network_UDP,
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Ip{Ip: ip}},
Port: 53,
},
}}
}
// localNameServer is a name server pointed at "localhost", which app/dns
// resolves through the system resolver.
func localNameServer() *appdns.NameServer {
return &appdns.NameServer{
Address: &net.Endpoint{
Network: net.Network_UDP,
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Domain{Domain: "localhost"}},
Port: 53,
},
}
}
// These drive the real feature lookup and the real router. verifyDNSRouting is
// the same function ConfigureSystemDNS calls, so a false positive here is a
// false positive in the takeover decision itself, which is what assertions on
// the resolvectl arguments could never catch.
func TestVerifyDNSRoutingDecisions(t *testing.T) {
tests := []struct {
name string
withDNSApp bool
nameServers []*appdns.NameServer
rules []*router.RoutingRule
wantErr string
}{
{
name: "independent upstream reaches the dns outbound",
withDNSApp: true,
nameServers: udpNameServer([]byte{9, 9, 9, 9}),
rules: []*router.RoutingRule{port53Rule()},
wantErr: "",
},
{
name: "no dns section falls back to the system resolver",
rules: []*router.RoutingRule{port53Rule()},
wantErr: "system resolver",
},
{
name: "dns section without name servers falls back too",
withDNSApp: true,
rules: []*router.RoutingRule{port53Rule()},
wantErr: "system resolver",
},
{
// An independent upstream is not enough on its own: name servers are
// selected per domain, so a local one can still be the one chosen.
// The refusal is deliberately domain-agnostic for that reason.
name: "a local name server alongside an independent one",
withDNSApp: true,
nameServers: append(udpNameServer([]byte{9, 9, 9, 9}), localNameServer()),
rules: []*router.RoutingRule{port53Rule()},
wantErr: "system resolver",
},
{
name: "a rule on the interface address diverts the real query",
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
rules: []*router.RoutingRule{
sourceBlockRule([]byte{192, 168, 100, 1}),
port53Rule(),
},
wantErr: "does not handle DNS",
},
{
name: "a rule on another address does not match it",
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
rules: []*router.RoutingRule{
sourceBlockRule([]byte{10, 0, 0, 1}),
port53Rule(),
},
wantErr: "",
},
{
name: "no rule matches the query",
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
wantErr: "no route",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := newRouteTestContext(t, tt.withDNSApp, tt.nameServers, tt.rules)
err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, routeTestDNSAddress)
if tt.wantErr == "" {
if err != nil {
t.Fatalf("expected the takeover to be accepted, got: %v", err)
}
return
}
if err == nil {
t.Fatalf("expected the takeover to be refused with %q, got nil", tt.wantErr)
}
if !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("error = %q, want it to contain %q", err.Error(), tt.wantErr)
}
})
}
}
// Without an IPv4 gateway, the takeover uses the first IPv6 one, and the probe
// carries IPv6 addresses.
func TestVerifyDNSRoutingIPv6(t *testing.T) {
ctx := newRouteTestContext(t, true, udpNameServer([]byte{9, 9, 9, 9}), []*router.RoutingRule{port53Rule()})
if err := verifyDNSRouting(ctx, routeTestInboundTag, "fc00::1", "fc00::2"); err != nil {
t.Fatalf("expected the takeover to be accepted, got: %v", err)
}
if err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, "fc00::2"); err == nil {
t.Fatal("expected mixed IPv4 and IPv6 addresses to be refused")
}
}
-106
View File
@@ -710,109 +710,3 @@ 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"
}
+120
View File
@@ -0,0 +1,120 @@
//go:build windows
package tun
import (
"context"
"slices"
"strings"
"sync"
"github.com/xtls/xray-core/common/errors"
"golang.org/x/sys/windows"
"golang.zx2c4.com/wireguard/windows/tunnel/winipcfg"
)
// outboundGuard keeps Windows to the binding of autoOutboundsInterface, which
// keeps Xray's own connections out of the TUN. With weak host send or
// forwarding on for an IP version on the bound interface, Windows sends them
// where the routes lead, into the TUN, from that interface's address, and
// drops what comes back to that address through the TUN, so they stall.
//
// For the IP versions routed to the TUN, weak host send is turned off on the
// bound interface while the TUN runs, and turned on again when the TUN stops
// or another interface takes over. Forwarding is what Mobile Hotspot and
// Internet Connection Sharing need, so it is only reported.
type outboundGuard struct {
sync.Mutex
families []winipcfg.AddressFamily
luid winipcfg.LUID // of the interface last checked
name string // of that interface
turnedOff []winipcfg.AddressFamily // where weak host send was turned off on it
forwarding bool // whether forwarding was on there
stopped bool
}
// check turns weak host send off on the bound interface, and warns when
// forwarding comes on there, but not again while it stays on.
func (g *outboundGuard) check() {
g.Lock()
defer g.Unlock()
if g.stopped {
return
}
var luid winipcfg.LUID
var name string
if iface := updater.Get(); iface != nil {
luid, _ = winipcfg.LUIDFromIndex(uint32(iface.Index))
name = iface.Name
}
if luid != g.luid {
g.restoreLocked()
g.luid, g.name = luid, name
g.forwarding = false // to warn about the new interface as well
}
if luid == 0 {
return
}
var forwarding []string
for _, family := range g.families {
row, err := luid.IPInterface(family)
if err != nil {
continue // the interface lacks that IP version
}
if row.ForwardingEnabled {
forwarding = append(forwarding, familyName(family))
}
if !row.WeakHostSend {
continue
}
if err := setWeakHostSend(row, false); err != nil {
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send off for ", familyName(family), " on ", name)
continue
}
if !slices.Contains(g.turnedOff, family) {
g.turnedOff = append(g.turnedOff, family)
errors.LogInfo(context.Background(), "[tun] weak host send turned off for ", familyName(family), " on ", name, " while the TUN runs, as Windows would ignore autoOutboundsInterface")
}
}
wasOn := g.forwarding
g.forwarding = len(forwarding) > 0
if g.forwarding && !wasOn {
errors.LogWarning(context.Background(), "[tun] forwarding is on for ", strings.Join(forwarding, " and "), " on ", name, " (Mobile Hotspot and Internet Connection Sharing turn it on), so Windows ignores autoOutboundsInterface there, and Xray's own connections go into the TUN and stall: turn the hotspot off, or have it share the TUN instead of ", name)
}
}
// restore turns weak host send on again where check turned it off, for good.
func (g *outboundGuard) restore() {
g.Lock()
defer g.Unlock()
g.restoreLocked()
g.stopped = true
}
func (g *outboundGuard) restoreLocked() {
for _, family := range g.turnedOff {
row, err := g.luid.IPInterface(family)
if err == nil {
err = setWeakHostSend(row, true)
}
if err != nil {
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send on again for ", familyName(family), " on ", g.name)
}
}
g.turnedOff = nil
}
func setWeakHostSend(row *winipcfg.MibIPInterfaceRow, on bool) error {
row.WeakHostSend = on
if row.Family == windows.AF_INET {
row.SitePrefixLength = 0 // as SetIpInterfaceEntry requires for IPv4
}
return row.Set()
}
func familyName(family winipcfg.AddressFamily) string {
if family == windows.AF_INET {
return "IPv4"
}
return "IPv6"
}
@@ -4,7 +4,6 @@ package tun
import (
"context"
"crypto/md5"
go_errors "errors"
"net"
"net/netip"
@@ -341,46 +340,3 @@ 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")
}
}
+14
View File
@@ -8,6 +8,20 @@ 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++ {
+82
View File
@@ -0,0 +1,82 @@
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,3 +80,43 @@ 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)
}
}
}
-7
View File
@@ -36,7 +36,6 @@ import (
"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"
@@ -525,12 +524,6 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
}
errors.LogInfo(ctx, "received request for ", request.Destination())
if stream, ok := session.StreamSettingsFromContext(h.ctx).(*internet.MemoryStreamConfig); ok && stream.ProtocolName == "xdrive" {
if request.Command != protocol.RequestCommandMux && request.Command != protocol.RequestCommandRvs {
return errors.New("VLESS over XDRIVE: inbound received a non-Mux/Rvs request")
}
}
inbound := session.InboundFromContext(ctx)
if inbound == nil {
panic("no inbound metadata")
+9 -13
View File
@@ -12,7 +12,6 @@ import (
"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"
)
@@ -42,19 +41,17 @@ type Client struct {
func NewClient(ctx context.Context, config *vless.Multiplex, network string, open func(context.Context) (context.Context, *transport.Link, error)) *Client {
c := &Client{config: config}
maxReuseTimes := uint32(1024)
if network == "xdrive" {
maxReuseTimes = 0 // unlimited
config.Concurrency = max(config.Concurrency, 128)
if config.XudpConcurrency > 0 {
config.XudpConcurrency = max(config.XudpConcurrency, 128)
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 config.Concurrency > 0 {
c.tcp = NewPool(ctx, ClientStrategy{MaxConcurrency: uint32(config.Concurrency), MaxConnection: maxReuseTimes}, open)
}
if config.XudpConcurrency > 0 {
c.udp = NewPool(ctx, ClientStrategy{MaxConcurrency: uint32(config.XudpConcurrency), MaxConnection: maxReuseTimes}, open)
if concurrency := config.GetXudpConcurrency(); concurrency > 0 {
c.udp = pool(concurrency)
}
return c
}
@@ -75,7 +72,6 @@ func (c *Client) Dispatch(ctx context.Context, link *transport.Link) (bool, erro
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
+1 -3
View File
@@ -26,9 +26,7 @@ func TestClientUDP443Policy(t *testing.T) {
opened = true
return nil, nil, context.Canceled
})
r, w := pipe.New()
common.Close(w)
handled, err := client.Dispatch(ctx, &transport.Link{Reader: r})
handled, err := client.Dispatch(ctx, &transport.Link{})
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)
+7 -7
View File
@@ -191,13 +191,6 @@ func (h *Handler) process(ctx context.Context, link *transport.Link, dialer inte
rec := h.server
var conn stat.Connection
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)
@@ -279,20 +272,27 @@ func (h *Handler) process(ctx context.Context, link *transport.Link, dialer inte
request.Address, request.Port = target.Address, target.Port
}
account := request.User.Account.(*vless.MemoryAccount)
requestAddons := &encoding.Addons{
Flow: account.Flow,
}
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 nil, nil, errors.New("XTLS rejected UDP/443 traffic")
}
case protocol.RequestCommandTCP, protocol.RequestCommandMux, protocol.RequestCommandRvs:
var target net.Conn
if commonConn, ok := conn.(*encryption.CommonConn); ok {
+1 -2
View File
@@ -255,11 +255,10 @@ func DialSystem(ctx context.Context, dest net.Destination, sockopt *SocketConfig
}
ips, err := LookupForIP(dest.Address.Domain(), finalStrategy, src)
if err != nil {
errors.LogErrorInner(ctx, err, "failed to resolve ip")
if sockopt.DomainStrategy.ForceIP() {
errors.LogErrorInner(ctx, err, "failed to resolve ip for: ", dest.Address.Domain())
return nil, err
}
errors.LogInfoInner(ctx, err, "failed to resolve ip for: ", dest.Address.Domain(), ", but continue due to USEIP* strategy")
} else if sockopt.HappyEyeballs == nil || sockopt.HappyEyeballs.TryDelayMs == 0 || sockopt.HappyEyeballs.MaxConcurrentTry == 0 || len(ips) < 2 || len(sockopt.DialerProxy) > 0 || dest.Network != net.Network_TCP {
dest.Address = net.IPAddress(ips[dice.Roll(len(ips))])
errors.LogInfo(ctx, "replace destination with "+dest.String())
+5 -12
View File
@@ -175,14 +175,7 @@ func (c *xdnsServer) read(buf []byte, addr net.Addr) {
c.decref(msg, addr)
return
}
kind := decoded[8] & 0x3F
fragmented := decoded[8]&0xC0 == 0xC0
dataOffset := 9 + 3
if fragmented {
dataOffset += 3
}
if TypeMap_[decoded[0]&3] != uint16(msg.Questions[0].Type) ||
(kind != 3 && kind != 8) || (kind == 3 && n <= dataOffset) || (kind == 8 && n != 9+8) {
if TypeMap_[decoded[0]&3] != uint16(msg.Questions[0].Type) || (decoded[8]&0x3F != 3 && decoded[8]&0x3F != 8) || (decoded[8]&0x3F == 3 && n < 9+3+1) || (decoded[8]&0x3F == 8 && n != 9+8) {
msg.Header.Response = true
msg.Header.Authoritative = true
msg.Header.RCode = dnsmessage.RCodeSuccess
@@ -208,14 +201,14 @@ func (c *xdnsServer) read(buf []byte, addr net.Addr) {
c.decref(msg, addr)
}
if kind == 8 {
if decoded[8]&0x3F == 8 {
return
}
p := pool4K.Get().([]byte)
p = p[:0]
if fragmented {
if decoded[8]&0xC0 == 0xC0 {
out := pool4K.Get().([]byte)
n := c.fragManager.Feed(out, FragKey{clientID: clientID, fragID: decoded[12]}, decoded[13], decoded[14], decoded[dataOffset:n])
n := c.fragManager.Feed(out, FragKey{clientID: clientID, fragID: decoded[12]}, decoded[13], decoded[14], decoded[15:n])
pool4K.Put(p[:cap(p)])
if n > 0 {
p = out[:n]
@@ -224,7 +217,7 @@ func (c *xdnsServer) read(buf []byte, addr net.Addr) {
return
}
} else {
p = append(p, decoded[dataOffset:n]...)
p = append(p, decoded[12:n]...)
}
select {
case <-c.closeCh:
+1 -5
View File
@@ -28,11 +28,7 @@ func (s *Proxy) Proxy(w http.ResponseWriter, r *ProxyRequest) (*Conn, error) {
w.WriteHeader(http.StatusOK)
if ok {
str, err := streamer.HTTPStream()
if err != nil {
return nil, err
}
return newProxiedConn(str), nil
return newProxiedConn(streamer.HTTPStream()), nil
}
controller := http.NewResponseController(w)
if err := controller.Flush(); err != nil {
+1 -5
View File
@@ -231,11 +231,7 @@ func TestDialWarpHTTP3(t *testing.T) {
}
w.WriteHeader(http.StatusOK)
w.(http.Flusher).Flush()
str, err := w.(http3.HTTPStreamer).HTTPStream()
if err != nil {
t.Error(err)
return
}
str := w.(http3.HTTPStreamer).HTTPStream()
go func() { capsules <- readCapsuleTypes(str, nil) }()
b, err := str.ReceiveDatagram(r.Context())
if err != nil {
+11 -11
View File
@@ -26,7 +26,6 @@ import (
"github.com/xtls/xray-core/common/net"
http_proto "github.com/xtls/xray-core/common/protocol/http"
"github.com/xtls/xray-core/common/signal/done"
"github.com/xtls/xray-core/common/task"
"github.com/xtls/xray-core/transport/internet"
"github.com/xtls/xray-core/transport/internet/hysteria/congestion"
"github.com/xtls/xray-core/transport/internet/hysteria/congestion/bbr"
@@ -79,9 +78,10 @@ func (h *requestHandler) upsertSession(sessionId string) *httpSession {
h.sessions.Store(sessionId, s)
shouldReap := done.New()
time.AfterFunc(30*time.Second, func() {
go func() {
time.Sleep(30 * time.Second)
shouldReap.Close()
})
}()
go func() {
select {
case <-shouldReap.Wait():
@@ -222,15 +222,15 @@ func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Req
scStreamUpServerSecs := h.config.GetNormalizedScStreamUpServerSecs()
hasLegacyRefererCompatMarker := request.Header.Get("Referer") != ""
if (hasLegacyRefererCompatMarker || obfsPaddingAccepted) && scStreamUpServerSecs.To > 0 {
writePadding := &task.Periodic{
Execute: func() error {
go func() {
for {
_, err := httpSC.Write(bytes.Repeat([]byte{'X'}, int(h.config.GetNormalizedXPaddingBytes().rand())))
return err
},
Interval: time.Duration(scStreamUpServerSecs.rand()) * time.Second,
}
defer writePadding.Close()
writePadding.Start()
if err != nil {
break
}
time.Sleep(time.Duration(scStreamUpServerSecs.rand()) * time.Second)
}
}()
}
select {
case <-request.Context().Done():
+12 -17
View File
@@ -6,11 +6,9 @@ import (
"time"
"github.com/gorilla/websocket"
"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/serial"
"github.com/xtls/xray-core/common/task"
)
var _ buf.Writer = (*connection)(nil)
@@ -22,27 +20,25 @@ type connection struct {
conn *websocket.Conn
reader io.Reader
remoteAddr net.Addr
keepalive *task.Periodic
}
func NewConnection(conn *websocket.Conn, remoteAddr net.Addr, extraReader io.Reader, heartbeatPeriod uint32) *connection {
wrappedConn := &connection{
if heartbeatPeriod != 0 {
go func() {
for {
time.Sleep(time.Duration(heartbeatPeriod) * time.Second)
if err := conn.WriteControl(websocket.PingMessage, []byte{}, time.Time{}); err != nil {
break
}
}
}()
}
return &connection{
conn: conn,
remoteAddr: remoteAddr,
reader: extraReader,
}
if heartbeatPeriod != 0 {
keepalive := task.Periodic{
Execute: func() error {
return conn.WriteControl(websocket.PingMessage, []byte{}, time.Time{})
},
Interval: time.Duration(heartbeatPeriod) * time.Second,
}
keepalive.Start()
wrappedConn.keepalive = &keepalive
}
return wrappedConn
}
// Read implements net.Conn.Read()
@@ -97,7 +93,6 @@ func (c *connection) WriteMultiBuffer(mb buf.MultiBuffer) error {
}
func (c *connection) Close() error {
common.CloseIfExists(c.keepalive)
var errs []interface{}
if err := c.conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Now().Add(time.Second*5)); err != nil {
errs = append(errs, err)