route.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package option
  2. import (
  3. "encoding/json"
  4. C "github.com/sagernet/sing-box/constant"
  5. E "github.com/sagernet/sing/common/exceptions"
  6. )
  7. var ErrUnknownRuleType = E.New("unknown rule type")
  8. type _Rule struct {
  9. Type string `json:"type"`
  10. DefaultOptions DefaultRule `json:"default_options,omitempty"`
  11. LogicalOptions LogicalRule `json:"logical_options,omitempty"`
  12. }
  13. type Rule _Rule
  14. func (r *Rule) MarshalJSON() ([]byte, error) {
  15. var content map[string]any
  16. switch r.Type {
  17. case "", C.RuleTypeDefault:
  18. return json.Marshal(r.DefaultOptions)
  19. case C.RuleTypeLogical:
  20. options, err := json.Marshal(r.LogicalOptions)
  21. if err != nil {
  22. return nil, err
  23. }
  24. err = json.Unmarshal(options, &content)
  25. if err != nil {
  26. return nil, err
  27. }
  28. content["type"] = r.Type
  29. return json.Marshal(content)
  30. default:
  31. return nil, E.Extend(ErrUnknownRuleType, r.Type)
  32. }
  33. }
  34. func (r *Rule) UnmarshalJSON(bytes []byte) error {
  35. err := json.Unmarshal(bytes, (*_Rule)(r))
  36. if err != nil {
  37. return err
  38. }
  39. switch r.Type {
  40. case "", C.RuleTypeDefault:
  41. err = json.Unmarshal(bytes, &r.DefaultOptions)
  42. case C.RuleTypeLogical:
  43. err = json.Unmarshal(bytes, &r.LogicalOptions)
  44. default:
  45. err = E.Extend(ErrUnknownRuleType, r.Type)
  46. }
  47. return err
  48. }
  49. type DefaultRule struct {
  50. Inbound []string `json:"inbound,omitempty"`
  51. IPVersion []int `json:"ip_version,omitempty"`
  52. Network []string `json:"network,omitempty"`
  53. Protocol []string `json:"protocol,omitempty"`
  54. Domain []string `json:"domain,omitempty"`
  55. DomainSuffix []string `json:"domain_suffix,omitempty"`
  56. DomainKeyword []string `json:"domain_keyword,omitempty"`
  57. SourceGeoIP []string `json:"source_geoip,omitempty"`
  58. GeoIP []string `json:"geoip,omitempty"`
  59. SourceIPCIDR []string `json:"source_ipcidr,omitempty"`
  60. SourcePort []string `json:"source_port,omitempty"`
  61. IPCIDR []string `json:"destination_ipcidr,omitempty"`
  62. Port []string `json:"destination_port,omitempty"`
  63. ProcessName []string `json:"process_name,omitempty"`
  64. ProcessPath []string `json:"process_path,omitempty"`
  65. Outbound string `json:"outbound,omitempty"`
  66. }
  67. type LogicalRule struct {
  68. Mode string `json:"mode"`
  69. Rules []DefaultRule `json:"rules,omitempty"`
  70. Outbound string `json:"outbound,omitempty"`
  71. }