port.go 1.1 KB

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