From 711e9043a016a903718acaf7c701c9d85bb074d5 Mon Sep 17 00:00:00 2001 From: PuerNya Date: Fri, 5 Jan 2024 22:31:35 +0800 Subject: [PATCH] Improve android process searcher --- common/process/searcher_android.go | 13 +++++++++- common/process/searcher_linux_shared.go | 32 +++++++++++++++++++++++-- 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/common/process/searcher_android.go b/common/process/searcher_android.go index e1835b476c..6da32b51fe 100644 --- a/common/process/searcher_android.go +++ b/common/process/searcher_android.go @@ -18,10 +18,21 @@ func NewSearcher(config Config) (Searcher, error) { } func (s *androidSearcher) FindProcessInfo(ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error) { - _, uid, err := resolveSocketByNetlink(network, source, destination) + inode, uid, err := resolveSocketByNetlink(network, source, destination) if err != nil { return nil, err } + if processPath, _ := resolveProcessNameByProcSearch(inode, uid); processPath != "" { + info := Info{ + UserId: int32(uid), + } + if _, loaded := s.packageManager.IDByPackage(processPath); loaded { + info.PackageName = processPath + } else { + info.ProcessPath = processPath + } + return &info, nil + } if sharedPackage, loaded := s.packageManager.SharedPackageByID(uid % 100000); loaded { return &Info{ UserId: int32(uid), diff --git a/common/process/searcher_linux_shared.go b/common/process/searcher_linux_shared.go index e75b0b4f9d..7397a813fb 100644 --- a/common/process/searcher_linux_shared.go +++ b/common/process/searcher_linux_shared.go @@ -10,6 +10,8 @@ import ( "net/netip" "os" "path" + "path/filepath" + "runtime" "strings" "syscall" "unicode" @@ -186,15 +188,41 @@ func resolveProcessNameByProcSearch(inode, uid uint32) (string, error) { continue } - if bytes.Equal(buffer[:n], socket) { - return os.Readlink(path.Join(processPath, "exe")) + if !bytes.Equal(buffer[:n], socket) { + continue + } + + exe, err := os.Readlink(path.Join(processPath, "exe")) + + if runtime.GOOS != "android" || !strings.HasPrefix(exe, "/system/bin/app_process") { + return exe, err + } + + cmdline, err := os.ReadFile(path.Join(processPath, "cmdline")) + if err != nil { + return "", err } + + return splitCmdline(cmdline), nil } } return "", fmt.Errorf("process of uid(%d),inode(%d) not found", uid, inode) } +func splitCmdline(cmdline []byte) string { + cmdline = bytes.Trim(cmdline, " ") + + idx := bytes.IndexFunc(cmdline, func(r rune) bool { + return unicode.IsControl(r) || unicode.IsSpace(r) || r == ':' + }) + + if idx == -1 { + return filepath.Base(string(cmdline)) + } + return filepath.Base(string(cmdline[:idx])) +} + func isPid(s string) bool { return strings.IndexFunc(s, func(r rune) bool { return !unicode.IsDigit(r)