rule_process.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package route
  2. import (
  3. "path/filepath"
  4. "strings"
  5. "github.com/sagernet/sing-box/adapter"
  6. "github.com/sagernet/sing-box/common/warning"
  7. C "github.com/sagernet/sing-box/constant"
  8. )
  9. var warnProcessNameOnNonSupportedPlatform = warning.New(
  10. func() bool { return !(C.IsLinux || C.IsWindows || C.IsDarwin) },
  11. "rule item `process_item` is only supported on Linux, Windows, and macOS",
  12. )
  13. var _ RuleItem = (*ProcessItem)(nil)
  14. type ProcessItem struct {
  15. processes []string
  16. processMap map[string]bool
  17. }
  18. func NewProcessItem(processNameList []string) *ProcessItem {
  19. warnProcessNameOnNonSupportedPlatform.Check()
  20. rule := &ProcessItem{
  21. processes: processNameList,
  22. processMap: make(map[string]bool),
  23. }
  24. for _, processName := range processNameList {
  25. rule.processMap[strings.ToLower(processName)] = true
  26. }
  27. return rule
  28. }
  29. func (r *ProcessItem) Match(metadata *adapter.InboundContext) bool {
  30. if metadata.ProcessInfo == nil || metadata.ProcessInfo.ProcessPath == "" {
  31. return false
  32. }
  33. return r.processMap[strings.ToLower(filepath.Base(metadata.ProcessInfo.ProcessPath))]
  34. }
  35. func (r *ProcessItem) String() string {
  36. var description string
  37. pLen := len(r.processes)
  38. if pLen == 1 {
  39. description = "process_name=" + r.processes[0]
  40. } else {
  41. description = "process_name=[" + strings.Join(r.processes, " ") + "]"
  42. }
  43. return description
  44. }