Compare commits

...
Author SHA1 Message Date
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
26 changed files with 221 additions and 137 deletions
+8 -5
View File
@@ -124,14 +124,17 @@ func (c *CacheController) writeAndShrink(expiredKeys []string) {
if rec == nil { if rec == nil {
continue continue
} }
if rec.A != nil && rec.A.Expire.Before(now) { a, aaaa := rec.A, rec.AAAA
rec.A = nil if a != nil && a.Expire.Before(now) {
a = nil
} }
if rec.AAAA != nil && rec.AAAA.Expire.Before(now) { if aaaa != nil && aaaa.Expire.Before(now) {
rec.AAAA = nil aaaa = nil
} }
if rec.A == nil && rec.AAAA == nil { if a == nil && aaaa == nil {
delete(c.ips, domain) 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 checker *task.Periodic
activeConn map[connID]*udpConn activeConn map[connID]*udpConn
ctx context.Context ctx context.Context
cone bool
} }
func (w *udpWorker) getConnection(id connID) (*udpConn, bool) { 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, src: source,
} }
if originalDest.IsValid() { if originalDest.IsValid() {
if !w.cone {
id.dest = originalDest
}
b.UDP = &originalDest b.UDP = &originalDest
} }
conn, existing := w.getConnection(id) conn, existing := w.getConnection(id)
@@ -418,8 +414,6 @@ func (w *udpWorker) Start() error {
return err return err
} }
w.cone = w.ctx.Value("cone").(bool)
w.checker = &task.Periodic{ w.checker = &task.Periodic{
Interval: time.Minute, Interval: time.Minute,
Execute: w.clean, Execute: w.clean,
+12 -11
View File
@@ -8,6 +8,7 @@ import (
"fmt" "fmt"
"net" "net"
"os" "os"
"slices"
"strconv" "strconv"
"strings" "strings"
@@ -31,7 +32,7 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
switch network { switch network {
case "tcp": case "tcp":
if net.ParseIP(srcIP).To4() != nil { if net.ParseIP(srcIP).To4() != nil {
procFiles = []string{"/proc/net/tcp"} procFiles = []string{"/proc/net/tcp", "/proc/net/tcp6"}
} else { } else {
procFiles = []string{"/proc/net/tcp6"} 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.") 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 := "" portFallback := ""
if network == "udp" { if network == "udp" {
portFallback = fmt.Sprintf(":%04X", srcPort) portFallback = fmt.Sprintf(":%04X", srcPort)
} }
inode, err := findInodeInFiles(procFiles, targetHexAddr, portFallback) inode, err := findInodeInFiles(procFiles, targetHexAddrs, portFallback)
if err != nil { if err != nil {
return 0, "", "", errors.New("could not search in ", strings.Join(procFiles, " and ")).Base(err) 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 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 { func formatProcNetAddress(addr net.IP, port Port) string {
var ipBytes []byte ipBytes := []byte(addr)
if ipv4 := addr.To4(); ipv4 != nil {
ipBytes = ipv4
} else {
ipBytes = addr.To16()
}
var formatted strings.Builder var formatted strings.Builder
formatted.Grow(len(ipBytes)*2 + 5) formatted.Grow(len(ipBytes)*2 + 5)
@@ -101,7 +102,7 @@ func formatProcNetAddress(addr net.IP, port Port) string {
return formatted.String() return formatted.String()
} }
func findInodeInFiles(filePaths []string, targetHexAddr, portFallback string) (string, error) { func findInodeInFiles(filePaths []string, targetHexAddrs []string, portFallback string) (string, error) {
onlyMatchedPort := "" onlyMatchedPort := ""
for i, filePath := range filePaths { for i, filePath := range filePaths {
@@ -122,7 +123,7 @@ func findInodeInFiles(filePaths []string, targetHexAddr, portFallback string) (s
} }
localAddress := fields[1] localAddress := fields[1]
if localAddress == targetHexAddr { if slices.Contains(targetHexAddrs, localAddress) {
return fields[9], nil return fields[9], nil
} }
if portFallback != "" && strings.HasSuffix(localAddress, portFallback) { 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" UseReadV = "xray.buf.readv"
UseFreedomSplice = "xray.buf.splice" UseFreedomSplice = "xray.buf.splice"
UseVmessPadding = "xray.vmess.padding" UseVmessPadding = "xray.vmess.padding"
UseCone = "xray.cone.disabled"
UseStrictJSON = "xray.json.strict" UseStrictJSON = "xray.json.strict"
BufferSize = "xray.ray.buffer.size" BufferSize = "xray.ray.buffer.size"
-3
View File
@@ -63,9 +63,6 @@ func init() {
} }
func GetGlobalID(ctx context.Context) (globalID [8]byte) { 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 && 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") { (inbound.Name == "dokodemo-door" || inbound.Name == "socks" || inbound.Name == "shadowsocks" || inbound.Name == "tun") {
h := blake3.New(8, ensureBaseKey()) 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 { if err := platform.ReloadEnvSettings(); err != nil {
return true, errors.New("failed to reload environment settings").Base(err) 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 { for _, appSettings := range config.App {
settings, err := appSettings.GetInstance() settings, err := appSettings.GetInstance()
+1 -1
View File
@@ -45,7 +45,7 @@ require (
github.com/huin/goupnp v1.2.0 // indirect github.com/huin/goupnp v1.2.0 // indirect
github.com/jackpal/go-nat-pmp v1.0.2 // indirect github.com/jackpal/go-nat-pmp v1.0.2 // indirect
github.com/juju/ratelimit 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/koron/go-ssdp v0.0.4 // indirect
github.com/libp2p/go-netroute v0.2.1 // indirect github.com/libp2p/go-netroute v0.2.1 // indirect
github.com/molecule-man/go-brrr v1.2.0 // 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/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 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=
github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= 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 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ=
github.com/klauspost/cpuid/v2 v2.4.2/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= github.com/klauspost/cpuid/v2 v2.4.2/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/koron/go-ssdp v0.0.4 h1:1IDwrghSKYM7yLf7XCzbByg2sJ/JcNOZRXS2jczTwz0= github.com/koron/go-ssdp v0.0.4 h1:1IDwrghSKYM7yLf7XCzbByg2sJ/JcNOZRXS2jczTwz0=
+1
View File
@@ -150,6 +150,7 @@ Start:
To: request.URL, To: request.URL,
Status: log.AccessAccepted, Status: log.AccessAccepted,
Reason: "", Reason: "",
Email: inbound.User.Email,
}) })
if strings.EqualFold(request.Method, "CONNECT") { if strings.EqualFold(request.Method, "CONNECT") {
+1 -3
View File
@@ -25,7 +25,6 @@ type Server struct {
config *ServerConfig config *ServerConfig
validator *Validator validator *Validator
policyManager policy.Manager policyManager policy.Manager
cone bool
} }
// NewServer create a new Shadowsocks server. // NewServer create a new Shadowsocks server.
@@ -47,7 +46,6 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
config: config, config: config,
validator: validator, validator: validator,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
cone: ctx.Value("cone").(bool),
} }
return s, nil return s, nil
@@ -185,7 +183,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis
data.UDP = &destination data.UDP = &destination
if !s.cone || dest == nil { if dest == nil {
dest = &destination dest = &destination
} }
+3 -3
View File
@@ -29,7 +29,6 @@ import (
type Server struct { type Server struct {
config *ServerConfig config *ServerConfig
policyManager policy.Manager policyManager policy.Manager
cone bool
httpServer *http.Server httpServer *http.Server
} }
@@ -39,7 +38,6 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
s := &Server{ s := &Server{
config: config, config: config,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
cone: ctx.Value("cone").(bool),
} }
httpConfig := &http.ServerConfig{ httpConfig := &http.ServerConfig{
UserLevel: config.UserLevel, UserLevel: config.UserLevel,
@@ -149,6 +147,7 @@ func (s *Server) processTCP(ctx context.Context, conn stat.Connection, dispatche
To: dest, To: dest,
Status: log.AccessAccepted, Status: log.AccessAccepted,
Reason: "", Reason: "",
Email: inbound.User.Email,
}) })
} }
if inbound.CanSpliceCopy == 2 { if inbound.CanSpliceCopy == 2 {
@@ -270,12 +269,13 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis
To: destination, To: destination,
Status: log.AccessAccepted, Status: log.AccessAccepted,
Reason: "", Reason: "",
Email: inbound.User.Email,
}) })
} }
payload.UDP = &destination payload.UDP = &destination
if !s.cone || dest == nil { if dest == nil {
dest = &destination dest = &destination
} }
+1 -3
View File
@@ -38,7 +38,6 @@ type Server struct {
policyManager policy.Manager policyManager policy.Manager
validator *Validator validator *Validator
fallbacks map[string]map[string]map[string]*Fallback // or nil fallbacks map[string]map[string]map[string]*Fallback // or nil
cone bool
} }
// NewServer creates a new trojan inbound handler. // NewServer creates a new trojan inbound handler.
@@ -59,7 +58,6 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
server := &Server{ server := &Server{
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
validator: validator, validator: validator,
cone: ctx.Value("cone").(bool),
} }
if config.Fallbacks != nil { 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) errors.LogInfo(ctx, "tunnelling request to ", destination)
if !s.cone || dest == nil { if dest == nil {
dest = &destination 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 // Handler is managing object that tie together tun interface, ip stack and dispatch connections to the routing
type Handler struct { 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 ctx context.Context
cancel context.CancelFunc
config *Config config *Config
stack Stack stack Stack
tun Tun tun Tun
@@ -96,7 +99,7 @@ func (t *Handler) Init(ctx context.Context, pm policy.Manager, dispatcher routin
t.sniffingRequest = content.SniffingRequest t.sniffingRequest = content.SniffingRequest
} }
t.ctx = core.ToBackgroundDetachedContext(ctx) t.ctx, t.cancel = context.WithCancel(core.ToBackgroundDetachedContext(ctx))
t.policyManager = pm t.policyManager = pm
t.dispatcher = dispatcher t.dispatcher = dispatcher
@@ -265,6 +268,11 @@ func (t *Handler) HandleConnection(conn net.Conn, destination net.Destination) {
// Close implements common.Closable. // Close implements common.Closable.
func (t *Handler) Close() error { 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)) 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") 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 { for _, u := range sockets {
u.queue.close() 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 return nil
} }
+23
View File
@@ -16,6 +16,8 @@ type udpConnectionHandler struct {
sync.RWMutex sync.RWMutex
udpConns map[net.Destination]*udpConn 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) handleConnection func(conn net.Conn, dest net.Destination)
writePacket func(data []byte, src net.Destination, dst net.Destination) error 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() u.Lock()
defer u.Unlock() defer u.Unlock()
if u.closed {
data.Release()
return
}
conn, found = u.udpConns[src] conn, found = u.udpConns[src]
if !found { if !found {
conn = &udpConn{handler: u, queue: newPacketQueue(udpQueueLimit), src: src, dst: dst} 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) { func (u *udpConnectionHandler) connectionFinished(conn *udpConn) {
u.Lock() u.Lock()
// Close runs twice per flow; a newer conn may already own this src. // 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)) 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 { type Handler struct {
server *protocol.ServerSpec server *protocol.ServerSpec
policyManager policy.Manager policyManager policy.Manager
cone bool
encryption *encryption.ClientInstance encryption *encryption.ClientInstance
reverse *Reverse reverse *Reverse
@@ -78,7 +77,6 @@ func New(ctx context.Context, config *Config) (*Handler, error) {
handler := &Handler{ handler := &Handler{
server: server, server: server,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
cone: ctx.Value("cone").(bool),
} }
a := handler.server.User.Account.(*vless.MemoryAccount) 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) clientReader := link.Reader // .(*pipe.Reader)
clientWriter := link.Writer // .(*pipe.Writer) clientWriter := link.Writer // .(*pipe.Writer)
trafficState := proxy.NewTrafficState(account.ID.Bytes()) 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.Command = protocol.RequestCommandMux
request.Address = net.DomainAddress("v1.mux.cool") request.Address = net.DomainAddress("v1.mux.cool")
request.Port = net.Port(666) 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/net"
"github.com/xtls/xray-core/common/protocol" "github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/session" "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/common/uuid"
"github.com/xtls/xray-core/core" "github.com/xtls/xray-core/core"
feature_inbound "github.com/xtls/xray-core/features/inbound" 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/features/routing"
"github.com/xtls/xray-core/proxy/vmess" "github.com/xtls/xray-core/proxy/vmess"
"github.com/xtls/xray-core/proxy/vmess/encoding" "github.com/xtls/xray-core/proxy/vmess/encoding"
"github.com/xtls/xray-core/transport"
"github.com/xtls/xray-core/transport/internet/stat" "github.com/xtls/xray-core/transport/internet/stat"
) )
@@ -185,44 +184,6 @@ func (h *Handler) RemoveUser(ctx context.Context, email string) error {
return nil 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(). // Process implements proxy.Inbound.Process().
func (h *Handler) Process(ctx context.Context, network net.Network, connection stat.Connection, dispatcher routing.Dispatcher) error { func (h *Handler) Process(ctx context.Context, network net.Network, connection stat.Connection, dispatcher routing.Dispatcher) error {
sessionPolicy := h.policyManager.ForLevel(0) 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.CanSpliceCopy = 3
inbound.User = request.User inbound.User = request.User
sessionPolicy = h.policyManager.ForLevel(request.User.Level) bodyReader, err := svrSession.DecodeRequestBody(request, reader)
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())
if err != nil { 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 { writer := buf.NewBufferedWriter(buf.NewWriter(connection))
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly) response := &protocol.ResponseHeader{
Command: h.generateCommand(ctx, request),
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
} }
svrSession.EncodeResponseHeader(response, writer)
responseDone := func() error { bodyWriter, err := svrSession.EncodeResponseBody(request, writer)
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) if err != nil {
return errors.New("failed to start decoding response").Base(err)
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)
} }
writer.SetFlushNext()
requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer)) if err := dispatcher.DispatchLink(ctx, request.Destination(), &transport.Link{
if err := task.Run(ctx, requestDonePost, responseDone); err != nil { Reader: bodyReader,
common.Interrupt(link.Reader) Writer: bodyWriter,
common.Interrupt(link.Writer) },
return errors.New("connection ends").Base(err) ); err != nil {
return errors.New("failed to dispatch request").Base(err)
} }
return nil return nil
} }
+1 -3
View File
@@ -32,7 +32,6 @@ import (
type Handler struct { type Handler struct {
server *protocol.ServerSpec server *protocol.ServerSpec
policyManager policy.Manager policyManager policy.Manager
cone bool
} }
// New creates a new VMess outbound handler. // New creates a new VMess outbound handler.
@@ -49,7 +48,6 @@ func New(ctx context.Context, config *Config) (*Handler, error) {
handler := &Handler{ handler := &Handler{
server: server, server: server,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
cone: ctx.Value("cone").(bool),
} }
return handler, nil return handler, nil
@@ -143,7 +141,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
} }
}, sessionPolicy.Timeouts.ConnectionIdle) }, 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.Command = protocol.RequestCommandMux
request.Address = net.DomainAddress("v1.mux.cool") request.Address = net.DomainAddress("v1.mux.cool")
request.Port = net.Port(666) 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 b := h.buf
h.index = len(h.buf) h.index = len(h.buf)
return buf.MultiBuffer{buf.NewExisted(b)}, nil return buf.MultiBuffer{buf.NewExisted(b)}, nil
@@ -74,14 +74,10 @@ func (h *MultiHunkReaderWriter) ReadMultiBuffer() (buf.MultiBuffer, error) {
continue continue
} }
if cap(b) >= buf.Size { if len(b) == buf.Size {
mb = append(mb, buf.NewExisted(b)) mb = append(mb, buf.NewExisted(b))
} else { } else {
nb := buf.New() mb = buf.MergeBytes(mb, b)
nb.Extend(int32(len(b)))
copy(nb.Bytes(), b)
mb = append(mb, nb)
} }
} }
+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.sxport[0], nl.sxport[1] = byte(raPort>>8), byte(raPort)
nl.dxport[0], nl.dxport[1] = byte(laPort>>8), byte(laPort) 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 { 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 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) conn, err := tr.DialEarly(ctx, udpAddr, tlsCfg, cfg)
if err != nil { 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 return nil, err
} }
context.AfterFunc(conn.Context(), func() { tr.Close(); pktConn.Close() }) context.AfterFunc(conn.Context(), func() { tr.Close(); pktConn.Close() })
+8 -7
View File
@@ -270,18 +270,12 @@ var PresetFingerprints = map[string]*utls.ClientHelloID{
var ModernFingerprints = map[string]*utls.ClientHelloID{ var ModernFingerprints = map[string]*utls.ClientHelloID{
// One of these will be chosen as `random` at startup // 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, "hellofirefox_148": &utls.HelloFirefox_148,
"hellochrome_120": &utls.HelloChrome_120,
"hellochrome_131": &utls.HelloChrome_131, "hellochrome_131": &utls.HelloChrome_131,
"hellochrome_133": &utls.HelloChrome_133, "hellochrome_133": &utls.HelloChrome_133,
"hellochrome_155": &utls.HelloChrome_155, "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, "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{ var OtherFingerprints = map[string]*utls.ClientHelloID{
@@ -298,6 +292,7 @@ var OtherFingerprints = map[string]*utls.ClientHelloID{
"hellofirefox_99": &utls.HelloFirefox_99, "hellofirefox_99": &utls.HelloFirefox_99,
"hellofirefox_102": &utls.HelloFirefox_102, "hellofirefox_102": &utls.HelloFirefox_102,
"hellofirefox_105": &utls.HelloFirefox_105, "hellofirefox_105": &utls.HelloFirefox_105,
"hellofirefox_120": &utls.HelloFirefox_120,
"hellochrome_auto": &utls.HelloChrome_Auto, "hellochrome_auto": &utls.HelloChrome_Auto,
"hellochrome_58": &utls.HelloChrome_58, "hellochrome_58": &utls.HelloChrome_58,
"hellochrome_62": &utls.HelloChrome_62, "hellochrome_62": &utls.HelloChrome_62,
@@ -309,17 +304,23 @@ var OtherFingerprints = map[string]*utls.ClientHelloID{
"hellochrome_100": &utls.HelloChrome_100, "hellochrome_100": &utls.HelloChrome_100,
"hellochrome_102": &utls.HelloChrome_102, "hellochrome_102": &utls.HelloChrome_102,
"hellochrome_106_shuffle": &utls.HelloChrome_106_Shuffle, "hellochrome_106_shuffle": &utls.HelloChrome_106_Shuffle,
"hellochrome_120": &utls.HelloChrome_120,
"helloios_auto": &utls.HelloIOS_Auto, "helloios_auto": &utls.HelloIOS_Auto,
"helloios_11_1": &utls.HelloIOS_11_1, "helloios_11_1": &utls.HelloIOS_11_1,
"helloios_12_1": &utls.HelloIOS_12_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, "helloandroid_11_okhttp": &utls.HelloAndroid_11_OkHttp,
"helloedge_85": &utls.HelloEdge_85, "helloedge_85": &utls.HelloEdge_85,
"helloedge_106": &utls.HelloEdge_106,
"helloedge_auto": &utls.HelloEdge_Auto, "helloedge_auto": &utls.HelloEdge_Auto,
"hellosafari_16_0": &utls.HelloSafari_16_0, "hellosafari_16_0": &utls.HelloSafari_16_0,
"hellosafari_auto": &utls.HelloSafari_Auto, "hellosafari_auto": &utls.HelloSafari_Auto,
"hello360_auto": &utls.Hello360_Auto, "hello360_auto": &utls.Hello360_Auto,
"hello360_7_5": &utls.Hello360_7_5, "hello360_7_5": &utls.Hello360_7_5,
"hello360_11_0": &utls.Hello360_11_0,
"helloqq_auto": &utls.HelloQQ_Auto, "helloqq_auto": &utls.HelloQQ_Auto,
"helloqq_11_1": &utls.HelloQQ_11_1,
// Chrome betas // Chrome betas
"hellochrome_100_psk": &utls.HelloChrome_100_PSK, "hellochrome_100_psk": &utls.HelloChrome_100_PSK,