ipsuffix.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package common
  2. import (
  3. C "github.com/metacubex/mihomo/constant"
  4. "net/netip"
  5. )
  6. type IPSuffix struct {
  7. *Base
  8. ipBytes []byte
  9. bits int
  10. payload string
  11. adapter string
  12. isSourceIP bool
  13. noResolveIP bool
  14. }
  15. func (is *IPSuffix) RuleType() C.RuleType {
  16. if is.isSourceIP {
  17. return C.SrcIPSuffix
  18. }
  19. return C.IPSuffix
  20. }
  21. func (is *IPSuffix) Match(metadata *C.Metadata) (bool, string) {
  22. ip := metadata.DstIP
  23. if is.isSourceIP {
  24. ip = metadata.SrcIP
  25. }
  26. mIPBytes := ip.AsSlice()
  27. if len(is.ipBytes) != len(mIPBytes) {
  28. return false, ""
  29. }
  30. size := len(mIPBytes)
  31. bits := is.bits
  32. for i := bits / 8; i > 0; i-- {
  33. if is.ipBytes[size-i] != mIPBytes[size-i] {
  34. return false, ""
  35. }
  36. }
  37. if (is.ipBytes[size-bits/8-1] << (8 - bits%8)) != (mIPBytes[size-bits/8-1] << (8 - bits%8)) {
  38. return false, ""
  39. }
  40. return true, is.adapter
  41. }
  42. func (is *IPSuffix) Adapter() string {
  43. return is.adapter
  44. }
  45. func (is *IPSuffix) Payload() string {
  46. return is.payload
  47. }
  48. func (is *IPSuffix) ShouldResolveIP() bool {
  49. return !is.noResolveIP
  50. }
  51. func NewIPSuffix(payload, adapter string, isSrc, noResolveIP bool) (*IPSuffix, error) {
  52. ipnet, err := netip.ParsePrefix(payload)
  53. if err != nil {
  54. return nil, errPayload
  55. }
  56. return &IPSuffix{
  57. Base: &Base{},
  58. payload: payload,
  59. ipBytes: ipnet.Addr().AsSlice(),
  60. bits: ipnet.Bits(),
  61. adapter: adapter,
  62. isSourceIP: isSrc,
  63. noResolveIP: noResolveIP,
  64. }, nil
  65. }