mirror of
https://github.com/XTLS/Xray-core.git
synced 2026-11-30 13:48:36 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1e6feeb12f | ||
|
|
ded8443fee | ||
|
|
5780f0df90 | ||
|
|
4d0bfb4d0d | ||
|
|
db6664bd68 | ||
|
|
67756b3674 | ||
|
|
9576662b8e | ||
|
|
c5ccb356aa | ||
|
|
b56ffef338 | ||
|
|
862e59a2f2 | ||
|
|
35805f9377 | ||
|
|
5d8b20239f |
@@ -7,7 +7,6 @@ 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"
|
||||
@@ -184,9 +183,6 @@ 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)
|
||||
}
|
||||
|
||||
+3
-23
@@ -15,8 +15,6 @@ const (
|
||||
|
||||
var ErrBufferFull = errors.New("buffer is full")
|
||||
|
||||
var pool = bytespool.GetPool(Size)
|
||||
|
||||
// ownership represents the data owner of the buffer.
|
||||
type ownership uint8
|
||||
|
||||
@@ -39,16 +37,7 @@ type Buffer struct {
|
||||
|
||||
// New creates a Buffer with 0 length and 8K capacity, managed.
|
||||
func New() *Buffer {
|
||||
buf := pool.Get().([]byte)
|
||||
if cap(buf) >= Size {
|
||||
buf = buf[:Size]
|
||||
} else {
|
||||
buf = make([]byte, Size)
|
||||
}
|
||||
|
||||
return &Buffer{
|
||||
v: buf,
|
||||
}
|
||||
return &Buffer{v: bytespool.Alloc(Size)}
|
||||
}
|
||||
|
||||
// NewExisted creates a standard size Buffer with an existed bytearray, managed.
|
||||
@@ -80,16 +69,7 @@ func FromBytes(b []byte) *Buffer {
|
||||
// StackNew creates a new Buffer object on stack, managed.
|
||||
// This method is for buffers that is released in the same function.
|
||||
func StackNew() Buffer {
|
||||
buf := pool.Get().([]byte)
|
||||
if cap(buf) >= Size {
|
||||
buf = buf[:Size]
|
||||
} else {
|
||||
buf = make([]byte, Size)
|
||||
}
|
||||
|
||||
return Buffer{
|
||||
v: buf,
|
||||
}
|
||||
return Buffer{v: bytespool.Alloc(Size)}
|
||||
}
|
||||
|
||||
// NewWithSize creates a Buffer with 0 length and capacity with at least the given size, bytespool's.
|
||||
@@ -113,7 +93,7 @@ func (b *Buffer) Release() {
|
||||
switch b.ownership {
|
||||
case managed:
|
||||
if cap(p) == Size {
|
||||
pool.Put(p)
|
||||
bytespool.Free(p)
|
||||
}
|
||||
case bytespools:
|
||||
bytespool.Free(p)
|
||||
|
||||
+64
-52
@@ -1,72 +1,84 @@
|
||||
package bytespool
|
||||
|
||||
import "sync"
|
||||
import (
|
||||
"math/bits"
|
||||
"sync"
|
||||
)
|
||||
|
||||
func createAllocFunc(size int32) func() interface{} {
|
||||
return func() interface{} {
|
||||
return make([]byte, size)
|
||||
}
|
||||
}
|
||||
|
||||
// The following parameters controls the size of buffer pools.
|
||||
// There are numPools pools. Starting from 2k size, the size of each pool is sizeMulti of the previous one.
|
||||
// Package buf is guaranteed to not use buffers larger than the largest pool.
|
||||
// Other packets may use larger buffers.
|
||||
const (
|
||||
numPools = 4
|
||||
sizeMulti = 4
|
||||
minShift = 10 // 1KB
|
||||
maxShift = 16 // 64KB
|
||||
numPools = maxShift - minShift + 1
|
||||
minSize = 1 << minShift
|
||||
maxSize = 1 << maxShift
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
// 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) }},
|
||||
}
|
||||
|
||||
// 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.
|
||||
// Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 1024.
|
||||
//
|
||||
// xray:api:stable
|
||||
func Alloc(size int32) []byte {
|
||||
pool := GetPool(size)
|
||||
if pool != nil {
|
||||
return pool.Get().([]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")
|
||||
}
|
||||
return make([]byte, size)
|
||||
}
|
||||
|
||||
// Free puts a byte slice into the internal pool.
|
||||
//
|
||||
// xray:api:stable
|
||||
func Free(b []byte) {
|
||||
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
|
||||
}
|
||||
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]))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,18 +191,10 @@ func getConfig() string {
|
||||
{
|
||||
"protocol": "vless",
|
||||
"settings": {
|
||||
"vnext": [
|
||||
{
|
||||
"address": "1.2.3.4",
|
||||
"port": 1234,
|
||||
"users": [
|
||||
{
|
||||
"id": "4784f9b8-a879-4fec-9718-ebddefa47750",
|
||||
"encryption": "none"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
"address": "1.2.3.4",
|
||||
"port": 1234,
|
||||
"id": "4784f9b8-a879-4fec-9718-ebddefa47750",
|
||||
"encryption": "none"
|
||||
},
|
||||
"tag": "XHTTP_IN",
|
||||
"streamSettings": {
|
||||
|
||||
@@ -70,8 +70,11 @@ 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())
|
||||
}
|
||||
|
||||
|
||||
@@ -58,15 +58,11 @@ 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
|
||||
}
|
||||
|
||||
|
||||
@@ -20,17 +20,17 @@ func TestPeriodicTaskStop(t *testing.T) {
|
||||
common.Must(task.Start())
|
||||
time.Sleep(time.Second * 5)
|
||||
common.Must(task.Close())
|
||||
if value != 3 {
|
||||
t.Fatal("expected 3, but got ", value)
|
||||
if value != 2 {
|
||||
t.Fatal("expected 2, but got ", value)
|
||||
}
|
||||
time.Sleep(time.Second * 4)
|
||||
if value != 3 {
|
||||
t.Fatal("expected 3, but got ", value)
|
||||
if value != 2 {
|
||||
t.Fatal("expected 2, but got ", value)
|
||||
}
|
||||
common.Must(task.Start())
|
||||
time.Sleep(time.Second * 3)
|
||||
if value != 5 {
|
||||
t.Fatal("Expected 5, but ", value)
|
||||
if value != 3 {
|
||||
t.Fatal("Expected 3, but ", value)
|
||||
}
|
||||
common.Must(task.Close())
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ module github.com/xtls/xray-core
|
||||
go 1.27
|
||||
|
||||
require (
|
||||
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c
|
||||
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a
|
||||
github.com/bufbuild/protocompile v0.14.1
|
||||
github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344
|
||||
github.com/golang/mock v1.7.0-rc.1
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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/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/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=
|
||||
|
||||
+24
-63
@@ -1,9 +1,6 @@
|
||||
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"
|
||||
@@ -49,73 +46,37 @@ 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"`
|
||||
Servers []*HTTPRemoteConfig `json:"servers"`
|
||||
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"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
}
|
||||
|
||||
func (v *HTTPClientConfig) Build() (proto.Message, error) {
|
||||
config := new(http.ClientConfig)
|
||||
if v.Address != nil {
|
||||
v.Servers = []*HTTPRemoteConfig{
|
||||
{
|
||||
Address: v.Address,
|
||||
Port: v.Port,
|
||||
},
|
||||
}
|
||||
if len(v.Username) > 0 {
|
||||
v.Servers[0].Users = []json.RawMessage{{}}
|
||||
}
|
||||
|
||||
server := &protocol.ServerEndpoint{
|
||||
Address: v.Address.Build(),
|
||||
Port: uint32(v.Port),
|
||||
}
|
||||
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
|
||||
if len(v.Username) > 0 {
|
||||
account := &HTTPAccount{
|
||||
Username: v.Username,
|
||||
Password: v.Password,
|
||||
}
|
||||
user := &protocol.User{
|
||||
Level: v.Level,
|
||||
Email: v.Email,
|
||||
Account: serial.ToTypedMessage(account.Build()),
|
||||
}
|
||||
server.User = user
|
||||
}
|
||||
|
||||
config.Server = server
|
||||
config.Header = make([]*http.Header, 0, 32)
|
||||
for key, value := range v.Headers {
|
||||
config.Header = append(config.Header, &http.Header{
|
||||
|
||||
+22
-48
@@ -177,7 +177,7 @@ func buildShadowsocks2022(v *ShadowsocksServerConfig) (proto.Message, error) {
|
||||
return config, nil
|
||||
}
|
||||
|
||||
type ShadowsocksServerTarget struct {
|
||||
type ShadowsocksClientConfig struct {
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
Level byte `json:"level"`
|
||||
@@ -186,69 +186,43 @@ type ShadowsocksServerTarget 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 {
|
||||
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 {
|
||||
if v.Address == nil {
|
||||
return nil, errors.New("Shadowsocks server address is not set.")
|
||||
}
|
||||
if server.Port == 0 {
|
||||
if v.Port == 0 {
|
||||
return nil, errors.New("Invalid Shadowsocks port.")
|
||||
}
|
||||
if server.Password == "" {
|
||||
if v.Password == "" {
|
||||
return nil, errors.New("Shadowsocks password is not specified.")
|
||||
}
|
||||
|
||||
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
|
||||
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,
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
config := new(shadowsocks.ClientConfig)
|
||||
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)
|
||||
if cipherFromString(v.Cipher) == shadowsocks.CipherType_UNKNOWN {
|
||||
return nil, errors.New("unknown cipher method: ", v.Cipher)
|
||||
}
|
||||
ss := &protocol.ServerEndpoint{
|
||||
Address: server.Address.Build(),
|
||||
Port: uint32(server.Port),
|
||||
Address: v.Address.Build(),
|
||||
Port: uint32(v.Port),
|
||||
User: &protocol.User{
|
||||
Level: uint32(server.Level),
|
||||
Email: server.Email,
|
||||
Account: serial.ToTypedMessage(account),
|
||||
Level: uint32(v.Level),
|
||||
Email: v.Email,
|
||||
Account: serial.ToTypedMessage(&shadowsocks.Account{
|
||||
Password: v.Password,
|
||||
CipherType: cipherFromString(v.Cipher),
|
||||
}),
|
||||
},
|
||||
}
|
||||
config.Server = ss
|
||||
|
||||
+23
-62
@@ -1,9 +1,6 @@
|
||||
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"
|
||||
@@ -67,71 +64,35 @@ 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"`
|
||||
Servers []*SocksRemoteConfig `json:"servers"`
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
Level uint32 `json:"level"`
|
||||
Email string `json:"email"`
|
||||
Username string `json:"user"`
|
||||
Password string `json:"pass"`
|
||||
}
|
||||
|
||||
func (v *SocksClientConfig) Build() (proto.Message, error) {
|
||||
config := new(socks.ClientConfig)
|
||||
if v.Address != nil {
|
||||
v.Servers = []*SocksRemoteConfig{
|
||||
{
|
||||
Address: v.Address,
|
||||
Port: v.Port,
|
||||
},
|
||||
}
|
||||
if len(v.Username) > 0 {
|
||||
v.Servers[0].Users = []json.RawMessage{{}}
|
||||
}
|
||||
|
||||
server := &protocol.ServerEndpoint{
|
||||
Address: v.Address.Build(),
|
||||
Port: uint32(v.Port),
|
||||
}
|
||||
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
|
||||
if len(v.Username) > 0 {
|
||||
account := &SocksAccount{
|
||||
Username: v.Username,
|
||||
Password: v.Password,
|
||||
}
|
||||
user := &protocol.User{
|
||||
Level: v.Level,
|
||||
Email: v.Email,
|
||||
Account: serial.ToTypedMessage(account.Build()),
|
||||
}
|
||||
server.User = user
|
||||
}
|
||||
|
||||
config.Server = server
|
||||
return config, nil
|
||||
}
|
||||
|
||||
@@ -53,35 +53,6 @@ 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",
|
||||
|
||||
@@ -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": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `}]}], "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
|
||||
`{"protocol": "vless", "settings": {"address": "127.0.0.1", "port": 443, ` + xdriveID + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
|
||||
} {
|
||||
if err := build(input); err != nil {
|
||||
t.Errorf("%s: %v", input, err)
|
||||
@@ -541,12 +541,9 @@ 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 + `}, ` + 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 + `, "multiplex": {"concurrency": 8, "xudpProxyUDP443": "skip"}}, ` + xdriveStream + `}`, `"xudpProxyUDP443":"skip"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
|
||||
{`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision"}]}], "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
|
||||
{`{"protocol": "vless", "settings": {"address": "127.0.0.1", "port": 443, ` + 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"},
|
||||
|
||||
+21
-60
@@ -17,76 +17,41 @@ import (
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// TrojanServerTarget is configuration of a single trojan server
|
||||
type TrojanServerTarget struct {
|
||||
// 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"`
|
||||
}
|
||||
|
||||
// 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{}
|
||||
|
||||
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`, ``)
|
||||
}
|
||||
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.")
|
||||
}
|
||||
|
||||
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
|
||||
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,
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
return config, nil
|
||||
@@ -107,7 +72,6 @@ type TrojanUserConfig struct {
|
||||
Password string `json:"password"`
|
||||
Level byte `json:"level"`
|
||||
Email string `json:"email"`
|
||||
Flow string `json:"flow"`
|
||||
}
|
||||
|
||||
// TrojanServerConfig is Inbound configuration
|
||||
@@ -131,9 +95,6 @@ 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),
|
||||
|
||||
@@ -159,6 +159,7 @@ 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",
|
||||
|
||||
+96
-141
@@ -256,26 +256,19 @@ 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"`
|
||||
Vnext []*VLessOutboundVnext `json:"vnext"`
|
||||
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"`
|
||||
}
|
||||
|
||||
// Build implements Buildable
|
||||
@@ -286,130 +279,92 @@ func (c *VLessOutboundConfig) Build() (proto.Message, error) {
|
||||
}
|
||||
config := &outbound.Config{Multiplex: multiplex}
|
||||
|
||||
if c.Address != nil {
|
||||
c.Vnext = []*VLessOutboundVnext{
|
||||
{
|
||||
Address: c.Address,
|
||||
Port: c.Port,
|
||||
Users: []json.RawMessage{{}},
|
||||
},
|
||||
}
|
||||
if c.Address == nil {
|
||||
return nil, errors.New(`VLESS: "address" is not set`)
|
||||
}
|
||||
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`)
|
||||
}
|
||||
if len(rec.Users) != 1 {
|
||||
return nil, errors.New(`VLESS vnext: "users" should have one and only one member. Multiple members in "users" should use multiple VLESS outbounds and routing balancer instead`)
|
||||
}
|
||||
spec := &protocol.ServerEndpoint{
|
||||
Address: rec.Address.Build(),
|
||||
Port: uint32(rec.Port),
|
||||
}
|
||||
for _, rawUser := range rec.Users {
|
||||
user := new(protocol.User)
|
||||
if c.Address != nil {
|
||||
user.Level = c.Level
|
||||
user.Email = c.Email
|
||||
} else {
|
||||
if err := json.Unmarshal(rawUser, user); err != nil {
|
||||
return nil, errors.New(`VLESS users: invalid user`).Base(err)
|
||||
}
|
||||
}
|
||||
account := new(vless.Account)
|
||||
if c.Address != nil {
|
||||
account.Id = c.Id
|
||||
account.Flow = c.Flow
|
||||
//account.Seed = c.Seed
|
||||
account.Encryption = c.Encryption
|
||||
if c.Reverse != nil {
|
||||
rvs, err := c.Reverse.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
account.Reverse = rvs
|
||||
}
|
||||
account.Testpre = c.Testpre
|
||||
account.Testseed = c.Testseed
|
||||
} else {
|
||||
if err := json.Unmarshal(rawUser, account); err != nil {
|
||||
return nil, errors.New(`VLESS users: invalid user`).Base(err)
|
||||
}
|
||||
// validateOutboundTransportSecurity needs to see these
|
||||
c.Encryption = account.Encryption
|
||||
c.Address = rec.Address
|
||||
if account.Reverse != nil { // may not be reached: error json unmarshal
|
||||
return nil, errors.New(`VLESS users: please use simplified outbound's config style to use "reverse"`)
|
||||
}
|
||||
}
|
||||
|
||||
u, err := uuid.ParseString(account.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
account.Id = u.String()
|
||||
|
||||
switch account.Flow {
|
||||
case "":
|
||||
case vless.XRV, vless.XRV + "-udp443":
|
||||
default:
|
||||
return nil, errors.New(`VLESS users: "flow" doesn't support "` + account.Flow + `" in this version`)
|
||||
}
|
||||
|
||||
if !func() bool {
|
||||
s := strings.Split(account.Encryption, ".")
|
||||
if len(s) < 4 || s[0] != "mlkem768x25519plus" {
|
||||
return false
|
||||
}
|
||||
switch s[1] {
|
||||
case "native":
|
||||
case "xorpub":
|
||||
account.XorMode = 1
|
||||
case "random":
|
||||
account.XorMode = 2
|
||||
default:
|
||||
return false
|
||||
}
|
||||
switch s[2] {
|
||||
case "1rtt":
|
||||
case "0rtt":
|
||||
account.Seconds = 1
|
||||
default:
|
||||
return false
|
||||
}
|
||||
padding := 0
|
||||
for _, r := range s[3:] {
|
||||
if len(r) < 20 {
|
||||
padding += len(r) + 1
|
||||
continue
|
||||
}
|
||||
if b, _ := base64.RawURLEncoding.DecodeString(r); len(b) != 32 && len(b) != 1184 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
account.Encryption = account.Encryption[27+len(s[2]):]
|
||||
if padding > 0 {
|
||||
account.Padding = account.Encryption[:padding-1]
|
||||
account.Encryption = account.Encryption[padding:]
|
||||
}
|
||||
return true
|
||||
}() && account.Encryption != "none" {
|
||||
if account.Encryption == "" {
|
||||
return nil, errors.New(`VLESS users: please add/set "encryption":"none" for every user`)
|
||||
}
|
||||
return nil, errors.New(`VLESS users: unsupported "encryption": ` + account.Encryption)
|
||||
}
|
||||
|
||||
user.Account = serial.ToTypedMessage(account)
|
||||
spec.User = user
|
||||
break
|
||||
}
|
||||
config.Vnext = spec
|
||||
break
|
||||
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
|
||||
}
|
||||
account.Reverse = rvs
|
||||
}
|
||||
|
||||
if !func() bool {
|
||||
s := strings.Split(account.Encryption, ".")
|
||||
if len(s) < 4 || s[0] != "mlkem768x25519plus" {
|
||||
return false
|
||||
}
|
||||
switch s[1] {
|
||||
case "native":
|
||||
case "xorpub":
|
||||
account.XorMode = 1
|
||||
case "random":
|
||||
account.XorMode = 2
|
||||
default:
|
||||
return false
|
||||
}
|
||||
switch s[2] {
|
||||
case "1rtt":
|
||||
case "0rtt":
|
||||
account.Seconds = 1
|
||||
default:
|
||||
return false
|
||||
}
|
||||
padding := 0
|
||||
for _, r := range s[3:] {
|
||||
if len(r) < 20 {
|
||||
padding += len(r) + 1
|
||||
continue
|
||||
}
|
||||
if b, _ := base64.RawURLEncoding.DecodeString(r); len(b) != 32 && len(b) != 1184 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
account.Encryption = account.Encryption[27+len(s[2]):]
|
||||
if padding > 0 {
|
||||
account.Padding = account.Encryption[:padding-1]
|
||||
account.Encryption = account.Encryption[padding:]
|
||||
}
|
||||
return true
|
||||
}() && account.Encryption != "none" {
|
||||
if account.Encryption == "" {
|
||||
return nil, errors.New(`VLESS users: please add/set "encryption":"none" for every user`)
|
||||
}
|
||||
return nil, errors.New(`VLESS users: unsupported "encryption": ` + account.Encryption)
|
||||
}
|
||||
|
||||
user.Account = serial.ToTypedMessage(account)
|
||||
spec.User = user
|
||||
|
||||
config.Vnext = spec
|
||||
return config, nil
|
||||
}
|
||||
|
||||
@@ -18,41 +18,6 @@ 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",
|
||||
|
||||
+31
-70
@@ -102,22 +102,15 @@ 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"`
|
||||
Receivers []*VMessOutboundTarget `json:"vnext"`
|
||||
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"`
|
||||
Multiplex *MultiplexConfig `json:"multiplex"`
|
||||
}
|
||||
|
||||
// Build implements Buildable
|
||||
@@ -129,62 +122,30 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
u, err := uuid.ParseString(account.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
account.ID = u.String()
|
||||
|
||||
user.Account = serial.ToTypedMessage(account.Build())
|
||||
spec.User = user
|
||||
break
|
||||
}
|
||||
config.Receiver = spec
|
||||
break
|
||||
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
|
||||
}
|
||||
|
||||
account := &VMessAccount{
|
||||
ID: uid.String(),
|
||||
Security: c.Security,
|
||||
Experiments: c.Experiments,
|
||||
}
|
||||
spec := &protocol.ServerEndpoint{
|
||||
Address: c.Address.Build(),
|
||||
Port: uint32(c.Port),
|
||||
User: &protocol.User{
|
||||
Level: c.Level,
|
||||
Email: c.Email,
|
||||
Account: serial.ToTypedMessage(account.Build()),
|
||||
},
|
||||
}
|
||||
|
||||
config.Receiver = spec
|
||||
return config, nil
|
||||
}
|
||||
|
||||
@@ -18,42 +18,6 @@ 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",
|
||||
|
||||
+14
-4
@@ -238,7 +238,7 @@ func validateOutboundTransportSecurity(rawConfig interface{}, senderSettings *pr
|
||||
}
|
||||
|
||||
if tjCfg, ok := rawConfig.(*TrojanClientConfig); ok {
|
||||
if requiresTransportSecurity(tjCfg.Servers[0].Address) {
|
||||
if requiresTransportSecurity(tjCfg.Address) {
|
||||
return errors.New("trojan without TLS is prohibited unless the server address is a private IP or domain")
|
||||
}
|
||||
}
|
||||
@@ -265,8 +265,13 @@ 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 && (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.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.Testpre != 0 {
|
||||
return errors.New(`the xdrive transport doesn't support VLESS "testpre"`)
|
||||
@@ -367,10 +372,15 @@ 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
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math/rand/v2"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/signal"
|
||||
)
|
||||
|
||||
// wait to drain all the possible incoming UDP data
|
||||
// because re-established QUIC UDP may bypass the sniffer
|
||||
func DropUDP(ctx context.Context, reader buf.Reader) {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
timer := signal.CancelAfterInactivity(ctx, func() {
|
||||
cancel()
|
||||
}, time.Duration(30+rand.N(60))*time.Second)
|
||||
context.AfterFunc(ctx, func() {
|
||||
common.Interrupt(reader)
|
||||
})
|
||||
buf.Copy(reader, buf.Discard, buf.UpdateActivity(timer))
|
||||
}
|
||||
+39
-14
@@ -5,6 +5,7 @@ import (
|
||||
go_errors "errors"
|
||||
"io"
|
||||
"math/rand"
|
||||
"slices"
|
||||
|
||||
"github.com/apernet/quic-go"
|
||||
"github.com/xtls/xray-core/common"
|
||||
@@ -174,10 +175,15 @@ 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 {
|
||||
@@ -193,21 +199,21 @@ func (w *UDPWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
for i, b := range mb {
|
||||
addr := w.addr
|
||||
if b.UDP != nil {
|
||||
addr = b.UDP.NetAddr()
|
||||
if *b.UDP != w.lastUDP {
|
||||
w.lastUDP = *b.UDP
|
||||
w.lastUDPAddr = b.UDP.NetAddr()
|
||||
}
|
||||
addr = w.lastUDPAddr
|
||||
}
|
||||
|
||||
msg := &UDPMessage{
|
||||
SessionID: 0,
|
||||
PacketID: 0,
|
||||
FragID: 0,
|
||||
FragCount: 1,
|
||||
Addr: addr,
|
||||
Data: b.Bytes(),
|
||||
}
|
||||
|
||||
err := w.SendMessage(msg)
|
||||
var errTooLarge *quic.DatagramTooLargeError
|
||||
if go_errors.As(err, &errTooLarge) {
|
||||
if errTooLarge, ok := go_errors.AsType[*quic.DatagramTooLargeError](err); ok {
|
||||
msg.PacketID = uint16(rand.Intn(0xFFFF)) + 1
|
||||
fMsgs := FragUDPMessage(msg, int(errTooLarge.MaxDatagramPayloadSize))
|
||||
for _, fMsg := range fMsgs {
|
||||
@@ -228,40 +234,59 @@ 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 {
|
||||
var packet [1500]byte
|
||||
|
||||
n, err := r.reader.Read(packet[:])
|
||||
n, err := r.reader.Read(r.packet[:])
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
|
||||
msg, err := ParseUDPMessage(packet[:n])
|
||||
if err != nil {
|
||||
if err := parseUDPMessage(r.packet[:n], r.lastAddr, &r.msg); 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
|
||||
}
|
||||
|
||||
dest, err := net.ParseDestination("udp:" + dfMsg.Addr)
|
||||
if err != 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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
package hysteria
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/apernet/quic-go"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
xnet "github.com/xtls/xray-core/common/net"
|
||||
)
|
||||
|
||||
// datagramReader returns one datagram per Read, like a QUIC datagram stream.
|
||||
type datagramReader struct {
|
||||
msgs [][]byte
|
||||
}
|
||||
|
||||
func (r *datagramReader) Read(p []byte) (int, error) {
|
||||
if len(r.msgs) == 0 {
|
||||
return 0, io.EOF
|
||||
}
|
||||
n := copy(p, r.msgs[0])
|
||||
r.msgs = r.msgs[1:]
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func newTestReader(msgs []UDPMessage) *UDPReader {
|
||||
datagrams := make([][]byte, len(msgs))
|
||||
for i := range msgs {
|
||||
datagrams[i] = make([]byte, msgs[i].Size())
|
||||
msgs[i].Serialize(datagrams[i])
|
||||
}
|
||||
return &UDPReader{reader: &datagramReader{msgs: datagrams}, df: &Defragger{}}
|
||||
}
|
||||
|
||||
func TestUDPReaderFragments(t *testing.T) {
|
||||
want := &UDPMessage{PacketID: 1, Addr: "example.com:443", Data: bytes.Repeat([]byte("0123456789"), 20)}
|
||||
frags := FragUDPMessage(want, 100)
|
||||
if len(frags) < 2 {
|
||||
t.Fatalf("got %d fragments, want at least 2", len(frags))
|
||||
}
|
||||
|
||||
p := make([]byte, buf.Size)
|
||||
n, dest, err := newTestReader(frags).ReadFrom(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dest.NetAddr() != want.Addr || !bytes.Equal(p[:n], want.Data) {
|
||||
t.Errorf("got %q to %v, want %q to %s", p[:n], dest, want.Data, want.Addr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUDPReaderDestinations(t *testing.T) {
|
||||
msgs := []UDPMessage{
|
||||
{Addr: "203.0.113.1:53", Data: []byte("first")},
|
||||
{Addr: "203.0.113.1:53", Data: []byte("second")},
|
||||
{Addr: "203.0.113.2:53", Data: []byte("third")},
|
||||
}
|
||||
r := newTestReader(msgs)
|
||||
p := make([]byte, buf.Size)
|
||||
for i, want := range msgs {
|
||||
n, dest, err := r.ReadFrom(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dest.NetAddr() != want.Addr || !bytes.Equal(p[:n], want.Data) {
|
||||
t.Errorf("packet %d: got %q to %v, want %q to %s", i, p[:n], dest, want.Data, want.Addr)
|
||||
}
|
||||
// Callers rewrite the destination in place, the next packet must not see it.
|
||||
dest.Port = 5353
|
||||
}
|
||||
}
|
||||
|
||||
type captureWriter struct {
|
||||
writes [][]byte
|
||||
}
|
||||
|
||||
func (w *captureWriter) Write(p []byte) (int, error) {
|
||||
w.writes = append(w.writes, bytes.Clone(p))
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func TestUDPWriterAddress(t *testing.T) {
|
||||
ip := xnet.UDPDestination(xnet.ParseAddress("203.0.113.1"), 53)
|
||||
domain := xnet.UDPDestination(xnet.DomainAddress("example.com"), 53)
|
||||
|
||||
cw := &captureWriter{}
|
||||
w := &UDPWriter{writer: cw, addr: "198.51.100.1:1"}
|
||||
for _, tc := range []struct {
|
||||
udp *xnet.Destination
|
||||
want string
|
||||
}{
|
||||
{&ip, "203.0.113.1:53"},
|
||||
{&domain, "example.com:53"},
|
||||
{nil, "198.51.100.1:1"},
|
||||
{&ip, "203.0.113.1:53"},
|
||||
} {
|
||||
b := buf.FromBytes([]byte("data"))
|
||||
b.UDP = tc.udp
|
||||
if err := w.WriteMultiBuffer(buf.MultiBuffer{b}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
msg, err := ParseUDPMessage(cw.writes[len(cw.writes)-1])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if msg.Addr != tc.want {
|
||||
t.Errorf("address = %q, want %q", msg.Addr, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fragmentingWriter rejects datagrams larger than max, like a QUIC connection.
|
||||
type fragmentingWriter struct {
|
||||
max int
|
||||
writes [][]byte
|
||||
}
|
||||
|
||||
func (w *fragmentingWriter) Write(p []byte) (int, error) {
|
||||
if len(p) > w.max {
|
||||
return 0, &quic.DatagramTooLargeError{MaxDatagramPayloadSize: int64(w.max)}
|
||||
}
|
||||
w.writes = append(w.writes, bytes.Clone(p))
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func TestUDPWriterFragmentation(t *testing.T) {
|
||||
data := bytes.Repeat([]byte("0123456789"), 20)
|
||||
fw := &fragmentingWriter{max: 100}
|
||||
w := &UDPWriter{writer: fw, addr: "example.com:443"}
|
||||
if err := w.WriteMultiBuffer(buf.MultiBuffer{buf.FromBytes(data)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(fw.writes) < 2 {
|
||||
t.Fatalf("got %d datagrams, want at least 2", len(fw.writes))
|
||||
}
|
||||
|
||||
r := &UDPReader{reader: &datagramReader{msgs: fw.writes}, df: &Defragger{}}
|
||||
p := make([]byte, buf.Size)
|
||||
n, dest, err := r.ReadFrom(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dest.NetAddr() != w.addr || !bytes.Equal(p[:n], data) {
|
||||
t.Errorf("got %q to %v, want %q to %s", p[:n], dest, data, w.addr)
|
||||
}
|
||||
}
|
||||
+28
-20
@@ -1,7 +1,6 @@
|
||||
package hysteria
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -183,35 +182,44 @@ func (m *UDPMessage) Serialize(buf []byte) int {
|
||||
}
|
||||
|
||||
func ParseUDPMessage(msg []byte) (*UDPMessage, error) {
|
||||
m := &UDPMessage{}
|
||||
buf := bytes.NewBuffer(msg)
|
||||
if err := binary.Read(buf, binary.BigEndian, &m.SessionID); err != nil {
|
||||
m := new(UDPMessage)
|
||||
if err := parseUDPMessage(msg, "", m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := binary.Read(buf, binary.BigEndian, &m.PacketID); 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.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)
|
||||
lAddr, n, err := quicvarint.Parse(msg[8:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
if lAddr == 0 || lAddr > MaxMessageLength {
|
||||
return nil, errors.New("invalid address length")
|
||||
return errors.New("invalid address length")
|
||||
}
|
||||
bs := buf.Bytes()
|
||||
bs := msg[8+n:]
|
||||
if len(bs) <= int(lAddr) {
|
||||
// We use <= instead of < here as we expect at least one byte of data after the address
|
||||
return nil, errors.New("invalid message length")
|
||||
return errors.New("invalid message length")
|
||||
}
|
||||
m.Addr = string(bs[:lAddr])
|
||||
m.Data = bs[lAddr:]
|
||||
return m, nil
|
||||
*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
|
||||
}
|
||||
|
||||
// varintPut is like quicvarint.Append, but instead of appending to a slice,
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package hysteria
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseUDPMessage(t *testing.T) {
|
||||
want := &UDPMessage{PacketID: 1, FragID: 2, FragCount: 3, Addr: "example.com:443", Data: []byte("hello")}
|
||||
msg := make([]byte, want.Size())
|
||||
want.Serialize(msg)
|
||||
|
||||
for _, lastAddr := range []string{"", want.Addr, "other:1"} {
|
||||
got := new(UDPMessage)
|
||||
if err := parseUDPMessage(msg, lastAddr, got); err != nil {
|
||||
t.Fatalf("lastAddr %q: %v", lastAddr, err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("lastAddr %q: got %+v, want %+v", lastAddr, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseUDPMessageInvalid(t *testing.T) {
|
||||
msg := &UDPMessage{Addr: "example.com:443", Data: []byte("hello")}
|
||||
buf := make([]byte, msg.Size())
|
||||
msg.Serialize(buf)
|
||||
|
||||
zeroAddrLen := bytes.Clone(buf)
|
||||
zeroAddrLen[8] = 0 // Address length varint follows the 8-byte header
|
||||
|
||||
noData := &UDPMessage{Addr: msg.Addr}
|
||||
noDataBuf := make([]byte, noData.Size())
|
||||
noData.Serialize(noDataBuf)
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
msg []byte
|
||||
}{
|
||||
{"short header", buf[:7]},
|
||||
{"zero address length", zeroAddrLen},
|
||||
{"no data after address", noDataBuf},
|
||||
} {
|
||||
if _, err := ParseUDPMessage(tc.msg); err == nil {
|
||||
t.Errorf("%s: expected error", tc.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,21 +53,23 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Inbound, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
udpCodec, err := NewUDPServerCodec(method, psk, 500*time.Second)
|
||||
user := &protocol.MemoryUser{
|
||||
Email: config.Email,
|
||||
Level: uint32(config.Level),
|
||||
}
|
||||
|
||||
udpCodec, err := NewUDPServerCodec(method, psk, user, 500*time.Second)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
v := core.MustFromContext(ctx)
|
||||
return &Inbound{
|
||||
networks: networks,
|
||||
method: method,
|
||||
psk: psk,
|
||||
saltFilter: antireplay.NewMapFilter[[32]byte](60),
|
||||
user: &protocol.MemoryUser{
|
||||
Email: config.Email,
|
||||
Level: uint32(config.Level),
|
||||
},
|
||||
networks: networks,
|
||||
method: method,
|
||||
psk: psk,
|
||||
saltFilter: antireplay.NewMapFilter[[32]byte](60),
|
||||
user: user,
|
||||
udpCodec: udpCodec,
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
}, nil
|
||||
@@ -155,20 +157,12 @@ func (i *Inbound) processUDP(ctx context.Context, conn stat.Connection, dispatch
|
||||
}
|
||||
|
||||
for _, b := range mb {
|
||||
decoded, err := i.udpCodec.DecodePacket(b.Bytes())
|
||||
sessionItem, decoded, err := i.udpCodec.DecodePacket(b.Bytes())
|
||||
b.Release()
|
||||
if err != nil || decoded.HeaderType != HeaderTypeClient {
|
||||
continue
|
||||
}
|
||||
|
||||
sessionItem := i.udpCodec.GetSession(decoded.SessionID)
|
||||
if sessionItem.User == nil {
|
||||
sessionItem.Lock()
|
||||
if sessionItem.User == nil {
|
||||
sessionItem.User = i.user
|
||||
}
|
||||
sessionItem.Unlock()
|
||||
}
|
||||
link := sessionItem.link.Load()
|
||||
if link != nil {
|
||||
sessionItem.UpdateConn(conn)
|
||||
|
||||
@@ -2,8 +2,6 @@ package shadowsocks_2022
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/cipher"
|
||||
"encoding/binary"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -34,16 +32,15 @@ func init() {
|
||||
|
||||
type MultiUserInbound struct {
|
||||
sync.Mutex
|
||||
networks []net.Network
|
||||
method *CipherMethod
|
||||
masterPSK []byte
|
||||
usersByHash *utils.TypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser]
|
||||
usersByEmail *utils.TypedSyncMap[string, *protocol.MemoryUser]
|
||||
userCount atomic.Int64
|
||||
saltFilter *antireplay.ReplayFilter[[32]byte]
|
||||
udpSessions *UDPSessionManager
|
||||
udpMasterCipher cipher.Block
|
||||
policyManager policy.Manager
|
||||
networks []net.Network
|
||||
method *CipherMethod
|
||||
masterPSK []byte
|
||||
usersByHash *utils.TypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser]
|
||||
usersByEmail *utils.TypedSyncMap[string, *protocol.MemoryUser]
|
||||
userCount atomic.Int64
|
||||
saltFilter *antireplay.ReplayFilter[[32]byte]
|
||||
udpCodec *UDPMultiServerCodec
|
||||
policyManager policy.Manager
|
||||
}
|
||||
|
||||
func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiUserInbound, error) {
|
||||
@@ -68,22 +65,21 @@ func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiU
|
||||
return nil, err
|
||||
}
|
||||
|
||||
masterBlock, err := method.NewBlock(masterPSK)
|
||||
udpCodec, err := NewUDPMultiServerCodec(method, masterPSK, 500*time.Second)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
v := core.MustFromContext(ctx)
|
||||
i := &MultiUserInbound{
|
||||
networks: networks,
|
||||
method: method,
|
||||
masterPSK: masterPSK,
|
||||
usersByHash: utils.NewTypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser](),
|
||||
usersByEmail: utils.NewTypedSyncMap[string, *protocol.MemoryUser](),
|
||||
saltFilter: antireplay.NewMapFilter[[32]byte](60),
|
||||
udpSessions: NewUDPSessionManager(500 * time.Second),
|
||||
udpMasterCipher: masterBlock,
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
networks: networks,
|
||||
method: method,
|
||||
masterPSK: masterPSK,
|
||||
usersByHash: utils.NewTypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser](),
|
||||
usersByEmail: utils.NewTypedSyncMap[string, *protocol.MemoryUser](),
|
||||
saltFilter: antireplay.NewMapFilter[[32]byte](60),
|
||||
udpCodec: udpCodec,
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
}
|
||||
|
||||
for idx, user := range config.Users {
|
||||
@@ -281,68 +277,26 @@ func (i *MultiUserInbound) processUDP(ctx context.Context, conn stat.Connection,
|
||||
}
|
||||
|
||||
for _, b := range mb {
|
||||
// In multi-user UDP:
|
||||
// Packet header is 16 bytes: Encrypted(SessionID + PacketID)
|
||||
// Followed by 16 bytes EIH
|
||||
packetBytes := b.Bytes()
|
||||
if len(packetBytes) < 32+1+8+2 {
|
||||
b.Release()
|
||||
continue
|
||||
}
|
||||
|
||||
var rawHeader [16]byte
|
||||
i.udpMasterCipher.Decrypt(rawHeader[:], packetBytes[:16])
|
||||
|
||||
sessionID := binary.BigEndian.Uint64(rawHeader[:8])
|
||||
packetID := binary.BigEndian.Uint64(rawHeader[8:16])
|
||||
|
||||
sessionItem := i.udpSessions.GetOrCreate(sessionID)
|
||||
|
||||
if !sessionItem.CheckPacketID(packetID) {
|
||||
b.Release()
|
||||
continue
|
||||
}
|
||||
|
||||
var userPSK []byte
|
||||
var currentUser *protocol.MemoryUser
|
||||
sessionItem.Lock()
|
||||
currentUser = sessionItem.User
|
||||
userPSK = sessionItem.UserPSK
|
||||
sessionItem.Unlock()
|
||||
|
||||
if currentUser == nil {
|
||||
// Decrypt EIH
|
||||
decryptedHash := DecryptUDPEIH(i.udpMasterCipher, rawHeader[:], packetBytes[16:32])
|
||||
|
||||
user, ok := i.usersByHash.Load(decryptedHash)
|
||||
sessionItem, decoded, user, err := i.udpCodec.DecodePacket(b.Bytes(), func(hash [AESBlockSize]byte) (*protocol.MemoryUser, []byte, bool) {
|
||||
u, ok := i.usersByHash.Load(hash)
|
||||
if !ok {
|
||||
b.Release()
|
||||
continue
|
||||
return nil, nil, false
|
||||
}
|
||||
currentUser = user
|
||||
userPSK = user.Account.(*MemoryAccount).Key
|
||||
}
|
||||
|
||||
decoded, err := sessionItem.DecryptAESPayload(i.method, userPSK, sessionID, packetID, rawHeader[:], packetBytes[32:])
|
||||
return u, u.Account.(*MemoryAccount).Key, true
|
||||
})
|
||||
b.Release()
|
||||
if err != nil {
|
||||
if err != nil || decoded.HeaderType != HeaderTypeClient {
|
||||
continue
|
||||
}
|
||||
|
||||
sessionItem.Lock()
|
||||
if sessionItem.User == nil {
|
||||
sessionItem.User = currentUser
|
||||
sessionItem.UserPSK = userPSK
|
||||
}
|
||||
sessionItem.Unlock()
|
||||
|
||||
link := sessionItem.link.Load()
|
||||
if link != nil {
|
||||
sessionItem.UpdateConn(conn)
|
||||
} else {
|
||||
userPSK := user.Account.(*MemoryAccount).Key
|
||||
var err error
|
||||
link, err = sessionItem.EnsureLink(ctx, conn, decoded.Destination, dispatcher, i.policyManager, func(replyDest net.Destination, payload []byte) ([]byte, error) {
|
||||
return i.encodeServerUDPPacket(sessionID, userPSK, replyDest, payload)
|
||||
return i.udpCodec.EncodeServerPacket(decoded.SessionID, userPSK, replyDest, payload)
|
||||
})
|
||||
if err != nil {
|
||||
continue
|
||||
@@ -356,7 +310,3 @@ func (i *MultiUserInbound) processUDP(ctx context.Context, conn stat.Connection,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (i *MultiUserInbound) encodeServerUDPPacket(clientSessionID uint64, userPSK []byte, dest net.Destination, payload []byte) ([]byte, error) {
|
||||
return i.udpSessions.EncodeServerPacket(i.method, userPSK, clientSessionID, dest, payload)
|
||||
}
|
||||
|
||||
@@ -243,16 +243,14 @@ func (i *RelayInbound) processUDP(ctx context.Context, conn stat.Connection, dis
|
||||
dest.Network = net.Network_UDP
|
||||
|
||||
sessionItem := i.udpSessions.GetOrCreate(sessionID)
|
||||
sessionItem.Lock()
|
||||
if sessionItem.User == nil {
|
||||
sessionItem.Lock()
|
||||
if sessionItem.User == nil {
|
||||
sessionItem.User = &protocol.MemoryUser{
|
||||
Email: targetDest.email,
|
||||
Level: targetDest.level,
|
||||
}
|
||||
sessionItem.User = &protocol.MemoryUser{
|
||||
Email: targetDest.email,
|
||||
Level: targetDest.level,
|
||||
}
|
||||
sessionItem.Unlock()
|
||||
}
|
||||
sessionItem.Unlock()
|
||||
link := sessionItem.link.Load()
|
||||
if link != nil {
|
||||
sessionItem.UpdateConn(conn)
|
||||
|
||||
@@ -30,7 +30,7 @@ type Outbound struct {
|
||||
method *CipherMethod
|
||||
pskList [][]byte
|
||||
finalPSK []byte
|
||||
udpCodec *UDPPacketCodec
|
||||
udpCodec *UDPClientCodec
|
||||
policyManager policy.Manager
|
||||
}
|
||||
|
||||
@@ -50,9 +50,9 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Outbound, error) {
|
||||
}
|
||||
|
||||
finalPSK := pskList[len(pskList)-1]
|
||||
udpCodec, err := NewUDPPacketCodec(method, pskList)
|
||||
udpCodec, err := NewUDPClientCodec(method, pskList)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to create udp packet codec").Base(err)
|
||||
return nil, errors.New("failed to create udp client codec").Base(err)
|
||||
}
|
||||
|
||||
v := core.MustFromContext(ctx)
|
||||
|
||||
+292
-147
@@ -7,33 +7,78 @@ import (
|
||||
"io"
|
||||
"math"
|
||||
mrand "math/rand/v2"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
)
|
||||
|
||||
type UDPCodec struct {
|
||||
type UDPClientCodec struct {
|
||||
method *CipherMethod
|
||||
pskList [][]byte
|
||||
psk []byte
|
||||
blockCipher cipher.Block
|
||||
blockCiphers []cipher.Block
|
||||
chachaCipher cipher.AEAD
|
||||
}
|
||||
|
||||
func NewUDPClientCodec(method *CipherMethod, pskList [][]byte) (*UDPClientCodec, error) {
|
||||
if len(pskList) == 0 {
|
||||
return nil, errors.New("empty psk list")
|
||||
}
|
||||
if method.IsChaCha && len(pskList) > 1 {
|
||||
return nil, errors.New("multi-key is not supported for chacha20-poly1305")
|
||||
}
|
||||
finalPSK := pskList[len(pskList)-1]
|
||||
c := &UDPClientCodec{
|
||||
method: method,
|
||||
pskList: pskList,
|
||||
psk: finalPSK,
|
||||
}
|
||||
var err error
|
||||
if method.IsChaCha {
|
||||
c.chachaCipher, err = method.NewUDPCipher(finalPSK)
|
||||
} else {
|
||||
c.blockCipher, err = method.NewBlock(finalPSK)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(pskList) > 1 {
|
||||
c.blockCiphers = make([]cipher.Block, len(pskList))
|
||||
for i, psk := range pskList {
|
||||
c.blockCiphers[i], err = method.NewBlock(psk)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func NewUDPPacketCodec(method *CipherMethod, pskList [][]byte) (*UDPClientCodec, error) {
|
||||
return NewUDPClientCodec(method, pskList)
|
||||
}
|
||||
|
||||
type UDPServerCodec struct {
|
||||
method *CipherMethod
|
||||
psk []byte
|
||||
user *protocol.MemoryUser
|
||||
blockCipher cipher.Block
|
||||
chachaCipher cipher.AEAD
|
||||
sessions *UDPSessionManager
|
||||
}
|
||||
|
||||
type (
|
||||
UDPPacketCodec = UDPCodec
|
||||
UDPServerCodec = UDPCodec
|
||||
)
|
||||
|
||||
func newUDPCodec(method *CipherMethod, psk []byte) (*UDPCodec, error) {
|
||||
c := &UDPCodec{
|
||||
method: method,
|
||||
psk: psk,
|
||||
func NewUDPServerCodec(method *CipherMethod, psk []byte, user *protocol.MemoryUser, sessionTimeout time.Duration) (*UDPServerCodec, error) {
|
||||
c := &UDPServerCodec{
|
||||
method: method,
|
||||
psk: psk,
|
||||
user: user,
|
||||
sessions: NewUDPSessionManager(sessionTimeout),
|
||||
}
|
||||
var err error
|
||||
if method.IsChaCha {
|
||||
@@ -47,46 +92,129 @@ func newUDPCodec(method *CipherMethod, psk []byte) (*UDPCodec, error) {
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func NewUDPPacketCodec(method *CipherMethod, pskList [][]byte) (*UDPCodec, error) {
|
||||
if method.IsChaCha && len(pskList) > 1 {
|
||||
return nil, errors.New("multi-key is not supported for chacha20-poly1305")
|
||||
}
|
||||
finalPSK := pskList[len(pskList)-1]
|
||||
c, err := newUDPCodec(method, finalPSK)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.pskList = pskList
|
||||
if len(pskList) > 1 {
|
||||
c.blockCiphers = make([]cipher.Block, len(pskList))
|
||||
for i, psk := range pskList {
|
||||
c.blockCiphers[i], err = method.NewBlock(psk)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func NewUDPServerCodec(method *CipherMethod, psk []byte, sessionTimeout time.Duration) (*UDPCodec, error) {
|
||||
c, err := newUDPCodec(method, psk)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.sessions = NewUDPSessionManager(sessionTimeout)
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *UDPCodec) Sessions() *UDPSessionManager {
|
||||
func (c *UDPServerCodec) Sessions() *UDPSessionManager {
|
||||
return c.sessions
|
||||
}
|
||||
|
||||
func (c *UDPCodec) GetSession(sessionID uint64) *ServerUDPSession {
|
||||
func (c *UDPServerCodec) GetSession(sessionID uint64) *ServerUDPSession {
|
||||
if c.sessions == nil {
|
||||
return nil
|
||||
}
|
||||
return c.sessions.GetOrCreate(sessionID)
|
||||
return c.sessions.Get(sessionID)
|
||||
}
|
||||
|
||||
type UDPMultiServerCodec struct {
|
||||
method *CipherMethod
|
||||
masterPSK []byte
|
||||
masterBlock cipher.Block
|
||||
sessions *UDPSessionManager
|
||||
}
|
||||
|
||||
func NewUDPMultiServerCodec(method *CipherMethod, masterPSK []byte, sessionTimeout time.Duration) (*UDPMultiServerCodec, error) {
|
||||
if method.IsChaCha {
|
||||
return nil, errors.New("multi-user is not supported for chacha20-poly1305")
|
||||
}
|
||||
masterBlock, err := method.NewBlock(masterPSK)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &UDPMultiServerCodec{
|
||||
method: method,
|
||||
masterPSK: masterPSK,
|
||||
masterBlock: masterBlock,
|
||||
sessions: NewUDPSessionManager(sessionTimeout),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *UDPMultiServerCodec) Sessions() *UDPSessionManager {
|
||||
return c.sessions
|
||||
}
|
||||
|
||||
func (c *UDPMultiServerCodec) GetSession(sessionID uint64) *ServerUDPSession {
|
||||
if c.sessions == nil {
|
||||
return nil
|
||||
}
|
||||
return c.sessions.Get(sessionID)
|
||||
}
|
||||
|
||||
type UserLookupFunc func(hash [AESBlockSize]byte) (*protocol.MemoryUser, []byte, bool)
|
||||
|
||||
func (c *UDPMultiServerCodec) DecodePacket(data []byte, userLookup UserLookupFunc) (*ServerUDPSession, DecodedUDPPacket, *protocol.MemoryUser, error) {
|
||||
if len(data) < 2*AESBlockSize+AEADTagSize+RequestHeaderFixedChunkLength {
|
||||
return nil, DecodedUDPPacket{}, nil, ErrPacketTooShort
|
||||
}
|
||||
|
||||
var rawHeader [16]byte
|
||||
c.masterBlock.Decrypt(rawHeader[:], data[:16])
|
||||
|
||||
sessionID := binary.BigEndian.Uint64(rawHeader[:8])
|
||||
packetID := binary.BigEndian.Uint64(rawHeader[8:16])
|
||||
|
||||
sessionItem := c.sessions.Get(sessionID)
|
||||
var currentUser *protocol.MemoryUser
|
||||
var userPSK []byte
|
||||
var bodyAead cipher.AEAD
|
||||
|
||||
if sessionItem != nil {
|
||||
sessionItem.Lock()
|
||||
currentUser = sessionItem.User
|
||||
userPSK = sessionItem.UserPSK
|
||||
bodyAead = sessionItem.clientBodyCipher
|
||||
sessionItem.Unlock()
|
||||
|
||||
if currentUser != nil {
|
||||
if !sessionItem.CheckPacketID(packetID) {
|
||||
return nil, DecodedUDPPacket{}, nil, ErrPacketIdNotUnique
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if currentUser == nil {
|
||||
decryptedHash := DecryptUDPEIH(c.masterBlock, rawHeader[:], data[16:32])
|
||||
user, psk, ok := userLookup(decryptedHash)
|
||||
if !ok {
|
||||
return nil, DecodedUDPPacket{}, nil, errors.New("user not found")
|
||||
}
|
||||
currentUser = user
|
||||
userPSK = psk
|
||||
}
|
||||
|
||||
if bodyAead == nil {
|
||||
bodyKey := DeriveSessionSubKey(userPSK, rawHeader[:8], c.method.KeySaltLength)
|
||||
var err error
|
||||
bodyAead, err = c.method.NewAEAD(bodyKey)
|
||||
if err != nil {
|
||||
return nil, DecodedUDPPacket{}, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
bodyNonce := rawHeader[4:16]
|
||||
bodyCipher := data[32:]
|
||||
bodyPlain, err := bodyAead.Open(nil, bodyNonce, bodyCipher, nil)
|
||||
if err != nil {
|
||||
return nil, DecodedUDPPacket{}, nil, errors.New("failed to decrypt aes udp body").Base(err)
|
||||
}
|
||||
|
||||
decoded, err := parsePlainUDPPacket(sessionID, packetID, bodyPlain)
|
||||
if err != nil {
|
||||
return nil, DecodedUDPPacket{}, nil, err
|
||||
}
|
||||
if decoded.HeaderType != HeaderTypeClient {
|
||||
return nil, DecodedUDPPacket{}, nil, ErrBadHeaderType
|
||||
}
|
||||
|
||||
if sessionItem == nil {
|
||||
sessionItem = c.sessions.GetOrCreate(sessionID)
|
||||
}
|
||||
if !sessionItem.Commit(packetID, bodyAead, currentUser, userPSK) {
|
||||
return nil, DecodedUDPPacket{}, nil, ErrPacketIdNotUnique
|
||||
}
|
||||
|
||||
return sessionItem, decoded, currentUser, nil
|
||||
}
|
||||
|
||||
func (c *UDPMultiServerCodec) EncodeServerPacket(clientSessionID uint64, userPSK []byte, dest net.Destination, payload []byte) ([]byte, error) {
|
||||
return c.sessions.EncodeServerPacket(c.method, userPSK, clientSessionID, dest, payload)
|
||||
}
|
||||
|
||||
type DecodedUDPPacket struct {
|
||||
@@ -193,44 +321,42 @@ func parsePlainUDPPacket(sessionID, packetID uint64, bodyPlain []byte) (DecodedU
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *UDPCodec) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
func (c *UDPServerCodec) DecodePacket(data []byte) (*ServerUDPSession, DecodedUDPPacket, error) {
|
||||
if len(data) < PacketMinimalHeaderSize {
|
||||
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||
return nil, DecodedUDPPacket{}, ErrPacketTooShort
|
||||
}
|
||||
|
||||
if c.method.IsChaCha {
|
||||
if len(data) < PacketNonceSize+AEADTagSize {
|
||||
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||
return nil, DecodedUDPPacket{}, ErrPacketTooShort
|
||||
}
|
||||
nonce := data[:PacketNonceSize]
|
||||
ciphertext := data[PacketNonceSize:]
|
||||
plain, err := c.chachaCipher.Open(nil, nonce, ciphertext, nil)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, errors.New("failed to decrypt chacha udp packet").Base(err)
|
||||
return nil, DecodedUDPPacket{}, errors.New("failed to decrypt chacha udp packet").Base(err)
|
||||
}
|
||||
if len(plain) < 16+1+8+2 {
|
||||
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||
return nil, DecodedUDPPacket{}, ErrPacketTooShort
|
||||
}
|
||||
|
||||
sessionID := binary.BigEndian.Uint64(plain[:8])
|
||||
packetID := binary.BigEndian.Uint64(plain[8:16])
|
||||
|
||||
sessionItem := c.sessions.GetOrCreate(sessionID)
|
||||
if !sessionItem.CheckPacketID(packetID) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
|
||||
decoded, err := parsePlainUDPPacket(sessionID, packetID, plain[16:])
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
return nil, DecodedUDPPacket{}, err
|
||||
}
|
||||
|
||||
if decoded.HeaderType != HeaderTypeClient {
|
||||
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||
return nil, DecodedUDPPacket{}, ErrBadHeaderType
|
||||
}
|
||||
|
||||
sessionItem.AddPacketID(packetID)
|
||||
return decoded, nil
|
||||
sessionItem := c.sessions.GetOrCreate(sessionID)
|
||||
if !sessionItem.Commit(packetID, nil, c.user, c.psk) {
|
||||
return nil, DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
return sessionItem, decoded, nil
|
||||
}
|
||||
|
||||
// AES mode
|
||||
@@ -239,49 +365,48 @@ func (c *UDPCodec) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
sessionID := binary.BigEndian.Uint64(rawHeader[:8])
|
||||
packetID := binary.BigEndian.Uint64(rawHeader[8:16])
|
||||
|
||||
sessionItem := c.sessions.GetOrCreate(sessionID)
|
||||
if !sessionItem.CheckPacketID(packetID) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
sessionItem := c.sessions.Get(sessionID)
|
||||
var bodyAead cipher.AEAD
|
||||
if sessionItem != nil {
|
||||
if !sessionItem.CheckPacketID(packetID) {
|
||||
return nil, DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
sessionItem.Lock()
|
||||
bodyAead = sessionItem.clientBodyCipher
|
||||
sessionItem.Unlock()
|
||||
}
|
||||
|
||||
return sessionItem.DecryptAESPayload(c.method, c.psk, sessionID, packetID, rawHeader[:], data[16:])
|
||||
}
|
||||
|
||||
func (s *ServerUDPSession) DecryptAESPayload(method *CipherMethod, psk []byte, sessionID, packetID uint64, rawHeader, bodyCipher []byte) (DecodedUDPPacket, error) {
|
||||
bodyAead := s.clientBodyCipher
|
||||
isNewCipher := false
|
||||
if bodyAead == nil {
|
||||
bodyKey := DeriveSessionSubKey(psk, rawHeader[:8], method.KeySaltLength)
|
||||
bodyKey := DeriveSessionSubKey(c.psk, rawHeader[:8], c.method.KeySaltLength)
|
||||
var err error
|
||||
bodyAead, err = method.NewAEAD(bodyKey)
|
||||
bodyAead, err = c.method.NewAEAD(bodyKey)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
return nil, DecodedUDPPacket{}, err
|
||||
}
|
||||
isNewCipher = true
|
||||
}
|
||||
|
||||
bodyNonce := rawHeader[4:16]
|
||||
bodyCipher := data[16:]
|
||||
bodyPlain, err := bodyAead.Open(nil, bodyNonce, bodyCipher, nil)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err)
|
||||
return nil, DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err)
|
||||
}
|
||||
|
||||
decoded, err := parsePlainUDPPacket(sessionID, packetID, bodyPlain)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
return nil, DecodedUDPPacket{}, err
|
||||
}
|
||||
|
||||
if decoded.HeaderType != HeaderTypeClient {
|
||||
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||
return nil, DecodedUDPPacket{}, ErrBadHeaderType
|
||||
}
|
||||
|
||||
s.AddPacketID(packetID)
|
||||
|
||||
if isNewCipher {
|
||||
s.clientBodyCipher = bodyAead
|
||||
if sessionItem == nil {
|
||||
sessionItem = c.sessions.GetOrCreate(sessionID)
|
||||
}
|
||||
|
||||
return decoded, nil
|
||||
if !sessionItem.Commit(packetID, bodyAead, c.user, c.psk) {
|
||||
return nil, DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
return sessionItem, decoded, nil
|
||||
}
|
||||
|
||||
func (s *ServerUDPSession) EnsureServerState(method *CipherMethod, psk []byte) error {
|
||||
@@ -303,6 +428,9 @@ func (s *ServerUDPSession) EnsureServerState(method *CipherMethod, psk []byte) e
|
||||
if method.IsChaCha {
|
||||
var err error
|
||||
s.serverChaCha, err = method.NewUDPCipher(psk)
|
||||
if err != nil {
|
||||
s.ServerSessionID = 0
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -387,11 +515,12 @@ func (s *ServerUDPSession) EncodeServerPacket(method *CipherMethod, clientSessio
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (c *UDPCodec) EncodeServerPacket(clientSessionID uint64, dest net.Destination, payload []byte) ([]byte, error) {
|
||||
func (c *UDPServerCodec) EncodeServerPacket(clientSessionID uint64, dest net.Destination, payload []byte) ([]byte, error) {
|
||||
return c.sessions.EncodeServerPacket(c.method, c.psk, clientSessionID, dest, payload)
|
||||
}
|
||||
|
||||
type serverSessionState struct {
|
||||
sync.Mutex
|
||||
sessionID uint64
|
||||
window *SlidingWindow
|
||||
cipher cipher.AEAD
|
||||
@@ -399,21 +528,24 @@ type serverSessionState struct {
|
||||
}
|
||||
|
||||
func (st *serverSessionState) check(packetID uint64) bool {
|
||||
if st.window == nil {
|
||||
st.window = new(SlidingWindow)
|
||||
}
|
||||
st.Lock()
|
||||
defer st.Unlock()
|
||||
return st.window.Check(packetID)
|
||||
}
|
||||
|
||||
func (st *serverSessionState) add(packetID uint64) {
|
||||
if st.window == nil {
|
||||
st.window = new(SlidingWindow)
|
||||
func (st *serverSessionState) commit(packetID uint64, now int64) bool {
|
||||
st.Lock()
|
||||
defer st.Unlock()
|
||||
if !st.window.CheckAndAdd(packetID) {
|
||||
return false
|
||||
}
|
||||
st.window.Add(packetID)
|
||||
st.lastSeen.Store(now)
|
||||
return true
|
||||
}
|
||||
|
||||
type ClientUDPSession struct {
|
||||
codec *UDPCodec
|
||||
mu sync.Mutex
|
||||
codec *UDPClientCodec
|
||||
clientSessionID uint64
|
||||
nextPacketID atomic.Uint64
|
||||
clientBodyCipher cipher.AEAD
|
||||
@@ -421,7 +553,7 @@ type ClientUDPSession struct {
|
||||
old atomic.Pointer[serverSessionState]
|
||||
}
|
||||
|
||||
func (c *UDPCodec) NewClientSession() (*ClientUDPSession, error) {
|
||||
func (c *UDPClientCodec) NewClientSession() (*ClientUDPSession, error) {
|
||||
var sessID [8]byte
|
||||
if _, err := io.ReadFull(rand.Reader, sessID[:]); err != nil {
|
||||
return nil, err
|
||||
@@ -446,51 +578,43 @@ func (c *UDPCodec) NewClientSession() (*ClientUDPSession, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *ClientUDPSession) getServerSession(sessionID uint64, now int64) (*serverSessionState, error) {
|
||||
cur := s.current.Load()
|
||||
if cur != nil && cur.sessionID == sessionID {
|
||||
func (s *ClientUDPSession) findServerSession(sessionID uint64, now int64) (*serverSessionState, error) {
|
||||
if cur := s.current.Load(); cur != nil && cur.sessionID == sessionID {
|
||||
return cur, nil
|
||||
}
|
||||
|
||||
old := s.old.Load()
|
||||
if old != nil && old.sessionID == sessionID {
|
||||
if now-old.lastSeen.Load() > 60 {
|
||||
s.old.CompareAndSwap(old, nil)
|
||||
return nil, errors.New("old server session expired")
|
||||
if old := s.old.Load(); old != nil {
|
||||
if old.sessionID == sessionID {
|
||||
if now-old.lastSeen.Load() > 60 {
|
||||
return nil, errors.New("old server session expired")
|
||||
}
|
||||
return old, nil
|
||||
}
|
||||
return old, nil
|
||||
}
|
||||
|
||||
// New server session:
|
||||
// Spec §3.2.4: reject newer server sessions when the last packet received from the old session is less than 1 minute old.
|
||||
if old != nil && now-old.lastSeen.Load() < 60 {
|
||||
return nil, errors.New("newer server session rejected: old session is less than 1 minute old")
|
||||
}
|
||||
|
||||
var bodyAead cipher.AEAD
|
||||
if !s.codec.method.IsChaCha {
|
||||
var sessBytes [8]byte
|
||||
binary.BigEndian.PutUint64(sessBytes[:], sessionID)
|
||||
bodyKey := DeriveSessionSubKey(s.codec.psk, sessBytes[:], s.codec.method.KeySaltLength)
|
||||
var err error
|
||||
bodyAead, err = s.codec.method.NewAEAD(bodyKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
// Spec §3.2.4: reject newer server sessions when the last packet received from the old session is less than 1 minute old.
|
||||
if now-old.lastSeen.Load() < 60 {
|
||||
return nil, errors.New("newer server session rejected: old session is less than 1 minute old")
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *ClientUDPSession) transitionServerSession(sessionID uint64, cipher cipher.AEAD, now int64) (*serverSessionState, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if st, err := s.findServerSession(sessionID, now); st != nil || err != nil {
|
||||
return st, err
|
||||
}
|
||||
|
||||
newState := &serverSessionState{
|
||||
sessionID: sessionID,
|
||||
cipher: bodyAead,
|
||||
window: new(SlidingWindow),
|
||||
cipher: cipher,
|
||||
}
|
||||
newState.lastSeen.Store(now)
|
||||
|
||||
if cur == nil {
|
||||
s.current.CompareAndSwap(nil, newState)
|
||||
return s.current.Load(), nil
|
||||
if cur := s.current.Load(); cur != nil {
|
||||
s.old.Store(cur)
|
||||
}
|
||||
|
||||
s.old.Store(cur)
|
||||
s.current.Store(newState)
|
||||
return newState, nil
|
||||
}
|
||||
@@ -505,7 +629,7 @@ func (s *ClientUDPSession) EncodePacket(dest net.Destination, payload []byte) (*
|
||||
|
||||
var paddingLen int
|
||||
if dest.Port == 53 && len(payload) < MaxPaddingLength {
|
||||
paddingLen = mrand.IntN(MaxPaddingLength) + 1
|
||||
paddingLen = mrand.IntN(MaxPaddingLength-len(payload)) + 1
|
||||
}
|
||||
|
||||
addrPortLen := AddrPortLength(dest)
|
||||
@@ -620,6 +744,8 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||
}
|
||||
|
||||
now := time.Now().Unix()
|
||||
|
||||
if s.codec.method.IsChaCha {
|
||||
if len(data) < PacketNonceSize+AEADTagSize {
|
||||
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||
@@ -637,20 +763,10 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
sessionID := binary.BigEndian.Uint64(plain[:8])
|
||||
packetID := binary.BigEndian.Uint64(plain[8:16])
|
||||
|
||||
now := time.Now().Unix()
|
||||
st, err := s.getServerSession(sessionID, now)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
if !st.check(packetID) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
|
||||
decoded, err := parsePlainUDPPacket(sessionID, packetID, plain[16:])
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
|
||||
if decoded.HeaderType != HeaderTypeServer {
|
||||
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||
}
|
||||
@@ -658,8 +774,20 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
return DecodedUDPPacket{}, errors.New("client session ID mismatch")
|
||||
}
|
||||
|
||||
st.add(packetID)
|
||||
st.lastSeen.Store(now)
|
||||
st, err := s.findServerSession(sessionID, now)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
if st == nil {
|
||||
st, err = s.transitionServerSession(sessionID, nil, now)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
}
|
||||
|
||||
if !st.commit(packetID, now) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
|
||||
return decoded, nil
|
||||
}
|
||||
@@ -670,19 +798,29 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
sessionID := binary.BigEndian.Uint64(rawHeader[:8])
|
||||
packetID := binary.BigEndian.Uint64(rawHeader[8:16])
|
||||
|
||||
now := time.Now().Unix()
|
||||
st, err := s.getServerSession(sessionID, now)
|
||||
st, err := s.findServerSession(sessionID, now)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
if !st.check(packetID) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
|
||||
var bodyAead cipher.AEAD
|
||||
if st != nil {
|
||||
if !st.check(packetID) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
bodyAead = st.cipher
|
||||
} else {
|
||||
var sessBytes [8]byte
|
||||
binary.BigEndian.PutUint64(sessBytes[:], sessionID)
|
||||
bodyKey := DeriveSessionSubKey(s.codec.psk, sessBytes[:], s.codec.method.KeySaltLength)
|
||||
bodyAead, err = s.codec.method.NewAEAD(bodyKey)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
}
|
||||
bodyAead := st.cipher
|
||||
|
||||
bodyNonce := rawHeader[4:16]
|
||||
bodyCipher := data[16:]
|
||||
bodyPlain, err := bodyAead.Open(nil, bodyNonce, bodyCipher, nil)
|
||||
bodyPlain, err := bodyAead.Open(nil, bodyNonce, data[16:], nil)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err)
|
||||
}
|
||||
@@ -691,7 +829,6 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
|
||||
if decoded.HeaderType != HeaderTypeServer {
|
||||
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||
}
|
||||
@@ -699,8 +836,16 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
return DecodedUDPPacket{}, errors.New("client session ID mismatch")
|
||||
}
|
||||
|
||||
st.add(packetID)
|
||||
st.lastSeen.Store(now)
|
||||
if st == nil {
|
||||
st, err = s.transitionServerSession(sessionID, bodyAead, now)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
}
|
||||
|
||||
if !st.commit(packetID, now) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
|
||||
return decoded, nil
|
||||
}
|
||||
|
||||
@@ -191,7 +191,7 @@ func TestRelayUDPSessionStabilityAndDispatch(t *testing.T) {
|
||||
// Verify downstream destination can decode both packets
|
||||
method, err := GetCipherMethod(MethodAES128GCM)
|
||||
common.Must(err)
|
||||
destCodec, err := NewUDPServerCodec(method, destKey, 300*time.Second)
|
||||
destCodec, err := NewUDPServerCodec(method, destKey, nil, 300*time.Second)
|
||||
common.Must(err)
|
||||
|
||||
mu.Lock()
|
||||
@@ -202,7 +202,8 @@ func TestRelayUDPSessionStabilityAndDispatch(t *testing.T) {
|
||||
t.Fatalf("expected 2 received packets at destination, got %d", len(pkts))
|
||||
}
|
||||
|
||||
dec1, err := destCodec.DecodePacket(pkts[0])
|
||||
dec1, dec2 := DecodedUDPPacket{}, DecodedUDPPacket{}
|
||||
_, dec1, err = destCodec.DecodePacket(pkts[0])
|
||||
if err != nil {
|
||||
t.Fatalf("dest failed to decode packet 1: %v", err)
|
||||
}
|
||||
@@ -210,7 +211,7 @@ func TestRelayUDPSessionStabilityAndDispatch(t *testing.T) {
|
||||
t.Fatalf("dec1 mismatch: sess=%x, pktID=%d, payload=%s", dec1.SessionID, dec1.PacketID, string(dec1.Payload))
|
||||
}
|
||||
|
||||
dec2, err := destCodec.DecodePacket(pkts[1])
|
||||
_, dec2, err = destCodec.DecodePacket(pkts[1])
|
||||
if err != nil {
|
||||
t.Fatalf("dest failed to decode packet 2: %v", err)
|
||||
}
|
||||
|
||||
@@ -100,19 +100,27 @@ type ServerUDPSession struct {
|
||||
func (s *ServerUDPSession) CheckPacketID(packetID uint64) bool {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
if s.Window == nil {
|
||||
s.Window = new(SlidingWindow)
|
||||
}
|
||||
return s.Window.Check(packetID)
|
||||
}
|
||||
|
||||
func (s *ServerUDPSession) AddPacketID(packetID uint64) {
|
||||
func (s *ServerUDPSession) Commit(packetID uint64, bodyAead cipher.AEAD, user *protocol.MemoryUser, userPSK []byte) bool {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
if s.Window == nil {
|
||||
s.Window = new(SlidingWindow)
|
||||
if s.User != nil && user != nil && s.User != user {
|
||||
return false
|
||||
}
|
||||
s.Window.Add(packetID)
|
||||
if !s.Window.CheckAndAdd(packetID) {
|
||||
return false
|
||||
}
|
||||
if s.clientBodyCipher == nil && bodyAead != nil {
|
||||
s.clientBodyCipher = bodyAead
|
||||
}
|
||||
if s.User == nil && user != nil {
|
||||
s.User = user
|
||||
s.UserPSK = userPSK
|
||||
}
|
||||
s.LastActive.Store(time.Now().Unix())
|
||||
return true
|
||||
}
|
||||
|
||||
type UDPSessionManager struct {
|
||||
@@ -128,6 +136,13 @@ func NewUDPSessionManager(timeout time.Duration) *UDPSessionManager {
|
||||
}
|
||||
}
|
||||
|
||||
func (m *UDPSessionManager) Get(sessionID uint64) *ServerUDPSession {
|
||||
if s, ok := m.sessions.Load(sessionID); ok {
|
||||
return s
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *UDPSessionManager) GetOrCreate(sessionID uint64) *ServerUDPSession {
|
||||
now := time.Now().Unix()
|
||||
if s, ok := m.sessions.Load(sessionID); ok {
|
||||
@@ -137,6 +152,7 @@ func (m *UDPSessionManager) GetOrCreate(sessionID uint64) *ServerUDPSession {
|
||||
|
||||
s := &ServerUDPSession{
|
||||
SessionID: sessionID,
|
||||
Window: new(SlidingWindow),
|
||||
manager: m,
|
||||
}
|
||||
s.LastActive.Store(now)
|
||||
|
||||
@@ -63,10 +63,16 @@ func (s *ServerUDPSession) EnsureLink(
|
||||
|
||||
s.currentConn.Store(conn)
|
||||
|
||||
sessCtx, cancel := context.WithCancel(ctx)
|
||||
// UDP Session might travel across multiple connections
|
||||
// don't bind its lifetime to a parent context
|
||||
sessCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
|
||||
inbound := session.InboundFromContext(sessCtx)
|
||||
if inbound != nil && s.User != nil {
|
||||
inbound.User = s.User
|
||||
if inbound != nil {
|
||||
newInbound := *inbound
|
||||
if s.User != nil {
|
||||
newInbound.User = s.User
|
||||
}
|
||||
sessCtx = session.ContextWithInbound(sessCtx, &newInbound)
|
||||
}
|
||||
var email string
|
||||
var level uint32
|
||||
|
||||
@@ -265,7 +265,7 @@ func TestUDPCodec(t *testing.T) {
|
||||
|
||||
clientCodec, err := NewUDPPacketCodec(method, [][]byte{psk})
|
||||
common.Must(err)
|
||||
serverCodec, err := NewUDPServerCodec(method, psk, time.Minute)
|
||||
serverCodec, err := NewUDPServerCodec(method, psk, nil, time.Minute)
|
||||
common.Must(err)
|
||||
|
||||
session, err := clientCodec.NewClientSession()
|
||||
@@ -277,7 +277,7 @@ func TestUDPCodec(t *testing.T) {
|
||||
rawCopy := make([]byte, pktBuf.Len())
|
||||
copy(rawCopy, pktBuf.Bytes())
|
||||
|
||||
decoded, err := serverCodec.DecodePacket(pktBuf.Bytes())
|
||||
_, decoded, err := serverCodec.DecodePacket(pktBuf.Bytes())
|
||||
common.Must(err)
|
||||
|
||||
if decoded.HeaderType != HeaderTypeClient {
|
||||
@@ -291,7 +291,7 @@ func TestUDPCodec(t *testing.T) {
|
||||
}
|
||||
|
||||
// Replay same packet wire bytes should fail with ErrPacketIdNotUnique
|
||||
_, err = serverCodec.DecodePacket(rawCopy)
|
||||
_, _, err = serverCodec.DecodePacket(rawCopy)
|
||||
if err != ErrPacketIdNotUnique {
|
||||
t.Fatalf("expected ErrPacketIdNotUnique on replay, got: %v", err)
|
||||
}
|
||||
@@ -427,7 +427,7 @@ func TestClientUDPSessionMultiDestination(t *testing.T) {
|
||||
|
||||
clientCodec, err := NewUDPPacketCodec(method, [][]byte{rawKey})
|
||||
common.Must(err)
|
||||
serverCodec, err := NewUDPServerCodec(method, rawKey, time.Minute)
|
||||
serverCodec, err := NewUDPServerCodec(method, rawKey, nil, time.Minute)
|
||||
common.Must(err)
|
||||
|
||||
session, err := clientCodec.NewClientSession()
|
||||
@@ -448,9 +448,9 @@ func TestClientUDPSessionMultiDestination(t *testing.T) {
|
||||
defer pkt2.Release()
|
||||
|
||||
// Server decodes both
|
||||
dec1, err := serverCodec.DecodePacket(pkt1.Bytes())
|
||||
_, dec1, err := serverCodec.DecodePacket(pkt1.Bytes())
|
||||
common.Must(err)
|
||||
dec2, err := serverCodec.DecodePacket(pkt2.Bytes())
|
||||
_, dec2, err := serverCodec.DecodePacket(pkt2.Bytes())
|
||||
common.Must(err)
|
||||
|
||||
if dec1.SessionID != session.ClientSessionID() || dec2.SessionID != session.ClientSessionID() {
|
||||
|
||||
@@ -337,7 +337,7 @@ func WriteTCPRequest(w io.Writer, method *CipherMethod, pskList [][]byte, dest n
|
||||
addrPortLen := AddrPortLength(dest)
|
||||
varHeaderLen := addrPortLen + 2 + paddingLen + payloadLen
|
||||
|
||||
totalHandshakeLen := int32(method.KeySaltLength + len(pskList)*AESBlockSize + RequestHeaderFixedChunkLength + AEADTagSize + varHeaderLen + AEADTagSize)
|
||||
totalHandshakeLen := int32(method.KeySaltLength + (len(pskList)-1)*AESBlockSize + RequestHeaderFixedChunkLength + AEADTagSize + varHeaderLen + AEADTagSize)
|
||||
handshakeBuf := buf.NewWithSize(totalHandshakeLen)
|
||||
defer handshakeBuf.Release()
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
)
|
||||
|
||||
@@ -49,3 +50,18 @@ func (updater *InterfaceUpdater) Update() {
|
||||
updater.iface = got
|
||||
errors.LogInfo(context.Background(), "[tun] update interface ", got.Name, " ", got.Index)
|
||||
}
|
||||
|
||||
// ParseGUID parses a canonical textual GUID, as in
|
||||
// "00000000-0000-0000-0000-000000000000", into the 16 bytes it denotes.
|
||||
// The form is all that is accepted, not the other ones uuid.Parse takes,
|
||||
// such as one without hyphens; the length check is what rules those out.
|
||||
func ParseGUID(s string) ([16]byte, error) {
|
||||
if len(s) != 36 {
|
||||
return [16]byte{}, errors.New("invalid guid: ", s, ", want xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
|
||||
}
|
||||
id, err := uuid.Parse(s)
|
||||
if err != nil {
|
||||
return [16]byte{}, errors.New("invalid guid: ", s, ", want xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").Base(err)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
//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")
|
||||
}
|
||||
}
|
||||
@@ -1,390 +0,0 @@
|
||||
//go:build freebsd
|
||||
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type probeCall struct {
|
||||
inboundTag string
|
||||
source string
|
||||
address string
|
||||
}
|
||||
|
||||
// stubDNSRouting replaces the routing probe for the duration of a test and
|
||||
// records how it was called, so tests can assert the probe is representative.
|
||||
func stubDNSRouting(t *testing.T, err error) *[]probeCall {
|
||||
t.Helper()
|
||||
original := verifyDNSRouting
|
||||
calls := []probeCall{}
|
||||
verifyDNSRouting = func(_ context.Context, inboundTag, source, address string) error {
|
||||
calls = append(calls, probeCall{inboundTag, source, address})
|
||||
return err
|
||||
}
|
||||
t.Cleanup(func() { verifyDNSRouting = original })
|
||||
return &calls
|
||||
}
|
||||
|
||||
// recorder installs a resolvconf stub for the duration of a test and returns
|
||||
// the captured invocations, each as the arguments followed by the stdin in
|
||||
// angle brackets when there was one. An empty failOn succeeds every call;
|
||||
// otherwise the named subcommand fails.
|
||||
func recorder(t *testing.T, failOn string) *[]string {
|
||||
t.Helper()
|
||||
original := resolvconfRunner
|
||||
calls := []string{}
|
||||
resolvconfRunner = func(stdin string, args ...string) ([]byte, error) {
|
||||
call := strings.Join(args, " ")
|
||||
if stdin != "" {
|
||||
call += " <" + stdin + ">"
|
||||
}
|
||||
calls = append(calls, call)
|
||||
if failOn != "" && len(args) > 0 && args[0] == failOn {
|
||||
return nil, errors.New("boom")
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
t.Cleanup(func() { resolvconfRunner = original })
|
||||
return &calls
|
||||
}
|
||||
|
||||
// files replaces the resolver files read by the applied check for the
|
||||
// duration of a test. A path not in the map does not exist.
|
||||
func files(t *testing.T, contents map[string]string) {
|
||||
t.Helper()
|
||||
original := readResolverFile
|
||||
readResolverFile = func(path string) ([]byte, error) {
|
||||
if data, ok := contents[path]; ok {
|
||||
return []byte(data), nil
|
||||
}
|
||||
return nil, fs.ErrNotExist
|
||||
}
|
||||
t.Cleanup(func() { readResolverFile = original })
|
||||
}
|
||||
|
||||
// takenOver is what the libc subscriber writes once the TUN's nameserver is
|
||||
// the exclusive one.
|
||||
const takenOver = "# Generated by resolvconf\nnameserver 192.168.100.1\n"
|
||||
|
||||
// untouched is the DHCP-supplied resolv.conf that resolvconf=NO leaves in
|
||||
// place.
|
||||
const untouched = "# Generated by resolvconf\nnameserver 10.0.0.1\n"
|
||||
|
||||
func optedInTun() *FreeBSDTun {
|
||||
return &FreeBSDTun{
|
||||
options: &Config{
|
||||
Name: "tun7",
|
||||
Gateway: []string{"192.168.100.1/30"},
|
||||
AutoSystemDnsToGateway: true,
|
||||
},
|
||||
name: "tun7",
|
||||
gateway: netip.MustParsePrefix("192.168.100.1/30"),
|
||||
local: netip.MustParseAddr("192.168.100.2"),
|
||||
}
|
||||
}
|
||||
|
||||
func joined(calls []string) string {
|
||||
return strings.Join(calls, " | ")
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSDisabledByDefault(t *testing.T) {
|
||||
probes := stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.options.AutoSystemDnsToGateway = false
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*calls) != 0 || len(*probes) != 0 {
|
||||
t.Errorf("nothing may run when the option is off, got %q and %d probes", joined(*calls), len(*probes))
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the option is off")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSLeavesOSDNSWhenNoRoute(t *testing.T) {
|
||||
stubDNSRouting(t, errors.New("no route"))
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the probe fails")
|
||||
}
|
||||
if len(*calls) != 0 {
|
||||
t.Errorf("resolvconf must not run when the probe fails, got %q", joined(*calls))
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the probe fails")
|
||||
}
|
||||
}
|
||||
|
||||
// On FreeBSD the addresses are the other way round from Linux: the local
|
||||
// address is the one after the gateway, and the gateway itself has no owner,
|
||||
// so a packet to it is routed into the TUN. The probe has to carry that pair,
|
||||
// and the resolver has to be pointed at the gateway.
|
||||
func TestConfigureSystemDNSProbeCarriesFreeBSDPair(t *testing.T) {
|
||||
probes := stubDNSRouting(t, nil)
|
||||
recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*probes) != 1 {
|
||||
t.Fatalf("expected one probe, got %d", len(*probes))
|
||||
}
|
||||
want := probeCall{"tun", "192.168.100.2", "192.168.100.1"}
|
||||
if (*probes)[0] != want {
|
||||
t.Errorf("probe = %+v, want %+v", (*probes)[0], want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSAppliesResolvconf(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !t1.systemDNSSet {
|
||||
t.Fatal("systemDNSSet should be true after a successful takeover")
|
||||
}
|
||||
|
||||
want := "-a tun7 -x <nameserver 192.168.100.1\n>"
|
||||
if got := joined(*calls); got != want {
|
||||
t.Errorf("resolvconf calls = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// resolvconf exits 0 with resolvconf=NO in resolvconf.conf, and still records
|
||||
// the entry for the interface, but runs no subscriber, so success has to be
|
||||
// confirmed in what the subscribers wrote.
|
||||
func TestConfigureSystemDNSRefusesWhenResolvconfDidNotApply(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the nameserver did not reach a resolver")
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the takeover did not take")
|
||||
}
|
||||
if !strings.HasSuffix(joined(*calls), "-d tun7") {
|
||||
t.Errorf("expected a removal after the failed check, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSIdempotent(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
before := len(*calls)
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*calls) != before {
|
||||
t.Errorf("second call must be a no-op, calls went %d -> %d", before, len(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSAddFailureIsNotDirty(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "-a")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when resolvconf -a fails")
|
||||
}
|
||||
if t1.systemDNSSet || t1.systemDNSDirty {
|
||||
t.Error("a failed add leaves nothing to clean up")
|
||||
}
|
||||
if len(*calls) != 1 {
|
||||
t.Errorf("nothing else may run after a failed add, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
// If the removal after a failed check fails too, the entry may still be
|
||||
// installed, so the state has to be remembered rather than silently dropped.
|
||||
func TestConfigureSystemDNSRollbackFailureKeepsDirty(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
recorder(t, "-d")
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the check fails")
|
||||
}
|
||||
if !t1.systemDNSDirty {
|
||||
t.Error("a failed removal must leave the resolver marked dirty")
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the takeover did not complete")
|
||||
}
|
||||
}
|
||||
|
||||
// A dirty resolver is retried before anything new is applied.
|
||||
func TestConfigureSystemDNSRetriesDirtyBeforeApplying(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.systemDNSDirty = true
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
got := joined(*calls)
|
||||
if !strings.HasPrefix(got, "-d tun7 | -a tun7") {
|
||||
t.Errorf("expected the stale removal first, got %q", got)
|
||||
}
|
||||
if t1.systemDNSDirty {
|
||||
t.Error("a successful retry should clear the dirty flag")
|
||||
}
|
||||
if !t1.systemDNSSet {
|
||||
t.Error("the takeover should proceed once the retry succeeds")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsetSystemDNSRemoves(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("setup failed: %v", err)
|
||||
}
|
||||
*calls = nil
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet should be false after unset")
|
||||
}
|
||||
if got := joined(*calls); got != "-d tun7" {
|
||||
t.Errorf("unset calls = %q, want %q", got, "-d tun7")
|
||||
}
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if len(*calls) != 1 {
|
||||
t.Errorf("unsetSystemDNS must be idempotent, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsetSystemDNSKeepsDirtyWhenRemoveFails(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "-d")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.systemDNSSet = true
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if !t1.systemDNSDirty {
|
||||
t.Error("a failed removal during unset must be remembered")
|
||||
}
|
||||
if got := joined(*calls); got != "-d tun7" {
|
||||
t.Errorf("expected a removal attempt, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedLibc(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("resolv.conf listing the nameserver must count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedNotWhenUntouched(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || ok {
|
||||
t.Errorf("an unchanged resolv.conf and no resolvconf.conf must not count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
// With inclusive_interfaces in resolvconf.conf the exclusive marking is
|
||||
// ignored and the DHCP nameservers stay listed, so the system falls back to
|
||||
// them; that is the leak the option exists to close, and it must not pass.
|
||||
func TestResolvconfAppliedNotWhenOthersRemain(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.1\nnameserver 10.0.0.1\n"})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("another nameserver alongside the TUN's must not count as applied")
|
||||
}
|
||||
}
|
||||
|
||||
// A loopback nameserver alongside is a local resolver that resolvconf feeds
|
||||
// (local_unbound with the libc subscriber left on), not a leak.
|
||||
func TestResolvconfAppliedWithLoopbackAlongside(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 127.0.0.1\nnameserver 192.168.100.1\n"})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("a loopback nameserver alongside must still count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedIgnoresPrefixMatches(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.10\n"})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("192.168.100.10 must not match 192.168.100.1")
|
||||
}
|
||||
}
|
||||
|
||||
// local-unbound-setup turns the libc subscriber off and has resolvconf write
|
||||
// unbound's forwarders instead; resolv.conf then stays pointed at loopback.
|
||||
func TestResolvconfAppliedUnbound(t *testing.T) {
|
||||
files(t, map[string]string{
|
||||
"/etc/resolv.conf": "# Generated by resolvconf\nnameserver 127.0.0.1\noptions edns0\n",
|
||||
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
|
||||
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 192.168.100.1\n",
|
||||
})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("the nameserver in unbound's forwarders must count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedNotWhenUnboundUntouched(t *testing.T) {
|
||||
files(t, map[string]string{
|
||||
"/etc/resolv.conf": "nameserver 127.0.0.1\n",
|
||||
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
|
||||
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 10.0.0.1\n",
|
||||
})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("unbound still forwarding to the old server must not count as applied")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedReportsUnreadableResolvConf(t *testing.T) {
|
||||
files(t, map[string]string{})
|
||||
if _, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err == nil {
|
||||
t.Error("a missing resolv.conf is an error, not a verdict")
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,11 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/net/route"
|
||||
@@ -148,3 +152,381 @@ func TestDefaultRouteFamilyRejectsShortAddrs(t *testing.T) {
|
||||
t.Fatal("message without addresses must not match")
|
||||
}
|
||||
}
|
||||
|
||||
type probeCall struct {
|
||||
inboundTag string
|
||||
source string
|
||||
address string
|
||||
}
|
||||
|
||||
// stubDNSRouting replaces the routing probe for the duration of a test and
|
||||
// records how it was called, so tests can assert the probe is representative.
|
||||
func stubDNSRouting(t *testing.T, err error) *[]probeCall {
|
||||
t.Helper()
|
||||
original := verifyDNSRouting
|
||||
calls := []probeCall{}
|
||||
verifyDNSRouting = func(_ context.Context, inboundTag, source, address string) error {
|
||||
calls = append(calls, probeCall{inboundTag, source, address})
|
||||
return err
|
||||
}
|
||||
t.Cleanup(func() { verifyDNSRouting = original })
|
||||
return &calls
|
||||
}
|
||||
|
||||
// recorder installs a resolvconf stub for the duration of a test and returns
|
||||
// the captured invocations, each as the arguments followed by the stdin in
|
||||
// angle brackets when there was one. An empty failOn succeeds every call;
|
||||
// otherwise the named subcommand fails.
|
||||
func recorder(t *testing.T, failOn string) *[]string {
|
||||
t.Helper()
|
||||
original := resolvconfRunner
|
||||
calls := []string{}
|
||||
resolvconfRunner = func(stdin string, args ...string) ([]byte, error) {
|
||||
call := strings.Join(args, " ")
|
||||
if stdin != "" {
|
||||
call += " <" + stdin + ">"
|
||||
}
|
||||
calls = append(calls, call)
|
||||
if failOn != "" && len(args) > 0 && args[0] == failOn {
|
||||
return nil, errors.New("boom")
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
t.Cleanup(func() { resolvconfRunner = original })
|
||||
return &calls
|
||||
}
|
||||
|
||||
// files replaces the resolver files read by the applied check for the
|
||||
// duration of a test. A path not in the map does not exist.
|
||||
func files(t *testing.T, contents map[string]string) {
|
||||
t.Helper()
|
||||
original := readResolverFile
|
||||
readResolverFile = func(path string) ([]byte, error) {
|
||||
if data, ok := contents[path]; ok {
|
||||
return []byte(data), nil
|
||||
}
|
||||
return nil, fs.ErrNotExist
|
||||
}
|
||||
t.Cleanup(func() { readResolverFile = original })
|
||||
}
|
||||
|
||||
// takenOver is what the libc subscriber writes once the TUN's nameserver is
|
||||
// the exclusive one.
|
||||
const takenOver = "# Generated by resolvconf\nnameserver 192.168.100.1\n"
|
||||
|
||||
// untouched is the DHCP-supplied resolv.conf that resolvconf=NO leaves in
|
||||
// place.
|
||||
const untouched = "# Generated by resolvconf\nnameserver 10.0.0.1\n"
|
||||
|
||||
func optedInTun() *FreeBSDTun {
|
||||
return &FreeBSDTun{
|
||||
options: &Config{
|
||||
Name: "tun7",
|
||||
Gateway: []string{"192.168.100.1/30"},
|
||||
AutoSystemDnsToGateway: true,
|
||||
},
|
||||
name: "tun7",
|
||||
gateway: netip.MustParsePrefix("192.168.100.1/30"),
|
||||
local: netip.MustParseAddr("192.168.100.2"),
|
||||
}
|
||||
}
|
||||
|
||||
func joined(calls []string) string {
|
||||
return strings.Join(calls, " | ")
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSDisabledByDefault(t *testing.T) {
|
||||
probes := stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.options.AutoSystemDnsToGateway = false
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*calls) != 0 || len(*probes) != 0 {
|
||||
t.Errorf("nothing may run when the option is off, got %q and %d probes", joined(*calls), len(*probes))
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the option is off")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSLeavesOSDNSWhenNoRoute(t *testing.T) {
|
||||
stubDNSRouting(t, errors.New("no route"))
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the probe fails")
|
||||
}
|
||||
if len(*calls) != 0 {
|
||||
t.Errorf("resolvconf must not run when the probe fails, got %q", joined(*calls))
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the probe fails")
|
||||
}
|
||||
}
|
||||
|
||||
// On FreeBSD the addresses are the other way round from Linux: the local
|
||||
// address is the one after the gateway, and the gateway itself has no owner,
|
||||
// so a packet to it is routed into the TUN. The probe has to carry that pair,
|
||||
// and the resolver has to be pointed at the gateway.
|
||||
func TestConfigureSystemDNSProbeCarriesFreeBSDPair(t *testing.T) {
|
||||
probes := stubDNSRouting(t, nil)
|
||||
recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*probes) != 1 {
|
||||
t.Fatalf("expected one probe, got %d", len(*probes))
|
||||
}
|
||||
want := probeCall{"tun", "192.168.100.2", "192.168.100.1"}
|
||||
if (*probes)[0] != want {
|
||||
t.Errorf("probe = %+v, want %+v", (*probes)[0], want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSAppliesResolvconf(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !t1.systemDNSSet {
|
||||
t.Fatal("systemDNSSet should be true after a successful takeover")
|
||||
}
|
||||
|
||||
want := "-a tun7 -x <nameserver 192.168.100.1\n>"
|
||||
if got := joined(*calls); got != want {
|
||||
t.Errorf("resolvconf calls = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// resolvconf exits 0 with resolvconf=NO in resolvconf.conf, and still records
|
||||
// the entry for the interface, but runs no subscriber, so success has to be
|
||||
// confirmed in what the subscribers wrote.
|
||||
func TestConfigureSystemDNSRefusesWhenResolvconfDidNotApply(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the nameserver did not reach a resolver")
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the takeover did not take")
|
||||
}
|
||||
if !strings.HasSuffix(joined(*calls), "-d tun7") {
|
||||
t.Errorf("expected a removal after the failed check, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSIdempotent(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
before := len(*calls)
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*calls) != before {
|
||||
t.Errorf("second call must be a no-op, calls went %d -> %d", before, len(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSAddFailureIsNotDirty(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "-a")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when resolvconf -a fails")
|
||||
}
|
||||
if t1.systemDNSSet || t1.systemDNSDirty {
|
||||
t.Error("a failed add leaves nothing to clean up")
|
||||
}
|
||||
if len(*calls) != 1 {
|
||||
t.Errorf("nothing else may run after a failed add, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
// If the removal after a failed check fails too, the entry may still be
|
||||
// installed, so the state has to be remembered rather than silently dropped.
|
||||
func TestConfigureSystemDNSRollbackFailureKeepsDirty(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
recorder(t, "-d")
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the check fails")
|
||||
}
|
||||
if !t1.systemDNSDirty {
|
||||
t.Error("a failed removal must leave the resolver marked dirty")
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the takeover did not complete")
|
||||
}
|
||||
}
|
||||
|
||||
// A dirty resolver is retried before anything new is applied.
|
||||
func TestConfigureSystemDNSRetriesDirtyBeforeApplying(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.systemDNSDirty = true
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
got := joined(*calls)
|
||||
if !strings.HasPrefix(got, "-d tun7 | -a tun7") {
|
||||
t.Errorf("expected the stale removal first, got %q", got)
|
||||
}
|
||||
if t1.systemDNSDirty {
|
||||
t.Error("a successful retry should clear the dirty flag")
|
||||
}
|
||||
if !t1.systemDNSSet {
|
||||
t.Error("the takeover should proceed once the retry succeeds")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsetSystemDNSRemoves(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("setup failed: %v", err)
|
||||
}
|
||||
*calls = nil
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet should be false after unset")
|
||||
}
|
||||
if got := joined(*calls); got != "-d tun7" {
|
||||
t.Errorf("unset calls = %q, want %q", got, "-d tun7")
|
||||
}
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if len(*calls) != 1 {
|
||||
t.Errorf("unsetSystemDNS must be idempotent, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsetSystemDNSKeepsDirtyWhenRemoveFails(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "-d")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.systemDNSSet = true
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if !t1.systemDNSDirty {
|
||||
t.Error("a failed removal during unset must be remembered")
|
||||
}
|
||||
if got := joined(*calls); got != "-d tun7" {
|
||||
t.Errorf("expected a removal attempt, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedLibc(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("resolv.conf listing the nameserver must count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedNotWhenUntouched(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || ok {
|
||||
t.Errorf("an unchanged resolv.conf and no resolvconf.conf must not count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
// With inclusive_interfaces in resolvconf.conf the exclusive marking is
|
||||
// ignored and the DHCP nameservers stay listed, so the system falls back to
|
||||
// them; that is the leak the option exists to close, and it must not pass.
|
||||
func TestResolvconfAppliedNotWhenOthersRemain(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.1\nnameserver 10.0.0.1\n"})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("another nameserver alongside the TUN's must not count as applied")
|
||||
}
|
||||
}
|
||||
|
||||
// A loopback nameserver alongside is a local resolver that resolvconf feeds
|
||||
// (local_unbound with the libc subscriber left on), not a leak.
|
||||
func TestResolvconfAppliedWithLoopbackAlongside(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 127.0.0.1\nnameserver 192.168.100.1\n"})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("a loopback nameserver alongside must still count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedIgnoresPrefixMatches(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.10\n"})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("192.168.100.10 must not match 192.168.100.1")
|
||||
}
|
||||
}
|
||||
|
||||
// local-unbound-setup turns the libc subscriber off and has resolvconf write
|
||||
// unbound's forwarders instead; resolv.conf then stays pointed at loopback.
|
||||
func TestResolvconfAppliedUnbound(t *testing.T) {
|
||||
files(t, map[string]string{
|
||||
"/etc/resolv.conf": "# Generated by resolvconf\nnameserver 127.0.0.1\noptions edns0\n",
|
||||
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
|
||||
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 192.168.100.1\n",
|
||||
})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("the nameserver in unbound's forwarders must count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedNotWhenUnboundUntouched(t *testing.T) {
|
||||
files(t, map[string]string{
|
||||
"/etc/resolv.conf": "nameserver 127.0.0.1\n",
|
||||
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
|
||||
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 10.0.0.1\n",
|
||||
})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("unbound still forwarding to the old server must not count as applied")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedReportsUnreadableResolvConf(t *testing.T) {
|
||||
files(t, map[string]string{})
|
||||
if _, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err == nil {
|
||||
t.Error("a missing resolv.conf is an error, not a verdict")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,204 +0,0 @@
|
||||
//go:build linux && !android
|
||||
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/app/dispatcher"
|
||||
appdns "github.com/xtls/xray-core/app/dns"
|
||||
"github.com/xtls/xray-core/app/proxyman"
|
||||
_ "github.com/xtls/xray-core/app/proxyman/inbound"
|
||||
_ "github.com/xtls/xray-core/app/proxyman/outbound"
|
||||
"github.com/xtls/xray-core/app/router"
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/core"
|
||||
proxydns "github.com/xtls/xray-core/proxy/dns"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
)
|
||||
|
||||
const (
|
||||
routeTestInboundTag = "tun"
|
||||
routeTestSource = "192.168.100.1"
|
||||
routeTestDNSAddress = "192.168.100.2"
|
||||
)
|
||||
|
||||
// port53Rule sends DNS queries arriving from the interface to the dns outbound.
|
||||
func port53Rule() *router.RoutingRule {
|
||||
return &router.RoutingRule{
|
||||
InboundTag: []string{routeTestInboundTag},
|
||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(53)}},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "dns"},
|
||||
}
|
||||
}
|
||||
|
||||
// sourceBlockRule diverts traffic from one address, which is the shape of a rule
|
||||
// that only matches because the real request carries a source.
|
||||
func sourceBlockRule(ip []byte) *router.RoutingRule {
|
||||
return &router.RoutingRule{
|
||||
SourceIp: []*geodata.IPRule{{
|
||||
Value: &geodata.IPRule_Custom{
|
||||
Custom: &geodata.CIDRRule{
|
||||
Cidr: &geodata.CIDR{Ip: ip, Prefix: 32},
|
||||
},
|
||||
},
|
||||
}},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "block"},
|
||||
}
|
||||
}
|
||||
|
||||
// newRouteTestContext builds a real but unstarted instance: no TUN device, no
|
||||
// running resolver. The instance is placed in the context through the key core
|
||||
// exports for tests.
|
||||
func newRouteTestContext(t *testing.T, withDNSApp bool, nameServers []*appdns.NameServer, rules []*router.RoutingRule) context.Context {
|
||||
t.Helper()
|
||||
|
||||
apps := []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&dispatcher.Config{}),
|
||||
serial.ToTypedMessage(&proxyman.InboundConfig{}),
|
||||
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
|
||||
serial.ToTypedMessage(&router.Config{Rule: rules}),
|
||||
}
|
||||
if withDNSApp {
|
||||
apps = append(apps, serial.ToTypedMessage(&appdns.Config{NameServer: nameServers}))
|
||||
}
|
||||
|
||||
instance, err := core.New(&core.Config{
|
||||
App: apps,
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})},
|
||||
{Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})},
|
||||
{Tag: "block", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("core.New: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = instance.Close() })
|
||||
|
||||
return context.WithValue(context.Background(), core.XrayKey(1), instance)
|
||||
}
|
||||
|
||||
func udpNameServer(ip []byte) []*appdns.NameServer {
|
||||
return []*appdns.NameServer{{
|
||||
Address: &net.Endpoint{
|
||||
Network: net.Network_UDP,
|
||||
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Ip{Ip: ip}},
|
||||
Port: 53,
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
// localNameServer is a name server pointed at "localhost", which app/dns
|
||||
// resolves through the system resolver.
|
||||
func localNameServer() *appdns.NameServer {
|
||||
return &appdns.NameServer{
|
||||
Address: &net.Endpoint{
|
||||
Network: net.Network_UDP,
|
||||
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Domain{Domain: "localhost"}},
|
||||
Port: 53,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// These drive the real feature lookup and the real router. verifyDNSRouting is
|
||||
// the same function ConfigureSystemDNS calls, so a false positive here is a
|
||||
// false positive in the takeover decision itself, which is what assertions on
|
||||
// the resolvectl arguments could never catch.
|
||||
func TestVerifyDNSRoutingDecisions(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
withDNSApp bool
|
||||
nameServers []*appdns.NameServer
|
||||
rules []*router.RoutingRule
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "independent upstream reaches the dns outbound",
|
||||
withDNSApp: true,
|
||||
nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "no dns section falls back to the system resolver",
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
name: "dns section without name servers falls back too",
|
||||
withDNSApp: true,
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
// An independent upstream is not enough on its own: name servers are
|
||||
// selected per domain, so a local one can still be the one chosen.
|
||||
// The refusal is deliberately domain-agnostic for that reason.
|
||||
name: "a local name server alongside an independent one",
|
||||
withDNSApp: true,
|
||||
nameServers: append(udpNameServer([]byte{9, 9, 9, 9}), localNameServer()),
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
name: "a rule on the interface address diverts the real query",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{
|
||||
sourceBlockRule([]byte{192, 168, 100, 1}),
|
||||
port53Rule(),
|
||||
},
|
||||
wantErr: "does not handle DNS",
|
||||
},
|
||||
{
|
||||
name: "a rule on another address does not match it",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{
|
||||
sourceBlockRule([]byte{10, 0, 0, 1}),
|
||||
port53Rule(),
|
||||
},
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "no rule matches the query",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
wantErr: "no route",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := newRouteTestContext(t, tt.withDNSApp, tt.nameServers, tt.rules)
|
||||
err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, routeTestDNSAddress)
|
||||
|
||||
if tt.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("expected the takeover to be accepted, got: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatalf("expected the takeover to be refused with %q, got nil", tt.wantErr)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Errorf("error = %q, want it to contain %q", err.Error(), tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Without an IPv4 gateway, the takeover uses the first IPv6 one, and the probe
|
||||
// carries IPv6 addresses.
|
||||
func TestVerifyDNSRoutingIPv6(t *testing.T) {
|
||||
ctx := newRouteTestContext(t, true, udpNameServer([]byte{9, 9, 9, 9}), []*router.RoutingRule{port53Rule()})
|
||||
if err := verifyDNSRouting(ctx, routeTestInboundTag, "fc00::1", "fc00::2"); err != nil {
|
||||
t.Fatalf("expected the takeover to be accepted, got: %v", err)
|
||||
}
|
||||
if err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, "fc00::2"); err == nil {
|
||||
t.Fatal("expected mixed IPv4 and IPv6 addresses to be refused")
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,18 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/vishvananda/netlink"
|
||||
"github.com/xtls/xray-core/app/dispatcher"
|
||||
appdns "github.com/xtls/xray-core/app/dns"
|
||||
"github.com/xtls/xray-core/app/proxyman"
|
||||
_ "github.com/xtls/xray-core/app/proxyman/inbound"
|
||||
_ "github.com/xtls/xray-core/app/proxyman/outbound"
|
||||
"github.com/xtls/xray-core/app/router"
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/core"
|
||||
proxydns "github.com/xtls/xray-core/proxy/dns"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
)
|
||||
|
||||
// testLink returns a minimal netlink.Link whose Attrs().Name is name, so the
|
||||
@@ -443,3 +455,185 @@ func TestBuildResolvectlArgs(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
routeTestInboundTag = "tun"
|
||||
routeTestSource = "192.168.100.1"
|
||||
routeTestDNSAddress = "192.168.100.2"
|
||||
)
|
||||
|
||||
// port53Rule sends DNS queries arriving from the interface to the dns outbound.
|
||||
func port53Rule() *router.RoutingRule {
|
||||
return &router.RoutingRule{
|
||||
InboundTag: []string{routeTestInboundTag},
|
||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(53)}},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "dns"},
|
||||
}
|
||||
}
|
||||
|
||||
// sourceBlockRule diverts traffic from one address, which is the shape of a rule
|
||||
// that only matches because the real request carries a source.
|
||||
func sourceBlockRule(ip []byte) *router.RoutingRule {
|
||||
return &router.RoutingRule{
|
||||
SourceIp: []*geodata.IPRule{{
|
||||
Value: &geodata.IPRule_Custom{
|
||||
Custom: &geodata.CIDRRule{
|
||||
Cidr: &geodata.CIDR{Ip: ip, Prefix: 32},
|
||||
},
|
||||
},
|
||||
}},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "block"},
|
||||
}
|
||||
}
|
||||
|
||||
// newRouteTestContext builds a real but unstarted instance: no TUN device, no
|
||||
// running resolver. The instance is placed in the context through the key core
|
||||
// exports for tests.
|
||||
func newRouteTestContext(t *testing.T, withDNSApp bool, nameServers []*appdns.NameServer, rules []*router.RoutingRule) context.Context {
|
||||
t.Helper()
|
||||
|
||||
apps := []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&dispatcher.Config{}),
|
||||
serial.ToTypedMessage(&proxyman.InboundConfig{}),
|
||||
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
|
||||
serial.ToTypedMessage(&router.Config{Rule: rules}),
|
||||
}
|
||||
if withDNSApp {
|
||||
apps = append(apps, serial.ToTypedMessage(&appdns.Config{NameServer: nameServers}))
|
||||
}
|
||||
|
||||
instance, err := core.New(&core.Config{
|
||||
App: apps,
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})},
|
||||
{Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})},
|
||||
{Tag: "block", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("core.New: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = instance.Close() })
|
||||
|
||||
return context.WithValue(context.Background(), core.XrayKey(1), instance)
|
||||
}
|
||||
|
||||
func udpNameServer(ip []byte) []*appdns.NameServer {
|
||||
return []*appdns.NameServer{{
|
||||
Address: &net.Endpoint{
|
||||
Network: net.Network_UDP,
|
||||
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Ip{Ip: ip}},
|
||||
Port: 53,
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
// localNameServer is a name server pointed at "localhost", which app/dns
|
||||
// resolves through the system resolver.
|
||||
func localNameServer() *appdns.NameServer {
|
||||
return &appdns.NameServer{
|
||||
Address: &net.Endpoint{
|
||||
Network: net.Network_UDP,
|
||||
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Domain{Domain: "localhost"}},
|
||||
Port: 53,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// These drive the real feature lookup and the real router. verifyDNSRouting is
|
||||
// the same function ConfigureSystemDNS calls, so a false positive here is a
|
||||
// false positive in the takeover decision itself, which is what assertions on
|
||||
// the resolvectl arguments could never catch.
|
||||
func TestVerifyDNSRoutingDecisions(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
withDNSApp bool
|
||||
nameServers []*appdns.NameServer
|
||||
rules []*router.RoutingRule
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "independent upstream reaches the dns outbound",
|
||||
withDNSApp: true,
|
||||
nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "no dns section falls back to the system resolver",
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
name: "dns section without name servers falls back too",
|
||||
withDNSApp: true,
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
// An independent upstream is not enough on its own: name servers are
|
||||
// selected per domain, so a local one can still be the one chosen.
|
||||
// The refusal is deliberately domain-agnostic for that reason.
|
||||
name: "a local name server alongside an independent one",
|
||||
withDNSApp: true,
|
||||
nameServers: append(udpNameServer([]byte{9, 9, 9, 9}), localNameServer()),
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
name: "a rule on the interface address diverts the real query",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{
|
||||
sourceBlockRule([]byte{192, 168, 100, 1}),
|
||||
port53Rule(),
|
||||
},
|
||||
wantErr: "does not handle DNS",
|
||||
},
|
||||
{
|
||||
name: "a rule on another address does not match it",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{
|
||||
sourceBlockRule([]byte{10, 0, 0, 1}),
|
||||
port53Rule(),
|
||||
},
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "no rule matches the query",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
wantErr: "no route",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := newRouteTestContext(t, tt.withDNSApp, tt.nameServers, tt.rules)
|
||||
err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, routeTestDNSAddress)
|
||||
|
||||
if tt.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("expected the takeover to be accepted, got: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatalf("expected the takeover to be refused with %q, got nil", tt.wantErr)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Errorf("error = %q, want it to contain %q", err.Error(), tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Without an IPv4 gateway, the takeover uses the first IPv6 one, and the probe
|
||||
// carries IPv6 addresses.
|
||||
func TestVerifyDNSRoutingIPv6(t *testing.T) {
|
||||
ctx := newRouteTestContext(t, true, udpNameServer([]byte{9, 9, 9, 9}), []*router.RoutingRule{port53Rule()})
|
||||
if err := verifyDNSRouting(ctx, routeTestInboundTag, "fc00::1", "fc00::2"); err != nil {
|
||||
t.Fatalf("expected the takeover to be accepted, got: %v", err)
|
||||
}
|
||||
if err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, "fc00::2"); err == nil {
|
||||
t.Fatal("expected mixed IPv4 and IPv6 addresses to be refused")
|
||||
}
|
||||
}
|
||||
@@ -710,3 +710,109 @@ func findOutboundInterface(tunIndex int, fixedName string) (*net.Interface, erro
|
||||
}
|
||||
return net.InterfaceByIndex(int(index))
|
||||
}
|
||||
|
||||
// outboundGuard keeps Windows to the binding of autoOutboundsInterface, which
|
||||
// keeps Xray's own connections out of the TUN. With weak host send or
|
||||
// forwarding on for an IP version on the bound interface, Windows sends them
|
||||
// where the routes lead, into the TUN, from that interface's address, and
|
||||
// drops what comes back to that address through the TUN, so they stall.
|
||||
//
|
||||
// For the IP versions routed to the TUN, weak host send is turned off on the
|
||||
// bound interface while the TUN runs, and turned on again when the TUN stops
|
||||
// or another interface takes over. Forwarding is what Mobile Hotspot and
|
||||
// Internet Connection Sharing need, so it is only reported.
|
||||
type outboundGuard struct {
|
||||
sync.Mutex
|
||||
families []winipcfg.AddressFamily
|
||||
luid winipcfg.LUID // of the interface last checked
|
||||
name string // of that interface
|
||||
turnedOff []winipcfg.AddressFamily // where weak host send was turned off on it
|
||||
forwarding bool // whether forwarding was on there
|
||||
stopped bool
|
||||
}
|
||||
|
||||
// check turns weak host send off on the bound interface, and warns when
|
||||
// forwarding comes on there, but not again while it stays on.
|
||||
func (g *outboundGuard) check() {
|
||||
g.Lock()
|
||||
defer g.Unlock()
|
||||
if g.stopped {
|
||||
return
|
||||
}
|
||||
var luid winipcfg.LUID
|
||||
var name string
|
||||
if iface := updater.Get(); iface != nil {
|
||||
luid, _ = winipcfg.LUIDFromIndex(uint32(iface.Index))
|
||||
name = iface.Name
|
||||
}
|
||||
if luid != g.luid {
|
||||
g.restoreLocked()
|
||||
g.luid, g.name = luid, name
|
||||
g.forwarding = false // to warn about the new interface as well
|
||||
}
|
||||
if luid == 0 {
|
||||
return
|
||||
}
|
||||
var forwarding []string
|
||||
for _, family := range g.families {
|
||||
row, err := luid.IPInterface(family)
|
||||
if err != nil {
|
||||
continue // the interface lacks that IP version
|
||||
}
|
||||
if row.ForwardingEnabled {
|
||||
forwarding = append(forwarding, familyName(family))
|
||||
}
|
||||
if !row.WeakHostSend {
|
||||
continue
|
||||
}
|
||||
if err := setWeakHostSend(row, false); err != nil {
|
||||
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send off for ", familyName(family), " on ", name)
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(g.turnedOff, family) {
|
||||
g.turnedOff = append(g.turnedOff, family)
|
||||
errors.LogInfo(context.Background(), "[tun] weak host send turned off for ", familyName(family), " on ", name, " while the TUN runs, as Windows would ignore autoOutboundsInterface")
|
||||
}
|
||||
}
|
||||
wasOn := g.forwarding
|
||||
g.forwarding = len(forwarding) > 0
|
||||
if g.forwarding && !wasOn {
|
||||
errors.LogWarning(context.Background(), "[tun] forwarding is on for ", strings.Join(forwarding, " and "), " on ", name, " (Mobile Hotspot and Internet Connection Sharing turn it on), so Windows ignores autoOutboundsInterface there, and Xray's own connections go into the TUN and stall: turn the hotspot off, or have it share the TUN instead of ", name)
|
||||
}
|
||||
}
|
||||
|
||||
// restore turns weak host send on again where check turned it off, for good.
|
||||
func (g *outboundGuard) restore() {
|
||||
g.Lock()
|
||||
defer g.Unlock()
|
||||
g.restoreLocked()
|
||||
g.stopped = true
|
||||
}
|
||||
|
||||
func (g *outboundGuard) restoreLocked() {
|
||||
for _, family := range g.turnedOff {
|
||||
row, err := g.luid.IPInterface(family)
|
||||
if err == nil {
|
||||
err = setWeakHostSend(row, true)
|
||||
}
|
||||
if err != nil {
|
||||
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send on again for ", familyName(family), " on ", g.name)
|
||||
}
|
||||
}
|
||||
g.turnedOff = nil
|
||||
}
|
||||
|
||||
func setWeakHostSend(row *winipcfg.MibIPInterfaceRow, on bool) error {
|
||||
row.WeakHostSend = on
|
||||
if row.Family == windows.AF_INET {
|
||||
row.SitePrefixLength = 0 // as SetIpInterfaceEntry requires for IPv4
|
||||
}
|
||||
return row.Set()
|
||||
}
|
||||
|
||||
func familyName(family winipcfg.AddressFamily) string {
|
||||
if family == windows.AF_INET {
|
||||
return "IPv4"
|
||||
}
|
||||
return "IPv6"
|
||||
}
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
//go:build windows
|
||||
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"golang.org/x/sys/windows"
|
||||
"golang.zx2c4.com/wireguard/windows/tunnel/winipcfg"
|
||||
)
|
||||
|
||||
// outboundGuard keeps Windows to the binding of autoOutboundsInterface, which
|
||||
// keeps Xray's own connections out of the TUN. With weak host send or
|
||||
// forwarding on for an IP version on the bound interface, Windows sends them
|
||||
// where the routes lead, into the TUN, from that interface's address, and
|
||||
// drops what comes back to that address through the TUN, so they stall.
|
||||
//
|
||||
// For the IP versions routed to the TUN, weak host send is turned off on the
|
||||
// bound interface while the TUN runs, and turned on again when the TUN stops
|
||||
// or another interface takes over. Forwarding is what Mobile Hotspot and
|
||||
// Internet Connection Sharing need, so it is only reported.
|
||||
type outboundGuard struct {
|
||||
sync.Mutex
|
||||
families []winipcfg.AddressFamily
|
||||
luid winipcfg.LUID // of the interface last checked
|
||||
name string // of that interface
|
||||
turnedOff []winipcfg.AddressFamily // where weak host send was turned off on it
|
||||
forwarding bool // whether forwarding was on there
|
||||
stopped bool
|
||||
}
|
||||
|
||||
// check turns weak host send off on the bound interface, and warns when
|
||||
// forwarding comes on there, but not again while it stays on.
|
||||
func (g *outboundGuard) check() {
|
||||
g.Lock()
|
||||
defer g.Unlock()
|
||||
if g.stopped {
|
||||
return
|
||||
}
|
||||
var luid winipcfg.LUID
|
||||
var name string
|
||||
if iface := updater.Get(); iface != nil {
|
||||
luid, _ = winipcfg.LUIDFromIndex(uint32(iface.Index))
|
||||
name = iface.Name
|
||||
}
|
||||
if luid != g.luid {
|
||||
g.restoreLocked()
|
||||
g.luid, g.name = luid, name
|
||||
g.forwarding = false // to warn about the new interface as well
|
||||
}
|
||||
if luid == 0 {
|
||||
return
|
||||
}
|
||||
var forwarding []string
|
||||
for _, family := range g.families {
|
||||
row, err := luid.IPInterface(family)
|
||||
if err != nil {
|
||||
continue // the interface lacks that IP version
|
||||
}
|
||||
if row.ForwardingEnabled {
|
||||
forwarding = append(forwarding, familyName(family))
|
||||
}
|
||||
if !row.WeakHostSend {
|
||||
continue
|
||||
}
|
||||
if err := setWeakHostSend(row, false); err != nil {
|
||||
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send off for ", familyName(family), " on ", name)
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(g.turnedOff, family) {
|
||||
g.turnedOff = append(g.turnedOff, family)
|
||||
errors.LogInfo(context.Background(), "[tun] weak host send turned off for ", familyName(family), " on ", name, " while the TUN runs, as Windows would ignore autoOutboundsInterface")
|
||||
}
|
||||
}
|
||||
wasOn := g.forwarding
|
||||
g.forwarding = len(forwarding) > 0
|
||||
if g.forwarding && !wasOn {
|
||||
errors.LogWarning(context.Background(), "[tun] forwarding is on for ", strings.Join(forwarding, " and "), " on ", name, " (Mobile Hotspot and Internet Connection Sharing turn it on), so Windows ignores autoOutboundsInterface there, and Xray's own connections go into the TUN and stall: turn the hotspot off, or have it share the TUN instead of ", name)
|
||||
}
|
||||
}
|
||||
|
||||
// restore turns weak host send on again where check turned it off, for good.
|
||||
func (g *outboundGuard) restore() {
|
||||
g.Lock()
|
||||
defer g.Unlock()
|
||||
g.restoreLocked()
|
||||
g.stopped = true
|
||||
}
|
||||
|
||||
func (g *outboundGuard) restoreLocked() {
|
||||
for _, family := range g.turnedOff {
|
||||
row, err := g.luid.IPInterface(family)
|
||||
if err == nil {
|
||||
err = setWeakHostSend(row, true)
|
||||
}
|
||||
if err != nil {
|
||||
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send on again for ", familyName(family), " on ", g.name)
|
||||
}
|
||||
}
|
||||
g.turnedOff = nil
|
||||
}
|
||||
|
||||
func setWeakHostSend(row *winipcfg.MibIPInterfaceRow, on bool) error {
|
||||
row.WeakHostSend = on
|
||||
if row.Family == windows.AF_INET {
|
||||
row.SitePrefixLength = 0 // as SetIpInterfaceEntry requires for IPv4
|
||||
}
|
||||
return row.Set()
|
||||
}
|
||||
|
||||
func familyName(family winipcfg.AddressFamily) string {
|
||||
if family == windows.AF_INET {
|
||||
return "IPv4"
|
||||
}
|
||||
return "IPv6"
|
||||
}
|
||||
@@ -4,6 +4,7 @@ package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
go_errors "errors"
|
||||
"net"
|
||||
"net/netip"
|
||||
@@ -340,3 +341,46 @@ func TestFlushDNSCache(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdapterGUID(t *testing.T) {
|
||||
// a configured GUID has to be the adapter GUID the text names: the groups
|
||||
// are field values, not the bytes of the text in order
|
||||
guid, err := adapterGUID("xray0", "01020304-0506-0708-090a-0b0c0d0e0f10")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := windows.GUID{
|
||||
Data1: 0x01020304,
|
||||
Data2: 0x0506,
|
||||
Data3: 0x0708,
|
||||
Data4: [8]byte{0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10},
|
||||
}
|
||||
if *guid != want {
|
||||
t.Errorf("adapterGUID = %+v, want %+v", *guid, want)
|
||||
}
|
||||
// the same struct Windows builds from that text, and the text Windows shows
|
||||
// for it
|
||||
if fromText, err := windows.GUIDFromString("{01020304-0506-0708-090A-0B0C0D0E0F10}"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if *guid != fromText {
|
||||
t.Errorf("adapterGUID = %s, want %s", guid.String(), fromText.String())
|
||||
}
|
||||
if got, want := guid.String(), "{01020304-0506-0708-090A-0B0C0D0E0F10}"; got != want {
|
||||
t.Errorf("adapterGUID = %s, want %s", got, want)
|
||||
}
|
||||
|
||||
// without one, the bytes of the MD5 of the name, as they always were; that
|
||||
// GUID is never read back as text, so its byte order does not matter
|
||||
guid, err = adapterGUID("xray0", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sum := md5.Sum([]byte("xray0"))
|
||||
if got := unsafe.Slice((*byte)(unsafe.Pointer(guid)), 16); string(got) != string(sum[:]) {
|
||||
t.Errorf("adapterGUID = %x, want %x", got, sum)
|
||||
}
|
||||
|
||||
if _, err := adapterGUID("xray0", "xray0"); err == nil {
|
||||
t.Error("an invalid guid was accepted")
|
||||
}
|
||||
}
|
||||
@@ -8,20 +8,6 @@ import (
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
)
|
||||
|
||||
// BenchmarkUDPNewSession measures what one new UDP flow costs the
|
||||
// inbound while it stays open: QUIC and DNS open many short flows, and each
|
||||
// one lives until the connection idle timeout.
|
||||
func BenchmarkUDPNewSession(b *testing.B) {
|
||||
u := newUdpConnectionHandler(func(conn net.Conn, dest net.Destination) {}, nil)
|
||||
dst := net.UDPDestination(net.ParseAddress("1.1.1.1"), 443)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
src := net.UDPDestination(net.IPAddress([]byte{10, byte(i >> 16), byte(i >> 8), byte(i)}), net.Port(1024+i%60000))
|
||||
u.HandlePacket(src, dst, &buf.Buffer{})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPacketQueueOrderAndClose(t *testing.T) {
|
||||
q := newPacketQueue(udpQueueLimit)
|
||||
for i := 0; i < 3; i++ {
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
)
|
||||
|
||||
const benchBatch = 64
|
||||
|
||||
// Raw cost of queueing and draining a small burst, as one flow's reader does.
|
||||
func BenchmarkQueueBurstChan(b *testing.B) {
|
||||
ch := make(chan *buf.Buffer, udpQueueLimit)
|
||||
p := &buf.Buffer{}
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
for j := 0; j < benchBatch; j++ {
|
||||
ch <- p
|
||||
}
|
||||
for j := 0; j < benchBatch; j++ {
|
||||
<-ch
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkQueueBurstPacketQueue(b *testing.B) {
|
||||
q := newPacketQueue(udpQueueLimit)
|
||||
p := &buf.Buffer{}
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
for j := 0; j < benchBatch; j++ {
|
||||
q.push(p)
|
||||
}
|
||||
for j := 0; j < benchBatch; j++ {
|
||||
q.pop()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Producer and consumer on different goroutines; the producer yields when the
|
||||
// queue is full instead of spinning, like a blocking channel send would.
|
||||
func BenchmarkQueueStreamChan(b *testing.B) {
|
||||
ch := make(chan *buf.Buffer, udpQueueLimit)
|
||||
p := &buf.Buffer{}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
for range ch {
|
||||
}
|
||||
close(done)
|
||||
}()
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
ch <- p
|
||||
}
|
||||
close(ch)
|
||||
<-done
|
||||
}
|
||||
|
||||
func BenchmarkQueueStreamPacketQueue(b *testing.B) {
|
||||
q := newPacketQueue(udpQueueLimit)
|
||||
p := &buf.Buffer{}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
for {
|
||||
if _, ok := q.pop(); !ok {
|
||||
break
|
||||
}
|
||||
}
|
||||
close(done)
|
||||
}()
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
for !q.push(p) {
|
||||
runtime.Gosched()
|
||||
}
|
||||
}
|
||||
q.close()
|
||||
<-done
|
||||
}
|
||||
@@ -80,43 +80,3 @@ func TestExpandWfpBlockLeak(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLeakCovers(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
value string
|
||||
protocol string
|
||||
port uint16
|
||||
covers bool
|
||||
}{
|
||||
{"tcp", "tcp", 1, true},
|
||||
{"tcp", "udp", 53, false},
|
||||
{"udp/53", "udp", 53, true},
|
||||
{"udp/53", "udp", 54, false},
|
||||
{"tcp/10-20", "tcp", 10, true},
|
||||
{"tcp/10-20", "tcp", 20, true},
|
||||
{"tcp/10-20", "tcp", 21, false},
|
||||
{"tcp/10-20", "tcp", 9, false},
|
||||
{"53", "udp", 53, true},
|
||||
{"53", "tcp", 53, true},
|
||||
{"10-20", "tcp", 15, true},
|
||||
{"10-20", "udp", 21, false},
|
||||
{"1.1.1.0/24:udp/53", "udp", 53, true},
|
||||
{"[::/0]:tcp", "tcp", 443, true},
|
||||
{"[2001:db8::/32]:53", "tcp", 53, true},
|
||||
{"0.0.0.0/0:icmp", "udp", 53, false},
|
||||
{"all", "udp", 53, true},
|
||||
{"1.1.1.1/32:all", "tcp", 1, true},
|
||||
{"allexceptlan", "udp", 53, false},
|
||||
{"misconfigtun", "udp", 53, false},
|
||||
{"windnsclient", "udp", 53, false},
|
||||
} {
|
||||
l, ok := parseLeak(c.value)
|
||||
if !ok {
|
||||
t.Errorf("%q was not parsed", c.value)
|
||||
continue
|
||||
}
|
||||
if got := l.covers(c.protocol, c.port); got != c.covers {
|
||||
t.Errorf("%q covers %s/%d = %v", c.value, c.protocol, c.port, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@ 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"
|
||||
@@ -524,6 +525,12 @@ 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")
|
||||
|
||||
@@ -12,6 +12,7 @@ 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"
|
||||
)
|
||||
@@ -41,17 +42,19 @@ 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}
|
||||
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)
|
||||
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)
|
||||
}
|
||||
c.tcp = pool(concurrency)
|
||||
}
|
||||
if concurrency := config.GetXudpConcurrency(); concurrency > 0 {
|
||||
c.udp = 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)
|
||||
}
|
||||
return c
|
||||
}
|
||||
@@ -72,6 +75,7 @@ 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
|
||||
|
||||
@@ -26,7 +26,9 @@ func TestClientUDP443Policy(t *testing.T) {
|
||||
opened = true
|
||||
return nil, nil, context.Canceled
|
||||
})
|
||||
handled, err := client.Dispatch(ctx, &transport.Link{})
|
||||
r, w := pipe.New()
|
||||
common.Close(w)
|
||||
handled, err := client.Dispatch(ctx, &transport.Link{Reader: r})
|
||||
wantRejected := policy == "reject"
|
||||
if opened || handled != wantRejected || (err != nil) != wantRejected {
|
||||
t.Fatalf("Dispatch() = (%t, %v), opened carrier = %t, want rejected = %t without opening a carrier", handled, err, opened, wantRejected)
|
||||
|
||||
@@ -191,6 +191,13 @@ 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)
|
||||
@@ -272,27 +279,20 @@ 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 {
|
||||
|
||||
@@ -255,10 +255,11 @@ 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())
|
||||
|
||||
@@ -175,7 +175,14 @@ func (c *xdnsServer) read(buf []byte, addr net.Addr) {
|
||||
c.decref(msg, addr)
|
||||
return
|
||||
}
|
||||
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) {
|
||||
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) {
|
||||
msg.Header.Response = true
|
||||
msg.Header.Authoritative = true
|
||||
msg.Header.RCode = dnsmessage.RCodeSuccess
|
||||
@@ -201,14 +208,14 @@ func (c *xdnsServer) read(buf []byte, addr net.Addr) {
|
||||
c.decref(msg, addr)
|
||||
}
|
||||
|
||||
if decoded[8]&0x3F == 8 {
|
||||
if kind == 8 {
|
||||
return
|
||||
}
|
||||
p := pool4K.Get().([]byte)
|
||||
p = p[:0]
|
||||
if decoded[8]&0xC0 == 0xC0 {
|
||||
if fragmented {
|
||||
out := pool4K.Get().([]byte)
|
||||
n := c.fragManager.Feed(out, FragKey{clientID: clientID, fragID: decoded[12]}, decoded[13], decoded[14], decoded[15:n])
|
||||
n := c.fragManager.Feed(out, FragKey{clientID: clientID, fragID: decoded[12]}, decoded[13], decoded[14], decoded[dataOffset:n])
|
||||
pool4K.Put(p[:cap(p)])
|
||||
if n > 0 {
|
||||
p = out[:n]
|
||||
@@ -217,7 +224,7 @@ func (c *xdnsServer) read(buf []byte, addr net.Addr) {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
p = append(p, decoded[12:n]...)
|
||||
p = append(p, decoded[dataOffset:n]...)
|
||||
}
|
||||
select {
|
||||
case <-c.closeCh:
|
||||
|
||||
@@ -28,7 +28,11 @@ func (s *Proxy) Proxy(w http.ResponseWriter, r *ProxyRequest) (*Conn, error) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
if ok {
|
||||
return newProxiedConn(streamer.HTTPStream()), nil
|
||||
str, err := streamer.HTTPStream()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newProxiedConn(str), nil
|
||||
}
|
||||
controller := http.NewResponseController(w)
|
||||
if err := controller.Flush(); err != nil {
|
||||
|
||||
@@ -231,7 +231,11 @@ func TestDialWarpHTTP3(t *testing.T) {
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.(http.Flusher).Flush()
|
||||
str := w.(http3.HTTPStreamer).HTTPStream()
|
||||
str, err := w.(http3.HTTPStreamer).HTTPStream()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
go func() { capsules <- readCapsuleTypes(str, nil) }()
|
||||
b, err := str.ReceiveDatagram(r.Context())
|
||||
if err != nil {
|
||||
|
||||
@@ -26,6 +26,7 @@ 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"
|
||||
@@ -78,10 +79,9 @@ func (h *requestHandler) upsertSession(sessionId string) *httpSession {
|
||||
h.sessions.Store(sessionId, s)
|
||||
|
||||
shouldReap := done.New()
|
||||
go func() {
|
||||
time.Sleep(30 * time.Second)
|
||||
time.AfterFunc(30*time.Second, func() {
|
||||
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 {
|
||||
go func() {
|
||||
for {
|
||||
writePadding := &task.Periodic{
|
||||
Execute: func() error {
|
||||
_, err := httpSC.Write(bytes.Repeat([]byte{'X'}, int(h.config.GetNormalizedXPaddingBytes().rand())))
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Duration(scStreamUpServerSecs.rand()) * time.Second)
|
||||
}
|
||||
}()
|
||||
return err
|
||||
},
|
||||
Interval: time.Duration(scStreamUpServerSecs.rand()) * time.Second,
|
||||
}
|
||||
defer writePadding.Close()
|
||||
writePadding.Start()
|
||||
}
|
||||
select {
|
||||
case <-request.Context().Done():
|
||||
|
||||
@@ -6,9 +6,11 @@ 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)
|
||||
@@ -20,25 +22,27 @@ 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 {
|
||||
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{
|
||||
wrappedConn := &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()
|
||||
@@ -93,6 +97,7 @@ 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)
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
_ "embed"
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
@@ -25,7 +24,7 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me
|
||||
if streamSettings.ProtocolSettings.(*Config).Ed > 0 {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
conn = &delayDialConn{
|
||||
dialed: make(chan bool),
|
||||
dialed: make(chan bool, 1),
|
||||
cancel: cancel,
|
||||
ctx: ctx,
|
||||
dest: dest,
|
||||
@@ -159,8 +158,8 @@ func dialWebSocket(ctx context.Context, dest net.Destination, streamSettings *in
|
||||
}
|
||||
|
||||
type delayDialConn struct {
|
||||
conn atomic.Value // net.Conn
|
||||
closed atomic.Bool
|
||||
net.Conn
|
||||
closed bool
|
||||
dialed chan bool
|
||||
cancel context.CancelFunc
|
||||
ctx context.Context
|
||||
@@ -172,124 +171,62 @@ type delayDialConn struct {
|
||||
// Without this method, Go promotes LocalAddr from the embedded net.Conn; the
|
||||
// embedded interface is nil before the first Write, so the promoted call panics.
|
||||
func (d *delayDialConn) LocalAddr() net.Addr {
|
||||
conn := d.conn.Load()
|
||||
if conn == nil {
|
||||
if d.Conn == nil {
|
||||
return nil
|
||||
}
|
||||
return (conn.(net.Conn)).LocalAddr()
|
||||
return d.Conn.LocalAddr()
|
||||
}
|
||||
|
||||
// RemoteAddr returns nil until the deferred WebSocket dial has completed.
|
||||
// See LocalAddr for why an explicit method is required here.
|
||||
func (d *delayDialConn) RemoteAddr() net.Addr {
|
||||
conn := d.conn.Load()
|
||||
if conn == nil {
|
||||
if d.Conn == nil {
|
||||
return nil
|
||||
}
|
||||
return (conn.(net.Conn)).RemoteAddr()
|
||||
return d.Conn.RemoteAddr()
|
||||
}
|
||||
|
||||
func (d *delayDialConn) Write(b []byte) (int, error) {
|
||||
if d.closed.Load() {
|
||||
if d.closed {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
conn := d.conn.Load()
|
||||
if conn == nil {
|
||||
if d.Conn == nil {
|
||||
ed := b
|
||||
if len(ed) > int(d.streamSettings.ProtocolSettings.(*Config).Ed) {
|
||||
ed = nil
|
||||
}
|
||||
c, err := dialWebSocket(d.ctx, d.dest, d.streamSettings, ed)
|
||||
if err != nil {
|
||||
var err error
|
||||
if d.Conn, err = dialWebSocket(d.ctx, d.dest, d.streamSettings, ed); err != nil {
|
||||
d.Close()
|
||||
return 0, errors.New("failed to dial WebSocket").Base(err)
|
||||
}
|
||||
d.conn.Store(c)
|
||||
// someone close the conn after dial success
|
||||
if d.closed.Load() {
|
||||
d.Close()
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
conn = c
|
||||
close(d.dialed)
|
||||
d.dialed <- true
|
||||
if ed != nil {
|
||||
return len(ed), nil
|
||||
}
|
||||
}
|
||||
return (conn.(net.Conn)).Write(b)
|
||||
return d.Conn.Write(b)
|
||||
}
|
||||
|
||||
func (d *delayDialConn) Read(b []byte) (int, error) {
|
||||
if d.closed.Load() {
|
||||
if d.closed {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
conn := d.conn.Load()
|
||||
if conn == nil {
|
||||
if d.Conn == nil {
|
||||
select {
|
||||
case <-d.ctx.Done():
|
||||
return 0, io.ErrUnexpectedEOF
|
||||
case <-d.dialed:
|
||||
}
|
||||
conn = d.conn.Load()
|
||||
}
|
||||
return (conn.(net.Conn)).Read(b)
|
||||
}
|
||||
|
||||
func (d *delayDialConn) SetDeadline(t time.Time) error {
|
||||
if d.closed.Load() {
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
conn := d.conn.Load()
|
||||
if conn == nil {
|
||||
d.setDelayedDeadline(t, d.SetDeadline)
|
||||
return nil
|
||||
}
|
||||
return (conn.(net.Conn)).SetDeadline(t)
|
||||
}
|
||||
|
||||
func (d *delayDialConn) SetReadDeadline(t time.Time) error {
|
||||
if d.closed.Load() {
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
conn := d.conn.Load()
|
||||
if conn == nil {
|
||||
d.setDelayedDeadline(t, d.SetReadDeadline)
|
||||
return nil
|
||||
}
|
||||
return (conn.(net.Conn)).SetReadDeadline(t)
|
||||
}
|
||||
|
||||
func (d *delayDialConn) SetWriteDeadline(t time.Time) error {
|
||||
if d.closed.Load() {
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
conn := d.conn.Load()
|
||||
if conn == nil {
|
||||
d.setDelayedDeadline(t, d.SetWriteDeadline)
|
||||
return nil
|
||||
}
|
||||
return (conn.(net.Conn)).SetWriteDeadline(t)
|
||||
}
|
||||
|
||||
func (d *delayDialConn) setDelayedDeadline(t time.Time, f func(time.Time) error) {
|
||||
ctx, cancel := context.WithTimeout(d.ctx, time.Until(t))
|
||||
go func() {
|
||||
defer cancel()
|
||||
select {
|
||||
case <-d.dialed:
|
||||
f(t)
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}()
|
||||
return d.Conn.Read(b)
|
||||
}
|
||||
|
||||
func (d *delayDialConn) Close() error {
|
||||
d.closed.Store(true)
|
||||
d.closed = true
|
||||
d.cancel()
|
||||
conn := d.conn.Load()
|
||||
if conn == nil {
|
||||
if d.Conn == nil {
|
||||
return nil
|
||||
}
|
||||
return (conn.(net.Conn)).Close()
|
||||
return d.Conn.Close()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user