github.com/metacubex/mihomo@v1.18.5/rules/common/process.go (about)

     1  package common
     2  
     3  import (
     4  	"strings"
     5  
     6  	C "github.com/metacubex/mihomo/constant"
     7  
     8  	"github.com/dlclark/regexp2"
     9  )
    10  
    11  type Process struct {
    12  	*Base
    13  	adapter  string
    14  	process  string
    15  	nameOnly bool
    16  	regexp   *regexp2.Regexp
    17  }
    18  
    19  func (ps *Process) RuleType() C.RuleType {
    20  	if ps.nameOnly {
    21  		if ps.regexp != nil {
    22  			return C.ProcessNameRegex
    23  		}
    24  		return C.ProcessName
    25  	}
    26  
    27  	if ps.regexp != nil {
    28  		return C.ProcessPathRegex
    29  	}
    30  	return C.ProcessPath
    31  }
    32  
    33  func (ps *Process) Match(metadata *C.Metadata) (bool, string) {
    34  	if ps.nameOnly {
    35  		if ps.regexp != nil {
    36  			match, _ := ps.regexp.MatchString(metadata.Process)
    37  			return match, ps.adapter
    38  		}
    39  		return strings.EqualFold(metadata.Process, ps.process), ps.adapter
    40  	}
    41  
    42  	if ps.regexp != nil {
    43  		match, _ := ps.regexp.MatchString(metadata.ProcessPath)
    44  		return match, ps.adapter
    45  	}
    46  	return strings.EqualFold(metadata.ProcessPath, ps.process), ps.adapter
    47  }
    48  
    49  func (ps *Process) Adapter() string {
    50  	return ps.adapter
    51  }
    52  
    53  func (ps *Process) Payload() string {
    54  	return ps.process
    55  }
    56  
    57  func (ps *Process) ShouldFindProcess() bool {
    58  	return true
    59  }
    60  
    61  func NewProcess(process string, adapter string, nameOnly bool, regex bool) (*Process, error) {
    62  	var r *regexp2.Regexp
    63  	var err error
    64  	if regex {
    65  		r, err = regexp2.Compile(process, regexp2.IgnoreCase)
    66  		if err != nil {
    67  			return nil, err
    68  		}
    69  	}
    70  	return &Process{
    71  		Base:     &Base{},
    72  		adapter:  adapter,
    73  		process:  process,
    74  		nameOnly: nameOnly,
    75  		regexp:   r,
    76  	}, nil
    77  }