Skip to content

Commit

Permalink
Improve android process searcher
Browse files Browse the repository at this point in the history
  • Loading branch information
PuerNya committed Jan 19, 2024
1 parent 415c60e commit 711e904
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
13 changes: 12 additions & 1 deletion common/process/searcher_android.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
32 changes: 30 additions & 2 deletions common/process/searcher_linux_shared.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"net/netip"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"syscall"
"unicode"
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 711e904

Please sign in to comment.