rule_item_domain.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package route
  2. import (
  3. "strings"
  4. "github.com/sagernet/sing-box/adapter"
  5. "github.com/sagernet/sing/common/domain"
  6. )
  7. var _ RuleItem = (*DomainItem)(nil)
  8. type DomainItem struct {
  9. matcher *domain.Matcher
  10. description string
  11. }
  12. func NewDomainItem(domains []string, domainSuffixes []string) *DomainItem {
  13. var description string
  14. if dLen := len(domains); dLen > 0 {
  15. if dLen == 1 {
  16. description = "domain=" + domains[0]
  17. } else if dLen > 3 {
  18. description = "domain=[" + strings.Join(domains[:3], " ") + "...]"
  19. } else {
  20. description = "domain=[" + strings.Join(domains, " ") + "]"
  21. }
  22. }
  23. if dsLen := len(domainSuffixes); dsLen > 0 {
  24. if len(description) > 0 {
  25. description += " "
  26. }
  27. if dsLen == 1 {
  28. description += "domainSuffix=" + domainSuffixes[0]
  29. } else if dsLen > 3 {
  30. description += "domainSuffix=[" + strings.Join(domainSuffixes[:3], " ") + "...]"
  31. } else {
  32. description += "domainSuffix=[" + strings.Join(domainSuffixes, " ") + "]"
  33. }
  34. }
  35. return &DomainItem{
  36. domain.NewMatcher(domains, domainSuffixes),
  37. description,
  38. }
  39. }
  40. func (r *DomainItem) Match(metadata *adapter.InboundContext) bool {
  41. var domainHost string
  42. if metadata.Domain != "" {
  43. domainHost = metadata.Domain
  44. } else {
  45. domainHost = metadata.Destination.Fqdn
  46. }
  47. if domainHost == "" {
  48. return false
  49. }
  50. return r.matcher.Match(strings.ToLower(domainHost))
  51. }
  52. func (r *DomainItem) String() string {
  53. return r.description
  54. }