From 40bc411e8d024e3f8c8f435c2a2ad5e4c0e04bce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=96=E7=95=8C?= Date: Tue, 20 Oct 2026 17:06:37 +0800 Subject: [PATCH] Fix connection owner lookup on legacy Android --- experimental/libbox/command_server.go | 1 - .../libbox/connection_owner_android.go | 32 ++++ experimental/libbox/internal/procfs/procfs.go | 137 ++++++++++++------ experimental/libbox/platform.go | 1 - experimental/libbox/service.go | 29 ---- 5 files changed, 121 insertions(+), 79 deletions(-) create mode 100644 experimental/libbox/connection_owner_android.go diff --git a/experimental/libbox/command_server.go b/experimental/libbox/command_server.go index 5dd456da..c727446f 100644 --- a/experimental/libbox/command_server.go +++ b/experimental/libbox/command_server.go @@ -57,7 +57,6 @@ func NewCommandServer(handler CommandServerHandler, platformInterface PlatformIn service.MustRegister[*powerreport.Manager](ctx, powerManager) platformWrapper := &platformInterfaceWrapper{ iif: platformInterface, - useProcFS: platformInterface.UseProcFS(), powerManager: powerManager, } service.MustRegister[adapter.PlatformInterface](ctx, platformWrapper) diff --git a/experimental/libbox/connection_owner_android.go b/experimental/libbox/connection_owner_android.go new file mode 100644 index 00000000..1048b59c --- /dev/null +++ b/experimental/libbox/connection_owner_android.go @@ -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 +} diff --git a/experimental/libbox/internal/procfs/procfs.go b/experimental/libbox/internal/procfs/procfs.go index 8c918a79..5eaa2196 100644 --- a/experimental/libbox/internal/procfs/procfs.go +++ b/experimental/libbox/internal/procfs/procfs.go @@ -4,10 +4,10 @@ import ( "bufio" "encoding/binary" "encoding/hex" - "fmt" "net" "net/netip" "os" + "slices" "strconv" "strings" "unsafe" @@ -16,9 +16,11 @@ import ( ) var ( - netIndexOfLocal = -1 - netIndexOfUid = -1 - nativeEndian binary.ByteOrder + netIndexOfLocal = -1 + netIndexOfRemote = -1 + netIndexOfUid = -1 + netIndexOfInode = -1 + nativeEndian binary.ByteOrder ) func init() { @@ -30,62 +32,97 @@ func init() { } } -func ResolveSocketByProcSearch(network string, source, _ netip.AddrPort) int32 { - if netIndexOfLocal < 0 || netIndexOfUid < 0 { +func ResolveSocketByProcSearch(network string, source netip.AddrPort, destination netip.AddrPort) int32 { + if netIndexOfLocal < 0 || netIndexOfRemote < 0 || netIndexOfUid < 0 || netIndexOfInode < 0 { return -1 } - - path := "/proc/net/" - - if network == N.NetworkTCP { - path += "tcp" - } else { - path += "udp" + path := "/proc/net/" + network + if source.Addr().Is4() { + uid := searchSocketTable(path, network, source, destination) + if uid != -1 { + return uid + } + // 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() { - 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[:])) - +func searchSocketTable(path string, network string, source netip.AddrPort, destination netip.AddrPort) int32 { file, err := os.Open(path) if err != nil { return -1 } - defer file.Close() - - reader := bufio.NewReader(file) - - for { - row, _, err := reader.ReadLine() - if err != nil { - return -1 - } - - fields := strings.Fields(string(row)) - - if len(fields) <= netIndexOfLocal || len(fields) <= netIndexOfUid { - continue - } - - if strings.EqualFold(local, fields[netIndexOfLocal]) { - uid, err := strconv.Atoi(fields[netIndexOfUid]) - if err != nil { - return -1 + local := formatSocketAddress(source) + var remote string + if destination.IsValid() { + remote = formatSocketAddress(destination) + } + var unspecifiedAddresses []string + if network == N.NetworkUDP { + if source.Addr().Is4() { + unspecifiedAddresses = append(unspecifiedAddresses, formatSocketAddress(netip.AddrPortFrom(netip.IPv4Unspecified(), source.Port()))) + } else { + unspecifiedAddresses = append(unspecifiedAddresses, formatSocketAddress(netip.AddrPortFrom(netip.IPv6Unspecified(), source.Port()))) + if source.Addr().Is4In6() { + unspecifiedAddresses = append(unspecifiedAddresses, formatSocketAddress(netip.AddrPortFrom(netip.AddrFrom16(netip.IPv4Unspecified().As16()), source.Port()))) } - - 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 { @@ -141,8 +178,12 @@ func init() { tmWhen = true case "local_address": netIndexOfLocal = idx + offset + case "rem_address": + netIndexOfRemote = idx + offset case "uid": netIndexOfUid = idx + offset + case "inode": + netIndexOfInode = idx + offset } } } diff --git a/experimental/libbox/platform.go b/experimental/libbox/platform.go index 108cc209..eb24d058 100644 --- a/experimental/libbox/platform.go +++ b/experimental/libbox/platform.go @@ -7,7 +7,6 @@ type PlatformInterface interface { UsePlatformAutoDetectInterfaceControl() bool AutoDetectInterfaceControl(fd int32) error OpenTun(options TunOptions) (int32, error) - UseProcFS() bool FindConnectionOwner(ipProtocol int32, sourceAddress string, sourcePort int32, destinationAddress string, destinationPort int32) (*ConnectionOwner, error) StartDefaultInterfaceMonitor(listener InterfaceUpdateListener) error CloseDefaultInterfaceMonitor(listener InterfaceUpdateListener) error diff --git a/experimental/libbox/service.go b/experimental/libbox/service.go index 4cd6045a..2c1dbe38 100644 --- a/experimental/libbox/service.go +++ b/experimental/libbox/service.go @@ -14,7 +14,6 @@ import ( "github.com/sagernet/sing-box/adapter" 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/service/powerreport" tun "github.com/sagernet/sing-tun" @@ -28,7 +27,6 @@ var _ adapter.PlatformInterface = (*platformInterfaceWrapper)(nil) type platformInterfaceWrapper struct { iif PlatformInterface - useProcFS bool networkManager adapter.NetworkManager powerManager *powerreport.Manager myTunName string @@ -191,33 +189,6 @@ func (w *platformInterfaceWrapper) UsePlatformConnectionOwnerFinder() bool { } 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) if err != nil { return nil, err