github.com/chwjbn/xclash@v0.2.0/rule/process.go (about) 1 package rules 2 3 import ( 4 "fmt" 5 "strconv" 6 "strings" 7 8 "github.com/chwjbn/xclash/common/cache" 9 "github.com/chwjbn/xclash/component/process" 10 C "github.com/chwjbn/xclash/constant" 11 "github.com/chwjbn/xclash/log" 12 ) 13 14 var processCache = cache.NewLRUCache(cache.WithAge(2), cache.WithSize(64)) 15 16 type Process struct { 17 adapter string 18 process string 19 } 20 21 func (ps *Process) RuleType() C.RuleType { 22 return C.Process 23 } 24 25 func (ps *Process) Match(metadata *C.Metadata) bool { 26 key := fmt.Sprintf("%s:%s:%s", metadata.NetWork.String(), metadata.SrcIP.String(), metadata.SrcPort) 27 cached, hit := processCache.Get(key) 28 if !hit { 29 srcPort, err := strconv.Atoi(metadata.SrcPort) 30 if err != nil { 31 processCache.Set(key, "") 32 return false 33 } 34 35 name, err := process.FindProcessName(metadata.NetWork.String(), metadata.SrcIP, srcPort) 36 if err != nil { 37 log.Debugln("[Rule] find process name %s error: %s", C.Process.String(), err.Error()) 38 } 39 40 processCache.Set(key, name) 41 42 cached = name 43 } 44 45 return strings.EqualFold(cached.(string), ps.process) 46 } 47 48 func (ps *Process) Adapter() string { 49 return ps.adapter 50 } 51 52 func (ps *Process) Payload() string { 53 return ps.process 54 } 55 56 func (ps *Process) ShouldResolveIP() bool { 57 return false 58 } 59 60 func NewProcess(process string, adapter string) (*Process, error) { 61 return &Process{ 62 adapter: adapter, 63 process: process, 64 }, nil 65 }