rule_item_port.go 996 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package rule
  2. import (
  3. "strings"
  4. "github.com/sagernet/sing-box/adapter"
  5. F "github.com/sagernet/sing/common/format"
  6. )
  7. var _ RuleItem = (*PortItem)(nil)
  8. type PortItem struct {
  9. ports []uint16
  10. portMap map[uint16]bool
  11. isSource bool
  12. }
  13. func NewPortItem(isSource bool, ports []uint16) *PortItem {
  14. portMap := make(map[uint16]bool)
  15. for _, port := range ports {
  16. portMap[port] = true
  17. }
  18. return &PortItem{
  19. ports: ports,
  20. portMap: portMap,
  21. isSource: isSource,
  22. }
  23. }
  24. func (r *PortItem) Match(metadata *adapter.InboundContext) bool {
  25. if r.isSource {
  26. return r.portMap[metadata.Source.Port]
  27. } else {
  28. return r.portMap[metadata.Destination.Port]
  29. }
  30. }
  31. func (r *PortItem) String() string {
  32. var description string
  33. if r.isSource {
  34. description = "source_port="
  35. } else {
  36. description = "port="
  37. }
  38. pLen := len(r.ports)
  39. if pLen == 1 {
  40. description += F.ToString(r.ports[0])
  41. } else {
  42. description += "[" + strings.Join(F.MapToString(r.ports), " ") + "]"
  43. }
  44. return description
  45. }