Compare commits

..
1 Commits
Author SHA1 Message Date
Fangliding bf3c512a70 Fix delayDialConn and some race 2026-11-30 21:02:58 +08:00
2 changed files with 178 additions and 143 deletions
+96 -124
View File
@@ -3,19 +3,15 @@
package net
import (
"bufio"
"encoding/binary"
"fmt"
"net"
"os"
"path/filepath"
"slices"
"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"
)
@@ -31,20 +27,50 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
panic("Unsupported network type for process lookup.")
}
socket, err := findSocketInode(network, net.ParseIP(srcIP), srcPort)
if err != nil {
return 0, "", "", errors.New("could not query sockets using netlink").Base(err)
}
if socket == nil {
return 0, "", "", errors.New("connection for ", srcIP, ":", srcPort, " not found")
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.")
}
pidStr, err := findPidByInode(socket.inode, socket.uid)
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)
if err != nil {
return 0, "", "", errors.New("could not find PID for inode ", socket.inode, ": ", err)
return 0, "", "", errors.New("could not search in ", strings.Join(procFiles, " and ")).Base(err)
}
if inode == "" {
return 0, "", "", errors.New("connection for ", srcIP, ":", srcPort, " not found in ", strings.Join(procFiles, " or "))
}
pidStr, err := findPidByInode(inode)
if err != nil {
return 0, "", "", errors.New("could not find PID for inode ", inode, ": ", err)
}
if pidStr == "" {
return 0, "", "", errors.New("no process found for inode ", socket.inode)
return 0, "", "", errors.New("no process found for inode ", inode)
}
absPath, err := getAbsPath(pidStr)
@@ -63,94 +89,59 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
return pid, procName, absPath, nil
}
type processSocket struct {
inode string
uid uint32
// 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()
}
// Layouts are defined by Linux's inet_diag_req_v2 and inet_diag_msg.
const (
inetDiagRequestSize = 56
inetDiagResponseSize = 72
tcpBoundInactive = 13
)
func findInodeInFiles(filePaths []string, targetHexAddrs []string, portFallback string) (string, error) {
onlyMatchedPort := ""
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
})
for i, filePath := range filePaths {
file, err := os.Open(filePath)
if err != nil {
return nil, err
if i > 0 && os.IsNotExist(err) {
continue
}
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 wildcard, nil
return onlyMatchedPort, nil
}
func findPidByInode(inode string, uid uint32) (string, error) {
func findPidByInode(inode string) (string, error) {
procDir, err := os.ReadDir("/proc")
if err != nil {
return "", err
@@ -167,45 +158,26 @@ func findPidByInode(inode string, uid uint32) (string, error) {
continue
}
info, err := entry.Info()
fdPath := fmt.Sprintf("/proc/%s/fd", pid)
fdDir, err := os.ReadDir(fdPath)
if err != nil {
continue
}
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 processHasSocket(pid, targetLink) {
return pid, nil
for _, fdEntry := range fdDir {
linkPath := fmt.Sprintf("%s/%s", fdPath, fdEntry.Name())
linkTarget, err := os.Readlink(linkPath)
if err != nil {
continue
}
if linkTarget == 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)
+82 -19
View File
@@ -5,6 +5,7 @@ import (
_ "embed"
"encoding/base64"
"io"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
@@ -24,7 +25,7 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me
if streamSettings.ProtocolSettings.(*Config).Ed > 0 {
ctx, cancel := context.WithCancel(ctx)
conn = &delayDialConn{
dialed: make(chan bool, 1),
dialed: make(chan bool),
cancel: cancel,
ctx: ctx,
dest: dest,
@@ -158,8 +159,8 @@ func dialWebSocket(ctx context.Context, dest net.Destination, streamSettings *in
}
type delayDialConn struct {
net.Conn
closed bool
conn atomic.Value // net.Conn
closed atomic.Bool
dialed chan bool
cancel context.CancelFunc
ctx context.Context
@@ -171,62 +172,124 @@ type delayDialConn struct {
// Without this method, Go promotes LocalAddr from the embedded net.Conn; the
// embedded interface is nil before the first Write, so the promoted call panics.
func (d *delayDialConn) LocalAddr() net.Addr {
if d.Conn == nil {
conn := d.conn.Load()
if conn == nil {
return nil
}
return d.Conn.LocalAddr()
return (conn.(net.Conn)).LocalAddr()
}
// RemoteAddr returns nil until the deferred WebSocket dial has completed.
// See LocalAddr for why an explicit method is required here.
func (d *delayDialConn) RemoteAddr() net.Addr {
if d.Conn == nil {
conn := d.conn.Load()
if conn == nil {
return nil
}
return d.Conn.RemoteAddr()
return (conn.(net.Conn)).RemoteAddr()
}
func (d *delayDialConn) Write(b []byte) (int, error) {
if d.closed {
if d.closed.Load() {
return 0, io.ErrClosedPipe
}
if d.Conn == nil {
conn := d.conn.Load()
if conn == nil {
ed := b
if len(ed) > int(d.streamSettings.ProtocolSettings.(*Config).Ed) {
ed = nil
}
var err error
if d.Conn, err = dialWebSocket(d.ctx, d.dest, d.streamSettings, ed); err != nil {
c, err := dialWebSocket(d.ctx, d.dest, d.streamSettings, ed)
if err != nil {
d.Close()
return 0, errors.New("failed to dial WebSocket").Base(err)
}
d.dialed <- true
d.conn.Store(c)
// someone close the conn after dial success
if d.closed.Load() {
d.Close()
return 0, io.ErrClosedPipe
}
conn = c
close(d.dialed)
if ed != nil {
return len(ed), nil
}
}
return d.Conn.Write(b)
return (conn.(net.Conn)).Write(b)
}
func (d *delayDialConn) Read(b []byte) (int, error) {
if d.closed {
if d.closed.Load() {
return 0, io.ErrClosedPipe
}
if d.Conn == nil {
conn := d.conn.Load()
if conn == nil {
select {
case <-d.ctx.Done():
return 0, io.ErrUnexpectedEOF
case <-d.dialed:
}
conn = d.conn.Load()
}
return d.Conn.Read(b)
return (conn.(net.Conn)).Read(b)
}
func (d *delayDialConn) SetDeadline(t time.Time) error {
if d.closed.Load() {
return io.ErrClosedPipe
}
conn := d.conn.Load()
if conn == nil {
d.setDelayedDeadline(t, d.SetDeadline)
return nil
}
return (conn.(net.Conn)).SetDeadline(t)
}
func (d *delayDialConn) SetReadDeadline(t time.Time) error {
if d.closed.Load() {
return io.ErrClosedPipe
}
conn := d.conn.Load()
if conn == nil {
d.setDelayedDeadline(t, d.SetReadDeadline)
return nil
}
return (conn.(net.Conn)).SetReadDeadline(t)
}
func (d *delayDialConn) SetWriteDeadline(t time.Time) error {
if d.closed.Load() {
return io.ErrClosedPipe
}
conn := d.conn.Load()
if conn == nil {
d.setDelayedDeadline(t, d.SetWriteDeadline)
return nil
}
return (conn.(net.Conn)).SetWriteDeadline(t)
}
func (d *delayDialConn) setDelayedDeadline(t time.Time, f func(time.Time) error) {
ctx, cancel := context.WithTimeout(d.ctx, time.Until(t))
go func() {
defer cancel()
select {
case <-d.dialed:
f(t)
case <-ctx.Done():
return
}
}()
}
func (d *delayDialConn) Close() error {
d.closed = true
d.closed.Store(true)
d.cancel()
if d.Conn == nil {
conn := d.conn.Load()
if conn == nil {
return nil
}
return d.Conn.Close()
return (conn.(net.Conn)).Close()
}