Fix connection owner lookup on legacy Android

This commit is contained in:
世界
2026-10-23 19:57:03 +08:00
parent af288b53e6
commit 40bc411e8d
5 changed files with 121 additions and 79 deletions
-1
View File
@@ -57,7 +57,6 @@ func NewCommandServer(handler CommandServerHandler, platformInterface PlatformIn
service.MustRegister[*powerreport.Manager](ctx, powerManager) service.MustRegister[*powerreport.Manager](ctx, powerManager)
platformWrapper := &platformInterfaceWrapper{ platformWrapper := &platformInterfaceWrapper{
iif: platformInterface, iif: platformInterface,
useProcFS: platformInterface.UseProcFS(),
powerManager: powerManager, powerManager: powerManager,
} }
service.MustRegister[adapter.PlatformInterface](ctx, platformWrapper) service.MustRegister[adapter.PlatformInterface](ctx, platformWrapper)
@@ -0,0 +1,32 @@
package libbox
import (
"net/netip"
"syscall"
"github.com/sagernet/sing-box/experimental/libbox/internal/procfs"
E "github.com/sagernet/sing/common/exceptions"
N "github.com/sagernet/sing/common/network"
)
func FindConnectionOwner(ipProtocol int32, sourceAddress string, sourcePort int32, destinationAddress string, destinationPort int32) (*ConnectionOwner, error) {
var network string
switch ipProtocol {
case syscall.IPPROTO_TCP:
network = N.NetworkTCP
case syscall.IPPROTO_UDP:
network = N.NetworkUDP
default:
return nil, E.New("unknown protocol: ", ipProtocol)
}
sourceIP, err := netip.ParseAddr(sourceAddress)
if err != nil {
return nil, E.Cause(err, "parse source")
}
destinationIP, _ := netip.ParseAddr(destinationAddress)
uid := procfs.ResolveSocketByProcSearch(network, netip.AddrPortFrom(sourceIP.Unmap(), uint16(sourcePort)), netip.AddrPortFrom(destinationIP.Unmap(), uint16(destinationPort)))
if uid == -1 {
return nil, E.New("procfs: not found")
}
return &ConnectionOwner{UserId: uid}, nil
}
+89 -48
View File
@@ -4,10 +4,10 @@ import (
"bufio" "bufio"
"encoding/binary" "encoding/binary"
"encoding/hex" "encoding/hex"
"fmt"
"net" "net"
"net/netip" "net/netip"
"os" "os"
"slices"
"strconv" "strconv"
"strings" "strings"
"unsafe" "unsafe"
@@ -16,9 +16,11 @@ import (
) )
var ( var (
netIndexOfLocal = -1 netIndexOfLocal = -1
netIndexOfUid = -1 netIndexOfRemote = -1
nativeEndian binary.ByteOrder netIndexOfUid = -1
netIndexOfInode = -1
nativeEndian binary.ByteOrder
) )
func init() { func init() {
@@ -30,62 +32,97 @@ func init() {
} }
} }
func ResolveSocketByProcSearch(network string, source, _ netip.AddrPort) int32 { func ResolveSocketByProcSearch(network string, source netip.AddrPort, destination netip.AddrPort) int32 {
if netIndexOfLocal < 0 || netIndexOfUid < 0 { if netIndexOfLocal < 0 || netIndexOfRemote < 0 || netIndexOfUid < 0 || netIndexOfInode < 0 {
return -1 return -1
} }
path := "/proc/net/" + network
path := "/proc/net/" if source.Addr().Is4() {
uid := searchSocketTable(path, network, source, destination)
if network == N.NetworkTCP { if uid != -1 {
path += "tcp" return uid
} else { }
path += "udp" // java.net sockets on Android are always dual-stack AF_INET6, so their IPv4 connections are only listed in the IPv6 table.
source = netip.AddrPortFrom(netip.AddrFrom16(source.Addr().As16()), source.Port())
if destination.Addr().Is4() {
destination = netip.AddrPortFrom(netip.AddrFrom16(destination.Addr().As16()), destination.Port())
}
} }
return searchSocketTable(path+"6", network, source, destination)
}
if source.Addr().Is6() { func searchSocketTable(path string, network string, source netip.AddrPort, destination netip.AddrPort) int32 {
path += "6"
}
sIP := source.Addr().AsSlice()
if len(sIP) == 0 {
return -1
}
var bytes [2]byte
binary.BigEndian.PutUint16(bytes[:], source.Port())
local := fmt.Sprintf("%s:%s", hex.EncodeToString(nativeEndianIP(sIP)), hex.EncodeToString(bytes[:]))
file, err := os.Open(path) file, err := os.Open(path)
if err != nil { if err != nil {
return -1 return -1
} }
defer file.Close() defer file.Close()
local := formatSocketAddress(source)
reader := bufio.NewReader(file) var remote string
if destination.IsValid() {
for { remote = formatSocketAddress(destination)
row, _, err := reader.ReadLine() }
if err != nil { var unspecifiedAddresses []string
return -1 if network == N.NetworkUDP {
} if source.Addr().Is4() {
unspecifiedAddresses = append(unspecifiedAddresses, formatSocketAddress(netip.AddrPortFrom(netip.IPv4Unspecified(), source.Port())))
fields := strings.Fields(string(row)) } else {
unspecifiedAddresses = append(unspecifiedAddresses, formatSocketAddress(netip.AddrPortFrom(netip.IPv6Unspecified(), source.Port())))
if len(fields) <= netIndexOfLocal || len(fields) <= netIndexOfUid { if source.Addr().Is4In6() {
continue unspecifiedAddresses = append(unspecifiedAddresses, formatSocketAddress(netip.AddrPortFrom(netip.AddrFrom16(netip.IPv4Unspecified().As16()), source.Port())))
}
if strings.EqualFold(local, fields[netIndexOfLocal]) {
uid, err := strconv.Atoi(fields[netIndexOfUid])
if err != nil {
return -1
} }
return int32(uid)
} }
} }
minFields := max(netIndexOfLocal, netIndexOfRemote, netIndexOfUid, netIndexOfInode) + 1
var (
row []byte
rank int
bestRank int
uid int
bestUID int32 = -1
)
reader := bufio.NewReader(file)
for {
row, _, err = reader.ReadLine()
if err != nil {
return bestUID
}
fields := strings.Fields(string(row))
if len(fields) < minFields || fields[netIndexOfInode] == "0" && fields[netIndexOfUid] == "0" {
continue
}
localAddress := fields[netIndexOfLocal]
switch {
case strings.EqualFold(localAddress, local) && (remote == "" || strings.EqualFold(fields[netIndexOfRemote], remote)):
rank = 3
case network != N.NetworkUDP:
continue
case strings.EqualFold(localAddress, local):
rank = 2
case slices.ContainsFunc(unspecifiedAddresses, func(address string) bool { return strings.EqualFold(localAddress, address) }):
rank = 1
default:
continue
}
if rank <= bestRank {
continue
}
uid, err = strconv.Atoi(fields[netIndexOfUid])
if err != nil {
continue
}
if rank == 3 {
return int32(uid)
}
bestRank = rank
bestUID = int32(uid)
}
}
func formatSocketAddress(address netip.AddrPort) string {
var portBytes [2]byte
binary.BigEndian.PutUint16(portBytes[:], address.Port())
return hex.EncodeToString(nativeEndianIP(address.Addr().AsSlice())) + ":" + hex.EncodeToString(portBytes[:])
} }
func nativeEndianIP(ip net.IP) []byte { func nativeEndianIP(ip net.IP) []byte {
@@ -141,8 +178,12 @@ func init() {
tmWhen = true tmWhen = true
case "local_address": case "local_address":
netIndexOfLocal = idx + offset netIndexOfLocal = idx + offset
case "rem_address":
netIndexOfRemote = idx + offset
case "uid": case "uid":
netIndexOfUid = idx + offset netIndexOfUid = idx + offset
case "inode":
netIndexOfInode = idx + offset
} }
} }
} }
-1
View File
@@ -7,7 +7,6 @@ type PlatformInterface interface {
UsePlatformAutoDetectInterfaceControl() bool UsePlatformAutoDetectInterfaceControl() bool
AutoDetectInterfaceControl(fd int32) error AutoDetectInterfaceControl(fd int32) error
OpenTun(options TunOptions) (int32, error) OpenTun(options TunOptions) (int32, error)
UseProcFS() bool
FindConnectionOwner(ipProtocol int32, sourceAddress string, sourcePort int32, destinationAddress string, destinationPort int32) (*ConnectionOwner, error) FindConnectionOwner(ipProtocol int32, sourceAddress string, sourcePort int32, destinationAddress string, destinationPort int32) (*ConnectionOwner, error)
StartDefaultInterfaceMonitor(listener InterfaceUpdateListener) error StartDefaultInterfaceMonitor(listener InterfaceUpdateListener) error
CloseDefaultInterfaceMonitor(listener InterfaceUpdateListener) error CloseDefaultInterfaceMonitor(listener InterfaceUpdateListener) error
-29
View File
@@ -14,7 +14,6 @@ import (
"github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/adapter"
C "github.com/sagernet/sing-box/constant" C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/experimental/libbox/internal/procfs"
"github.com/sagernet/sing-box/option" "github.com/sagernet/sing-box/option"
"github.com/sagernet/sing-box/service/powerreport" "github.com/sagernet/sing-box/service/powerreport"
tun "github.com/sagernet/sing-tun" tun "github.com/sagernet/sing-tun"
@@ -28,7 +27,6 @@ var _ adapter.PlatformInterface = (*platformInterfaceWrapper)(nil)
type platformInterfaceWrapper struct { type platformInterfaceWrapper struct {
iif PlatformInterface iif PlatformInterface
useProcFS bool
networkManager adapter.NetworkManager networkManager adapter.NetworkManager
powerManager *powerreport.Manager powerManager *powerreport.Manager
myTunName string myTunName string
@@ -191,33 +189,6 @@ func (w *platformInterfaceWrapper) UsePlatformConnectionOwnerFinder() bool {
} }
func (w *platformInterfaceWrapper) FindConnectionOwner(request *adapter.FindConnectionOwnerRequest) (*adapter.ConnectionOwner, error) { func (w *platformInterfaceWrapper) FindConnectionOwner(request *adapter.FindConnectionOwnerRequest) (*adapter.ConnectionOwner, error) {
if w.useProcFS {
var source netip.AddrPort
var destination netip.AddrPort
sourceAddr, _ := netip.ParseAddr(request.SourceAddress)
source = netip.AddrPortFrom(sourceAddr, uint16(request.SourcePort))
destAddr, _ := netip.ParseAddr(request.DestinationAddress)
destination = netip.AddrPortFrom(destAddr, uint16(request.DestinationPort))
var network string
switch request.IpProtocol {
case int32(syscall.IPPROTO_TCP):
network = "tcp"
case int32(syscall.IPPROTO_UDP):
network = "udp"
default:
return nil, E.New("unknown protocol: ", request.IpProtocol)
}
uid := procfs.ResolveSocketByProcSearch(network, source, destination)
if uid == -1 {
return nil, E.New("procfs: not found")
}
return &adapter.ConnectionOwner{
UserId: uid,
}, nil
}
result, err := w.iif.FindConnectionOwner(request.IpProtocol, request.SourceAddress, request.SourcePort, request.DestinationAddress, request.DestinationPort) result, err := w.iif.FindConnectionOwner(request.IpProtocol, request.SourceAddress, request.SourcePort, request.DestinationAddress, request.DestinationPort)
if err != nil { if err != nil {
return nil, err return nil, err