Compare commits

..
Author SHA1 Message Date
Fangliding 953097e9dc reduce alloc 2026-11-27 01:01:00 +08:00
风扇滑翔翼andGitHub 73a3beff39 Switch to netlink 2026-11-25 13:33:36 +00:00
7 changed files with 134 additions and 122 deletions
+119 -91
View File
@@ -3,15 +3,19 @@
package net
import (
"bufio"
"encoding/binary"
"fmt"
"net"
"os"
"slices"
"path/filepath"
"strconv"
"strings"
"syscall"
"github.com/vishvananda/netlink/nl"
"golang.org/x/sys/unix"
"github.com/xtls/xray-core/common/bytespool"
"github.com/xtls/xray-core/common/errors"
)
@@ -27,50 +31,20 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
panic("Unsupported network type for process lookup.")
}
var procFiles []string
switch network {
case "tcp":
if net.ParseIP(srcIP).To4() != nil {
procFiles = []string{"/proc/net/tcp", "/proc/net/tcp6"}
} else {
procFiles = []string{"/proc/net/tcp6"}
}
case "udp":
if net.ParseIP(srcIP).To4() != nil {
procFiles = []string{"/proc/net/udp", "/proc/net/udp6"}
} else {
procFiles = []string{"/proc/net/udp6", "/proc/net/udp"}
}
default:
panic("Unsupported network type for process lookup.")
}
targetHexAddrs := []string{formatProcNetAddress(net.ParseIP(srcIP).To16(), Port(srcPort))}
if ipv4 := net.ParseIP(srcIP).To4(); ipv4 != nil {
// the one above is then the IPv4-mapped IPv6 address that an IPv6 socket has it as, in the IPv6 file
targetHexAddrs = append(targetHexAddrs, formatProcNetAddress(ipv4, Port(srcPort)))
}
portFallback := ""
if network == "udp" {
portFallback = fmt.Sprintf(":%04X", srcPort)
}
inode, err := findInodeInFiles(procFiles, targetHexAddrs, portFallback)
socket, err := findSocketInode(network, net.ParseIP(srcIP), srcPort)
if err != nil {
return 0, "", "", errors.New("could not search in ", strings.Join(procFiles, " and ")).Base(err)
return 0, "", "", errors.New("could not query sockets using netlink").Base(err)
}
if inode == "" {
return 0, "", "", errors.New("connection for ", srcIP, ":", srcPort, " not found in ", strings.Join(procFiles, " or "))
if socket == nil {
return 0, "", "", errors.New("connection for ", srcIP, ":", srcPort, " not found")
}
pidStr, err := findPidByInode(inode)
pidStr, err := findPidByInode(socket.inode, socket.uid)
if err != nil {
return 0, "", "", errors.New("could not find PID for inode ", inode, ": ", err)
return 0, "", "", errors.New("could not find PID for inode ", socket.inode, ": ", err)
}
if pidStr == "" {
return 0, "", "", errors.New("no process found for inode ", inode)
return 0, "", "", errors.New("no process found for inode ", socket.inode)
}
absPath, err := getAbsPath(pidStr)
@@ -89,59 +63,94 @@ 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 formatted strings.Builder
formatted.Grow(len(ipBytes)*2 + 5)
for i := 0; i < len(ipBytes); i += 4 {
fmt.Fprintf(&formatted, "%08X", binary.NativeEndian.Uint32(ipBytes[i:i+4]))
}
fmt.Fprintf(&formatted, ":%04X", uint16(port))
return formatted.String()
type processSocket struct {
inode string
uid uint32
}
func findInodeInFiles(filePaths []string, targetHexAddrs []string, portFallback string) (string, error) {
onlyMatchedPort := ""
// Layouts are defined by Linux's inet_diag_req_v2 and inet_diag_msg.
const (
inetDiagRequestSize = 56
inetDiagResponseSize = 72
tcpBoundInactive = 13
)
for i, filePath := range filePaths {
file, err := os.Open(filePath)
func findSocketInode(network string, ip net.IP, port uint16) (*processSocket, error) {
families := []uint8{unix.AF_INET6}
if ip.To4() != nil {
families = []uint8{unix.AF_INET, unix.AF_INET6}
} else if network == "udp" {
families = append(families, unix.AF_INET)
}
protocol := byte(unix.IPPROTO_UDP)
if network == "tcp" {
protocol = unix.IPPROTO_TCP
}
var wildcard *processSocket
request := make([]byte, inetDiagRequestSize)
for _, family := range families {
clear(request)
request[0], request[1] = family, protocol
states := ^uint32(0)
if network == "tcp" {
states &^= 1 << tcpBoundInactive
}
binary.NativeEndian.PutUint32(request[4:8], states)
binary.BigEndian.PutUint16(request[8:10], port)
if family == unix.AF_INET {
copy(request[12:28], ip.To4())
} else {
copy(request[12:28], ip.To16())
}
binary.NativeEndian.PutUint32(request[48:52], ^uint32(0))
binary.NativeEndian.PutUint32(request[52:56], ^uint32(0))
req := nl.NewNetlinkRequest(nl.SOCK_DIAG_BY_FAMILY, unix.NLM_F_DUMP)
req.AddRawData(request)
var exact *processSocket
var parseErr error
err := req.ExecuteIter(unix.NETLINK_INET_DIAG, nl.SOCK_DIAG_BY_FAMILY, func(msg []byte) bool {
if len(msg) < inetDiagResponseSize {
parseErr = fmt.Errorf("short inet_diag response: %d bytes", len(msg))
return false
}
if msg[0] != family || binary.BigEndian.Uint16(msg[4:6]) != port {
return true
}
source := net.IP(msg[8:24])
if family == unix.AF_INET {
source = source[:4]
}
if !source.Equal(ip) && !(network == "udp" && source.IsUnspecified()) {
return true
}
socket := &processSocket{
uid: binary.NativeEndian.Uint32(msg[64:68]),
inode: strconv.FormatUint(uint64(binary.NativeEndian.Uint32(msg[68:72])), 10),
}
if source.Equal(ip) {
exact = socket
return false
}
wildcard = socket
return true
})
if err != nil {
if i > 0 && os.IsNotExist(err) {
continue
return nil, err
}
return "", err
if parseErr != nil {
return nil, parseErr
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) < 10 {
continue
}
localAddress := fields[1]
if slices.Contains(targetHexAddrs, localAddress) {
return fields[9], nil
}
if portFallback != "" && strings.HasSuffix(localAddress, portFallback) {
wildcardIP := strings.TrimSuffix(localAddress, portFallback)
if (len(wildcardIP) == 8 || len(wildcardIP) == 32) && strings.Trim(wildcardIP, "0") == "" {
onlyMatchedPort = fields[9]
if exact != nil {
return exact, nil
}
}
}
if err := scanner.Err(); err != nil {
return "", err
}
}
return onlyMatchedPort, nil
return wildcard, nil
}
func findPidByInode(inode string) (string, error) {
func findPidByInode(inode string, uid uint32) (string, error) {
procDir, err := os.ReadDir("/proc")
if err != nil {
return "", err
@@ -158,26 +167,45 @@ func findPidByInode(inode string) (string, error) {
continue
}
fdPath := fmt.Sprintf("/proc/%s/fd", pid)
fdDir, err := os.ReadDir(fdPath)
info, err := entry.Info()
if err != nil {
continue
}
for _, fdEntry := range fdDir {
linkPath := fmt.Sprintf("%s/%s", fdPath, fdEntry.Name())
linkTarget, err := os.Readlink(linkPath)
if err != nil {
stat, ok := info.Sys().(*syscall.Stat_t)
if !ok {
return "", fmt.Errorf("unexpected stat data for process %s", pid)
}
if stat.Uid != uid {
continue
}
if linkTarget == targetLink {
if processHasSocket(pid, targetLink) {
return pid, nil
}
}
}
return "", nil
}
func processHasSocket(pid, targetLink string) bool {
fdPath := filepath.Join("/proc", pid, "fd")
fdDir, err := os.ReadDir(fdPath)
if err != nil {
return false
}
buffer := bytespool.Alloc(unix.PathMax)
defer bytespool.Free(buffer)
for _, fdEntry := range fdDir {
n, err := unix.Readlink(filepath.Join(fdPath, fdEntry.Name()), buffer)
if err != nil {
continue
}
if string(buffer[:n]) == targetLink {
return true
}
}
return false
}
func getAbsPath(pid string) (string, error) {
path := fmt.Sprintf("/proc/%s/exe", pid)
return os.Readlink(path)
+1 -5
View File
@@ -241,7 +241,6 @@ type MultiplexConfig struct {
Concurrency int16 `json:"concurrency"`
XudpConcurrency int16 `json:"xudpConcurrency"`
XudpProxyUDP443 string `json:"xudpProxyUDP443"`
MaxReuseTimes int32 `json:"maxReuseTimes"`
}
func (c *MultiplexConfig) Build() (*vless.Multiplex, error) {
@@ -253,10 +252,7 @@ func (c *MultiplexConfig) Build() (*vless.Multiplex, error) {
udp443 = "reject"
}
return multiplex.NormalizeConfig(&vless.Multiplex{
Concurrency: int32(c.Concurrency),
XudpConcurrency: int32(c.XudpConcurrency),
XudpProxyUDP443: udp443,
MaxReuseTimes: c.MaxReuseTimes,
Concurrency: int32(c.Concurrency), XudpConcurrency: int32(c.XudpConcurrency), XudpProxyUDP443: udp443,
})
}
-2
View File
@@ -236,11 +236,9 @@ func TestMultiplexConfig_Build(t *testing.T) {
{name: "empty", fields: `{}`},
{name: "both zero", fields: `{"concurrency":0,"xudpConcurrency":0}`},
{name: "regular pool", fields: `{"concurrency":4}`, want: &vless.Multiplex{Concurrency: 4, XudpProxyUDP443: "reject"}},
{name: "regular pool with maxReuseTimes", fields: `{"concurrency":4,"maxReuseTimes":128}`, want: &vless.Multiplex{Concurrency: 4, XudpProxyUDP443: "reject", MaxReuseTimes: 128}},
{name: "XUDP only", fields: `{"xudpConcurrency":8}`, want: &vless.Multiplex{XudpConcurrency: 8, XudpProxyUDP443: "reject"}},
{name: "negative concurrency", fields: `{"concurrency":-1,"xudpConcurrency":8}`, bad: true},
{name: "negative XUDP concurrency", fields: `{"concurrency":4,"xudpConcurrency":-1}`, bad: true},
{name: "negative maxReuseTimes", fields: `{"concurrency":4,"maxReuseTimes":-1}`, bad: true},
{name: "invalid UDP policy", fields: `{"concurrency":4,"xudpProxyUDP443":"invalid"}`, bad: true},
} {
t.Run(tc.name, func(t *testing.T) {
+2 -11
View File
@@ -189,7 +189,6 @@ type Multiplex struct {
Concurrency int32 `protobuf:"varint,1,opt,name=concurrency,proto3" json:"concurrency,omitempty"`
XudpConcurrency int32 `protobuf:"varint,2,opt,name=xudpConcurrency,proto3" json:"xudpConcurrency,omitempty"`
XudpProxyUDP443 string `protobuf:"bytes,3,opt,name=xudpProxyUDP443,proto3" json:"xudpProxyUDP443,omitempty"`
MaxReuseTimes int32 `protobuf:"varint,4,opt,name=maxReuseTimes,proto3" json:"maxReuseTimes,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -245,13 +244,6 @@ func (x *Multiplex) GetXudpProxyUDP443() string {
return ""
}
func (x *Multiplex) GetMaxReuseTimes() int32 {
if x != nil {
return x.MaxReuseTimes
}
return 0
}
var File_proxy_vless_account_proto protoreflect.FileDescriptor
const file_proxy_vless_account_proto_rawDesc = "" +
@@ -271,12 +263,11 @@ const file_proxy_vless_account_proto_rawDesc = "" +
"\apadding\x18\x06 \x01(\tR\apadding\x123\n" +
"\areverse\x18\a \x01(\v2\x19.xray.proxy.vless.ReverseR\areverse\x12\x18\n" +
"\atestpre\x18\b \x01(\rR\atestpre\x12\x1a\n" +
"\btestseed\x18\t \x03(\rR\btestseed\"\xa7\x01\n" +
"\btestseed\x18\t \x03(\rR\btestseed\"\x81\x01\n" +
"\tMultiplex\x12 \n" +
"\vconcurrency\x18\x01 \x01(\x05R\vconcurrency\x12(\n" +
"\x0fxudpConcurrency\x18\x02 \x01(\x05R\x0fxudpConcurrency\x12(\n" +
"\x0fxudpProxyUDP443\x18\x03 \x01(\tR\x0fxudpProxyUDP443\x12$\n" +
"\rmaxReuseTimes\x18\x04 \x01(\x05R\rmaxReuseTimesBR\n" +
"\x0fxudpProxyUDP443\x18\x03 \x01(\tR\x0fxudpProxyUDP443BR\n" +
"\x14com.xray.proxy.vlessP\x01Z%github.com/xtls/xray-core/proxy/vless\xaa\x02\x10Xray.Proxy.Vlessb\x06proto3"
var (
-1
View File
@@ -34,5 +34,4 @@ message Multiplex {
int32 concurrency = 1;
int32 xudpConcurrency = 2;
string xudpProxyUDP443 = 3;
int32 maxReuseTimes = 4;
}
+8 -8
View File
@@ -18,8 +18,8 @@ import (
// NormalizeConfig validates the pool settings and returns nil when both pools are off.
func NormalizeConfig(config *vless.Multiplex) (*vless.Multiplex, error) {
if config.GetConcurrency() < 0 || config.GetXudpConcurrency() < 0 || config.GetMaxReuseTimes() < 0 {
return nil, errors.New(`multiplex "concurrency", "xudpConcurrency" and "maxReuseTimes" must be non-negative`)
if config.GetConcurrency() < 0 || config.GetXudpConcurrency() < 0 {
return nil, errors.New(`multiplex "concurrency" and "xudpConcurrency" must be non-negative`)
}
switch config.GetXudpProxyUDP443() {
case "", "reject", "allow", "skip":
@@ -41,17 +41,17 @@ type Client struct {
func NewClient(ctx context.Context, config *vless.Multiplex, network string, open func(context.Context) (context.Context, *transport.Link, error)) *Client {
c := &Client{config: config}
pool := func(concurrency int32, maxReuseTimes uint32) *Pool {
return NewPool(ctx, ClientStrategy{MaxConcurrency: uint32(concurrency), MaxReuseTimes: maxReuseTimes}, open)
pool := func(concurrency int32) *Pool {
return NewPool(ctx, ClientStrategy{MaxConcurrency: uint32(concurrency), MaxConnection: 1024}, open)
}
if concurrency := config.GetConcurrency(); concurrency > 0 {
if network == "xdrive" {
concurrency = max(concurrency, 128)
}
c.tcp = pool(concurrency, uint32(config.GetMaxReuseTimes()))
c.tcp = pool(concurrency)
}
if concurrency := config.GetXudpConcurrency(); concurrency > 0 {
c.udp = pool(concurrency, 1024)
c.udp = pool(concurrency)
}
return c
}
@@ -211,7 +211,7 @@ func (p *Pool) Admit(ctx context.Context, s *Session) error {
type ClientStrategy struct {
MaxConcurrency uint32
MaxReuseTimes uint32
MaxConnection uint32
}
type ClientWorker struct {
@@ -258,7 +258,7 @@ func (m *ClientWorker) TryAdmit(ctx context.Context, s *Session) bool {
defer m.Unlock()
if ctx.Err() != nil || m.Closed() || m.count == 65535 ||
(m.strategy.MaxConcurrency > 0 && m.active >= int(m.strategy.MaxConcurrency)) ||
(m.strategy.MaxReuseTimes > 0 && uint32(m.count) >= m.strategy.MaxReuseTimes) {
(m.strategy.MaxConnection > 0 && uint32(m.count) >= m.strategy.MaxConnection) {
return false
}
s.parent, s.ID, s.phase, s.done = m.carrier, m.count+1, outputOpen, make(chan struct{})
+1 -1
View File
@@ -85,7 +85,7 @@ func TestClientWorkerClose(t *testing.T) {
links := []*transport.Link{{Reader: r1, Writer: w1}, {Reader: r2, Writer: w2}}
owner, stop := context.WithCancel(context.Background())
defer stop()
pool := NewPool(owner, ClientStrategy{MaxConcurrency: 4, MaxReuseTimes: 4}, func(ctx context.Context) (context.Context, *transport.Link, error) {
pool := NewPool(owner, ClientStrategy{MaxConcurrency: 4, MaxConnection: 4}, func(ctx context.Context) (context.Context, *transport.Link, error) {
if len(links) == 0 {
return nil, nil, errors.New("unexpected opening")
}