Compare commits

..
37 changed files with 227 additions and 277 deletions
+5 -8
View File
@@ -124,17 +124,14 @@ func (c *CacheController) writeAndShrink(expiredKeys []string) {
if rec == nil {
continue
}
a, aaaa := rec.A, rec.AAAA
if a != nil && a.Expire.Before(now) {
a = nil
if rec.A != nil && rec.A.Expire.Before(now) {
rec.A = nil
}
if aaaa != nil && aaaa.Expire.Before(now) {
aaaa = nil
if rec.AAAA != nil && rec.AAAA.Expire.Before(now) {
rec.AAAA = nil
}
if a == nil && aaaa == nil {
if rec.A == nil && rec.AAAA == nil {
delete(c.ips, domain)
} else if a != rec.A || aaaa != rec.AAAA {
c.ips[domain] = &record{A: a, AAAA: aaaa}
}
}
+7 -1
View File
@@ -273,7 +273,8 @@ type udpWorker struct {
checker *task.Periodic
activeConn map[connID]*udpConn
ctx context.Context
ctx context.Context
cone bool
}
func (w *udpWorker) getConnection(id connID) (*udpConn, bool) {
@@ -315,6 +316,9 @@ 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)
@@ -414,6 +418,8 @@ func (w *udpWorker) Start() error {
return err
}
w.cone = w.ctx.Value("cone").(bool)
w.checker = &task.Periodic{
Interval: time.Minute,
Execute: w.clean,
+22 -19
View File
@@ -181,26 +181,29 @@ func (h *Handler) Tag() string {
func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) {
outbounds := session.OutboundsFromContext(ctx)
ob := outbounds[len(outbounds)-1]
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
}
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")
} 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())
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())
}
}
}
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
+2 -3
View File
@@ -44,9 +44,8 @@ func (c routingContext) GetRuleTag() string {
return ""
}
// 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
// GetSkipDNSResolve implements routing.Context.
// The protobuf RoutingContext has no skip flag, so API contexts use false.
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.NewReadOnlySlicePusher[uint32](L)),
"Match": newLuaDomainMatch(xlua.NewSlicePusher[uint32](L)),
"MatchAny": luaDomainMatchAny,
})
return 1
+1 -3
View File
@@ -104,9 +104,7 @@ for _, value in ipairs({matcher, domain}) do
assert(not pcall(function() return value ^ {} end))
end
assert(domain:matchAny("example.com"))
local indices = domain:Match("example.com")
assert(#indices == 1)
assert(not pcall(function() indices[1] = 7 end))
assert(#domain:Match("example.com") == 1)
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) {
+43 -21
View File
@@ -9,20 +9,53 @@ import (
luar "layeh.com/gopher-luar"
)
func TestReadOnlySlicePusher(t *testing.T) {
func TestSlicePusher(t *testing.T) {
L := glua.NewState()
defer L.Close()
push := NewReadOnlySlicePusher[int](L)
push := NewSlicePusher[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 co = coroutine.create(function() return getValues() end)
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 ok, result = coroutine.resume(co)
assert(ok, result)
values = result
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(#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))
@@ -36,17 +69,6 @@ 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) {
@@ -208,23 +230,23 @@ assert(not pcall(function() return nested + nested end))
}
}
func TestReadOnlySlicePusherMetatablePerState(t *testing.T) {
func TestSlicePusherMetatablePerState(t *testing.T) {
first := glua.NewState()
defer first.Close()
second := glua.NewState()
defer second.Close()
NewReadOnlySlicePusher[int](first)(first, []int{1})
NewReadOnlySlicePusher[int](second)(second, []int{1})
NewSlicePusher[int](first)(first, []int{1})
NewSlicePusher[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 BenchmarkReadOnlySlicePusher(b *testing.B) {
func BenchmarkSlicePusher(b *testing.B) {
L := glua.NewState()
defer L.Close()
ips := []net.IP{net.ParseIP("127.0.0.1")}
pushIPs := NewReadOnlySlicePusher[net.IP](L)
pushIPs := NewSlicePusher[net.IP](L)
for _, benchmark := range []struct {
name string
push func(*glua.LState, []net.IP)
+4 -2
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"}))
NewReadOnlySlicePusher[net.IP](L)(L, []net.IP{net.ParseIP("192.0.2.1")})
NewSlicePusher[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,7 +865,9 @@ assert(not ok and a == "{<address> <address>}")
PushUserData(L, struct{ Pointer *int }{&target})
L.SetGlobal("testObject", L.Get(-1))
L.Pop(1)
L.SetGlobal("testValues", luar.New(L, []int{1}))
NewSlicePusher[int](L)(L, []int{1})
L.SetGlobal("testValues", L.Get(-1))
L.Pop(1)
L.SetGlobal("testPanic", L.NewFunction(func(L *glua.LState) int {
panic(struct{ First, Second *int }{&target, &target})
}))
+11 -12
View File
@@ -8,7 +8,6 @@ import (
"fmt"
"net"
"os"
"slices"
"strconv"
"strings"
@@ -32,7 +31,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", "/proc/net/tcp6"}
procFiles = []string{"/proc/net/tcp"}
} else {
procFiles = []string{"/proc/net/tcp6"}
}
@@ -46,18 +45,14 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
panic("Unsupported network type for process lookup.")
}
targetHexAddrs := []string{formatProcNetAddress(net.ParseIP(srcIP).To16(), Port(srcPort))}
if ipv4 := net.ParseIP(srcIP).To4(); ipv4 != nil {
// the one above is then the IPv4-mapped IPv6 address that an IPv6 socket has it as, in the IPv6 file
targetHexAddrs = append(targetHexAddrs, formatProcNetAddress(ipv4, Port(srcPort)))
}
targetHexAddr := formatProcNetAddress(net.ParseIP(srcIP), Port(srcPort))
portFallback := ""
if network == "udp" {
portFallback = fmt.Sprintf(":%04X", srcPort)
}
inode, err := findInodeInFiles(procFiles, targetHexAddrs, portFallback)
inode, err := findInodeInFiles(procFiles, targetHexAddr, portFallback)
if err != nil {
return 0, "", "", errors.New("could not search in ", strings.Join(procFiles, " and ")).Base(err)
}
@@ -89,9 +84,13 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
return pid, procName, absPath, nil
}
// formatProcNetAddress formats the 4 or 16 bytes of addr as they are: an IPv4-mapped IPv6 address stays one
func formatProcNetAddress(addr net.IP, port Port) string {
ipBytes := []byte(addr)
var ipBytes []byte
if ipv4 := addr.To4(); ipv4 != nil {
ipBytes = ipv4
} else {
ipBytes = addr.To16()
}
var formatted strings.Builder
formatted.Grow(len(ipBytes)*2 + 5)
@@ -102,7 +101,7 @@ func formatProcNetAddress(addr net.IP, port Port) string {
return formatted.String()
}
func findInodeInFiles(filePaths []string, targetHexAddrs []string, portFallback string) (string, error) {
func findInodeInFiles(filePaths []string, targetHexAddr, portFallback string) (string, error) {
onlyMatchedPort := ""
for i, filePath := range filePaths {
@@ -123,7 +122,7 @@ func findInodeInFiles(filePaths []string, targetHexAddrs []string, portFallback
}
localAddress := fields[1]
if slices.Contains(targetHexAddrs, localAddress) {
if localAddress == targetHexAddr {
return fields[9], nil
}
if portFallback != "" && strings.HasSuffix(localAddress, portFallback) {
-50
View File
@@ -1,50 +0,0 @@
//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,6 +16,7 @@ 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,6 +77,11 @@ 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,6 +63,9 @@ 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,6 +192,8 @@ 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.4 // indirect
github.com/klauspost/compress v1.20.1 // 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,8 +33,6 @@ 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,6 +318,7 @@ 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 {
@@ -350,6 +351,10 @@ 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,7 +150,6 @@ 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 = true
content.SkipDNSResolve = session.SkipDNSResolveFromContext(ctx)
content.SniffingRequest = l.sniffingRequest
ctx = session.ContextWithContent(ctx, content)
+3 -1
View File
@@ -25,6 +25,7 @@ type Server struct {
config *ServerConfig
validator *Validator
policyManager policy.Manager
cone bool
}
// NewServer create a new Shadowsocks server.
@@ -46,6 +47,7 @@ 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
@@ -183,7 +185,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis
data.UDP = &destination
if dest == nil {
if !s.cone || dest == nil {
dest = &destination
}
+3 -3
View File
@@ -29,6 +29,7 @@ import (
type Server struct {
config *ServerConfig
policyManager policy.Manager
cone bool
httpServer *http.Server
}
@@ -38,6 +39,7 @@ 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,
@@ -147,7 +149,6 @@ 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 {
@@ -269,13 +270,12 @@ 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 dest == nil {
if !s.cone || dest == nil {
dest = &destination
}
+3 -1
View File
@@ -38,6 +38,7 @@ 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.
@@ -58,6 +59,7 @@ 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 {
@@ -300,7 +302,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, sessionPolicy policy.Sess
}
errors.LogInfo(ctx, "tunnelling request to ", destination)
if dest == nil {
if !s.cone || dest == nil {
dest = &destination
}
+1 -9
View File
@@ -25,10 +25,7 @@ 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
@@ -99,7 +96,7 @@ func (t *Handler) Init(ctx context.Context, pm policy.Manager, dispatcher routin
t.sniffingRequest = content.SniffingRequest
}
t.ctx, t.cancel = context.WithCancel(core.ToBackgroundDetachedContext(ctx))
t.ctx = core.ToBackgroundDetachedContext(ctx)
t.policyManager = pm
t.dispatcher = dispatcher
@@ -268,11 +265,6 @@ 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,37 +179,3 @@ 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,11 +148,6 @@ 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,8 +16,6 @@ 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
@@ -53,10 +51,6 @@ 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}
@@ -72,23 +66,6 @@ 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,39 +89,3 @@ 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)
}
}
+3 -1
View File
@@ -50,6 +50,7 @@ func init() {
type Handler struct {
server *protocol.ServerSpec
policyManager policy.Manager
cone bool
encryption *encryption.ClientInstance
reverse *Reverse
@@ -77,6 +78,7 @@ 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)
@@ -298,7 +300,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 || (request.Port != 53 && request.Port != 443)) {
if request.Command == protocol.RequestCommandUDP && (requestAddons.Flow == vless.XRV || (h.cone && request.Port != 53 && request.Port != 443)) {
request.Command = protocol.RequestCommandMux
request.Address = net.DomainAddress("v1.mux.cool")
request.Port = net.Port(666)
+78 -19
View File
@@ -14,6 +14,8 @@ 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"
@@ -21,7 +23,6 @@ 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"
)
@@ -184,6 +185,44 @@ 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)
@@ -234,29 +273,49 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
inbound.CanSpliceCopy = 3
inbound.User = request.User
bodyReader, err := svrSession.DecodeRequestBody(request, reader)
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())
if err != nil {
return errors.New("failed to start decoding").Base(err)
return errors.New("failed to dispatch request to ", request.Destination()).Base(err)
}
writer := buf.NewBufferedWriter(buf.NewWriter(connection))
response := &protocol.ResponseHeader{
Command: h.generateCommand(ctx, request),
}
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()
requestDone := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
if err := dispatcher.DispatchLink(ctx, request.Destination(), &transport.Link{
Reader: bodyReader,
Writer: bodyWriter,
},
); err != nil {
return errors.New("failed to dispatch request").Base(err)
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
}
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)
}
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)
}
return nil
}
+3 -1
View File
@@ -32,6 +32,7 @@ import (
type Handler struct {
server *protocol.ServerSpec
policyManager policy.Manager
cone bool
}
// New creates a new VMess outbound handler.
@@ -48,6 +49,7 @@ 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
@@ -141,7 +143,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
}
}, sessionPolicy.Timeouts.ConnectionIdle)
if request.Command == protocol.RequestCommandUDP && request.Port != 53 && request.Port != 443 {
if request.Command == protocol.RequestCommandUDP && h.cone && 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 len(h.buf) == buf.Size {
if cap(h.buf) >= buf.Size {
b := h.buf
h.index = len(h.buf)
return buf.MultiBuffer{buf.NewExisted(b)}, nil
@@ -74,10 +74,14 @@ func (h *MultiHunkReaderWriter) ReadMultiBuffer() (buf.MultiBuffer, error) {
continue
}
if len(b) == buf.Size {
if cap(b) >= buf.Size {
mb = append(mb, buf.NewExisted(b))
} else {
mb = buf.MergeBytes(mb, b)
nb := buf.New()
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.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", errno)
return net.IP{}, -1, os.NewSyscallError("ioctl", err)
}
odPort := nl.rdxport
-3
View File
@@ -227,9 +227,6 @@ 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 = true
content.SkipDNSResolve = tag != ""
ctx = session.ContextWithContent(ctx, content)
ctx = session.SetForcedOutboundTagToContext(ctx, tag)
+7 -8
View File
@@ -270,12 +270,18 @@ var PresetFingerprints = map[string]*utls.ClientHelloID{
var ModernFingerprints = map[string]*utls.ClientHelloID{
// One of these will be chosen as `random` at startup
// All of them must have X25519MLKEM768 before optional X25519, otherwise REALITY servers (since v26.9.9) will reject them
"hellofirefox_120": &utls.HelloFirefox_120,
"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{
@@ -292,7 +298,6 @@ 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,
@@ -304,23 +309,17 @@ 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,