mirror of
https://github.com/XTLS/Xray-core.git
synced 2026-11-27 03:50:08 +00:00
Compare commits
2
Commits
main
..
findprocess
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
953097e9dc | ||
|
|
73a3beff39 |
@@ -7,6 +7,7 @@ import (
|
||||
"github.com/xtls/xray-core/app/proxyman"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/core"
|
||||
@@ -183,6 +184,9 @@ func NewHandler(ctx context.Context, config *core.InboundHandlerConfig) (inbound
|
||||
Mark: streamSettings.SocketSettings.Mark,
|
||||
})
|
||||
}
|
||||
if streamSettings != nil && (streamSettings.ProtocolName == "splithttp" || streamSettings.ProtocolName == "masque") {
|
||||
ctx = session.ContextWithAllowedNetwork(ctx, net.Network_UDP)
|
||||
}
|
||||
|
||||
return NewAlwaysOnInboundHandler(ctx, tag, receiverSettings, proxySettings)
|
||||
}
|
||||
|
||||
+23
-3
@@ -15,6 +15,8 @@ const (
|
||||
|
||||
var ErrBufferFull = errors.New("buffer is full")
|
||||
|
||||
var pool = bytespool.GetPool(Size)
|
||||
|
||||
// ownership represents the data owner of the buffer.
|
||||
type ownership uint8
|
||||
|
||||
@@ -37,7 +39,16 @@ type Buffer struct {
|
||||
|
||||
// New creates a Buffer with 0 length and 8K capacity, managed.
|
||||
func New() *Buffer {
|
||||
return &Buffer{v: bytespool.Alloc(Size)}
|
||||
buf := pool.Get().([]byte)
|
||||
if cap(buf) >= Size {
|
||||
buf = buf[:Size]
|
||||
} else {
|
||||
buf = make([]byte, Size)
|
||||
}
|
||||
|
||||
return &Buffer{
|
||||
v: buf,
|
||||
}
|
||||
}
|
||||
|
||||
// NewExisted creates a standard size Buffer with an existed bytearray, managed.
|
||||
@@ -69,7 +80,16 @@ func FromBytes(b []byte) *Buffer {
|
||||
// StackNew creates a new Buffer object on stack, managed.
|
||||
// This method is for buffers that is released in the same function.
|
||||
func StackNew() Buffer {
|
||||
return Buffer{v: bytespool.Alloc(Size)}
|
||||
buf := pool.Get().([]byte)
|
||||
if cap(buf) >= Size {
|
||||
buf = buf[:Size]
|
||||
} else {
|
||||
buf = make([]byte, Size)
|
||||
}
|
||||
|
||||
return Buffer{
|
||||
v: buf,
|
||||
}
|
||||
}
|
||||
|
||||
// NewWithSize creates a Buffer with 0 length and capacity with at least the given size, bytespool's.
|
||||
@@ -93,7 +113,7 @@ func (b *Buffer) Release() {
|
||||
switch b.ownership {
|
||||
case managed:
|
||||
if cap(p) == Size {
|
||||
bytespool.Free(p)
|
||||
pool.Put(p)
|
||||
}
|
||||
case bytespools:
|
||||
bytespool.Free(p)
|
||||
|
||||
+55
-67
@@ -1,84 +1,72 @@
|
||||
package bytespool
|
||||
|
||||
import (
|
||||
"math/bits"
|
||||
"sync"
|
||||
)
|
||||
import "sync"
|
||||
|
||||
const (
|
||||
minShift = 10 // 1KB
|
||||
maxShift = 16 // 64KB
|
||||
numPools = maxShift - minShift + 1
|
||||
minSize = 1 << minShift
|
||||
maxSize = 1 << maxShift
|
||||
)
|
||||
|
||||
// pools hold array pointers (*[N]byte) to avoid interface boxing allocations on Put.
|
||||
var pools = [numPools]sync.Pool{
|
||||
{New: func() any { return new([1 << 10]byte) }},
|
||||
{New: func() any { return new([1 << 11]byte) }},
|
||||
{New: func() any { return new([1 << 12]byte) }},
|
||||
{New: func() any { return new([1 << 13]byte) }},
|
||||
{New: func() any { return new([1 << 14]byte) }},
|
||||
{New: func() any { return new([1 << 15]byte) }},
|
||||
{New: func() any { return new([1 << 16]byte) }},
|
||||
func createAllocFunc(size int32) func() interface{} {
|
||||
return func() interface{} {
|
||||
return make([]byte, size)
|
||||
}
|
||||
}
|
||||
|
||||
// Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 1024.
|
||||
// The following parameters controls the size of buffer pools.
|
||||
// There are numPools pools. Starting from 2k size, the size of each pool is sizeMulti of the previous one.
|
||||
// Package buf is guaranteed to not use buffers larger than the largest pool.
|
||||
// Other packets may use larger buffers.
|
||||
const (
|
||||
numPools = 4
|
||||
sizeMulti = 4
|
||||
)
|
||||
|
||||
var (
|
||||
pool [numPools]sync.Pool
|
||||
poolSize [numPools]int32
|
||||
)
|
||||
|
||||
func init() {
|
||||
size := int32(2048)
|
||||
for i := 0; i < numPools; i++ {
|
||||
pool[i] = sync.Pool{
|
||||
New: createAllocFunc(size),
|
||||
}
|
||||
poolSize[i] = size
|
||||
size *= sizeMulti
|
||||
}
|
||||
}
|
||||
|
||||
// GetPool returns a sync.Pool that generates bytes array with at least the given size.
|
||||
// It may return nil if no such pool exists.
|
||||
//
|
||||
// xray:api:stable
|
||||
func GetPool(size int32) *sync.Pool {
|
||||
for idx, ps := range poolSize {
|
||||
if size <= ps {
|
||||
return &pool[idx]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 2048.
|
||||
//
|
||||
// xray:api:stable
|
||||
func Alloc(size int32) []byte {
|
||||
if size > maxSize {
|
||||
return make([]byte, size)
|
||||
}
|
||||
index := 0
|
||||
if size > minSize {
|
||||
index = bits.Len32(uint32(size-1)) - minShift
|
||||
}
|
||||
p := pools[index].Get()
|
||||
switch index {
|
||||
case 0:
|
||||
return p.(*[1 << 10]byte)[:]
|
||||
case 1:
|
||||
return p.(*[1 << 11]byte)[:]
|
||||
case 2:
|
||||
return p.(*[1 << 12]byte)[:]
|
||||
case 3:
|
||||
return p.(*[1 << 13]byte)[:]
|
||||
case 4:
|
||||
return p.(*[1 << 14]byte)[:]
|
||||
case 5:
|
||||
return p.(*[1 << 15]byte)[:]
|
||||
case 6:
|
||||
return p.(*[1 << 16]byte)[:]
|
||||
default:
|
||||
panic("invalid pool index")
|
||||
pool := GetPool(size)
|
||||
if pool != nil {
|
||||
return pool.Get().([]byte)
|
||||
}
|
||||
return make([]byte, size)
|
||||
}
|
||||
|
||||
// Free puts a byte slice into the internal pool.
|
||||
//
|
||||
// xray:api:stable
|
||||
func Free(b []byte) {
|
||||
c := cap(b)
|
||||
if c < minSize || c > maxSize {
|
||||
return
|
||||
}
|
||||
index := bits.Len(uint(c)) - 1 - minShift
|
||||
switch index {
|
||||
case 0:
|
||||
pools[0].Put((*[1 << 10]byte)(b[:1<<10]))
|
||||
case 1:
|
||||
pools[1].Put((*[1 << 11]byte)(b[:1<<11]))
|
||||
case 2:
|
||||
pools[2].Put((*[1 << 12]byte)(b[:1<<12]))
|
||||
case 3:
|
||||
pools[3].Put((*[1 << 13]byte)(b[:1<<13]))
|
||||
case 4:
|
||||
pools[4].Put((*[1 << 14]byte)(b[:1<<14]))
|
||||
case 5:
|
||||
pools[5].Put((*[1 << 15]byte)(b[:1<<15]))
|
||||
case 6:
|
||||
pools[6].Put((*[1 << 16]byte)(b[:1<<16]))
|
||||
size := int32(cap(b))
|
||||
b = b[0:cap(b)]
|
||||
for i := numPools - 1; i >= 0; i-- {
|
||||
if size >= poolSize[i] {
|
||||
pool[i].Put(b)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,15 +3,19 @@
|
||||
package net
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"slices"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"github.com/vishvananda/netlink/nl"
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"github.com/xtls/xray-core/common/bytespool"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
)
|
||||
|
||||
@@ -27,50 +31,20 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
|
||||
panic("Unsupported network type for process lookup.")
|
||||
}
|
||||
|
||||
var procFiles []string
|
||||
|
||||
switch network {
|
||||
case "tcp":
|
||||
if net.ParseIP(srcIP).To4() != nil {
|
||||
procFiles = []string{"/proc/net/tcp", "/proc/net/tcp6"}
|
||||
} else {
|
||||
procFiles = []string{"/proc/net/tcp6"}
|
||||
}
|
||||
case "udp":
|
||||
if net.ParseIP(srcIP).To4() != nil {
|
||||
procFiles = []string{"/proc/net/udp", "/proc/net/udp6"}
|
||||
} else {
|
||||
procFiles = []string{"/proc/net/udp6", "/proc/net/udp"}
|
||||
}
|
||||
default:
|
||||
panic("Unsupported network type for process lookup.")
|
||||
}
|
||||
|
||||
targetHexAddrs := []string{formatProcNetAddress(net.ParseIP(srcIP).To16(), Port(srcPort))}
|
||||
if ipv4 := net.ParseIP(srcIP).To4(); ipv4 != nil {
|
||||
// the one above is then the IPv4-mapped IPv6 address that an IPv6 socket has it as, in the IPv6 file
|
||||
targetHexAddrs = append(targetHexAddrs, formatProcNetAddress(ipv4, Port(srcPort)))
|
||||
}
|
||||
|
||||
portFallback := ""
|
||||
if network == "udp" {
|
||||
portFallback = fmt.Sprintf(":%04X", srcPort)
|
||||
}
|
||||
|
||||
inode, err := findInodeInFiles(procFiles, targetHexAddrs, portFallback)
|
||||
socket, err := findSocketInode(network, net.ParseIP(srcIP), srcPort)
|
||||
if err != nil {
|
||||
return 0, "", "", errors.New("could not search in ", strings.Join(procFiles, " and ")).Base(err)
|
||||
return 0, "", "", errors.New("could not query sockets using netlink").Base(err)
|
||||
}
|
||||
if inode == "" {
|
||||
return 0, "", "", errors.New("connection for ", srcIP, ":", srcPort, " not found in ", strings.Join(procFiles, " or "))
|
||||
if socket == nil {
|
||||
return 0, "", "", errors.New("connection for ", srcIP, ":", srcPort, " not found")
|
||||
}
|
||||
|
||||
pidStr, err := findPidByInode(inode)
|
||||
pidStr, err := findPidByInode(socket.inode, socket.uid)
|
||||
if err != nil {
|
||||
return 0, "", "", errors.New("could not find PID for inode ", inode, ": ", err)
|
||||
return 0, "", "", errors.New("could not find PID for inode ", socket.inode, ": ", err)
|
||||
}
|
||||
if pidStr == "" {
|
||||
return 0, "", "", errors.New("no process found for inode ", inode)
|
||||
return 0, "", "", errors.New("no process found for inode ", socket.inode)
|
||||
}
|
||||
|
||||
absPath, err := getAbsPath(pidStr)
|
||||
@@ -89,59 +63,94 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
|
||||
return pid, procName, absPath, nil
|
||||
}
|
||||
|
||||
// formatProcNetAddress formats the 4 or 16 bytes of addr as they are: an IPv4-mapped IPv6 address stays one
|
||||
func formatProcNetAddress(addr net.IP, port Port) string {
|
||||
ipBytes := []byte(addr)
|
||||
|
||||
var formatted strings.Builder
|
||||
formatted.Grow(len(ipBytes)*2 + 5)
|
||||
for i := 0; i < len(ipBytes); i += 4 {
|
||||
fmt.Fprintf(&formatted, "%08X", binary.NativeEndian.Uint32(ipBytes[i:i+4]))
|
||||
}
|
||||
fmt.Fprintf(&formatted, ":%04X", uint16(port))
|
||||
return formatted.String()
|
||||
type processSocket struct {
|
||||
inode string
|
||||
uid uint32
|
||||
}
|
||||
|
||||
func findInodeInFiles(filePaths []string, targetHexAddrs []string, portFallback string) (string, error) {
|
||||
onlyMatchedPort := ""
|
||||
// Layouts are defined by Linux's inet_diag_req_v2 and inet_diag_msg.
|
||||
const (
|
||||
inetDiagRequestSize = 56
|
||||
inetDiagResponseSize = 72
|
||||
tcpBoundInactive = 13
|
||||
)
|
||||
|
||||
for i, filePath := range filePaths {
|
||||
file, err := os.Open(filePath)
|
||||
func findSocketInode(network string, ip net.IP, port uint16) (*processSocket, error) {
|
||||
families := []uint8{unix.AF_INET6}
|
||||
if ip.To4() != nil {
|
||||
families = []uint8{unix.AF_INET, unix.AF_INET6}
|
||||
} else if network == "udp" {
|
||||
families = append(families, unix.AF_INET)
|
||||
}
|
||||
|
||||
protocol := byte(unix.IPPROTO_UDP)
|
||||
if network == "tcp" {
|
||||
protocol = unix.IPPROTO_TCP
|
||||
}
|
||||
|
||||
var wildcard *processSocket
|
||||
request := make([]byte, inetDiagRequestSize)
|
||||
for _, family := range families {
|
||||
clear(request)
|
||||
request[0], request[1] = family, protocol
|
||||
states := ^uint32(0)
|
||||
if network == "tcp" {
|
||||
states &^= 1 << tcpBoundInactive
|
||||
}
|
||||
binary.NativeEndian.PutUint32(request[4:8], states)
|
||||
binary.BigEndian.PutUint16(request[8:10], port)
|
||||
if family == unix.AF_INET {
|
||||
copy(request[12:28], ip.To4())
|
||||
} else {
|
||||
copy(request[12:28], ip.To16())
|
||||
}
|
||||
binary.NativeEndian.PutUint32(request[48:52], ^uint32(0))
|
||||
binary.NativeEndian.PutUint32(request[52:56], ^uint32(0))
|
||||
|
||||
req := nl.NewNetlinkRequest(nl.SOCK_DIAG_BY_FAMILY, unix.NLM_F_DUMP)
|
||||
req.AddRawData(request)
|
||||
var exact *processSocket
|
||||
var parseErr error
|
||||
err := req.ExecuteIter(unix.NETLINK_INET_DIAG, nl.SOCK_DIAG_BY_FAMILY, func(msg []byte) bool {
|
||||
if len(msg) < inetDiagResponseSize {
|
||||
parseErr = fmt.Errorf("short inet_diag response: %d bytes", len(msg))
|
||||
return false
|
||||
}
|
||||
if msg[0] != family || binary.BigEndian.Uint16(msg[4:6]) != port {
|
||||
return true
|
||||
}
|
||||
source := net.IP(msg[8:24])
|
||||
if family == unix.AF_INET {
|
||||
source = source[:4]
|
||||
}
|
||||
if !source.Equal(ip) && !(network == "udp" && source.IsUnspecified()) {
|
||||
return true
|
||||
}
|
||||
socket := &processSocket{
|
||||
uid: binary.NativeEndian.Uint32(msg[64:68]),
|
||||
inode: strconv.FormatUint(uint64(binary.NativeEndian.Uint32(msg[68:72])), 10),
|
||||
}
|
||||
if source.Equal(ip) {
|
||||
exact = socket
|
||||
return false
|
||||
}
|
||||
wildcard = socket
|
||||
return true
|
||||
})
|
||||
if err != nil {
|
||||
if i > 0 && os.IsNotExist(err) {
|
||||
continue
|
||||
}
|
||||
return "", err
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
for scanner.Scan() {
|
||||
fields := strings.Fields(scanner.Text())
|
||||
if len(fields) < 10 {
|
||||
continue
|
||||
}
|
||||
|
||||
localAddress := fields[1]
|
||||
if slices.Contains(targetHexAddrs, localAddress) {
|
||||
return fields[9], nil
|
||||
}
|
||||
if portFallback != "" && strings.HasSuffix(localAddress, portFallback) {
|
||||
wildcardIP := strings.TrimSuffix(localAddress, portFallback)
|
||||
if (len(wildcardIP) == 8 || len(wildcardIP) == 32) && strings.Trim(wildcardIP, "0") == "" {
|
||||
onlyMatchedPort = fields[9]
|
||||
}
|
||||
}
|
||||
if parseErr != nil {
|
||||
return nil, parseErr
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return "", err
|
||||
if exact != nil {
|
||||
return exact, nil
|
||||
}
|
||||
}
|
||||
|
||||
return onlyMatchedPort, nil
|
||||
return wildcard, nil
|
||||
}
|
||||
|
||||
func findPidByInode(inode string) (string, error) {
|
||||
func findPidByInode(inode string, uid uint32) (string, error) {
|
||||
procDir, err := os.ReadDir("/proc")
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -158,26 +167,45 @@ func findPidByInode(inode string) (string, error) {
|
||||
continue
|
||||
}
|
||||
|
||||
fdPath := fmt.Sprintf("/proc/%s/fd", pid)
|
||||
fdDir, err := os.ReadDir(fdPath)
|
||||
info, err := entry.Info()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
for _, fdEntry := range fdDir {
|
||||
linkPath := fmt.Sprintf("%s/%s", fdPath, fdEntry.Name())
|
||||
linkTarget, err := os.Readlink(linkPath)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if linkTarget == targetLink {
|
||||
return pid, nil
|
||||
}
|
||||
stat, ok := info.Sys().(*syscall.Stat_t)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("unexpected stat data for process %s", pid)
|
||||
}
|
||||
if stat.Uid != uid {
|
||||
continue
|
||||
}
|
||||
if processHasSocket(pid, targetLink) {
|
||||
return pid, nil
|
||||
}
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func processHasSocket(pid, targetLink string) bool {
|
||||
fdPath := filepath.Join("/proc", pid, "fd")
|
||||
fdDir, err := os.ReadDir(fdPath)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
buffer := bytespool.Alloc(unix.PathMax)
|
||||
defer bytespool.Free(buffer)
|
||||
for _, fdEntry := range fdDir {
|
||||
n, err := unix.Readlink(filepath.Join(fdPath, fdEntry.Name()), buffer)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if string(buffer[:n]) == targetLink {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func getAbsPath(pid string) (string, error) {
|
||||
path := fmt.Sprintf("/proc/%s/exe", pid)
|
||||
return os.Readlink(path)
|
||||
|
||||
@@ -71,6 +71,7 @@ func (t *ActivityTimer) SetTimeout(timeout time.Duration) {
|
||||
}
|
||||
common.CloseIfExists(t.checkTask)
|
||||
t.checkTask = newCheckTask
|
||||
t.Update()
|
||||
common.Must(newCheckTask.Start())
|
||||
}
|
||||
|
||||
|
||||
@@ -58,11 +58,15 @@ func (t *Periodic) Start() error {
|
||||
return nil
|
||||
}
|
||||
t.running = true
|
||||
t.timer = time.AfterFunc(t.Interval, func() {
|
||||
t.checkedExecute()
|
||||
})
|
||||
t.access.Unlock()
|
||||
|
||||
if err := t.checkedExecute(); err != nil {
|
||||
t.access.Lock()
|
||||
t.running = false
|
||||
t.access.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -20,17 +20,17 @@ func TestPeriodicTaskStop(t *testing.T) {
|
||||
common.Must(task.Start())
|
||||
time.Sleep(time.Second * 5)
|
||||
common.Must(task.Close())
|
||||
if value != 2 {
|
||||
t.Fatal("expected 2, but got ", value)
|
||||
if value != 3 {
|
||||
t.Fatal("expected 3, but got ", value)
|
||||
}
|
||||
time.Sleep(time.Second * 4)
|
||||
if value != 2 {
|
||||
t.Fatal("expected 2, but got ", value)
|
||||
if value != 3 {
|
||||
t.Fatal("expected 3, but got ", value)
|
||||
}
|
||||
common.Must(task.Start())
|
||||
time.Sleep(time.Second * 3)
|
||||
if value != 3 {
|
||||
t.Fatal("Expected 3, but ", value)
|
||||
if value != 5 {
|
||||
t.Fatal("Expected 5, but ", value)
|
||||
}
|
||||
common.Must(task.Close())
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ module github.com/xtls/xray-core
|
||||
go 1.27
|
||||
|
||||
require (
|
||||
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a
|
||||
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c
|
||||
github.com/bufbuild/protocompile v0.14.1
|
||||
github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344
|
||||
github.com/golang/mock v1.7.0-rc.1
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a h1:uCIlOCbXUtBkFk47HxIkQieCkV+zKv5VCDawLtj3Pkc=
|
||||
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a/go.mod h1:J7UZVOMF2M1LiE3iiUZWPuy8YCPAcLJOwVURrfJCvc0=
|
||||
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c h1:cxK8qTA0YCsj68A7zLYDCfPgMTOyt3ePkHh+oXEmYU0=
|
||||
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c/go.mod h1:J7UZVOMF2M1LiE3iiUZWPuy8YCPAcLJOwVURrfJCvc0=
|
||||
github.com/bufbuild/protocompile v0.14.1 h1:iA73zAf/fyljNjQKwYzUHD6AD4R8KMasmwa/FBatYVw=
|
||||
github.com/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU5DoEw9xY/FUi1c=
|
||||
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
|
||||
|
||||
@@ -541,7 +541,10 @@ func TestXDriveOutboundConfig(t *testing.T) {
|
||||
for _, c := range []struct{ input, err string }{
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, "encryption": "none", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"encryption"`},
|
||||
{`{"protocol": "vless", "settings": {"address": "example.com", "port": 443, ` + xdriveID + `, "encryption": "none", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"encryption"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8, "xudpProxyUDP443": "skip"}}, ` + xdriveStream + `}`, `"xudpProxyUDP443":"skip"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `}`, `"settings.multiplex.concurrency"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"settings.multiplex.concurrency"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"xudpConcurrency": 8}}, ` + xdriveStream + `}`, `"settings.multiplex.concurrency"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8, "xudpProxyUDP443": "skip"}}, ` + xdriveStream + `}`, `"settings.multiplex.concurrency"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
|
||||
{`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision"}]}], "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "testpre": 1, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"testpre"`},
|
||||
|
||||
@@ -159,7 +159,6 @@ func TestTunConfigGUID(t *testing.T) {
|
||||
for _, guid := range []string{
|
||||
"xray0",
|
||||
"6ba7b810-9dad-11d1-80b4-00c04fd430c",
|
||||
"6ba7b8109-dad-11d1-80b4-00c04fd430c8", // the right length, a hyphen out of place
|
||||
"6ba7b8109dad11d180b400c04fd430c8",
|
||||
"{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
|
||||
"urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8",
|
||||
|
||||
+3
-13
@@ -265,13 +265,8 @@ func validateXDrive(ts proto.Message, ss *internet.StreamConfig, pl *net.PortLis
|
||||
return errors.New(`the xdrive transport needs VLESS "encryption", run "xray vlessenc" to get one`)
|
||||
}
|
||||
// Reverse opens its own multiplexed connection.
|
||||
if account.Reverse == nil {
|
||||
if c.Multiplex == nil {
|
||||
c.Multiplex = &vless.Multiplex{Concurrency: 128}
|
||||
}
|
||||
if c.Multiplex.XudpProxyUDP443 == "skip" {
|
||||
return errors.New(`the xdrive transport does not support "xudpProxyUDP443":"skip"`)
|
||||
}
|
||||
if account.Reverse == nil && (c.Multiplex.GetConcurrency() == 0 || c.Multiplex.GetXudpProxyUDP443() == "skip") {
|
||||
return errors.New(`the xdrive transport needs positive "settings.multiplex.concurrency" and does not support "xudpProxyUDP443":"skip"`)
|
||||
}
|
||||
if account.Testpre != 0 {
|
||||
return errors.New(`the xdrive transport doesn't support VLESS "testpre"`)
|
||||
@@ -372,15 +367,10 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to build outbound handler for protocol ", c.Protocol).Base(err)
|
||||
}
|
||||
|
||||
if senderSettings.StreamSettings != nil && senderSettings.StreamSettings.ProtocolName == "splithttp" {
|
||||
if v, ok := ts.(*outbound.Config); ok && v.Multiplex != nil && v.Multiplex.Concurrency != 0 {
|
||||
errors.LogWarning(context.Background(), `ATTENTION: Using VLESS Multiplex over XHTTP XMUX`)
|
||||
}
|
||||
}
|
||||
if err := validateXDrive(ts, senderSettings.StreamSettings, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := validateOutboundTransportSecurity(rawConfig, senderSettings); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math/rand/v2"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/signal"
|
||||
)
|
||||
|
||||
// wait to drain all the possible incoming UDP data
|
||||
// because re-established QUIC UDP may bypass the sniffer
|
||||
func DropUDP(ctx context.Context, reader buf.Reader) {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
timer := signal.CancelAfterInactivity(ctx, func() {
|
||||
cancel()
|
||||
}, time.Duration(30+rand.N(60))*time.Second)
|
||||
context.AfterFunc(ctx, func() {
|
||||
common.Interrupt(reader)
|
||||
})
|
||||
buf.Copy(reader, buf.Discard, buf.UpdateActivity(timer))
|
||||
}
|
||||
+14
-39
@@ -5,7 +5,6 @@ import (
|
||||
go_errors "errors"
|
||||
"io"
|
||||
"math/rand"
|
||||
"slices"
|
||||
|
||||
"github.com/apernet/quic-go"
|
||||
"github.com/xtls/xray-core/common"
|
||||
@@ -175,15 +174,10 @@ func init() {
|
||||
}))
|
||||
}
|
||||
|
||||
// UDPWriter is not safe for concurrent writes.
|
||||
type UDPWriter struct {
|
||||
writer io.Writer
|
||||
addr string
|
||||
buf [buf.Size]byte
|
||||
|
||||
// Last b.UDP and its NetAddr, which allocates on every call.
|
||||
lastUDP net.Destination
|
||||
lastUDPAddr string
|
||||
}
|
||||
|
||||
func (w *UDPWriter) SendMessage(msg *UDPMessage) error {
|
||||
@@ -199,21 +193,21 @@ func (w *UDPWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
for i, b := range mb {
|
||||
addr := w.addr
|
||||
if b.UDP != nil {
|
||||
if *b.UDP != w.lastUDP {
|
||||
w.lastUDP = *b.UDP
|
||||
w.lastUDPAddr = b.UDP.NetAddr()
|
||||
}
|
||||
addr = w.lastUDPAddr
|
||||
addr = b.UDP.NetAddr()
|
||||
}
|
||||
|
||||
msg := &UDPMessage{
|
||||
SessionID: 0,
|
||||
PacketID: 0,
|
||||
FragID: 0,
|
||||
FragCount: 1,
|
||||
Addr: addr,
|
||||
Data: b.Bytes(),
|
||||
}
|
||||
|
||||
err := w.SendMessage(msg)
|
||||
if errTooLarge, ok := go_errors.AsType[*quic.DatagramTooLargeError](err); ok {
|
||||
var errTooLarge *quic.DatagramTooLargeError
|
||||
if go_errors.As(err, &errTooLarge) {
|
||||
msg.PacketID = uint16(rand.Intn(0xFFFF)) + 1
|
||||
fMsgs := FragUDPMessage(msg, int(errTooLarge.MaxDatagramPayloadSize))
|
||||
for _, fMsg := range fMsgs {
|
||||
@@ -234,59 +228,40 @@ func (w *UDPWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// UDPReader is not safe for concurrent reads.
|
||||
type UDPReader struct {
|
||||
reader io.Reader
|
||||
df *Defragger
|
||||
firstBuf *buf.Buffer
|
||||
|
||||
// Last message address and its parsed destination.
|
||||
lastAddr string
|
||||
lastDest net.Destination
|
||||
|
||||
packet [1500]byte
|
||||
msg UDPMessage
|
||||
}
|
||||
|
||||
func (r *UDPReader) ReadFrom(p []byte) (n int, addr *net.Destination, err error) {
|
||||
for {
|
||||
n, err := r.reader.Read(r.packet[:])
|
||||
var packet [1500]byte
|
||||
|
||||
n, err := r.reader.Read(packet[:])
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
|
||||
if err := parseUDPMessage(r.packet[:n], r.lastAddr, &r.msg); err != nil {
|
||||
msg, err := ParseUDPMessage(packet[:n])
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
msg := &r.msg
|
||||
if msg.FragCount > 1 {
|
||||
// The defragger keeps fragments between calls, so they must not alias packet.
|
||||
frag := *msg
|
||||
frag.Data = slices.Clone(msg.Data)
|
||||
msg = &frag
|
||||
}
|
||||
|
||||
dfMsg := r.df.Feed(msg)
|
||||
if dfMsg == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if dfMsg.Addr != r.lastAddr {
|
||||
dest, err := net.ParseDestination("udp:" + dfMsg.Addr)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
r.lastAddr = dfMsg.Addr
|
||||
r.lastDest = dest
|
||||
dest, err := net.ParseDestination("udp:" + dfMsg.Addr)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if len(p) < len(dfMsg.Data) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Callers can rewrite the packet destination in place.
|
||||
dest := r.lastDest
|
||||
return copy(p, dfMsg.Data), &dest, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
package hysteria
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/apernet/quic-go"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
xnet "github.com/xtls/xray-core/common/net"
|
||||
)
|
||||
|
||||
// datagramReader returns one datagram per Read, like a QUIC datagram stream.
|
||||
type datagramReader struct {
|
||||
msgs [][]byte
|
||||
}
|
||||
|
||||
func (r *datagramReader) Read(p []byte) (int, error) {
|
||||
if len(r.msgs) == 0 {
|
||||
return 0, io.EOF
|
||||
}
|
||||
n := copy(p, r.msgs[0])
|
||||
r.msgs = r.msgs[1:]
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func newTestReader(msgs []UDPMessage) *UDPReader {
|
||||
datagrams := make([][]byte, len(msgs))
|
||||
for i := range msgs {
|
||||
datagrams[i] = make([]byte, msgs[i].Size())
|
||||
msgs[i].Serialize(datagrams[i])
|
||||
}
|
||||
return &UDPReader{reader: &datagramReader{msgs: datagrams}, df: &Defragger{}}
|
||||
}
|
||||
|
||||
func TestUDPReaderFragments(t *testing.T) {
|
||||
want := &UDPMessage{PacketID: 1, Addr: "example.com:443", Data: bytes.Repeat([]byte("0123456789"), 20)}
|
||||
frags := FragUDPMessage(want, 100)
|
||||
if len(frags) < 2 {
|
||||
t.Fatalf("got %d fragments, want at least 2", len(frags))
|
||||
}
|
||||
|
||||
p := make([]byte, buf.Size)
|
||||
n, dest, err := newTestReader(frags).ReadFrom(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dest.NetAddr() != want.Addr || !bytes.Equal(p[:n], want.Data) {
|
||||
t.Errorf("got %q to %v, want %q to %s", p[:n], dest, want.Data, want.Addr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUDPReaderDestinations(t *testing.T) {
|
||||
msgs := []UDPMessage{
|
||||
{Addr: "203.0.113.1:53", Data: []byte("first")},
|
||||
{Addr: "203.0.113.1:53", Data: []byte("second")},
|
||||
{Addr: "203.0.113.2:53", Data: []byte("third")},
|
||||
}
|
||||
r := newTestReader(msgs)
|
||||
p := make([]byte, buf.Size)
|
||||
for i, want := range msgs {
|
||||
n, dest, err := r.ReadFrom(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dest.NetAddr() != want.Addr || !bytes.Equal(p[:n], want.Data) {
|
||||
t.Errorf("packet %d: got %q to %v, want %q to %s", i, p[:n], dest, want.Data, want.Addr)
|
||||
}
|
||||
// Callers rewrite the destination in place, the next packet must not see it.
|
||||
dest.Port = 5353
|
||||
}
|
||||
}
|
||||
|
||||
type captureWriter struct {
|
||||
writes [][]byte
|
||||
}
|
||||
|
||||
func (w *captureWriter) Write(p []byte) (int, error) {
|
||||
w.writes = append(w.writes, bytes.Clone(p))
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func TestUDPWriterAddress(t *testing.T) {
|
||||
ip := xnet.UDPDestination(xnet.ParseAddress("203.0.113.1"), 53)
|
||||
domain := xnet.UDPDestination(xnet.DomainAddress("example.com"), 53)
|
||||
|
||||
cw := &captureWriter{}
|
||||
w := &UDPWriter{writer: cw, addr: "198.51.100.1:1"}
|
||||
for _, tc := range []struct {
|
||||
udp *xnet.Destination
|
||||
want string
|
||||
}{
|
||||
{&ip, "203.0.113.1:53"},
|
||||
{&domain, "example.com:53"},
|
||||
{nil, "198.51.100.1:1"},
|
||||
{&ip, "203.0.113.1:53"},
|
||||
} {
|
||||
b := buf.FromBytes([]byte("data"))
|
||||
b.UDP = tc.udp
|
||||
if err := w.WriteMultiBuffer(buf.MultiBuffer{b}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
msg, err := ParseUDPMessage(cw.writes[len(cw.writes)-1])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if msg.Addr != tc.want {
|
||||
t.Errorf("address = %q, want %q", msg.Addr, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fragmentingWriter rejects datagrams larger than max, like a QUIC connection.
|
||||
type fragmentingWriter struct {
|
||||
max int
|
||||
writes [][]byte
|
||||
}
|
||||
|
||||
func (w *fragmentingWriter) Write(p []byte) (int, error) {
|
||||
if len(p) > w.max {
|
||||
return 0, &quic.DatagramTooLargeError{MaxDatagramPayloadSize: int64(w.max)}
|
||||
}
|
||||
w.writes = append(w.writes, bytes.Clone(p))
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func TestUDPWriterFragmentation(t *testing.T) {
|
||||
data := bytes.Repeat([]byte("0123456789"), 20)
|
||||
fw := &fragmentingWriter{max: 100}
|
||||
w := &UDPWriter{writer: fw, addr: "example.com:443"}
|
||||
if err := w.WriteMultiBuffer(buf.MultiBuffer{buf.FromBytes(data)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(fw.writes) < 2 {
|
||||
t.Fatalf("got %d datagrams, want at least 2", len(fw.writes))
|
||||
}
|
||||
|
||||
r := &UDPReader{reader: &datagramReader{msgs: fw.writes}, df: &Defragger{}}
|
||||
p := make([]byte, buf.Size)
|
||||
n, dest, err := r.ReadFrom(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dest.NetAddr() != w.addr || !bytes.Equal(p[:n], data) {
|
||||
t.Errorf("got %q to %v, want %q to %s", p[:n], dest, data, w.addr)
|
||||
}
|
||||
}
|
||||
+20
-28
@@ -1,6 +1,7 @@
|
||||
package hysteria
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -182,44 +183,35 @@ func (m *UDPMessage) Serialize(buf []byte) int {
|
||||
}
|
||||
|
||||
func ParseUDPMessage(msg []byte) (*UDPMessage, error) {
|
||||
m := new(UDPMessage)
|
||||
if err := parseUDPMessage(msg, "", m); err != nil {
|
||||
m := &UDPMessage{}
|
||||
buf := bytes.NewBuffer(msg)
|
||||
if err := binary.Read(buf, binary.BigEndian, &m.SessionID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// parseUDPMessage parses msg into m. m.Data aliases msg; m.Addr is lastAddr
|
||||
// when they are equal, so an unchanged address is not allocated again.
|
||||
func parseUDPMessage(msg []byte, lastAddr string, m *UDPMessage) error {
|
||||
if len(msg) < 8 {
|
||||
return io.ErrUnexpectedEOF
|
||||
if err := binary.Read(buf, binary.BigEndian, &m.PacketID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lAddr, n, err := quicvarint.Parse(msg[8:])
|
||||
if err := binary.Read(buf, binary.BigEndian, &m.FragID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := binary.Read(buf, binary.BigEndian, &m.FragCount); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lAddr, err := quicvarint.Read(buf)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if lAddr == 0 || lAddr > MaxMessageLength {
|
||||
return errors.New("invalid address length")
|
||||
return nil, errors.New("invalid address length")
|
||||
}
|
||||
bs := msg[8+n:]
|
||||
bs := buf.Bytes()
|
||||
if len(bs) <= int(lAddr) {
|
||||
// We use <= instead of < here as we expect at least one byte of data after the address
|
||||
return errors.New("invalid message length")
|
||||
return nil, errors.New("invalid message length")
|
||||
}
|
||||
*m = UDPMessage{
|
||||
SessionID: binary.BigEndian.Uint32(msg),
|
||||
PacketID: binary.BigEndian.Uint16(msg[4:]),
|
||||
FragID: msg[6],
|
||||
FragCount: msg[7],
|
||||
Data: bs[lAddr:],
|
||||
}
|
||||
if string(bs[:lAddr]) == lastAddr {
|
||||
m.Addr = lastAddr
|
||||
} else {
|
||||
m.Addr = string(bs[:lAddr])
|
||||
}
|
||||
return nil
|
||||
m.Addr = string(bs[:lAddr])
|
||||
m.Data = bs[lAddr:]
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// varintPut is like quicvarint.Append, but instead of appending to a slice,
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
package hysteria
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseUDPMessage(t *testing.T) {
|
||||
want := &UDPMessage{PacketID: 1, FragID: 2, FragCount: 3, Addr: "example.com:443", Data: []byte("hello")}
|
||||
msg := make([]byte, want.Size())
|
||||
want.Serialize(msg)
|
||||
|
||||
for _, lastAddr := range []string{"", want.Addr, "other:1"} {
|
||||
got := new(UDPMessage)
|
||||
if err := parseUDPMessage(msg, lastAddr, got); err != nil {
|
||||
t.Fatalf("lastAddr %q: %v", lastAddr, err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("lastAddr %q: got %+v, want %+v", lastAddr, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseUDPMessageInvalid(t *testing.T) {
|
||||
msg := &UDPMessage{Addr: "example.com:443", Data: []byte("hello")}
|
||||
buf := make([]byte, msg.Size())
|
||||
msg.Serialize(buf)
|
||||
|
||||
zeroAddrLen := bytes.Clone(buf)
|
||||
zeroAddrLen[8] = 0 // Address length varint follows the 8-byte header
|
||||
|
||||
noData := &UDPMessage{Addr: msg.Addr}
|
||||
noDataBuf := make([]byte, noData.Size())
|
||||
noData.Serialize(noDataBuf)
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
msg []byte
|
||||
}{
|
||||
{"short header", buf[:7]},
|
||||
{"zero address length", zeroAddrLen},
|
||||
{"no data after address", noDataBuf},
|
||||
} {
|
||||
if _, err := ParseUDPMessage(tc.msg); err == nil {
|
||||
t.Errorf("%s: expected error", tc.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,23 +53,21 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Inbound, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user := &protocol.MemoryUser{
|
||||
Email: config.Email,
|
||||
Level: uint32(config.Level),
|
||||
}
|
||||
|
||||
udpCodec, err := NewUDPServerCodec(method, psk, user, 500*time.Second)
|
||||
udpCodec, err := NewUDPServerCodec(method, psk, 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: user,
|
||||
networks: networks,
|
||||
method: method,
|
||||
psk: psk,
|
||||
saltFilter: antireplay.NewMapFilter[[32]byte](60),
|
||||
user: &protocol.MemoryUser{
|
||||
Email: config.Email,
|
||||
Level: uint32(config.Level),
|
||||
},
|
||||
udpCodec: udpCodec,
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
}, nil
|
||||
@@ -157,12 +155,20 @@ func (i *Inbound) processUDP(ctx context.Context, conn stat.Connection, dispatch
|
||||
}
|
||||
|
||||
for _, b := range mb {
|
||||
sessionItem, decoded, err := i.udpCodec.DecodePacket(b.Bytes())
|
||||
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,6 +2,8 @@ package shadowsocks_2022
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/cipher"
|
||||
"encoding/binary"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -32,15 +34,16 @@ 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]
|
||||
udpCodec *UDPMultiServerCodec
|
||||
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]
|
||||
udpSessions *UDPSessionManager
|
||||
udpMasterCipher cipher.Block
|
||||
policyManager policy.Manager
|
||||
}
|
||||
|
||||
func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiUserInbound, error) {
|
||||
@@ -65,21 +68,22 @@ func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiU
|
||||
return nil, err
|
||||
}
|
||||
|
||||
udpCodec, err := NewUDPMultiServerCodec(method, masterPSK, 500*time.Second)
|
||||
masterBlock, err := method.NewBlock(masterPSK)
|
||||
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),
|
||||
udpCodec: udpCodec,
|
||||
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),
|
||||
udpSessions: NewUDPSessionManager(500 * time.Second),
|
||||
udpMasterCipher: masterBlock,
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
}
|
||||
|
||||
for idx, user := range config.Users {
|
||||
@@ -277,26 +281,68 @@ func (i *MultiUserInbound) processUDP(ctx context.Context, conn stat.Connection,
|
||||
}
|
||||
|
||||
for _, b := range mb {
|
||||
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 {
|
||||
return nil, nil, false
|
||||
}
|
||||
return u, u.Account.(*MemoryAccount).Key, true
|
||||
})
|
||||
b.Release()
|
||||
if err != nil || decoded.HeaderType != HeaderTypeClient {
|
||||
// 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)
|
||||
if !ok {
|
||||
b.Release()
|
||||
continue
|
||||
}
|
||||
currentUser = user
|
||||
userPSK = user.Account.(*MemoryAccount).Key
|
||||
}
|
||||
|
||||
decoded, err := sessionItem.DecryptAESPayload(i.method, userPSK, sessionID, packetID, rawHeader[:], packetBytes[32:])
|
||||
b.Release()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
sessionItem.Lock()
|
||||
if sessionItem.User == nil {
|
||||
sessionItem.User = currentUser
|
||||
sessionItem.UserPSK = userPSK
|
||||
}
|
||||
sessionItem.Unlock()
|
||||
|
||||
link := sessionItem.link.Load()
|
||||
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.udpCodec.EncodeServerPacket(decoded.SessionID, userPSK, replyDest, payload)
|
||||
return i.encodeServerUDPPacket(sessionID, userPSK, replyDest, payload)
|
||||
})
|
||||
if err != nil {
|
||||
continue
|
||||
@@ -310,3 +356,7 @@ func (i *MultiUserInbound) processUDP(ctx context.Context, conn stat.Connection,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (i *MultiUserInbound) encodeServerUDPPacket(clientSessionID uint64, userPSK []byte, dest net.Destination, payload []byte) ([]byte, error) {
|
||||
return i.udpSessions.EncodeServerPacket(i.method, userPSK, clientSessionID, dest, payload)
|
||||
}
|
||||
|
||||
@@ -243,14 +243,16 @@ 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.User = &protocol.MemoryUser{
|
||||
Email: targetDest.email,
|
||||
Level: targetDest.level,
|
||||
sessionItem.Lock()
|
||||
if sessionItem.User == nil {
|
||||
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 *UDPClientCodec
|
||||
udpCodec *UDPPacketCodec
|
||||
policyManager policy.Manager
|
||||
}
|
||||
|
||||
@@ -50,9 +50,9 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Outbound, error) {
|
||||
}
|
||||
|
||||
finalPSK := pskList[len(pskList)-1]
|
||||
udpCodec, err := NewUDPClientCodec(method, pskList)
|
||||
udpCodec, err := NewUDPPacketCodec(method, pskList)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to create udp client codec").Base(err)
|
||||
return nil, errors.New("failed to create udp packet codec").Base(err)
|
||||
}
|
||||
|
||||
v := core.MustFromContext(ctx)
|
||||
|
||||
+143
-288
@@ -7,78 +7,33 @@ 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 UDPClientCodec struct {
|
||||
type UDPCodec 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
|
||||
}
|
||||
|
||||
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),
|
||||
type (
|
||||
UDPPacketCodec = UDPCodec
|
||||
UDPServerCodec = UDPCodec
|
||||
)
|
||||
|
||||
func newUDPCodec(method *CipherMethod, psk []byte) (*UDPCodec, error) {
|
||||
c := &UDPCodec{
|
||||
method: method,
|
||||
psk: psk,
|
||||
}
|
||||
var err error
|
||||
if method.IsChaCha {
|
||||
@@ -92,129 +47,46 @@ func NewUDPServerCodec(method *CipherMethod, psk []byte, user *protocol.MemoryUs
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *UDPServerCodec) Sessions() *UDPSessionManager {
|
||||
return c.sessions
|
||||
}
|
||||
|
||||
func (c *UDPServerCodec) GetSession(sessionID uint64) *ServerUDPSession {
|
||||
if c.sessions == nil {
|
||||
return 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")
|
||||
}
|
||||
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)
|
||||
finalPSK := pskList[len(pskList)-1]
|
||||
c, err := newUDPCodec(method, finalPSK)
|
||||
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
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
return c, 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)
|
||||
func NewUDPServerCodec(method *CipherMethod, psk []byte, sessionTimeout time.Duration) (*UDPCodec, error) {
|
||||
c, err := newUDPCodec(method, psk)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.sessions = NewUDPSessionManager(sessionTimeout)
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *UDPCodec) Sessions() *UDPSessionManager {
|
||||
return c.sessions
|
||||
}
|
||||
|
||||
func (c *UDPCodec) GetSession(sessionID uint64) *ServerUDPSession {
|
||||
if c.sessions == nil {
|
||||
return nil
|
||||
}
|
||||
return c.sessions.GetOrCreate(sessionID)
|
||||
}
|
||||
|
||||
type DecodedUDPPacket struct {
|
||||
@@ -321,42 +193,44 @@ func parsePlainUDPPacket(sessionID, packetID uint64, bodyPlain []byte) (DecodedU
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *UDPServerCodec) DecodePacket(data []byte) (*ServerUDPSession, DecodedUDPPacket, error) {
|
||||
func (c *UDPCodec) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
if len(data) < PacketMinimalHeaderSize {
|
||||
return nil, DecodedUDPPacket{}, ErrPacketTooShort
|
||||
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||
}
|
||||
|
||||
if c.method.IsChaCha {
|
||||
if len(data) < PacketNonceSize+AEADTagSize {
|
||||
return nil, DecodedUDPPacket{}, ErrPacketTooShort
|
||||
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||
}
|
||||
nonce := data[:PacketNonceSize]
|
||||
ciphertext := data[PacketNonceSize:]
|
||||
plain, err := c.chachaCipher.Open(nil, nonce, ciphertext, nil)
|
||||
if err != nil {
|
||||
return nil, DecodedUDPPacket{}, errors.New("failed to decrypt chacha udp packet").Base(err)
|
||||
return DecodedUDPPacket{}, errors.New("failed to decrypt chacha udp packet").Base(err)
|
||||
}
|
||||
if len(plain) < 16+1+8+2 {
|
||||
return nil, DecodedUDPPacket{}, ErrPacketTooShort
|
||||
return 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 nil, DecodedUDPPacket{}, err
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
|
||||
if decoded.HeaderType != HeaderTypeClient {
|
||||
return nil, DecodedUDPPacket{}, ErrBadHeaderType
|
||||
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||
}
|
||||
|
||||
sessionItem := c.sessions.GetOrCreate(sessionID)
|
||||
if !sessionItem.Commit(packetID, nil, c.user, c.psk) {
|
||||
return nil, DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
return sessionItem, decoded, nil
|
||||
sessionItem.AddPacketID(packetID)
|
||||
return decoded, nil
|
||||
}
|
||||
|
||||
// AES mode
|
||||
@@ -365,48 +239,49 @@ func (c *UDPServerCodec) DecodePacket(data []byte) (*ServerUDPSession, DecodedUD
|
||||
sessionID := binary.BigEndian.Uint64(rawHeader[:8])
|
||||
packetID := binary.BigEndian.Uint64(rawHeader[8:16])
|
||||
|
||||
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()
|
||||
sessionItem := c.sessions.GetOrCreate(sessionID)
|
||||
if !sessionItem.CheckPacketID(packetID) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
|
||||
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(c.psk, rawHeader[:8], c.method.KeySaltLength)
|
||||
bodyKey := DeriveSessionSubKey(psk, rawHeader[:8], method.KeySaltLength)
|
||||
var err error
|
||||
bodyAead, err = c.method.NewAEAD(bodyKey)
|
||||
bodyAead, err = method.NewAEAD(bodyKey)
|
||||
if err != nil {
|
||||
return nil, DecodedUDPPacket{}, err
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
isNewCipher = true
|
||||
}
|
||||
|
||||
bodyNonce := rawHeader[4:16]
|
||||
bodyCipher := data[16:]
|
||||
bodyPlain, err := bodyAead.Open(nil, bodyNonce, bodyCipher, nil)
|
||||
if err != nil {
|
||||
return nil, DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err)
|
||||
return DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err)
|
||||
}
|
||||
|
||||
decoded, err := parsePlainUDPPacket(sessionID, packetID, bodyPlain)
|
||||
if err != nil {
|
||||
return nil, DecodedUDPPacket{}, err
|
||||
}
|
||||
if decoded.HeaderType != HeaderTypeClient {
|
||||
return nil, DecodedUDPPacket{}, ErrBadHeaderType
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
|
||||
if sessionItem == nil {
|
||||
sessionItem = c.sessions.GetOrCreate(sessionID)
|
||||
if decoded.HeaderType != HeaderTypeClient {
|
||||
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||
}
|
||||
if !sessionItem.Commit(packetID, bodyAead, c.user, c.psk) {
|
||||
return nil, DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
|
||||
s.AddPacketID(packetID)
|
||||
|
||||
if isNewCipher {
|
||||
s.clientBodyCipher = bodyAead
|
||||
}
|
||||
return sessionItem, decoded, nil
|
||||
|
||||
return decoded, nil
|
||||
}
|
||||
|
||||
func (s *ServerUDPSession) EnsureServerState(method *CipherMethod, psk []byte) error {
|
||||
@@ -428,9 +303,6 @@ 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
|
||||
}
|
||||
|
||||
@@ -515,12 +387,11 @@ func (s *ServerUDPSession) EncodeServerPacket(method *CipherMethod, clientSessio
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (c *UDPServerCodec) EncodeServerPacket(clientSessionID uint64, dest net.Destination, payload []byte) ([]byte, error) {
|
||||
func (c *UDPCodec) EncodeServerPacket(clientSessionID uint64, dest net.Destination, payload []byte) ([]byte, error) {
|
||||
return c.sessions.EncodeServerPacket(c.method, c.psk, clientSessionID, dest, payload)
|
||||
}
|
||||
|
||||
type serverSessionState struct {
|
||||
sync.Mutex
|
||||
sessionID uint64
|
||||
window *SlidingWindow
|
||||
cipher cipher.AEAD
|
||||
@@ -528,24 +399,21 @@ type serverSessionState struct {
|
||||
}
|
||||
|
||||
func (st *serverSessionState) check(packetID uint64) bool {
|
||||
st.Lock()
|
||||
defer st.Unlock()
|
||||
if st.window == nil {
|
||||
st.window = new(SlidingWindow)
|
||||
}
|
||||
return st.window.Check(packetID)
|
||||
}
|
||||
|
||||
func (st *serverSessionState) commit(packetID uint64, now int64) bool {
|
||||
st.Lock()
|
||||
defer st.Unlock()
|
||||
if !st.window.CheckAndAdd(packetID) {
|
||||
return false
|
||||
func (st *serverSessionState) add(packetID uint64) {
|
||||
if st.window == nil {
|
||||
st.window = new(SlidingWindow)
|
||||
}
|
||||
st.lastSeen.Store(now)
|
||||
return true
|
||||
st.window.Add(packetID)
|
||||
}
|
||||
|
||||
type ClientUDPSession struct {
|
||||
mu sync.Mutex
|
||||
codec *UDPClientCodec
|
||||
codec *UDPCodec
|
||||
clientSessionID uint64
|
||||
nextPacketID atomic.Uint64
|
||||
clientBodyCipher cipher.AEAD
|
||||
@@ -553,7 +421,7 @@ type ClientUDPSession struct {
|
||||
old atomic.Pointer[serverSessionState]
|
||||
}
|
||||
|
||||
func (c *UDPClientCodec) NewClientSession() (*ClientUDPSession, error) {
|
||||
func (c *UDPCodec) NewClientSession() (*ClientUDPSession, error) {
|
||||
var sessID [8]byte
|
||||
if _, err := io.ReadFull(rand.Reader, sessID[:]); err != nil {
|
||||
return nil, err
|
||||
@@ -578,43 +446,51 @@ func (c *UDPClientCodec) NewClientSession() (*ClientUDPSession, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *ClientUDPSession) findServerSession(sessionID uint64, now int64) (*serverSessionState, error) {
|
||||
if cur := s.current.Load(); cur != nil && cur.sessionID == sessionID {
|
||||
func (s *ClientUDPSession) getServerSession(sessionID uint64, now int64) (*serverSessionState, error) {
|
||||
cur := s.current.Load()
|
||||
if cur != nil && cur.sessionID == sessionID {
|
||||
return cur, nil
|
||||
}
|
||||
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
|
||||
}
|
||||
// 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")
|
||||
|
||||
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")
|
||||
}
|
||||
return old, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *ClientUDPSession) transitionServerSession(sessionID uint64, cipher cipher.AEAD, now int64) (*serverSessionState, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
// 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")
|
||||
}
|
||||
|
||||
if st, err := s.findServerSession(sessionID, now); st != nil || err != nil {
|
||||
return st, err
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
newState := &serverSessionState{
|
||||
sessionID: sessionID,
|
||||
window: new(SlidingWindow),
|
||||
cipher: cipher,
|
||||
cipher: bodyAead,
|
||||
}
|
||||
newState.lastSeen.Store(now)
|
||||
|
||||
if cur := s.current.Load(); cur != nil {
|
||||
s.old.Store(cur)
|
||||
if cur == nil {
|
||||
s.current.CompareAndSwap(nil, newState)
|
||||
return s.current.Load(), nil
|
||||
}
|
||||
|
||||
s.old.Store(cur)
|
||||
s.current.Store(newState)
|
||||
return newState, nil
|
||||
}
|
||||
@@ -629,7 +505,7 @@ func (s *ClientUDPSession) EncodePacket(dest net.Destination, payload []byte) (*
|
||||
|
||||
var paddingLen int
|
||||
if dest.Port == 53 && len(payload) < MaxPaddingLength {
|
||||
paddingLen = mrand.IntN(MaxPaddingLength-len(payload)) + 1
|
||||
paddingLen = mrand.IntN(MaxPaddingLength) + 1
|
||||
}
|
||||
|
||||
addrPortLen := AddrPortLength(dest)
|
||||
@@ -744,8 +620,6 @@ 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
|
||||
@@ -763,10 +637,20 @@ 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
|
||||
}
|
||||
@@ -774,20 +658,8 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
return DecodedUDPPacket{}, errors.New("client session ID mismatch")
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
st.add(packetID)
|
||||
st.lastSeen.Store(now)
|
||||
|
||||
return decoded, nil
|
||||
}
|
||||
@@ -798,29 +670,19 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
sessionID := binary.BigEndian.Uint64(rawHeader[:8])
|
||||
packetID := binary.BigEndian.Uint64(rawHeader[8:16])
|
||||
|
||||
st, err := s.findServerSession(sessionID, now)
|
||||
now := time.Now().Unix()
|
||||
st, err := s.getServerSession(sessionID, now)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
if !st.check(packetID) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
bodyAead := st.cipher
|
||||
|
||||
bodyNonce := rawHeader[4:16]
|
||||
bodyPlain, err := bodyAead.Open(nil, bodyNonce, data[16:], nil)
|
||||
bodyCipher := data[16:]
|
||||
bodyPlain, err := bodyAead.Open(nil, bodyNonce, bodyCipher, nil)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err)
|
||||
}
|
||||
@@ -829,6 +691,7 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
|
||||
if decoded.HeaderType != HeaderTypeServer {
|
||||
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||
}
|
||||
@@ -836,16 +699,8 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
return DecodedUDPPacket{}, errors.New("client session ID mismatch")
|
||||
}
|
||||
|
||||
if st == nil {
|
||||
st, err = s.transitionServerSession(sessionID, bodyAead, now)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
}
|
||||
|
||||
if !st.commit(packetID, now) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
st.add(packetID)
|
||||
st.lastSeen.Store(now)
|
||||
|
||||
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, nil, 300*time.Second)
|
||||
destCodec, err := NewUDPServerCodec(method, destKey, 300*time.Second)
|
||||
common.Must(err)
|
||||
|
||||
mu.Lock()
|
||||
@@ -202,8 +202,7 @@ func TestRelayUDPSessionStabilityAndDispatch(t *testing.T) {
|
||||
t.Fatalf("expected 2 received packets at destination, got %d", len(pkts))
|
||||
}
|
||||
|
||||
dec1, dec2 := DecodedUDPPacket{}, DecodedUDPPacket{}
|
||||
_, dec1, err = destCodec.DecodePacket(pkts[0])
|
||||
dec1, err := destCodec.DecodePacket(pkts[0])
|
||||
if err != nil {
|
||||
t.Fatalf("dest failed to decode packet 1: %v", err)
|
||||
}
|
||||
@@ -211,7 +210,7 @@ func TestRelayUDPSessionStabilityAndDispatch(t *testing.T) {
|
||||
t.Fatalf("dec1 mismatch: sess=%x, pktID=%d, payload=%s", dec1.SessionID, dec1.PacketID, string(dec1.Payload))
|
||||
}
|
||||
|
||||
_, 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,27 +100,19 @@ 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) Commit(packetID uint64, bodyAead cipher.AEAD, user *protocol.MemoryUser, userPSK []byte) bool {
|
||||
func (s *ServerUDPSession) AddPacketID(packetID uint64) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
if s.User != nil && user != nil && s.User != user {
|
||||
return false
|
||||
if s.Window == nil {
|
||||
s.Window = new(SlidingWindow)
|
||||
}
|
||||
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
|
||||
s.Window.Add(packetID)
|
||||
}
|
||||
|
||||
type UDPSessionManager struct {
|
||||
@@ -136,13 +128,6 @@ func NewUDPSessionManager(timeout time.Duration) *UDPSessionManager {
|
||||
}
|
||||
}
|
||||
|
||||
func (m *UDPSessionManager) Get(sessionID uint64) *ServerUDPSession {
|
||||
if s, ok := m.sessions.Load(sessionID); ok {
|
||||
return s
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *UDPSessionManager) GetOrCreate(sessionID uint64) *ServerUDPSession {
|
||||
now := time.Now().Unix()
|
||||
if s, ok := m.sessions.Load(sessionID); ok {
|
||||
@@ -152,7 +137,6 @@ func (m *UDPSessionManager) GetOrCreate(sessionID uint64) *ServerUDPSession {
|
||||
|
||||
s := &ServerUDPSession{
|
||||
SessionID: sessionID,
|
||||
Window: new(SlidingWindow),
|
||||
manager: m,
|
||||
}
|
||||
s.LastActive.Store(now)
|
||||
|
||||
@@ -63,16 +63,10 @@ func (s *ServerUDPSession) EnsureLink(
|
||||
|
||||
s.currentConn.Store(conn)
|
||||
|
||||
// UDP Session might travel across multiple connections
|
||||
// don't bind its lifetime to a parent context
|
||||
sessCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
|
||||
sessCtx, cancel := context.WithCancel(ctx)
|
||||
inbound := session.InboundFromContext(sessCtx)
|
||||
if inbound != nil {
|
||||
newInbound := *inbound
|
||||
if s.User != nil {
|
||||
newInbound.User = s.User
|
||||
}
|
||||
sessCtx = session.ContextWithInbound(sessCtx, &newInbound)
|
||||
if inbound != nil && s.User != nil {
|
||||
inbound.User = s.User
|
||||
}
|
||||
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, nil, time.Minute)
|
||||
serverCodec, err := NewUDPServerCodec(method, psk, 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, nil, time.Minute)
|
||||
serverCodec, err := NewUDPServerCodec(method, rawKey, 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)-1)*AESBlockSize + RequestHeaderFixedChunkLength + AEADTagSize + varHeaderLen + AEADTagSize)
|
||||
totalHandshakeLen := int32(method.KeySaltLength + len(pskList)*AESBlockSize + RequestHeaderFixedChunkLength + AEADTagSize + varHeaderLen + AEADTagSize)
|
||||
handshakeBuf := buf.NewWithSize(totalHandshakeLen)
|
||||
defer handshakeBuf.Release()
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
)
|
||||
|
||||
@@ -50,18 +49,3 @@ func (updater *InterfaceUpdater) Update() {
|
||||
updater.iface = got
|
||||
errors.LogInfo(context.Background(), "[tun] update interface ", got.Name, " ", got.Index)
|
||||
}
|
||||
|
||||
// ParseGUID parses a canonical textual GUID, as in
|
||||
// "00000000-0000-0000-0000-000000000000", into the 16 bytes it denotes.
|
||||
// The form is all that is accepted, not the other ones uuid.Parse takes,
|
||||
// such as one without hyphens; the length check is what rules those out.
|
||||
func ParseGUID(s string) ([16]byte, error) {
|
||||
if len(s) != 36 {
|
||||
return [16]byte{}, errors.New("invalid guid: ", s, ", want xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
|
||||
}
|
||||
id, err := uuid.Parse(s)
|
||||
if err != nil {
|
||||
return [16]byte{}, errors.New("invalid guid: ", s, ", want xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").Base(err)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
)
|
||||
|
||||
// ParseGUID parses a canonical textual GUID, as in
|
||||
// "00000000-0000-0000-0000-000000000000", into the 16 bytes it denotes.
|
||||
// The form is all that is accepted, not the other ones uuid.Parse takes,
|
||||
// such as one without hyphens; the length check is what rules those out.
|
||||
func ParseGUID(s string) ([16]byte, error) {
|
||||
if len(s) != 36 {
|
||||
return [16]byte{}, errors.New("invalid guid: ", s, ", want xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
|
||||
}
|
||||
id, err := uuid.Parse(s)
|
||||
if err != nil {
|
||||
return [16]byte{}, errors.New("invalid guid: ", s, ", want xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").Base(err)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package tun_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/proxy/tun"
|
||||
)
|
||||
|
||||
func TestParseGUID(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
guid string
|
||||
raw [16]byte
|
||||
}{
|
||||
{"00000000-0000-0000-0000-000000000000", [16]byte{}},
|
||||
{"00010203-0405-0607-0809-0a0b0c0d0e0f", [16]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}},
|
||||
{"6ba7b810-9dad-11d1-80b4-00c04fd430c8", [16]byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}},
|
||||
{"6BA7B810-9DAD-11D1-80B4-00C04FD430C8", [16]byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}},
|
||||
{"ffffffff-ffff-ffff-ffff-ffffffffffff", [16]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
|
||||
} {
|
||||
raw, err := tun.ParseGUID(c.guid)
|
||||
if err != nil {
|
||||
t.Errorf("ParseGUID(%q) failed: %v", c.guid, err)
|
||||
continue
|
||||
}
|
||||
if raw != c.raw {
|
||||
t.Errorf("ParseGUID(%q) = %x, want %x", c.guid, raw, c.raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseGUIDInvalid(t *testing.T) {
|
||||
for _, guid := range []string{
|
||||
"",
|
||||
" ",
|
||||
"xray0",
|
||||
// right characters, wrong places of the hyphens
|
||||
"6ba7b8109-dad-11d1-80b4-00c04fd430c8",
|
||||
"6ba7b810-9dad-11d1-80b4-00c04fd430c",
|
||||
"6ba7b810-9dad-11d1-80b4-00c04fd430c88",
|
||||
"6ba7b810-9dad-11d1-80b4_00c04fd430c8",
|
||||
// not hexadecimal
|
||||
"6ba7b81g-9dad-11d1-80b4-00c04fd430c8",
|
||||
"6ba7b810-9dad-11d1-80b4-00c04fd430cg",
|
||||
// forms other than the canonical one
|
||||
"6ba7b8109dad11d180b400c04fd430c8",
|
||||
"{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
|
||||
"urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8",
|
||||
"6ba7b810-9dad-11d1-80b4-00c04fd430c8 ",
|
||||
} {
|
||||
if raw, err := tun.ParseGUID(guid); err == nil {
|
||||
t.Errorf("ParseGUID(%q) = %x, want an error", guid, raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
//go:build windows
|
||||
|
||||
package tun
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"testing"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
func TestAdapterGUID(t *testing.T) {
|
||||
// a configured GUID has to be the adapter GUID the text names: the groups
|
||||
// are field values, not the bytes of the text in order
|
||||
guid, err := adapterGUID("xray0", "01020304-0506-0708-090a-0b0c0d0e0f10")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := windows.GUID{
|
||||
Data1: 0x01020304,
|
||||
Data2: 0x0506,
|
||||
Data3: 0x0708,
|
||||
Data4: [8]byte{0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10},
|
||||
}
|
||||
if *guid != want {
|
||||
t.Errorf("adapterGUID = %+v, want %+v", *guid, want)
|
||||
}
|
||||
// the same struct Windows builds from that text, and the text Windows shows
|
||||
// for it
|
||||
if fromText, err := windows.GUIDFromString("{01020304-0506-0708-090A-0B0C0D0E0F10}"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if *guid != fromText {
|
||||
t.Errorf("adapterGUID = %s, want %s", guid.String(), fromText.String())
|
||||
}
|
||||
if got, want := guid.String(), "{01020304-0506-0708-090A-0B0C0D0E0F10}"; got != want {
|
||||
t.Errorf("adapterGUID = %s, want %s", got, want)
|
||||
}
|
||||
|
||||
// without one, the bytes of the MD5 of the name, as they always were; that
|
||||
// GUID is never read back as text, so its byte order does not matter
|
||||
guid, err = adapterGUID("xray0", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sum := md5.Sum([]byte("xray0"))
|
||||
if got := unsafe.Slice((*byte)(unsafe.Pointer(guid)), 16); string(got) != string(sum[:]) {
|
||||
t.Errorf("adapterGUID = %x, want %x", got, sum)
|
||||
}
|
||||
|
||||
if _, err := adapterGUID("xray0", "xray0"); err == nil {
|
||||
t.Error("an invalid guid was accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
//go:build freebsd
|
||||
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type probeCall struct {
|
||||
inboundTag string
|
||||
source string
|
||||
address string
|
||||
}
|
||||
|
||||
// stubDNSRouting replaces the routing probe for the duration of a test and
|
||||
// records how it was called, so tests can assert the probe is representative.
|
||||
func stubDNSRouting(t *testing.T, err error) *[]probeCall {
|
||||
t.Helper()
|
||||
original := verifyDNSRouting
|
||||
calls := []probeCall{}
|
||||
verifyDNSRouting = func(_ context.Context, inboundTag, source, address string) error {
|
||||
calls = append(calls, probeCall{inboundTag, source, address})
|
||||
return err
|
||||
}
|
||||
t.Cleanup(func() { verifyDNSRouting = original })
|
||||
return &calls
|
||||
}
|
||||
|
||||
// recorder installs a resolvconf stub for the duration of a test and returns
|
||||
// the captured invocations, each as the arguments followed by the stdin in
|
||||
// angle brackets when there was one. An empty failOn succeeds every call;
|
||||
// otherwise the named subcommand fails.
|
||||
func recorder(t *testing.T, failOn string) *[]string {
|
||||
t.Helper()
|
||||
original := resolvconfRunner
|
||||
calls := []string{}
|
||||
resolvconfRunner = func(stdin string, args ...string) ([]byte, error) {
|
||||
call := strings.Join(args, " ")
|
||||
if stdin != "" {
|
||||
call += " <" + stdin + ">"
|
||||
}
|
||||
calls = append(calls, call)
|
||||
if failOn != "" && len(args) > 0 && args[0] == failOn {
|
||||
return nil, errors.New("boom")
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
t.Cleanup(func() { resolvconfRunner = original })
|
||||
return &calls
|
||||
}
|
||||
|
||||
// files replaces the resolver files read by the applied check for the
|
||||
// duration of a test. A path not in the map does not exist.
|
||||
func files(t *testing.T, contents map[string]string) {
|
||||
t.Helper()
|
||||
original := readResolverFile
|
||||
readResolverFile = func(path string) ([]byte, error) {
|
||||
if data, ok := contents[path]; ok {
|
||||
return []byte(data), nil
|
||||
}
|
||||
return nil, fs.ErrNotExist
|
||||
}
|
||||
t.Cleanup(func() { readResolverFile = original })
|
||||
}
|
||||
|
||||
// takenOver is what the libc subscriber writes once the TUN's nameserver is
|
||||
// the exclusive one.
|
||||
const takenOver = "# Generated by resolvconf\nnameserver 192.168.100.1\n"
|
||||
|
||||
// untouched is the DHCP-supplied resolv.conf that resolvconf=NO leaves in
|
||||
// place.
|
||||
const untouched = "# Generated by resolvconf\nnameserver 10.0.0.1\n"
|
||||
|
||||
func optedInTun() *FreeBSDTun {
|
||||
return &FreeBSDTun{
|
||||
options: &Config{
|
||||
Name: "tun7",
|
||||
Gateway: []string{"192.168.100.1/30"},
|
||||
AutoSystemDnsToGateway: true,
|
||||
},
|
||||
name: "tun7",
|
||||
gateway: netip.MustParsePrefix("192.168.100.1/30"),
|
||||
local: netip.MustParseAddr("192.168.100.2"),
|
||||
}
|
||||
}
|
||||
|
||||
func joined(calls []string) string {
|
||||
return strings.Join(calls, " | ")
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSDisabledByDefault(t *testing.T) {
|
||||
probes := stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.options.AutoSystemDnsToGateway = false
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*calls) != 0 || len(*probes) != 0 {
|
||||
t.Errorf("nothing may run when the option is off, got %q and %d probes", joined(*calls), len(*probes))
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the option is off")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSLeavesOSDNSWhenNoRoute(t *testing.T) {
|
||||
stubDNSRouting(t, errors.New("no route"))
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the probe fails")
|
||||
}
|
||||
if len(*calls) != 0 {
|
||||
t.Errorf("resolvconf must not run when the probe fails, got %q", joined(*calls))
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the probe fails")
|
||||
}
|
||||
}
|
||||
|
||||
// On FreeBSD the addresses are the other way round from Linux: the local
|
||||
// address is the one after the gateway, and the gateway itself has no owner,
|
||||
// so a packet to it is routed into the TUN. The probe has to carry that pair,
|
||||
// and the resolver has to be pointed at the gateway.
|
||||
func TestConfigureSystemDNSProbeCarriesFreeBSDPair(t *testing.T) {
|
||||
probes := stubDNSRouting(t, nil)
|
||||
recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*probes) != 1 {
|
||||
t.Fatalf("expected one probe, got %d", len(*probes))
|
||||
}
|
||||
want := probeCall{"tun", "192.168.100.2", "192.168.100.1"}
|
||||
if (*probes)[0] != want {
|
||||
t.Errorf("probe = %+v, want %+v", (*probes)[0], want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSAppliesResolvconf(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !t1.systemDNSSet {
|
||||
t.Fatal("systemDNSSet should be true after a successful takeover")
|
||||
}
|
||||
|
||||
want := "-a tun7 -x <nameserver 192.168.100.1\n>"
|
||||
if got := joined(*calls); got != want {
|
||||
t.Errorf("resolvconf calls = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// resolvconf exits 0 with resolvconf=NO in resolvconf.conf, and still records
|
||||
// the entry for the interface, but runs no subscriber, so success has to be
|
||||
// confirmed in what the subscribers wrote.
|
||||
func TestConfigureSystemDNSRefusesWhenResolvconfDidNotApply(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the nameserver did not reach a resolver")
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the takeover did not take")
|
||||
}
|
||||
if !strings.HasSuffix(joined(*calls), "-d tun7") {
|
||||
t.Errorf("expected a removal after the failed check, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSIdempotent(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
before := len(*calls)
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*calls) != before {
|
||||
t.Errorf("second call must be a no-op, calls went %d -> %d", before, len(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSAddFailureIsNotDirty(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "-a")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when resolvconf -a fails")
|
||||
}
|
||||
if t1.systemDNSSet || t1.systemDNSDirty {
|
||||
t.Error("a failed add leaves nothing to clean up")
|
||||
}
|
||||
if len(*calls) != 1 {
|
||||
t.Errorf("nothing else may run after a failed add, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
// If the removal after a failed check fails too, the entry may still be
|
||||
// installed, so the state has to be remembered rather than silently dropped.
|
||||
func TestConfigureSystemDNSRollbackFailureKeepsDirty(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
recorder(t, "-d")
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the check fails")
|
||||
}
|
||||
if !t1.systemDNSDirty {
|
||||
t.Error("a failed removal must leave the resolver marked dirty")
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the takeover did not complete")
|
||||
}
|
||||
}
|
||||
|
||||
// A dirty resolver is retried before anything new is applied.
|
||||
func TestConfigureSystemDNSRetriesDirtyBeforeApplying(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.systemDNSDirty = true
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
got := joined(*calls)
|
||||
if !strings.HasPrefix(got, "-d tun7 | -a tun7") {
|
||||
t.Errorf("expected the stale removal first, got %q", got)
|
||||
}
|
||||
if t1.systemDNSDirty {
|
||||
t.Error("a successful retry should clear the dirty flag")
|
||||
}
|
||||
if !t1.systemDNSSet {
|
||||
t.Error("the takeover should proceed once the retry succeeds")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsetSystemDNSRemoves(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("setup failed: %v", err)
|
||||
}
|
||||
*calls = nil
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet should be false after unset")
|
||||
}
|
||||
if got := joined(*calls); got != "-d tun7" {
|
||||
t.Errorf("unset calls = %q, want %q", got, "-d tun7")
|
||||
}
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if len(*calls) != 1 {
|
||||
t.Errorf("unsetSystemDNS must be idempotent, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsetSystemDNSKeepsDirtyWhenRemoveFails(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "-d")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.systemDNSSet = true
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if !t1.systemDNSDirty {
|
||||
t.Error("a failed removal during unset must be remembered")
|
||||
}
|
||||
if got := joined(*calls); got != "-d tun7" {
|
||||
t.Errorf("expected a removal attempt, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedLibc(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("resolv.conf listing the nameserver must count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedNotWhenUntouched(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || ok {
|
||||
t.Errorf("an unchanged resolv.conf and no resolvconf.conf must not count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
// With inclusive_interfaces in resolvconf.conf the exclusive marking is
|
||||
// ignored and the DHCP nameservers stay listed, so the system falls back to
|
||||
// them; that is the leak the option exists to close, and it must not pass.
|
||||
func TestResolvconfAppliedNotWhenOthersRemain(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.1\nnameserver 10.0.0.1\n"})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("another nameserver alongside the TUN's must not count as applied")
|
||||
}
|
||||
}
|
||||
|
||||
// A loopback nameserver alongside is a local resolver that resolvconf feeds
|
||||
// (local_unbound with the libc subscriber left on), not a leak.
|
||||
func TestResolvconfAppliedWithLoopbackAlongside(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 127.0.0.1\nnameserver 192.168.100.1\n"})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("a loopback nameserver alongside must still count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedIgnoresPrefixMatches(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.10\n"})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("192.168.100.10 must not match 192.168.100.1")
|
||||
}
|
||||
}
|
||||
|
||||
// local-unbound-setup turns the libc subscriber off and has resolvconf write
|
||||
// unbound's forwarders instead; resolv.conf then stays pointed at loopback.
|
||||
func TestResolvconfAppliedUnbound(t *testing.T) {
|
||||
files(t, map[string]string{
|
||||
"/etc/resolv.conf": "# Generated by resolvconf\nnameserver 127.0.0.1\noptions edns0\n",
|
||||
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
|
||||
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 192.168.100.1\n",
|
||||
})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("the nameserver in unbound's forwarders must count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedNotWhenUnboundUntouched(t *testing.T) {
|
||||
files(t, map[string]string{
|
||||
"/etc/resolv.conf": "nameserver 127.0.0.1\n",
|
||||
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
|
||||
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 10.0.0.1\n",
|
||||
})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("unbound still forwarding to the old server must not count as applied")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedReportsUnreadableResolvConf(t *testing.T) {
|
||||
files(t, map[string]string{})
|
||||
if _, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err == nil {
|
||||
t.Error("a missing resolv.conf is an error, not a verdict")
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,7 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/net/route"
|
||||
@@ -152,381 +148,3 @@ func TestDefaultRouteFamilyRejectsShortAddrs(t *testing.T) {
|
||||
t.Fatal("message without addresses must not match")
|
||||
}
|
||||
}
|
||||
|
||||
type probeCall struct {
|
||||
inboundTag string
|
||||
source string
|
||||
address string
|
||||
}
|
||||
|
||||
// stubDNSRouting replaces the routing probe for the duration of a test and
|
||||
// records how it was called, so tests can assert the probe is representative.
|
||||
func stubDNSRouting(t *testing.T, err error) *[]probeCall {
|
||||
t.Helper()
|
||||
original := verifyDNSRouting
|
||||
calls := []probeCall{}
|
||||
verifyDNSRouting = func(_ context.Context, inboundTag, source, address string) error {
|
||||
calls = append(calls, probeCall{inboundTag, source, address})
|
||||
return err
|
||||
}
|
||||
t.Cleanup(func() { verifyDNSRouting = original })
|
||||
return &calls
|
||||
}
|
||||
|
||||
// recorder installs a resolvconf stub for the duration of a test and returns
|
||||
// the captured invocations, each as the arguments followed by the stdin in
|
||||
// angle brackets when there was one. An empty failOn succeeds every call;
|
||||
// otherwise the named subcommand fails.
|
||||
func recorder(t *testing.T, failOn string) *[]string {
|
||||
t.Helper()
|
||||
original := resolvconfRunner
|
||||
calls := []string{}
|
||||
resolvconfRunner = func(stdin string, args ...string) ([]byte, error) {
|
||||
call := strings.Join(args, " ")
|
||||
if stdin != "" {
|
||||
call += " <" + stdin + ">"
|
||||
}
|
||||
calls = append(calls, call)
|
||||
if failOn != "" && len(args) > 0 && args[0] == failOn {
|
||||
return nil, errors.New("boom")
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
t.Cleanup(func() { resolvconfRunner = original })
|
||||
return &calls
|
||||
}
|
||||
|
||||
// files replaces the resolver files read by the applied check for the
|
||||
// duration of a test. A path not in the map does not exist.
|
||||
func files(t *testing.T, contents map[string]string) {
|
||||
t.Helper()
|
||||
original := readResolverFile
|
||||
readResolverFile = func(path string) ([]byte, error) {
|
||||
if data, ok := contents[path]; ok {
|
||||
return []byte(data), nil
|
||||
}
|
||||
return nil, fs.ErrNotExist
|
||||
}
|
||||
t.Cleanup(func() { readResolverFile = original })
|
||||
}
|
||||
|
||||
// takenOver is what the libc subscriber writes once the TUN's nameserver is
|
||||
// the exclusive one.
|
||||
const takenOver = "# Generated by resolvconf\nnameserver 192.168.100.1\n"
|
||||
|
||||
// untouched is the DHCP-supplied resolv.conf that resolvconf=NO leaves in
|
||||
// place.
|
||||
const untouched = "# Generated by resolvconf\nnameserver 10.0.0.1\n"
|
||||
|
||||
func optedInTun() *FreeBSDTun {
|
||||
return &FreeBSDTun{
|
||||
options: &Config{
|
||||
Name: "tun7",
|
||||
Gateway: []string{"192.168.100.1/30"},
|
||||
AutoSystemDnsToGateway: true,
|
||||
},
|
||||
name: "tun7",
|
||||
gateway: netip.MustParsePrefix("192.168.100.1/30"),
|
||||
local: netip.MustParseAddr("192.168.100.2"),
|
||||
}
|
||||
}
|
||||
|
||||
func joined(calls []string) string {
|
||||
return strings.Join(calls, " | ")
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSDisabledByDefault(t *testing.T) {
|
||||
probes := stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.options.AutoSystemDnsToGateway = false
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*calls) != 0 || len(*probes) != 0 {
|
||||
t.Errorf("nothing may run when the option is off, got %q and %d probes", joined(*calls), len(*probes))
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the option is off")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSLeavesOSDNSWhenNoRoute(t *testing.T) {
|
||||
stubDNSRouting(t, errors.New("no route"))
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the probe fails")
|
||||
}
|
||||
if len(*calls) != 0 {
|
||||
t.Errorf("resolvconf must not run when the probe fails, got %q", joined(*calls))
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the probe fails")
|
||||
}
|
||||
}
|
||||
|
||||
// On FreeBSD the addresses are the other way round from Linux: the local
|
||||
// address is the one after the gateway, and the gateway itself has no owner,
|
||||
// so a packet to it is routed into the TUN. The probe has to carry that pair,
|
||||
// and the resolver has to be pointed at the gateway.
|
||||
func TestConfigureSystemDNSProbeCarriesFreeBSDPair(t *testing.T) {
|
||||
probes := stubDNSRouting(t, nil)
|
||||
recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*probes) != 1 {
|
||||
t.Fatalf("expected one probe, got %d", len(*probes))
|
||||
}
|
||||
want := probeCall{"tun", "192.168.100.2", "192.168.100.1"}
|
||||
if (*probes)[0] != want {
|
||||
t.Errorf("probe = %+v, want %+v", (*probes)[0], want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSAppliesResolvconf(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !t1.systemDNSSet {
|
||||
t.Fatal("systemDNSSet should be true after a successful takeover")
|
||||
}
|
||||
|
||||
want := "-a tun7 -x <nameserver 192.168.100.1\n>"
|
||||
if got := joined(*calls); got != want {
|
||||
t.Errorf("resolvconf calls = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// resolvconf exits 0 with resolvconf=NO in resolvconf.conf, and still records
|
||||
// the entry for the interface, but runs no subscriber, so success has to be
|
||||
// confirmed in what the subscribers wrote.
|
||||
func TestConfigureSystemDNSRefusesWhenResolvconfDidNotApply(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the nameserver did not reach a resolver")
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the takeover did not take")
|
||||
}
|
||||
if !strings.HasSuffix(joined(*calls), "-d tun7") {
|
||||
t.Errorf("expected a removal after the failed check, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSIdempotent(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
before := len(*calls)
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*calls) != before {
|
||||
t.Errorf("second call must be a no-op, calls went %d -> %d", before, len(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSAddFailureIsNotDirty(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "-a")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when resolvconf -a fails")
|
||||
}
|
||||
if t1.systemDNSSet || t1.systemDNSDirty {
|
||||
t.Error("a failed add leaves nothing to clean up")
|
||||
}
|
||||
if len(*calls) != 1 {
|
||||
t.Errorf("nothing else may run after a failed add, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
// If the removal after a failed check fails too, the entry may still be
|
||||
// installed, so the state has to be remembered rather than silently dropped.
|
||||
func TestConfigureSystemDNSRollbackFailureKeepsDirty(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
recorder(t, "-d")
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the check fails")
|
||||
}
|
||||
if !t1.systemDNSDirty {
|
||||
t.Error("a failed removal must leave the resolver marked dirty")
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the takeover did not complete")
|
||||
}
|
||||
}
|
||||
|
||||
// A dirty resolver is retried before anything new is applied.
|
||||
func TestConfigureSystemDNSRetriesDirtyBeforeApplying(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.systemDNSDirty = true
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
got := joined(*calls)
|
||||
if !strings.HasPrefix(got, "-d tun7 | -a tun7") {
|
||||
t.Errorf("expected the stale removal first, got %q", got)
|
||||
}
|
||||
if t1.systemDNSDirty {
|
||||
t.Error("a successful retry should clear the dirty flag")
|
||||
}
|
||||
if !t1.systemDNSSet {
|
||||
t.Error("the takeover should proceed once the retry succeeds")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsetSystemDNSRemoves(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("setup failed: %v", err)
|
||||
}
|
||||
*calls = nil
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet should be false after unset")
|
||||
}
|
||||
if got := joined(*calls); got != "-d tun7" {
|
||||
t.Errorf("unset calls = %q, want %q", got, "-d tun7")
|
||||
}
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if len(*calls) != 1 {
|
||||
t.Errorf("unsetSystemDNS must be idempotent, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsetSystemDNSKeepsDirtyWhenRemoveFails(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "-d")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.systemDNSSet = true
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if !t1.systemDNSDirty {
|
||||
t.Error("a failed removal during unset must be remembered")
|
||||
}
|
||||
if got := joined(*calls); got != "-d tun7" {
|
||||
t.Errorf("expected a removal attempt, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedLibc(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("resolv.conf listing the nameserver must count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedNotWhenUntouched(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || ok {
|
||||
t.Errorf("an unchanged resolv.conf and no resolvconf.conf must not count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
// With inclusive_interfaces in resolvconf.conf the exclusive marking is
|
||||
// ignored and the DHCP nameservers stay listed, so the system falls back to
|
||||
// them; that is the leak the option exists to close, and it must not pass.
|
||||
func TestResolvconfAppliedNotWhenOthersRemain(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.1\nnameserver 10.0.0.1\n"})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("another nameserver alongside the TUN's must not count as applied")
|
||||
}
|
||||
}
|
||||
|
||||
// A loopback nameserver alongside is a local resolver that resolvconf feeds
|
||||
// (local_unbound with the libc subscriber left on), not a leak.
|
||||
func TestResolvconfAppliedWithLoopbackAlongside(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 127.0.0.1\nnameserver 192.168.100.1\n"})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("a loopback nameserver alongside must still count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedIgnoresPrefixMatches(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.10\n"})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("192.168.100.10 must not match 192.168.100.1")
|
||||
}
|
||||
}
|
||||
|
||||
// local-unbound-setup turns the libc subscriber off and has resolvconf write
|
||||
// unbound's forwarders instead; resolv.conf then stays pointed at loopback.
|
||||
func TestResolvconfAppliedUnbound(t *testing.T) {
|
||||
files(t, map[string]string{
|
||||
"/etc/resolv.conf": "# Generated by resolvconf\nnameserver 127.0.0.1\noptions edns0\n",
|
||||
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
|
||||
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 192.168.100.1\n",
|
||||
})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("the nameserver in unbound's forwarders must count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedNotWhenUnboundUntouched(t *testing.T) {
|
||||
files(t, map[string]string{
|
||||
"/etc/resolv.conf": "nameserver 127.0.0.1\n",
|
||||
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
|
||||
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 10.0.0.1\n",
|
||||
})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("unbound still forwarding to the old server must not count as applied")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedReportsUnreadableResolvConf(t *testing.T) {
|
||||
files(t, map[string]string{})
|
||||
if _, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err == nil {
|
||||
t.Error("a missing resolv.conf is an error, not a verdict")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
//go:build linux && !android
|
||||
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/app/dispatcher"
|
||||
appdns "github.com/xtls/xray-core/app/dns"
|
||||
"github.com/xtls/xray-core/app/proxyman"
|
||||
_ "github.com/xtls/xray-core/app/proxyman/inbound"
|
||||
_ "github.com/xtls/xray-core/app/proxyman/outbound"
|
||||
"github.com/xtls/xray-core/app/router"
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/core"
|
||||
proxydns "github.com/xtls/xray-core/proxy/dns"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
)
|
||||
|
||||
const (
|
||||
routeTestInboundTag = "tun"
|
||||
routeTestSource = "192.168.100.1"
|
||||
routeTestDNSAddress = "192.168.100.2"
|
||||
)
|
||||
|
||||
// port53Rule sends DNS queries arriving from the interface to the dns outbound.
|
||||
func port53Rule() *router.RoutingRule {
|
||||
return &router.RoutingRule{
|
||||
InboundTag: []string{routeTestInboundTag},
|
||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(53)}},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "dns"},
|
||||
}
|
||||
}
|
||||
|
||||
// sourceBlockRule diverts traffic from one address, which is the shape of a rule
|
||||
// that only matches because the real request carries a source.
|
||||
func sourceBlockRule(ip []byte) *router.RoutingRule {
|
||||
return &router.RoutingRule{
|
||||
SourceIp: []*geodata.IPRule{{
|
||||
Value: &geodata.IPRule_Custom{
|
||||
Custom: &geodata.CIDRRule{
|
||||
Cidr: &geodata.CIDR{Ip: ip, Prefix: 32},
|
||||
},
|
||||
},
|
||||
}},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "block"},
|
||||
}
|
||||
}
|
||||
|
||||
// newRouteTestContext builds a real but unstarted instance: no TUN device, no
|
||||
// running resolver. The instance is placed in the context through the key core
|
||||
// exports for tests.
|
||||
func newRouteTestContext(t *testing.T, withDNSApp bool, nameServers []*appdns.NameServer, rules []*router.RoutingRule) context.Context {
|
||||
t.Helper()
|
||||
|
||||
apps := []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&dispatcher.Config{}),
|
||||
serial.ToTypedMessage(&proxyman.InboundConfig{}),
|
||||
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
|
||||
serial.ToTypedMessage(&router.Config{Rule: rules}),
|
||||
}
|
||||
if withDNSApp {
|
||||
apps = append(apps, serial.ToTypedMessage(&appdns.Config{NameServer: nameServers}))
|
||||
}
|
||||
|
||||
instance, err := core.New(&core.Config{
|
||||
App: apps,
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})},
|
||||
{Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})},
|
||||
{Tag: "block", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("core.New: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = instance.Close() })
|
||||
|
||||
return context.WithValue(context.Background(), core.XrayKey(1), instance)
|
||||
}
|
||||
|
||||
func udpNameServer(ip []byte) []*appdns.NameServer {
|
||||
return []*appdns.NameServer{{
|
||||
Address: &net.Endpoint{
|
||||
Network: net.Network_UDP,
|
||||
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Ip{Ip: ip}},
|
||||
Port: 53,
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
// localNameServer is a name server pointed at "localhost", which app/dns
|
||||
// resolves through the system resolver.
|
||||
func localNameServer() *appdns.NameServer {
|
||||
return &appdns.NameServer{
|
||||
Address: &net.Endpoint{
|
||||
Network: net.Network_UDP,
|
||||
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Domain{Domain: "localhost"}},
|
||||
Port: 53,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// These drive the real feature lookup and the real router. verifyDNSRouting is
|
||||
// the same function ConfigureSystemDNS calls, so a false positive here is a
|
||||
// false positive in the takeover decision itself, which is what assertions on
|
||||
// the resolvectl arguments could never catch.
|
||||
func TestVerifyDNSRoutingDecisions(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
withDNSApp bool
|
||||
nameServers []*appdns.NameServer
|
||||
rules []*router.RoutingRule
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "independent upstream reaches the dns outbound",
|
||||
withDNSApp: true,
|
||||
nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "no dns section falls back to the system resolver",
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
name: "dns section without name servers falls back too",
|
||||
withDNSApp: true,
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
// An independent upstream is not enough on its own: name servers are
|
||||
// selected per domain, so a local one can still be the one chosen.
|
||||
// The refusal is deliberately domain-agnostic for that reason.
|
||||
name: "a local name server alongside an independent one",
|
||||
withDNSApp: true,
|
||||
nameServers: append(udpNameServer([]byte{9, 9, 9, 9}), localNameServer()),
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
name: "a rule on the interface address diverts the real query",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{
|
||||
sourceBlockRule([]byte{192, 168, 100, 1}),
|
||||
port53Rule(),
|
||||
},
|
||||
wantErr: "does not handle DNS",
|
||||
},
|
||||
{
|
||||
name: "a rule on another address does not match it",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{
|
||||
sourceBlockRule([]byte{10, 0, 0, 1}),
|
||||
port53Rule(),
|
||||
},
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "no rule matches the query",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
wantErr: "no route",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := newRouteTestContext(t, tt.withDNSApp, tt.nameServers, tt.rules)
|
||||
err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, routeTestDNSAddress)
|
||||
|
||||
if tt.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("expected the takeover to be accepted, got: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatalf("expected the takeover to be refused with %q, got nil", tt.wantErr)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Errorf("error = %q, want it to contain %q", err.Error(), tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Without an IPv4 gateway, the takeover uses the first IPv6 one, and the probe
|
||||
// carries IPv6 addresses.
|
||||
func TestVerifyDNSRoutingIPv6(t *testing.T) {
|
||||
ctx := newRouteTestContext(t, true, udpNameServer([]byte{9, 9, 9, 9}), []*router.RoutingRule{port53Rule()})
|
||||
if err := verifyDNSRouting(ctx, routeTestInboundTag, "fc00::1", "fc00::2"); err != nil {
|
||||
t.Fatalf("expected the takeover to be accepted, got: %v", err)
|
||||
}
|
||||
if err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, "fc00::2"); err == nil {
|
||||
t.Fatal("expected mixed IPv4 and IPv6 addresses to be refused")
|
||||
}
|
||||
}
|
||||
@@ -9,18 +9,6 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/vishvananda/netlink"
|
||||
"github.com/xtls/xray-core/app/dispatcher"
|
||||
appdns "github.com/xtls/xray-core/app/dns"
|
||||
"github.com/xtls/xray-core/app/proxyman"
|
||||
_ "github.com/xtls/xray-core/app/proxyman/inbound"
|
||||
_ "github.com/xtls/xray-core/app/proxyman/outbound"
|
||||
"github.com/xtls/xray-core/app/router"
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/core"
|
||||
proxydns "github.com/xtls/xray-core/proxy/dns"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
)
|
||||
|
||||
// testLink returns a minimal netlink.Link whose Attrs().Name is name, so the
|
||||
@@ -455,185 +443,3 @@ func TestBuildResolvectlArgs(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
routeTestInboundTag = "tun"
|
||||
routeTestSource = "192.168.100.1"
|
||||
routeTestDNSAddress = "192.168.100.2"
|
||||
)
|
||||
|
||||
// port53Rule sends DNS queries arriving from the interface to the dns outbound.
|
||||
func port53Rule() *router.RoutingRule {
|
||||
return &router.RoutingRule{
|
||||
InboundTag: []string{routeTestInboundTag},
|
||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(53)}},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "dns"},
|
||||
}
|
||||
}
|
||||
|
||||
// sourceBlockRule diverts traffic from one address, which is the shape of a rule
|
||||
// that only matches because the real request carries a source.
|
||||
func sourceBlockRule(ip []byte) *router.RoutingRule {
|
||||
return &router.RoutingRule{
|
||||
SourceIp: []*geodata.IPRule{{
|
||||
Value: &geodata.IPRule_Custom{
|
||||
Custom: &geodata.CIDRRule{
|
||||
Cidr: &geodata.CIDR{Ip: ip, Prefix: 32},
|
||||
},
|
||||
},
|
||||
}},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "block"},
|
||||
}
|
||||
}
|
||||
|
||||
// newRouteTestContext builds a real but unstarted instance: no TUN device, no
|
||||
// running resolver. The instance is placed in the context through the key core
|
||||
// exports for tests.
|
||||
func newRouteTestContext(t *testing.T, withDNSApp bool, nameServers []*appdns.NameServer, rules []*router.RoutingRule) context.Context {
|
||||
t.Helper()
|
||||
|
||||
apps := []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&dispatcher.Config{}),
|
||||
serial.ToTypedMessage(&proxyman.InboundConfig{}),
|
||||
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
|
||||
serial.ToTypedMessage(&router.Config{Rule: rules}),
|
||||
}
|
||||
if withDNSApp {
|
||||
apps = append(apps, serial.ToTypedMessage(&appdns.Config{NameServer: nameServers}))
|
||||
}
|
||||
|
||||
instance, err := core.New(&core.Config{
|
||||
App: apps,
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})},
|
||||
{Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})},
|
||||
{Tag: "block", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("core.New: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = instance.Close() })
|
||||
|
||||
return context.WithValue(context.Background(), core.XrayKey(1), instance)
|
||||
}
|
||||
|
||||
func udpNameServer(ip []byte) []*appdns.NameServer {
|
||||
return []*appdns.NameServer{{
|
||||
Address: &net.Endpoint{
|
||||
Network: net.Network_UDP,
|
||||
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Ip{Ip: ip}},
|
||||
Port: 53,
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
// localNameServer is a name server pointed at "localhost", which app/dns
|
||||
// resolves through the system resolver.
|
||||
func localNameServer() *appdns.NameServer {
|
||||
return &appdns.NameServer{
|
||||
Address: &net.Endpoint{
|
||||
Network: net.Network_UDP,
|
||||
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Domain{Domain: "localhost"}},
|
||||
Port: 53,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// These drive the real feature lookup and the real router. verifyDNSRouting is
|
||||
// the same function ConfigureSystemDNS calls, so a false positive here is a
|
||||
// false positive in the takeover decision itself, which is what assertions on
|
||||
// the resolvectl arguments could never catch.
|
||||
func TestVerifyDNSRoutingDecisions(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
withDNSApp bool
|
||||
nameServers []*appdns.NameServer
|
||||
rules []*router.RoutingRule
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "independent upstream reaches the dns outbound",
|
||||
withDNSApp: true,
|
||||
nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "no dns section falls back to the system resolver",
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
name: "dns section without name servers falls back too",
|
||||
withDNSApp: true,
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
// An independent upstream is not enough on its own: name servers are
|
||||
// selected per domain, so a local one can still be the one chosen.
|
||||
// The refusal is deliberately domain-agnostic for that reason.
|
||||
name: "a local name server alongside an independent one",
|
||||
withDNSApp: true,
|
||||
nameServers: append(udpNameServer([]byte{9, 9, 9, 9}), localNameServer()),
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
name: "a rule on the interface address diverts the real query",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{
|
||||
sourceBlockRule([]byte{192, 168, 100, 1}),
|
||||
port53Rule(),
|
||||
},
|
||||
wantErr: "does not handle DNS",
|
||||
},
|
||||
{
|
||||
name: "a rule on another address does not match it",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{
|
||||
sourceBlockRule([]byte{10, 0, 0, 1}),
|
||||
port53Rule(),
|
||||
},
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "no rule matches the query",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
wantErr: "no route",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := newRouteTestContext(t, tt.withDNSApp, tt.nameServers, tt.rules)
|
||||
err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, routeTestDNSAddress)
|
||||
|
||||
if tt.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("expected the takeover to be accepted, got: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatalf("expected the takeover to be refused with %q, got nil", tt.wantErr)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Errorf("error = %q, want it to contain %q", err.Error(), tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Without an IPv4 gateway, the takeover uses the first IPv6 one, and the probe
|
||||
// carries IPv6 addresses.
|
||||
func TestVerifyDNSRoutingIPv6(t *testing.T) {
|
||||
ctx := newRouteTestContext(t, true, udpNameServer([]byte{9, 9, 9, 9}), []*router.RoutingRule{port53Rule()})
|
||||
if err := verifyDNSRouting(ctx, routeTestInboundTag, "fc00::1", "fc00::2"); err != nil {
|
||||
t.Fatalf("expected the takeover to be accepted, got: %v", err)
|
||||
}
|
||||
if err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, "fc00::2"); err == nil {
|
||||
t.Fatal("expected mixed IPv4 and IPv6 addresses to be refused")
|
||||
}
|
||||
}
|
||||
@@ -710,109 +710,3 @@ func findOutboundInterface(tunIndex int, fixedName string) (*net.Interface, erro
|
||||
}
|
||||
return net.InterfaceByIndex(int(index))
|
||||
}
|
||||
|
||||
// outboundGuard keeps Windows to the binding of autoOutboundsInterface, which
|
||||
// keeps Xray's own connections out of the TUN. With weak host send or
|
||||
// forwarding on for an IP version on the bound interface, Windows sends them
|
||||
// where the routes lead, into the TUN, from that interface's address, and
|
||||
// drops what comes back to that address through the TUN, so they stall.
|
||||
//
|
||||
// For the IP versions routed to the TUN, weak host send is turned off on the
|
||||
// bound interface while the TUN runs, and turned on again when the TUN stops
|
||||
// or another interface takes over. Forwarding is what Mobile Hotspot and
|
||||
// Internet Connection Sharing need, so it is only reported.
|
||||
type outboundGuard struct {
|
||||
sync.Mutex
|
||||
families []winipcfg.AddressFamily
|
||||
luid winipcfg.LUID // of the interface last checked
|
||||
name string // of that interface
|
||||
turnedOff []winipcfg.AddressFamily // where weak host send was turned off on it
|
||||
forwarding bool // whether forwarding was on there
|
||||
stopped bool
|
||||
}
|
||||
|
||||
// check turns weak host send off on the bound interface, and warns when
|
||||
// forwarding comes on there, but not again while it stays on.
|
||||
func (g *outboundGuard) check() {
|
||||
g.Lock()
|
||||
defer g.Unlock()
|
||||
if g.stopped {
|
||||
return
|
||||
}
|
||||
var luid winipcfg.LUID
|
||||
var name string
|
||||
if iface := updater.Get(); iface != nil {
|
||||
luid, _ = winipcfg.LUIDFromIndex(uint32(iface.Index))
|
||||
name = iface.Name
|
||||
}
|
||||
if luid != g.luid {
|
||||
g.restoreLocked()
|
||||
g.luid, g.name = luid, name
|
||||
g.forwarding = false // to warn about the new interface as well
|
||||
}
|
||||
if luid == 0 {
|
||||
return
|
||||
}
|
||||
var forwarding []string
|
||||
for _, family := range g.families {
|
||||
row, err := luid.IPInterface(family)
|
||||
if err != nil {
|
||||
continue // the interface lacks that IP version
|
||||
}
|
||||
if row.ForwardingEnabled {
|
||||
forwarding = append(forwarding, familyName(family))
|
||||
}
|
||||
if !row.WeakHostSend {
|
||||
continue
|
||||
}
|
||||
if err := setWeakHostSend(row, false); err != nil {
|
||||
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send off for ", familyName(family), " on ", name)
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(g.turnedOff, family) {
|
||||
g.turnedOff = append(g.turnedOff, family)
|
||||
errors.LogInfo(context.Background(), "[tun] weak host send turned off for ", familyName(family), " on ", name, " while the TUN runs, as Windows would ignore autoOutboundsInterface")
|
||||
}
|
||||
}
|
||||
wasOn := g.forwarding
|
||||
g.forwarding = len(forwarding) > 0
|
||||
if g.forwarding && !wasOn {
|
||||
errors.LogWarning(context.Background(), "[tun] forwarding is on for ", strings.Join(forwarding, " and "), " on ", name, " (Mobile Hotspot and Internet Connection Sharing turn it on), so Windows ignores autoOutboundsInterface there, and Xray's own connections go into the TUN and stall: turn the hotspot off, or have it share the TUN instead of ", name)
|
||||
}
|
||||
}
|
||||
|
||||
// restore turns weak host send on again where check turned it off, for good.
|
||||
func (g *outboundGuard) restore() {
|
||||
g.Lock()
|
||||
defer g.Unlock()
|
||||
g.restoreLocked()
|
||||
g.stopped = true
|
||||
}
|
||||
|
||||
func (g *outboundGuard) restoreLocked() {
|
||||
for _, family := range g.turnedOff {
|
||||
row, err := g.luid.IPInterface(family)
|
||||
if err == nil {
|
||||
err = setWeakHostSend(row, true)
|
||||
}
|
||||
if err != nil {
|
||||
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send on again for ", familyName(family), " on ", g.name)
|
||||
}
|
||||
}
|
||||
g.turnedOff = nil
|
||||
}
|
||||
|
||||
func setWeakHostSend(row *winipcfg.MibIPInterfaceRow, on bool) error {
|
||||
row.WeakHostSend = on
|
||||
if row.Family == windows.AF_INET {
|
||||
row.SitePrefixLength = 0 // as SetIpInterfaceEntry requires for IPv4
|
||||
}
|
||||
return row.Set()
|
||||
}
|
||||
|
||||
func familyName(family winipcfg.AddressFamily) string {
|
||||
if family == windows.AF_INET {
|
||||
return "IPv4"
|
||||
}
|
||||
return "IPv6"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
//go:build windows
|
||||
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"golang.org/x/sys/windows"
|
||||
"golang.zx2c4.com/wireguard/windows/tunnel/winipcfg"
|
||||
)
|
||||
|
||||
// outboundGuard keeps Windows to the binding of autoOutboundsInterface, which
|
||||
// keeps Xray's own connections out of the TUN. With weak host send or
|
||||
// forwarding on for an IP version on the bound interface, Windows sends them
|
||||
// where the routes lead, into the TUN, from that interface's address, and
|
||||
// drops what comes back to that address through the TUN, so they stall.
|
||||
//
|
||||
// For the IP versions routed to the TUN, weak host send is turned off on the
|
||||
// bound interface while the TUN runs, and turned on again when the TUN stops
|
||||
// or another interface takes over. Forwarding is what Mobile Hotspot and
|
||||
// Internet Connection Sharing need, so it is only reported.
|
||||
type outboundGuard struct {
|
||||
sync.Mutex
|
||||
families []winipcfg.AddressFamily
|
||||
luid winipcfg.LUID // of the interface last checked
|
||||
name string // of that interface
|
||||
turnedOff []winipcfg.AddressFamily // where weak host send was turned off on it
|
||||
forwarding bool // whether forwarding was on there
|
||||
stopped bool
|
||||
}
|
||||
|
||||
// check turns weak host send off on the bound interface, and warns when
|
||||
// forwarding comes on there, but not again while it stays on.
|
||||
func (g *outboundGuard) check() {
|
||||
g.Lock()
|
||||
defer g.Unlock()
|
||||
if g.stopped {
|
||||
return
|
||||
}
|
||||
var luid winipcfg.LUID
|
||||
var name string
|
||||
if iface := updater.Get(); iface != nil {
|
||||
luid, _ = winipcfg.LUIDFromIndex(uint32(iface.Index))
|
||||
name = iface.Name
|
||||
}
|
||||
if luid != g.luid {
|
||||
g.restoreLocked()
|
||||
g.luid, g.name = luid, name
|
||||
g.forwarding = false // to warn about the new interface as well
|
||||
}
|
||||
if luid == 0 {
|
||||
return
|
||||
}
|
||||
var forwarding []string
|
||||
for _, family := range g.families {
|
||||
row, err := luid.IPInterface(family)
|
||||
if err != nil {
|
||||
continue // the interface lacks that IP version
|
||||
}
|
||||
if row.ForwardingEnabled {
|
||||
forwarding = append(forwarding, familyName(family))
|
||||
}
|
||||
if !row.WeakHostSend {
|
||||
continue
|
||||
}
|
||||
if err := setWeakHostSend(row, false); err != nil {
|
||||
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send off for ", familyName(family), " on ", name)
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(g.turnedOff, family) {
|
||||
g.turnedOff = append(g.turnedOff, family)
|
||||
errors.LogInfo(context.Background(), "[tun] weak host send turned off for ", familyName(family), " on ", name, " while the TUN runs, as Windows would ignore autoOutboundsInterface")
|
||||
}
|
||||
}
|
||||
wasOn := g.forwarding
|
||||
g.forwarding = len(forwarding) > 0
|
||||
if g.forwarding && !wasOn {
|
||||
errors.LogWarning(context.Background(), "[tun] forwarding is on for ", strings.Join(forwarding, " and "), " on ", name, " (Mobile Hotspot and Internet Connection Sharing turn it on), so Windows ignores autoOutboundsInterface there, and Xray's own connections go into the TUN and stall: turn the hotspot off, or have it share the TUN instead of ", name)
|
||||
}
|
||||
}
|
||||
|
||||
// restore turns weak host send on again where check turned it off, for good.
|
||||
func (g *outboundGuard) restore() {
|
||||
g.Lock()
|
||||
defer g.Unlock()
|
||||
g.restoreLocked()
|
||||
g.stopped = true
|
||||
}
|
||||
|
||||
func (g *outboundGuard) restoreLocked() {
|
||||
for _, family := range g.turnedOff {
|
||||
row, err := g.luid.IPInterface(family)
|
||||
if err == nil {
|
||||
err = setWeakHostSend(row, true)
|
||||
}
|
||||
if err != nil {
|
||||
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send on again for ", familyName(family), " on ", g.name)
|
||||
}
|
||||
}
|
||||
g.turnedOff = nil
|
||||
}
|
||||
|
||||
func setWeakHostSend(row *winipcfg.MibIPInterfaceRow, on bool) error {
|
||||
row.WeakHostSend = on
|
||||
if row.Family == windows.AF_INET {
|
||||
row.SitePrefixLength = 0 // as SetIpInterfaceEntry requires for IPv4
|
||||
}
|
||||
return row.Set()
|
||||
}
|
||||
|
||||
func familyName(family winipcfg.AddressFamily) string {
|
||||
if family == windows.AF_INET {
|
||||
return "IPv4"
|
||||
}
|
||||
return "IPv6"
|
||||
}
|
||||
@@ -4,7 +4,6 @@ package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
go_errors "errors"
|
||||
"net"
|
||||
"net/netip"
|
||||
@@ -341,46 +340,3 @@ func TestFlushDNSCache(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdapterGUID(t *testing.T) {
|
||||
// a configured GUID has to be the adapter GUID the text names: the groups
|
||||
// are field values, not the bytes of the text in order
|
||||
guid, err := adapterGUID("xray0", "01020304-0506-0708-090a-0b0c0d0e0f10")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := windows.GUID{
|
||||
Data1: 0x01020304,
|
||||
Data2: 0x0506,
|
||||
Data3: 0x0708,
|
||||
Data4: [8]byte{0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10},
|
||||
}
|
||||
if *guid != want {
|
||||
t.Errorf("adapterGUID = %+v, want %+v", *guid, want)
|
||||
}
|
||||
// the same struct Windows builds from that text, and the text Windows shows
|
||||
// for it
|
||||
if fromText, err := windows.GUIDFromString("{01020304-0506-0708-090A-0B0C0D0E0F10}"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if *guid != fromText {
|
||||
t.Errorf("adapterGUID = %s, want %s", guid.String(), fromText.String())
|
||||
}
|
||||
if got, want := guid.String(), "{01020304-0506-0708-090A-0B0C0D0E0F10}"; got != want {
|
||||
t.Errorf("adapterGUID = %s, want %s", got, want)
|
||||
}
|
||||
|
||||
// without one, the bytes of the MD5 of the name, as they always were; that
|
||||
// GUID is never read back as text, so its byte order does not matter
|
||||
guid, err = adapterGUID("xray0", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sum := md5.Sum([]byte("xray0"))
|
||||
if got := unsafe.Slice((*byte)(unsafe.Pointer(guid)), 16); string(got) != string(sum[:]) {
|
||||
t.Errorf("adapterGUID = %x, want %x", got, sum)
|
||||
}
|
||||
|
||||
if _, err := adapterGUID("xray0", "xray0"); err == nil {
|
||||
t.Error("an invalid guid was accepted")
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,20 @@ import (
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
)
|
||||
|
||||
// BenchmarkUDPNewSession measures what one new UDP flow costs the
|
||||
// inbound while it stays open: QUIC and DNS open many short flows, and each
|
||||
// one lives until the connection idle timeout.
|
||||
func BenchmarkUDPNewSession(b *testing.B) {
|
||||
u := newUdpConnectionHandler(func(conn net.Conn, dest net.Destination) {}, nil)
|
||||
dst := net.UDPDestination(net.ParseAddress("1.1.1.1"), 443)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
src := net.UDPDestination(net.IPAddress([]byte{10, byte(i >> 16), byte(i >> 8), byte(i)}), net.Port(1024+i%60000))
|
||||
u.HandlePacket(src, dst, &buf.Buffer{})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPacketQueueOrderAndClose(t *testing.T) {
|
||||
q := newPacketQueue(udpQueueLimit)
|
||||
for i := 0; i < 3; i++ {
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
)
|
||||
|
||||
const benchBatch = 64
|
||||
|
||||
// Raw cost of queueing and draining a small burst, as one flow's reader does.
|
||||
func BenchmarkQueueBurstChan(b *testing.B) {
|
||||
ch := make(chan *buf.Buffer, udpQueueLimit)
|
||||
p := &buf.Buffer{}
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
for j := 0; j < benchBatch; j++ {
|
||||
ch <- p
|
||||
}
|
||||
for j := 0; j < benchBatch; j++ {
|
||||
<-ch
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkQueueBurstPacketQueue(b *testing.B) {
|
||||
q := newPacketQueue(udpQueueLimit)
|
||||
p := &buf.Buffer{}
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
for j := 0; j < benchBatch; j++ {
|
||||
q.push(p)
|
||||
}
|
||||
for j := 0; j < benchBatch; j++ {
|
||||
q.pop()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Producer and consumer on different goroutines; the producer yields when the
|
||||
// queue is full instead of spinning, like a blocking channel send would.
|
||||
func BenchmarkQueueStreamChan(b *testing.B) {
|
||||
ch := make(chan *buf.Buffer, udpQueueLimit)
|
||||
p := &buf.Buffer{}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
for range ch {
|
||||
}
|
||||
close(done)
|
||||
}()
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
ch <- p
|
||||
}
|
||||
close(ch)
|
||||
<-done
|
||||
}
|
||||
|
||||
func BenchmarkQueueStreamPacketQueue(b *testing.B) {
|
||||
q := newPacketQueue(udpQueueLimit)
|
||||
p := &buf.Buffer{}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
for {
|
||||
if _, ok := q.pop(); !ok {
|
||||
break
|
||||
}
|
||||
}
|
||||
close(done)
|
||||
}()
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
for !q.push(p) {
|
||||
runtime.Gosched()
|
||||
}
|
||||
}
|
||||
q.close()
|
||||
<-done
|
||||
}
|
||||
@@ -80,3 +80,43 @@ func TestExpandWfpBlockLeak(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLeakCovers(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
value string
|
||||
protocol string
|
||||
port uint16
|
||||
covers bool
|
||||
}{
|
||||
{"tcp", "tcp", 1, true},
|
||||
{"tcp", "udp", 53, false},
|
||||
{"udp/53", "udp", 53, true},
|
||||
{"udp/53", "udp", 54, false},
|
||||
{"tcp/10-20", "tcp", 10, true},
|
||||
{"tcp/10-20", "tcp", 20, true},
|
||||
{"tcp/10-20", "tcp", 21, false},
|
||||
{"tcp/10-20", "tcp", 9, false},
|
||||
{"53", "udp", 53, true},
|
||||
{"53", "tcp", 53, true},
|
||||
{"10-20", "tcp", 15, true},
|
||||
{"10-20", "udp", 21, false},
|
||||
{"1.1.1.0/24:udp/53", "udp", 53, true},
|
||||
{"[::/0]:tcp", "tcp", 443, true},
|
||||
{"[2001:db8::/32]:53", "tcp", 53, true},
|
||||
{"0.0.0.0/0:icmp", "udp", 53, false},
|
||||
{"all", "udp", 53, true},
|
||||
{"1.1.1.1/32:all", "tcp", 1, true},
|
||||
{"allexceptlan", "udp", 53, false},
|
||||
{"misconfigtun", "udp", 53, false},
|
||||
{"windnsclient", "udp", 53, false},
|
||||
} {
|
||||
l, ok := parseLeak(c.value)
|
||||
if !ok {
|
||||
t.Errorf("%q was not parsed", c.value)
|
||||
continue
|
||||
}
|
||||
if got := l.covers(c.protocol, c.port); got != c.covers {
|
||||
t.Errorf("%q covers %s/%d = %v", c.value, c.protocol, c.port, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,6 @@ import (
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
"github.com/xtls/xray-core/proxy/vless/reverse"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"github.com/xtls/xray-core/transport/internet/reality"
|
||||
"github.com/xtls/xray-core/transport/internet/stat"
|
||||
"github.com/xtls/xray-core/transport/internet/tls"
|
||||
@@ -525,12 +524,6 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
|
||||
}
|
||||
errors.LogInfo(ctx, "received request for ", request.Destination())
|
||||
|
||||
if stream, ok := session.StreamSettingsFromContext(h.ctx).(*internet.MemoryStreamConfig); ok && stream.ProtocolName == "xdrive" {
|
||||
if request.Command != protocol.RequestCommandMux && request.Command != protocol.RequestCommandRvs {
|
||||
return errors.New("VLESS over XDRIVE: inbound received a non-Mux/Rvs request")
|
||||
}
|
||||
}
|
||||
|
||||
inbound := session.InboundFromContext(ctx)
|
||||
if inbound == nil {
|
||||
panic("no inbound metadata")
|
||||
|
||||
@@ -12,7 +12,6 @@ import (
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/proxy"
|
||||
"github.com/xtls/xray-core/proxy/vless"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
)
|
||||
@@ -42,19 +41,17 @@ type Client struct {
|
||||
|
||||
func NewClient(ctx context.Context, config *vless.Multiplex, network string, open func(context.Context) (context.Context, *transport.Link, error)) *Client {
|
||||
c := &Client{config: config}
|
||||
maxReuseTimes := uint32(1024)
|
||||
if network == "xdrive" {
|
||||
maxReuseTimes = 0 // unlimited
|
||||
config.Concurrency = max(config.Concurrency, 128)
|
||||
if config.XudpConcurrency > 0 {
|
||||
config.XudpConcurrency = max(config.XudpConcurrency, 128)
|
||||
pool := func(concurrency int32) *Pool {
|
||||
return NewPool(ctx, ClientStrategy{MaxConcurrency: uint32(concurrency), MaxConnection: 1024}, open)
|
||||
}
|
||||
if concurrency := config.GetConcurrency(); concurrency > 0 {
|
||||
if network == "xdrive" {
|
||||
concurrency = max(concurrency, 128)
|
||||
}
|
||||
c.tcp = pool(concurrency)
|
||||
}
|
||||
if config.Concurrency > 0 {
|
||||
c.tcp = NewPool(ctx, ClientStrategy{MaxConcurrency: uint32(config.Concurrency), MaxConnection: maxReuseTimes}, open)
|
||||
}
|
||||
if config.XudpConcurrency > 0 {
|
||||
c.udp = NewPool(ctx, ClientStrategy{MaxConcurrency: uint32(config.XudpConcurrency), MaxConnection: maxReuseTimes}, open)
|
||||
if concurrency := config.GetXudpConcurrency(); concurrency > 0 {
|
||||
c.udp = pool(concurrency)
|
||||
}
|
||||
return c
|
||||
}
|
||||
@@ -75,7 +72,6 @@ func (c *Client) Dispatch(ctx context.Context, link *transport.Link) (bool, erro
|
||||
if target.Network == net.Network_UDP && target.Port == 443 {
|
||||
switch c.config.GetXudpProxyUDP443() {
|
||||
case "reject", "":
|
||||
proxy.DropUDP(ctx, link.Reader)
|
||||
return true, errors.New("XUDP rejected UDP/443 traffic")
|
||||
case "skip":
|
||||
return false, nil
|
||||
|
||||
@@ -26,9 +26,7 @@ func TestClientUDP443Policy(t *testing.T) {
|
||||
opened = true
|
||||
return nil, nil, context.Canceled
|
||||
})
|
||||
r, w := pipe.New()
|
||||
common.Close(w)
|
||||
handled, err := client.Dispatch(ctx, &transport.Link{Reader: r})
|
||||
handled, err := client.Dispatch(ctx, &transport.Link{})
|
||||
wantRejected := policy == "reject"
|
||||
if opened || handled != wantRejected || (err != nil) != wantRejected {
|
||||
t.Fatalf("Dispatch() = (%t, %v), opened carrier = %t, want rejected = %t without opening a carrier", handled, err, opened, wantRejected)
|
||||
|
||||
@@ -191,13 +191,6 @@ func (h *Handler) process(ctx context.Context, link *transport.Link, dialer inte
|
||||
rec := h.server
|
||||
var conn stat.Connection
|
||||
|
||||
account := rec.User.Account.(*vless.MemoryAccount)
|
||||
|
||||
if !native && ob.Target.Network == net.Network_UDP && ob.Target.Port == 443 && account.Flow == vless.XRV {
|
||||
proxy.DropUDP(ctx, link.Reader)
|
||||
return nil, nil, errors.New("XTLS rejected UDP/443 traffic")
|
||||
}
|
||||
|
||||
if h.testpre > 0 {
|
||||
h.initpre.Do(func() {
|
||||
h.preConns = make(chan *ConnExpire)
|
||||
@@ -279,20 +272,27 @@ func (h *Handler) process(ctx context.Context, link *transport.Link, dialer inte
|
||||
request.Address, request.Port = target.Address, target.Port
|
||||
}
|
||||
|
||||
account := request.User.Account.(*vless.MemoryAccount)
|
||||
|
||||
requestAddons := &encoding.Addons{
|
||||
Flow: account.Flow,
|
||||
}
|
||||
|
||||
var input *bytes.Reader
|
||||
var rawInput **bytes.Buffer
|
||||
allowUDP443 := false
|
||||
switch requestAddons.Flow {
|
||||
case vless.XRV + "-udp443":
|
||||
allowUDP443 = true
|
||||
requestAddons.Flow = requestAddons.Flow[:16]
|
||||
fallthrough
|
||||
case vless.XRV:
|
||||
ob.CanSpliceCopy = 2
|
||||
switch request.Command {
|
||||
case protocol.RequestCommandUDP:
|
||||
if !allowUDP443 && request.Port == 443 {
|
||||
return nil, nil, errors.New("XTLS rejected UDP/443 traffic")
|
||||
}
|
||||
case protocol.RequestCommandTCP, protocol.RequestCommandMux, protocol.RequestCommandRvs:
|
||||
var target net.Conn
|
||||
if commonConn, ok := conn.(*encryption.CommonConn); ok {
|
||||
|
||||
@@ -255,11 +255,10 @@ func DialSystem(ctx context.Context, dest net.Destination, sockopt *SocketConfig
|
||||
}
|
||||
ips, err := LookupForIP(dest.Address.Domain(), finalStrategy, src)
|
||||
if err != nil {
|
||||
errors.LogErrorInner(ctx, err, "failed to resolve ip")
|
||||
if sockopt.DomainStrategy.ForceIP() {
|
||||
errors.LogErrorInner(ctx, err, "failed to resolve ip for: ", dest.Address.Domain())
|
||||
return nil, err
|
||||
}
|
||||
errors.LogInfoInner(ctx, err, "failed to resolve ip for: ", dest.Address.Domain(), ", but continue due to USEIP* strategy")
|
||||
} else if sockopt.HappyEyeballs == nil || sockopt.HappyEyeballs.TryDelayMs == 0 || sockopt.HappyEyeballs.MaxConcurrentTry == 0 || len(ips) < 2 || len(sockopt.DialerProxy) > 0 || dest.Network != net.Network_TCP {
|
||||
dest.Address = net.IPAddress(ips[dice.Roll(len(ips))])
|
||||
errors.LogInfo(ctx, "replace destination with "+dest.String())
|
||||
|
||||
@@ -28,11 +28,7 @@ func (s *Proxy) Proxy(w http.ResponseWriter, r *ProxyRequest) (*Conn, error) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
if ok {
|
||||
str, err := streamer.HTTPStream()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newProxiedConn(str), nil
|
||||
return newProxiedConn(streamer.HTTPStream()), nil
|
||||
}
|
||||
controller := http.NewResponseController(w)
|
||||
if err := controller.Flush(); err != nil {
|
||||
|
||||
@@ -231,11 +231,7 @@ func TestDialWarpHTTP3(t *testing.T) {
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.(http.Flusher).Flush()
|
||||
str, err := w.(http3.HTTPStreamer).HTTPStream()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
str := w.(http3.HTTPStreamer).HTTPStream()
|
||||
go func() { capsules <- readCapsuleTypes(str, nil) }()
|
||||
b, err := str.ReceiveDatagram(r.Context())
|
||||
if err != nil {
|
||||
|
||||
@@ -26,7 +26,6 @@ import (
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
http_proto "github.com/xtls/xray-core/common/protocol/http"
|
||||
"github.com/xtls/xray-core/common/signal/done"
|
||||
"github.com/xtls/xray-core/common/task"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"github.com/xtls/xray-core/transport/internet/hysteria/congestion"
|
||||
"github.com/xtls/xray-core/transport/internet/hysteria/congestion/bbr"
|
||||
@@ -79,9 +78,10 @@ func (h *requestHandler) upsertSession(sessionId string) *httpSession {
|
||||
h.sessions.Store(sessionId, s)
|
||||
|
||||
shouldReap := done.New()
|
||||
time.AfterFunc(30*time.Second, func() {
|
||||
go func() {
|
||||
time.Sleep(30 * time.Second)
|
||||
shouldReap.Close()
|
||||
})
|
||||
}()
|
||||
go func() {
|
||||
select {
|
||||
case <-shouldReap.Wait():
|
||||
@@ -222,15 +222,15 @@ func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Req
|
||||
scStreamUpServerSecs := h.config.GetNormalizedScStreamUpServerSecs()
|
||||
hasLegacyRefererCompatMarker := request.Header.Get("Referer") != ""
|
||||
if (hasLegacyRefererCompatMarker || obfsPaddingAccepted) && scStreamUpServerSecs.To > 0 {
|
||||
writePadding := &task.Periodic{
|
||||
Execute: func() error {
|
||||
go func() {
|
||||
for {
|
||||
_, err := httpSC.Write(bytes.Repeat([]byte{'X'}, int(h.config.GetNormalizedXPaddingBytes().rand())))
|
||||
return err
|
||||
},
|
||||
Interval: time.Duration(scStreamUpServerSecs.rand()) * time.Second,
|
||||
}
|
||||
defer writePadding.Close()
|
||||
writePadding.Start()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Duration(scStreamUpServerSecs.rand()) * time.Second)
|
||||
}
|
||||
}()
|
||||
}
|
||||
select {
|
||||
case <-request.Context().Done():
|
||||
|
||||
@@ -6,11 +6,9 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/task"
|
||||
)
|
||||
|
||||
var _ buf.Writer = (*connection)(nil)
|
||||
@@ -22,27 +20,25 @@ type connection struct {
|
||||
conn *websocket.Conn
|
||||
reader io.Reader
|
||||
remoteAddr net.Addr
|
||||
keepalive *task.Periodic
|
||||
}
|
||||
|
||||
func NewConnection(conn *websocket.Conn, remoteAddr net.Addr, extraReader io.Reader, heartbeatPeriod uint32) *connection {
|
||||
wrappedConn := &connection{
|
||||
if heartbeatPeriod != 0 {
|
||||
go func() {
|
||||
for {
|
||||
time.Sleep(time.Duration(heartbeatPeriod) * time.Second)
|
||||
if err := conn.WriteControl(websocket.PingMessage, []byte{}, time.Time{}); err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
return &connection{
|
||||
conn: conn,
|
||||
remoteAddr: remoteAddr,
|
||||
reader: extraReader,
|
||||
}
|
||||
if heartbeatPeriod != 0 {
|
||||
keepalive := task.Periodic{
|
||||
Execute: func() error {
|
||||
return conn.WriteControl(websocket.PingMessage, []byte{}, time.Time{})
|
||||
},
|
||||
Interval: time.Duration(heartbeatPeriod) * time.Second,
|
||||
}
|
||||
keepalive.Start()
|
||||
wrappedConn.keepalive = &keepalive
|
||||
}
|
||||
|
||||
return wrappedConn
|
||||
}
|
||||
|
||||
// Read implements net.Conn.Read()
|
||||
@@ -97,7 +93,6 @@ func (c *connection) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
}
|
||||
|
||||
func (c *connection) Close() error {
|
||||
common.CloseIfExists(c.keepalive)
|
||||
var errs []interface{}
|
||||
if err := c.conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Now().Add(time.Second*5)); err != nil {
|
||||
errs = append(errs, err)
|
||||
|
||||
Reference in New Issue
Block a user