Compare commits

..
Author SHA1 Message Date
Meo597 84ce7568bb Lua: Expose Go slices as read-only 2026-11-20 05:16:13 +08:00
MinyandGitHub 02cf0f60ea Dependency: Update github.com/klauspost/compress to v1.20.4 to fix CVE-2026-116591 (#7431)
https://github.com/XTLS/Xray-core/pull/7431#issuecomment-7016054619
2026-11-19 17:13:28 +00:00
f73471e6b4 gRPC transport: Pass standard size buffer (#7449)
https://github.com/XTLS/Xray-core/pull/7438#issuecomment-7008713358

Fixes https://github.com/XTLS/Xray-core/issues/7369 and https://github.com/XTLS/Xray-core/pull/7424

---------

Co-authored-by: b84330808 <b84330808@gmail.com>
Co-authored-by: anonymousmeower <arasouli@duck.com>
2026-11-19 13:48:04 +00:00
8e07407486 XHTTP/3 client: Close the UDP socket when the QUIC dial fails (#7413)
https://github.com/XTLS/Xray-core/pull/7413#pullrequestreview-5975182281

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: 风扇滑翔翼 <Fangliding.fshxy@outlook.com>
2026-11-19 12:54:02 +00:00
febc082f03 DNS: Avoid mutating cache records during cleanup (#7442)
https://github.com/XTLS/Xray-core/pull/7442#pullrequestreview-5958707394

---------

Co-authored-by: Meow <197331664+Meo597@users.noreply.github.com>
2026-11-19 12:36:34 +00:00
anonymousmeowerandGitHub 09b1b0701f Sockopt: Report the real ioctl error from OriginalDst on Darwin (#7367)
https://github.com/XTLS/Xray-core/pull/7367#issuecomment-7008748396
2026-11-19 12:14:35 +00:00
MeowandGitHub ce074ce572 Env: Remove XRAY_CONE_DISABLED (#6110)
https://github.com/XTLS/Xray-core/pull/6057#issuecomment-4364744151
https://github.com/XTLS/Xray-core/pull/6075#issuecomment-4395258425
https://github.com/XTLS/Xray-core/pull/6110#issuecomment-7003152469
2026-11-19 11:25:41 +00:00
b1dfdf25e7 uTLS: Pick "random" only from fingerprints that have X25519MLKEM768 (#7432)
https://github.com/XTLS/Xray-core/issues/7259#issuecomment-6718349626

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 08:07:29 +00:00
Roy Hill-PercivalandGitHub 1c5a1fbf70 TUN inbound: End UDP flows and cancel dispatches when the inbound closes (#7350)
https://github.com/XTLS/Xray-core/pull/7350#pullrequestreview-5901009138
2026-11-19 07:57:32 +00:00
deadnewsandGitHub b983473390 Socks & HTTP inbounds: Add email to access log (#7437)
Fixes https://github.com/XTLS/Xray-core/issues/7436
2026-11-19 07:11:16 +00:00
5e861653c2 VMess inbound: Refactor code to use DispatchLink() (#5143)
https://github.com/XTLS/Xray-core/pull/5143#issuecomment-3403697498
https://github.com/XTLS/Xray-core/pull/5143#issuecomment-6743282472
https://github.com/XTLS/Xray-core/pull/5143#issuecomment-7000643202

---------

Co-authored-by: RPRX <63339210+RPRX@users.noreply.github.com>
2026-11-19 06:38:22 +00:00
36112cd886 Routing: Fix process for Linux IPv4-mapped sockets (#7414)
https://github.com/XTLS/Xray-core/pull/7414#issuecomment-6987317102

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 18:13:31 +00:00
37 changed files with 275 additions and 225 deletions
+8 -5
View File
@@ -124,14 +124,17 @@ func (c *CacheController) writeAndShrink(expiredKeys []string) {
if rec == nil {
continue
}
if rec.A != nil && rec.A.Expire.Before(now) {
rec.A = nil
a, aaaa := rec.A, rec.AAAA
if a != nil && a.Expire.Before(now) {
a = nil
}
if rec.AAAA != nil && rec.AAAA.Expire.Before(now) {
rec.AAAA = nil
if aaaa != nil && aaaa.Expire.Before(now) {
aaaa = nil
}
if rec.A == nil && rec.AAAA == nil {
if a == nil && aaaa == nil {
delete(c.ips, domain)
} else if a != rec.A || aaaa != rec.AAAA {
c.ips[domain] = &record{A: a, AAAA: aaaa}
}
}
+1 -7
View File
@@ -273,8 +273,7 @@ type udpWorker struct {
checker *task.Periodic
activeConn map[connID]*udpConn
ctx context.Context
cone bool
ctx context.Context
}
func (w *udpWorker) getConnection(id connID) (*udpConn, bool) {
@@ -316,9 +315,6 @@ func (w *udpWorker) callback(b *buf.Buffer, source net.Destination, originalDest
src: source,
}
if originalDest.IsValid() {
if !w.cone {
id.dest = originalDest
}
b.UDP = &originalDest
}
conn, existing := w.getConnection(id)
@@ -418,8 +414,6 @@ func (w *udpWorker) Start() error {
return err
}
w.cone = w.ctx.Value("cone").(bool)
w.checker = &task.Periodic{
Interval: time.Minute,
Execute: w.clean,
+19 -22
View File
@@ -181,29 +181,26 @@ func (h *Handler) Tag() string {
func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) {
outbounds := session.OutboundsFromContext(ctx)
ob := outbounds[len(outbounds)-1]
if h.senderSettings != nil && h.senderSettings.TargetStrategy.HasStrategy() && ob.Target.Address.Family().IsDomain() {
if session.SkipDNSResolveFromContext(ctx) {
errors.LogInfo(ctx, "bypassing targetStrategy ", h.senderSettings.TargetStrategy, " for ", ob.Target, "; preserving target domain")
content := session.ContentFromContext(ctx)
if h.senderSettings != nil && h.senderSettings.TargetStrategy.HasStrategy() && ob.Target.Address.Family().IsDomain() && (content == nil || !content.SkipDNSResolve) {
strategy := h.senderSettings.TargetStrategy
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil {
strategy = strategy.GetDynamicStrategy(ob.OriginalTarget.Address.Family())
}
ips, err := internet.LookupForIP(ob.Target.Address.Domain(), strategy, nil)
if err != nil {
errors.LogInfoInner(ctx, err, "failed to resolve ip for target ", ob.Target.Address.Domain())
if h.senderSettings.TargetStrategy.ForceIP() {
err := errors.New("failed to resolve ip for target ", ob.Target.Address.Domain()).Base(err)
session.SubmitOutboundErrorToOriginator(ctx, err)
common.Interrupt(link.Writer)
common.Interrupt(link.Reader)
return
}
} else {
strategy := h.senderSettings.TargetStrategy
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil {
strategy = strategy.GetDynamicStrategy(ob.OriginalTarget.Address.Family())
}
ips, err := internet.LookupForIP(ob.Target.Address.Domain(), strategy, nil)
if err != nil {
errors.LogInfoInner(ctx, err, "failed to resolve ip for target ", ob.Target.Address.Domain())
if h.senderSettings.TargetStrategy.ForceIP() {
err := errors.New("failed to resolve ip for target ", ob.Target.Address.Domain()).Base(err)
session.SubmitOutboundErrorToOriginator(ctx, err)
common.Interrupt(link.Writer)
common.Interrupt(link.Reader)
return
}
} else {
unchangedDomain := ob.Target.Address.Domain()
ob.Target.Address = net.IPAddress(ips[dice.Roll(len(ips))])
errors.LogInfo(ctx, "target: ", unchangedDomain, " resolved to: ", ob.Target.Address.String())
}
unchangedDomain := ob.Target.Address.Domain()
ob.Target.Address = net.IPAddress(ips[dice.Roll(len(ips))])
errors.LogInfo(ctx, "target: ", unchangedDomain, " resolved to: ", ob.Target.Address.String())
}
}
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
+3 -2
View File
@@ -44,8 +44,9 @@ func (c routingContext) GetRuleTag() string {
return ""
}
// GetSkipDNSResolve implements routing.Context.
// The protobuf RoutingContext has no skip flag, so API contexts use false.
// GetSkipDNSResolve is a mock implementation here to match the interface,
// SkipDNSResolve is set from dns module, no use if coming from a protobuf object?
// TODO: please confirm @Vigilans
func (c routingContext) GetSkipDNSResolve() bool {
return false
}
+1 -1
View File
@@ -23,7 +23,7 @@ func RegisterLua(L *lua.LState) {
return 0
}
xlua.PushWithDirectMethods(L, matcher, map[string]xlua.DirectMethod{
"Match": newLuaDomainMatch(xlua.NewSlicePusher[uint32](L)),
"Match": newLuaDomainMatch(xlua.NewReadOnlySlicePusher[uint32](L)),
"MatchAny": luaDomainMatchAny,
})
return 1
+3 -1
View File
@@ -104,7 +104,9 @@ for _, value in ipairs({matcher, domain}) do
assert(not pcall(function() return value ^ {} end))
end
assert(domain:matchAny("example.com"))
assert(#domain:Match("example.com") == 1)
local indices = domain:Match("example.com")
assert(#indices == 1)
assert(not pcall(function() indices[1] = 7 end))
assert(domain:match("example.com")[1] == 0)
assert(not pcall(function() matcher:AnyMatch() end))
assert(not pcall(function() matcher:AnyMatch(matched, true) end))
+3 -3
View File
@@ -8,10 +8,10 @@ import (
luar "layeh.com/gopher-luar"
)
// NewSlicePusher captures luar's slice metatable during state initialization.
// newSlicePusher captures luar's slice metatable during state initialization.
// The returned function wraps slices without reflection or metatable lookup,
// and pushes nil for nil slices. Use it with this state or its coroutines.
func NewSlicePusher[T any](L *glua.LState) func(*glua.LState, []T) {
func newSlicePusher[T any](L *glua.LState) func(*glua.LState, []T) {
metatable := luar.MT(L, []T(nil)).LTable
return func(L *glua.LState, values []T) {
if values == nil {
@@ -38,7 +38,7 @@ func NewReadOnlySlicePusher[T any](L *glua.LState) func(*glua.LState, []T) {
})
setSliceReadOnly[[]T](L, readOnly)
}
return NewSlicePusher[T](L)
return newSlicePusher[T](L)
}
func setSliceReadOnly[S ~[]E, E any](L *glua.LState, readOnly *glua.LFunction) {
+21 -43
View File
@@ -9,53 +9,20 @@ import (
luar "layeh.com/gopher-luar"
)
func TestSlicePusher(t *testing.T) {
func TestReadOnlySlicePusher(t *testing.T) {
L := glua.NewState()
defer L.Close()
push := NewSlicePusher[int](L)
push := NewReadOnlySlicePusher[int](L)
values := []int{3, 5}
L.SetGlobal("getValues", L.NewFunction(func(L *glua.LState) int {
push(L, values)
return 1
}))
if err := L.DoString(`
local values = getValues()
assert(#values == 2 and values[1] == 3 and values[2] == 5)
values[2] = 7
local co = coroutine.create(function()
local values = getValues()
assert(#values == 2 and values[1] == 3 and values[2] == 7)
return true
end)
local co = coroutine.create(function() return getValues() end)
local ok, result = coroutine.resume(co)
assert(ok and result == true)
`); err != nil {
t.Fatal(err)
}
if values[1] != 7 {
t.Fatal("slice storage was copied")
}
push(L, nil)
if L.Get(-1) != glua.LNil {
t.Fatal("nil slice must push Lua nil")
}
L.Pop(1)
push(L, []int{})
L.SetGlobal("empty", L.Get(-1))
L.Pop(1)
if err := L.DoString(`assert(type(empty) == "userdata" and #empty == 0)`); err != nil {
t.Fatal(err)
}
}
func TestReadOnlySlicePusher(t *testing.T) {
L := glua.NewState()
defer L.Close()
values := []int{3, 5}
NewReadOnlySlicePusher[int](L)(L, values)
L.SetGlobal("values", L.Get(-1))
L.Pop(1)
if err := L.DoString(`
assert(ok, result)
values = result
assert(#values == 2 and values[1] == 3 and values[2] == 5)
assert(not pcall(function() values[1] = 7 end))
assert(not pcall(function() return values + 7 end))
@@ -69,6 +36,17 @@ assert(sum == 8)
if &got[0] != &values[0] || values[0] != 3 || values[1] != 5 {
t.Fatal("read-only binding copied or modified the slice")
}
push(L, nil)
if L.Get(-1) != glua.LNil {
t.Fatal("nil slice must push Lua nil")
}
L.Pop(1)
push(L, []int{})
L.SetGlobal("empty", L.Get(-1))
L.Pop(1)
if err := L.DoString(`assert(type(empty) == "userdata" and #empty == 0)`); err != nil {
t.Fatal(err)
}
}
func TestReadOnlyIPSlicePusher(t *testing.T) {
@@ -230,23 +208,23 @@ assert(not pcall(function() return nested + nested end))
}
}
func TestSlicePusherMetatablePerState(t *testing.T) {
func TestReadOnlySlicePusherMetatablePerState(t *testing.T) {
first := glua.NewState()
defer first.Close()
second := glua.NewState()
defer second.Close()
NewSlicePusher[int](first)(first, []int{1})
NewSlicePusher[int](second)(second, []int{1})
NewReadOnlySlicePusher[int](first)(first, []int{1})
NewReadOnlySlicePusher[int](second)(second, []int{1})
if first.Get(-1).(*glua.LUserData).Metatable == second.Get(-1).(*glua.LUserData).Metatable {
t.Fatal("independent states share a slice metatable")
}
}
func BenchmarkSlicePusher(b *testing.B) {
func BenchmarkReadOnlySlicePusher(b *testing.B) {
L := glua.NewState()
defer L.Close()
ips := []net.IP{net.ParseIP("127.0.0.1")}
pushIPs := NewSlicePusher[net.IP](L)
pushIPs := NewReadOnlySlicePusher[net.IP](L)
for _, benchmark := range []struct {
name string
push func(*glua.LState, []net.IP)
+2 -4
View File
@@ -671,7 +671,7 @@ string.__tostring = nil
L.SetGlobal("testNativeError", L.Get(-1))
L.Pop(1)
L.SetGlobal("testGoStruct", luar.New(L, &struct{ Value string }{"readable field"}))
NewSlicePusher[net.IP](L)(L, []net.IP{net.ParseIP("192.0.2.1")})
NewReadOnlySlicePusher[net.IP](L)(L, []net.IP{net.ParseIP("192.0.2.1")})
L.SetGlobal("testIPs", L.Get(-1))
L.Pop(1)
userdata := L.NewUserData()
@@ -865,9 +865,7 @@ assert(not ok and a == "{<address> <address>}")
PushUserData(L, struct{ Pointer *int }{&target})
L.SetGlobal("testObject", L.Get(-1))
L.Pop(1)
NewSlicePusher[int](L)(L, []int{1})
L.SetGlobal("testValues", L.Get(-1))
L.Pop(1)
L.SetGlobal("testValues", luar.New(L, []int{1}))
L.SetGlobal("testPanic", L.NewFunction(func(L *glua.LState) int {
panic(struct{ First, Second *int }{&target, &target})
}))
+12 -11
View File
@@ -8,6 +8,7 @@ import (
"fmt"
"net"
"os"
"slices"
"strconv"
"strings"
@@ -31,7 +32,7 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
switch network {
case "tcp":
if net.ParseIP(srcIP).To4() != nil {
procFiles = []string{"/proc/net/tcp"}
procFiles = []string{"/proc/net/tcp", "/proc/net/tcp6"}
} else {
procFiles = []string{"/proc/net/tcp6"}
}
@@ -45,14 +46,18 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
panic("Unsupported network type for process lookup.")
}
targetHexAddr := formatProcNetAddress(net.ParseIP(srcIP), Port(srcPort))
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, targetHexAddr, portFallback)
inode, err := findInodeInFiles(procFiles, targetHexAddrs, portFallback)
if err != nil {
return 0, "", "", errors.New("could not search in ", strings.Join(procFiles, " and ")).Base(err)
}
@@ -84,13 +89,9 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
return pid, procName, absPath, nil
}
// formatProcNetAddress formats the 4 or 16 bytes of addr as they are: an IPv4-mapped IPv6 address stays one
func formatProcNetAddress(addr net.IP, port Port) string {
var ipBytes []byte
if ipv4 := addr.To4(); ipv4 != nil {
ipBytes = ipv4
} else {
ipBytes = addr.To16()
}
ipBytes := []byte(addr)
var formatted strings.Builder
formatted.Grow(len(ipBytes)*2 + 5)
@@ -101,7 +102,7 @@ func formatProcNetAddress(addr net.IP, port Port) string {
return formatted.String()
}
func findInodeInFiles(filePaths []string, targetHexAddr, portFallback string) (string, error) {
func findInodeInFiles(filePaths []string, targetHexAddrs []string, portFallback string) (string, error) {
onlyMatchedPort := ""
for i, filePath := range filePaths {
@@ -122,7 +123,7 @@ func findInodeInFiles(filePaths []string, targetHexAddr, portFallback string) (s
}
localAddress := fields[1]
if localAddress == targetHexAddr {
if slices.Contains(targetHexAddrs, localAddress) {
return fields[9], nil
}
if portFallback != "" && strings.HasSuffix(localAddress, portFallback) {
+50
View File
@@ -0,0 +1,50 @@
//go:build linux && !android
package net
import (
"errors"
stdnet "net"
"net/netip"
"os"
"syscall"
"testing"
)
func TestFindProcessIPv4Mapped(t *testing.T) {
listener, err := stdnet.Listen("tcp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
peer, err := stdnet.ListenPacket("udp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer peer.Close()
// an IPv6 socket that connects to an IPv4 address, as the sockets of Java and .NET are
for _, c := range []struct{ local, remote stdnet.Addr }{
{&stdnet.TCPAddr{IP: stdnet.IPv6zero}, listener.Addr()},
{&stdnet.UDPAddr{IP: stdnet.IPv6zero}, peer.LocalAddr()},
} {
network := c.remote.Network()
conn, err := (&stdnet.Dialer{LocalAddr: c.local}).Dial(network, c.remote.String())
if errors.Is(err, syscall.EAFNOSUPPORT) {
t.Skip("no IPv6 sockets here")
}
if err != nil {
t.Fatal(err)
}
defer conn.Close()
local := netip.MustParseAddrPort(conn.LocalAddr().String())
remote := netip.MustParseAddrPort(c.remote.String())
pid, _, _, err := FindProcess(network, "127.0.0.1", local.Port(), "127.0.0.1", remote.Port())
if err != nil {
t.Errorf("%s: %v", network, err)
} else if pid != os.Getpid() {
t.Errorf("%s: found PID %d, want %d", network, pid, os.Getpid())
}
}
}
-1
View File
@@ -16,7 +16,6 @@ const (
UseReadV = "xray.buf.readv"
UseFreedomSplice = "xray.buf.splice"
UseVmessPadding = "xray.vmess.padding"
UseCone = "xray.cone.disabled"
UseStrictJSON = "xray.json.strict"
BufferSize = "xray.ray.buffer.size"
-5
View File
@@ -77,11 +77,6 @@ func ContentFromContext(ctx context.Context) *Content {
return nil
}
func SkipDNSResolveFromContext(ctx context.Context) bool {
content := ContentFromContext(ctx)
return content != nil && content.SkipDNSResolve
}
func ContextWithIsReverseMux(ctx context.Context, isReverseMux bool) context.Context {
return context.WithValue(ctx, isReverseMuxKey, isReverseMux)
}
-3
View File
@@ -63,9 +63,6 @@ func init() {
}
func GetGlobalID(ctx context.Context) (globalID [8]byte) {
if cone := ctx.Value("cone"); cone == nil || !cone.(bool) { // cone is nil only in some unit tests
return
}
if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.Network == net.Network_UDP &&
(inbound.Name == "dokodemo-door" || inbound.Name == "socks" || inbound.Name == "shadowsocks" || inbound.Name == "tun") {
h := blake3.New(8, ensureBaseKey())
-2
View File
@@ -192,8 +192,6 @@ func initInstanceWithConfig(config *Config, server *Instance) (bool, error) {
if err := platform.ReloadEnvSettings(); err != nil {
return true, errors.New("failed to reload environment settings").Base(err)
}
server.ctx = context.WithValue(server.ctx, "cone",
platform.NewEnvFlag(platform.UseCone).GetValue(func() string { return "" }) != "true")
for _, appSettings := range config.App {
settings, err := appSettings.GetInstance()
+1 -1
View File
@@ -45,7 +45,7 @@ require (
github.com/huin/goupnp v1.2.0 // indirect
github.com/jackpal/go-nat-pmp v1.0.2 // indirect
github.com/juju/ratelimit v1.0.2 // indirect
github.com/klauspost/compress v1.20.1 // indirect
github.com/klauspost/compress v1.20.4 // indirect
github.com/koron/go-ssdp v0.0.4 // indirect
github.com/libp2p/go-netroute v0.2.1 // indirect
github.com/molecule-man/go-brrr v1.2.0 // indirect
+2
View File
@@ -33,6 +33,8 @@ github.com/juju/ratelimit v1.0.2 h1:sRxmtRiajbvrcLQT7S+JbqU0ntsb9W2yhSdNN8tWfaI=
github.com/juju/ratelimit v1.0.2/go.mod h1:qapgC/Gy+xNh9UxzV13HGGl/6UXNN+ct+vwSgWNm/qk=
github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=
github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/cpuid/v2 v2.4.2 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ=
github.com/klauspost/cpuid/v2 v2.4.2/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/koron/go-ssdp v0.0.4 h1:1IDwrghSKYM7yLf7XCzbByg2sJ/JcNOZRXS2jczTwz0=
-5
View File
@@ -318,7 +318,6 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
}
ob.Name = "freedom"
ob.CanSpliceCopy = 1
if !h.usesDialerProxy && len(h.firewall) > 0 {
rule := h.firewall[0]
if rule.action == RuleAction_Block && rule.network == allNetworks && len(rule.port) == 0 && rule.ip == nil {
@@ -351,10 +350,6 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
}
}
if h.resolveStrategy.HasStrategy() && session.SkipDNSResolveFromContext(ctx) {
errors.LogInfo(ctx, "DNS-origin connection to ", destination, " may recursively resolve with sockopt.domainStrategy ", h.resolveStrategy)
}
input := link.Reader
output := link.Writer
+1
View File
@@ -150,6 +150,7 @@ Start:
To: request.URL,
Status: log.AccessAccepted,
Reason: "",
Email: inbound.User.Email,
})
if strings.EqualFold(request.Method, "CONNECT") {
+1 -1
View File
@@ -30,7 +30,7 @@ func (l *Loopback) Process(ctx context.Context, link *transport.Link, _ internet
errors.LogInfo(ctx, "opening connection to ", destination)
content := new(session.Content)
content.SkipDNSResolve = session.SkipDNSResolveFromContext(ctx)
content.SkipDNSResolve = true
content.SniffingRequest = l.sniffingRequest
ctx = session.ContextWithContent(ctx, content)
+1 -3
View File
@@ -25,7 +25,6 @@ type Server struct {
config *ServerConfig
validator *Validator
policyManager policy.Manager
cone bool
}
// NewServer create a new Shadowsocks server.
@@ -47,7 +46,6 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
config: config,
validator: validator,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
cone: ctx.Value("cone").(bool),
}
return s, nil
@@ -185,7 +183,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis
data.UDP = &destination
if !s.cone || dest == nil {
if dest == nil {
dest = &destination
}
+3 -3
View File
@@ -29,7 +29,6 @@ import (
type Server struct {
config *ServerConfig
policyManager policy.Manager
cone bool
httpServer *http.Server
}
@@ -39,7 +38,6 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
s := &Server{
config: config,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
cone: ctx.Value("cone").(bool),
}
httpConfig := &http.ServerConfig{
UserLevel: config.UserLevel,
@@ -149,6 +147,7 @@ func (s *Server) processTCP(ctx context.Context, conn stat.Connection, dispatche
To: dest,
Status: log.AccessAccepted,
Reason: "",
Email: inbound.User.Email,
})
}
if inbound.CanSpliceCopy == 2 {
@@ -270,12 +269,13 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis
To: destination,
Status: log.AccessAccepted,
Reason: "",
Email: inbound.User.Email,
})
}
payload.UDP = &destination
if !s.cone || dest == nil {
if dest == nil {
dest = &destination
}
+1 -3
View File
@@ -38,7 +38,6 @@ type Server struct {
policyManager policy.Manager
validator *Validator
fallbacks map[string]map[string]map[string]*Fallback // or nil
cone bool
}
// NewServer creates a new trojan inbound handler.
@@ -59,7 +58,6 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
server := &Server{
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
validator: validator,
cone: ctx.Value("cone").(bool),
}
if config.Fallbacks != nil {
@@ -302,7 +300,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, sessionPolicy policy.Sess
}
errors.LogInfo(ctx, "tunnelling request to ", destination)
if !s.cone || dest == nil {
if dest == nil {
dest = &destination
}
+9 -1
View File
@@ -25,7 +25,10 @@ import (
// Handler is managing object that tie together tun interface, ip stack and dispatch connections to the routing
type Handler struct {
// ctx is detached from the instance's; cancel ends it, and with it every dispatch started from it,
// when the handler closes, since nothing else would
ctx context.Context
cancel context.CancelFunc
config *Config
stack Stack
tun Tun
@@ -96,7 +99,7 @@ func (t *Handler) Init(ctx context.Context, pm policy.Manager, dispatcher routin
t.sniffingRequest = content.SniffingRequest
}
t.ctx = core.ToBackgroundDetachedContext(ctx)
t.ctx, t.cancel = context.WithCancel(core.ToBackgroundDetachedContext(ctx))
t.policyManager = pm
t.dispatcher = dispatcher
@@ -265,6 +268,11 @@ func (t *Handler) HandleConnection(conn net.Conn, destination net.Destination) {
// Close implements common.Closable.
func (t *Handler) Close() error {
// cancel first so every dispatch in flight unwinds, then close the stack (resets TCP, ends UDP flows)
// and the tun
if t.cancel != nil {
t.cancel()
}
return errors.Combine(common.CloseIfExists(t.stack), common.CloseIfExists(t.tun))
}
+34
View File
@@ -179,3 +179,37 @@ func TestHandlerCountsTunConnectionTraffic(t *testing.T) {
t.Fatalf("connection write mismatch: got %q, want %q", got, "downlink")
}
}
// a dispatcher that only returns when its context ends
type blockingDispatcher struct {
testDispatcher
entered chan struct{}
}
func (d *blockingDispatcher) DispatchLink(ctx context.Context, dest xnet.Destination, link *transport.Link) error {
close(d.entered)
<-ctx.Done()
return ctx.Err()
}
// Closing the handler must end a dispatch that is not reading its connection: the handler's context
// is detached from the instance's, so Close is what cancels it
func TestHandlerCloseCancelsDispatches(t *testing.T) {
dispatcher := &blockingDispatcher{entered: make(chan struct{})}
handler := &Handler{config: &Config{}, dispatcher: dispatcher}
handler.ctx, handler.cancel = context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
handler.HandleConnection(newTestConn(nil), xnet.TCPDestination(xnet.LocalHostIP, 443))
close(done)
}()
<-dispatcher.entered
if err := handler.Close(); err != nil {
t.Fatal(err)
}
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("dispatch still running after Close")
}
}
+5
View File
@@ -148,6 +148,11 @@ func (s *stack) Close() error {
for _, u := range sockets {
u.queue.close()
}
// the UDP flows the other side opened are in neither conns nor sockets; end them too, or their
// dispatches and what they hold survive the instance
if s.udp != nil {
s.udp.closeAll()
}
return nil
}
+23
View File
@@ -16,6 +16,8 @@ type udpConnectionHandler struct {
sync.RWMutex
udpConns map[net.Destination]*udpConn
// closed is set by closeAll; a packet that arrives after it opens no flow
closed bool
handleConnection func(conn net.Conn, dest net.Destination)
writePacket func(data []byte, src net.Destination, dst net.Destination) error
@@ -51,6 +53,10 @@ func (u *udpConnectionHandler) HandlePacket(src net.Destination, dst net.Destina
u.Lock()
defer u.Unlock()
if u.closed {
data.Release()
return
}
conn, found = u.udpConns[src]
if !found {
conn = &udpConn{handler: u, queue: newPacketQueue(udpQueueLimit), src: src, dst: dst}
@@ -66,6 +72,23 @@ func (u *udpConnectionHandler) HandlePacket(src net.Destination, dst net.Destina
}
}
// closeAll ends every UDP flow and takes no new ones: the readers get EOF, so the dispatch of each flow
// returns and lets go of its outbound. Called when the stack closes; without it an inbound's UDP flows,
// and whatever carries them, outlive the instance.
func (u *udpConnectionHandler) closeAll() {
u.Lock()
u.closed = true
conns := make([]*udpConn, 0, len(u.udpConns))
for _, c := range u.udpConns {
conns = append(conns, c)
}
u.udpConns = make(map[net.Destination]*udpConn)
u.Unlock()
for _, c := range conns {
c.queue.close()
}
}
func (u *udpConnectionHandler) connectionFinished(conn *udpConn) {
u.Lock()
// Close runs twice per flow; a newer conn may already own this src.
+36
View File
@@ -89,3 +89,39 @@ func TestPacketQueueDropsDrainedStorage(t *testing.T) {
t.Fatalf("drained queue still holds %d slots", cap(q.items))
}
}
// A closing stack must end its UDP flows: the dispatch reading a flow gets EOF and returns, instead of
// waiting on the queue forever and keeping its outbound alive past the instance; a packet that arrives
// afterwards opens no flow.
func TestUDPHandlerCloseAllEndsFlows(t *testing.T) {
done := make(chan struct{}, 2)
handler := newUdpConnectionHandler(func(conn net.Conn, dest net.Destination) {
b := make([]byte, 2048)
for {
if _, err := conn.Read(b); err != nil {
done <- struct{}{}
return
}
}
}, func(data []byte, src net.Destination, dst net.Destination) error { return nil })
dst := net.UDPDestination(net.IPAddress([]byte{10, 6, 0, 2}), 53)
for _, port := range []net.Port{40000, 40001} {
src := net.UDPDestination(net.IPAddress([]byte{10, 255, 0, 2}), port)
handler.HandlePacket(src, dst, buf.FromBytes([]byte("query")))
}
handler.closeAll()
for i := 0; i < 2; i++ {
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatalf("flow %d still running after closeAll", i)
}
}
handler.HandlePacket(net.UDPDestination(net.IPAddress([]byte{10, 255, 0, 2}), 40002), dst, buf.FromBytes([]byte("late")))
handler.RLock()
n := len(handler.udpConns)
handler.RUnlock()
if n != 0 {
t.Fatalf("%d flows in the table after closeAll", n)
}
}
+1 -3
View File
@@ -50,7 +50,6 @@ func init() {
type Handler struct {
server *protocol.ServerSpec
policyManager policy.Manager
cone bool
encryption *encryption.ClientInstance
reverse *Reverse
@@ -78,7 +77,6 @@ func New(ctx context.Context, config *Config) (*Handler, error) {
handler := &Handler{
server: server,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
cone: ctx.Value("cone").(bool),
}
a := handler.server.User.Account.(*vless.MemoryAccount)
@@ -300,7 +298,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
clientReader := link.Reader // .(*pipe.Reader)
clientWriter := link.Writer // .(*pipe.Writer)
trafficState := proxy.NewTrafficState(account.ID.Bytes())
if request.Command == protocol.RequestCommandUDP && (requestAddons.Flow == vless.XRV || (h.cone && request.Port != 53 && request.Port != 443)) {
if request.Command == protocol.RequestCommandUDP && (requestAddons.Flow == vless.XRV || (request.Port != 53 && request.Port != 443)) {
request.Command = protocol.RequestCommandMux
request.Address = net.DomainAddress("v1.mux.cool")
request.Port = net.Port(666)
+17 -76
View File
@@ -14,8 +14,6 @@ import (
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/common/signal"
"github.com/xtls/xray-core/common/task"
"github.com/xtls/xray-core/common/uuid"
"github.com/xtls/xray-core/core"
feature_inbound "github.com/xtls/xray-core/features/inbound"
@@ -23,6 +21,7 @@ import (
"github.com/xtls/xray-core/features/routing"
"github.com/xtls/xray-core/proxy/vmess"
"github.com/xtls/xray-core/proxy/vmess/encoding"
"github.com/xtls/xray-core/transport"
"github.com/xtls/xray-core/transport/internet/stat"
)
@@ -185,44 +184,6 @@ func (h *Handler) RemoveUser(ctx context.Context, email string) error {
return nil
}
func transferResponse(timer signal.ActivityUpdater, session *encoding.ServerSession, request *protocol.RequestHeader, response *protocol.ResponseHeader, input buf.Reader, output *buf.BufferedWriter) error {
session.EncodeResponseHeader(response, output)
bodyWriter, err := session.EncodeResponseBody(request, output)
if err != nil {
return errors.New("failed to start decoding response").Base(err)
}
{
// Optimize for small response packet
data, err := input.ReadMultiBuffer()
if err != nil {
return err
}
if err := bodyWriter.WriteMultiBuffer(data); err != nil {
return err
}
}
if err := output.SetBuffered(false); err != nil {
return err
}
if err := buf.Copy(input, bodyWriter, buf.UpdateActivity(timer)); err != nil {
return err
}
account := request.User.Account.(*vmess.MemoryAccount)
if request.Option.Has(protocol.RequestOptionChunkStream) && !account.NoTerminationSignal {
if err := bodyWriter.WriteMultiBuffer(buf.MultiBuffer{}); err != nil {
return err
}
}
return nil
}
// Process implements proxy.Inbound.Process().
func (h *Handler) Process(ctx context.Context, network net.Network, connection stat.Connection, dispatcher routing.Dispatcher) error {
sessionPolicy := h.policyManager.ForLevel(0)
@@ -273,49 +234,29 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
inbound.CanSpliceCopy = 3
inbound.User = request.User
sessionPolicy = h.policyManager.ForLevel(request.User.Level)
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
link, err := dispatcher.Dispatch(ctx, request.Destination())
bodyReader, err := svrSession.DecodeRequestBody(request, reader)
if err != nil {
return errors.New("failed to dispatch request to ", request.Destination()).Base(err)
return errors.New("failed to start decoding").Base(err)
}
requestDone := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
bodyReader, err := svrSession.DecodeRequestBody(request, reader)
if err != nil {
return errors.New("failed to start decoding").Base(err)
}
if err := buf.Copy(bodyReader, link.Writer, buf.UpdateActivity(timer)); err != nil {
return errors.New("failed to transfer request").Base(err)
}
return nil
writer := buf.NewBufferedWriter(buf.NewWriter(connection))
response := &protocol.ResponseHeader{
Command: h.generateCommand(ctx, request),
}
responseDone := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
writer := buf.NewBufferedWriter(buf.NewWriter(connection))
defer writer.Flush()
response := &protocol.ResponseHeader{
Command: h.generateCommand(ctx, request),
}
return transferResponse(timer, svrSession, request, response, link.Reader, writer)
svrSession.EncodeResponseHeader(response, writer)
bodyWriter, err := svrSession.EncodeResponseBody(request, writer)
if err != nil {
return errors.New("failed to start decoding response").Base(err)
}
writer.SetFlushNext()
requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDonePost, responseDone); err != nil {
common.Interrupt(link.Reader)
common.Interrupt(link.Writer)
return errors.New("connection ends").Base(err)
if err := dispatcher.DispatchLink(ctx, request.Destination(), &transport.Link{
Reader: bodyReader,
Writer: bodyWriter,
},
); err != nil {
return errors.New("failed to dispatch request").Base(err)
}
return nil
}
+1 -3
View File
@@ -32,7 +32,6 @@ import (
type Handler struct {
server *protocol.ServerSpec
policyManager policy.Manager
cone bool
}
// New creates a new VMess outbound handler.
@@ -49,7 +48,6 @@ func New(ctx context.Context, config *Config) (*Handler, error) {
handler := &Handler{
server: server,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
cone: ctx.Value("cone").(bool),
}
return handler, nil
@@ -143,7 +141,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
}
}, sessionPolicy.Timeouts.ConnectionIdle)
if request.Command == protocol.RequestCommandUDP && h.cone && request.Port != 53 && request.Port != 443 {
if request.Command == protocol.RequestCommandUDP && request.Port != 53 && request.Port != 443 {
request.Command = protocol.RequestCommandMux
request.Address = net.DomainAddress("v1.mux.cool")
request.Port = net.Port(666)
+1 -1
View File
@@ -91,7 +91,7 @@ func (h *HunkReaderWriter) ReadMultiBuffer() (buf.MultiBuffer, error) {
}
}
if cap(h.buf) >= buf.Size {
if len(h.buf) == buf.Size {
b := h.buf
h.index = len(h.buf)
return buf.MultiBuffer{buf.NewExisted(b)}, nil
@@ -74,14 +74,10 @@ func (h *MultiHunkReaderWriter) ReadMultiBuffer() (buf.MultiBuffer, error) {
continue
}
if cap(b) >= buf.Size {
if len(b) == buf.Size {
mb = append(mb, buf.NewExisted(b))
} else {
nb := buf.New()
nb.Extend(int32(len(b)))
copy(nb.Bytes(), b)
mb = append(mb, nb)
mb = buf.MergeBytes(mb, b)
}
}
+1 -1
View File
@@ -84,7 +84,7 @@ func OriginalDst(la, ra net.Addr) (net.IP, int, error) {
nl.sxport[0], nl.sxport[1] = byte(raPort>>8), byte(raPort)
nl.dxport[0], nl.dxport[1] = byte(laPort>>8), byte(laPort)
if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, fd, DIOCNATLOOK, uintptr(unsafe.Pointer(&nl))); errno != 0 {
return net.IP{}, -1, os.NewSyscallError("ioctl", err)
return net.IP{}, -1, os.NewSyscallError("ioctl", errno)
}
odPort := nl.rdxport
+3
View File
@@ -227,6 +227,9 @@ func createHTTPClient(dest net.Destination, streamSettings *internet.MemoryStrea
conn, err := tr.DialEarly(ctx, udpAddr, tlsCfg, cfg)
if err != nil {
// pktConn first: tr.Close() waits for the read from it to return, which with dialerProxy has no deadline
pktConn.Close()
tr.Close()
return nil, err
}
context.AfterFunc(conn.Context(), func() { tr.Close(); pktConn.Close() })
+1 -1
View File
@@ -17,7 +17,7 @@ func DialTaggedOutbound(ctx context.Context, dispatcher routing.Dispatcher, dest
return nil, errors.New("Instance context variable is not in context, dial denied. ")
}
content := new(session.Content)
content.SkipDNSResolve = tag != ""
content.SkipDNSResolve = true
ctx = session.ContextWithContent(ctx, content)
ctx = session.SetForcedOutboundTagToContext(ctx, tag)
+8 -7
View File
@@ -270,18 +270,12 @@ var PresetFingerprints = map[string]*utls.ClientHelloID{
var ModernFingerprints = map[string]*utls.ClientHelloID{
// One of these will be chosen as `random` at startup
"hellofirefox_120": &utls.HelloFirefox_120,
// All of them must have X25519MLKEM768 before optional X25519, otherwise REALITY servers (since v26.9.9) will reject them
"hellofirefox_148": &utls.HelloFirefox_148,
"hellochrome_120": &utls.HelloChrome_120,
"hellochrome_131": &utls.HelloChrome_131,
"hellochrome_133": &utls.HelloChrome_133,
"hellochrome_155": &utls.HelloChrome_155,
"helloios_13": &utls.HelloIOS_13,
"helloios_14": &utls.HelloIOS_14,
"helloedge_106": &utls.HelloEdge_106,
"hellosafari_26_3": &utls.HelloSafari_26_3,
"hello360_11_0": &utls.Hello360_11_0,
"helloqq_11_1": &utls.HelloQQ_11_1,
}
var OtherFingerprints = map[string]*utls.ClientHelloID{
@@ -298,6 +292,7 @@ var OtherFingerprints = map[string]*utls.ClientHelloID{
"hellofirefox_99": &utls.HelloFirefox_99,
"hellofirefox_102": &utls.HelloFirefox_102,
"hellofirefox_105": &utls.HelloFirefox_105,
"hellofirefox_120": &utls.HelloFirefox_120,
"hellochrome_auto": &utls.HelloChrome_Auto,
"hellochrome_58": &utls.HelloChrome_58,
"hellochrome_62": &utls.HelloChrome_62,
@@ -309,17 +304,23 @@ var OtherFingerprints = map[string]*utls.ClientHelloID{
"hellochrome_100": &utls.HelloChrome_100,
"hellochrome_102": &utls.HelloChrome_102,
"hellochrome_106_shuffle": &utls.HelloChrome_106_Shuffle,
"hellochrome_120": &utls.HelloChrome_120,
"helloios_auto": &utls.HelloIOS_Auto,
"helloios_11_1": &utls.HelloIOS_11_1,
"helloios_12_1": &utls.HelloIOS_12_1,
"helloios_13": &utls.HelloIOS_13,
"helloios_14": &utls.HelloIOS_14,
"helloandroid_11_okhttp": &utls.HelloAndroid_11_OkHttp,
"helloedge_85": &utls.HelloEdge_85,
"helloedge_106": &utls.HelloEdge_106,
"helloedge_auto": &utls.HelloEdge_Auto,
"hellosafari_16_0": &utls.HelloSafari_16_0,
"hellosafari_auto": &utls.HelloSafari_Auto,
"hello360_auto": &utls.Hello360_Auto,
"hello360_7_5": &utls.Hello360_7_5,
"hello360_11_0": &utls.Hello360_11_0,
"helloqq_auto": &utls.HelloQQ_Auto,
"helloqq_11_1": &utls.HelloQQ_11_1,
// Chrome betas
"hellochrome_100_psk": &utls.HelloChrome_100_PSK,