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