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

     1  package common
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/metacubex/mihomo/common/utils"
     7  	C "github.com/metacubex/mihomo/constant"
     8  )
     9  
    10  type Port struct {
    11  	*Base
    12  	adapter    string
    13  	port       string
    14  	ruleType   C.RuleType
    15  	portRanges utils.IntRanges[uint16]
    16  }
    17  
    18  func (p *Port) RuleType() C.RuleType {
    19  	return p.ruleType
    20  }
    21  
    22  func (p *Port) Match(metadata *C.Metadata) (bool, string) {
    23  	targetPort := metadata.DstPort
    24  	switch p.ruleType {
    25  	case C.InPort:
    26  		targetPort = metadata.InPort
    27  	case C.SrcPort:
    28  		targetPort = metadata.SrcPort
    29  	}
    30  	return p.portRanges.Check(targetPort), p.adapter
    31  }
    32  
    33  func (p *Port) Adapter() string {
    34  	return p.adapter
    35  }
    36  
    37  func (p *Port) Payload() string {
    38  	return p.port
    39  }
    40  
    41  func NewPort(port string, adapter string, ruleType C.RuleType) (*Port, error) {
    42  	portRanges, err := utils.NewUnsignedRanges[uint16](port)
    43  	if err != nil {
    44  		return nil, fmt.Errorf("%w, %w", errPayload, err)
    45  	}
    46  
    47  	if len(portRanges) == 0 {
    48  		return nil, errPayload
    49  	}
    50  
    51  	return &Port{
    52  		Base:       &Base{},
    53  		adapter:    adapter,
    54  		port:       port,
    55  		ruleType:   ruleType,
    56  		portRanges: portRanges,
    57  	}, nil
    58  }
    59  
    60  var _ C.Rule = (*Port)(nil)