Compare commits

...
11 changed files with 197 additions and 95 deletions
+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
@@ -150,6 +150,7 @@ Start:
To: request.URL,
Status: log.AccessAccepted,
Reason: "",
Email: inbound.User.Email,
})
if strings.EqualFold(request.Method, "CONNECT") {
+2
View File
@@ -149,6 +149,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,6 +271,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis
To: destination,
Status: log.AccessAccepted,
Reason: "",
Email: inbound.User.Email,
})
}
+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)
}
}
+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
}
+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,