From 0e4b9daaadd6aefc772852ec94d70ad2593ecad1 Mon Sep 17 00:00:00 2001 From: Dreamacro <305009791@qq.com> Date: Wed, 22 Jul 2020 20:35:27 +0800 Subject: [PATCH] Improve: add cache for macOS PROCESS-NAME --- rules/process_darwin.go | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/rules/process_darwin.go b/rules/process_darwin.go index cc99a6f7..dea589e7 100644 --- a/rules/process_darwin.go +++ b/rules/process_darwin.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/binary" "errors" + "fmt" "net" "path/filepath" "strconv" @@ -11,10 +12,14 @@ import ( "syscall" "unsafe" + "github.com/Dreamacro/clash/common/cache" C "github.com/Dreamacro/clash/constant" "github.com/Dreamacro/clash/log" ) +// store process name for when dealing with multiple PROCESS-NAME rules +var processCache = cache.NewLRUCache(cache.WithAge(2), cache.WithSize(64)) + type Process struct { adapter string process string @@ -25,13 +30,19 @@ func (ps *Process) RuleType() C.RuleType { } func (ps *Process) Match(metadata *C.Metadata) bool { - name, err := getExecPathFromAddress(metadata.SrcIP, metadata.SrcPort, metadata.NetWork == C.TCP) - if err != nil { - log.Debugln("[%s] getExecPathFromAddress error: %s", C.Process.String(), err.Error()) - return false + key := fmt.Sprintf("%s:%s:%s", metadata.NetWork.String(), metadata.SrcIP.String(), metadata.SrcPort) + cached, hit := processCache.Get(key) + if !hit { + name, err := getExecPathFromAddress(metadata.SrcIP, metadata.SrcPort, metadata.NetWork == C.TCP) + if err != nil { + log.Debugln("[%s] getExecPathFromAddress error: %s", C.Process.String(), err.Error()) + return false + } + + cached = name } - return strings.ToLower(name) == ps.process + return strings.EqualFold(cached.(string), ps.process) } func (p *Process) Adapter() string {