rules.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package json
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "net"
  6. "strings"
  7. "github.com/v2ray/v2ray-core/app/point/config"
  8. v2net "github.com/v2ray/v2ray-core/common/net"
  9. v2netjson "github.com/v2ray/v2ray-core/common/net/json"
  10. )
  11. type Rule struct {
  12. Type string `json:"type"`
  13. OutboundTag string `json:"outboundTag"`
  14. }
  15. func (this *Rule) Tag() *config.DetourTag {
  16. detourTag := config.DetourTag(this.OutboundTag)
  17. return &detourTag
  18. }
  19. func (this *Rule) Apply(dest v2net.Destination) bool {
  20. return false
  21. }
  22. type FieldRule struct {
  23. Rule
  24. Domain string
  25. IP *net.IPNet
  26. Port v2net.PortRange
  27. Network v2net.NetworkList
  28. }
  29. func (this *FieldRule) Apply(dest v2net.Destination) bool {
  30. address := dest.Address()
  31. if len(this.Domain) > 0 && address.IsDomain() {
  32. if !strings.Contains(address.Domain(), this.Domain) {
  33. return false
  34. }
  35. }
  36. if this.IP != nil && (address.IsIPv4() || address.IsIPv6()) {
  37. if !this.IP.Contains(address.IP()) {
  38. return false
  39. }
  40. }
  41. if this.Port != nil {
  42. port := address.Port()
  43. if port < this.Port.From() || port > this.Port.To() {
  44. return false
  45. }
  46. }
  47. if this.Network != nil {
  48. if !this.Network.HasNetwork(v2net.Network(dest.Network())) {
  49. return false
  50. }
  51. }
  52. return true
  53. }
  54. func (this *FieldRule) UnmarshalJSON(data []byte) error {
  55. type RawFieldRule struct {
  56. Rule
  57. Domain string `json:"domain"`
  58. IP string `json:"ip"`
  59. Port *v2netjson.PortRange
  60. Network *v2netjson.NetworkList
  61. }
  62. rawFieldRule := RawFieldRule{}
  63. err := json.Unmarshal(data, &rawFieldRule)
  64. if err != nil {
  65. return err
  66. }
  67. this.Type = rawFieldRule.Type
  68. this.OutboundTag = rawFieldRule.OutboundTag
  69. this.Domain = rawFieldRule.Domain
  70. _, ipNet, err := net.ParseCIDR(rawFieldRule.IP)
  71. if err != nil {
  72. return errors.New("Invalid IP range in router rule: " + err.Error())
  73. }
  74. this.IP = ipNet
  75. if rawFieldRule.Port != nil {
  76. this.Port = rawFieldRule.Port
  77. }
  78. if rawFieldRule.Network != nil {
  79. this.Network = rawFieldRule.Network
  80. }
  81. return nil
  82. }