rule_item_domain_regex.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package rule
  2. import (
  3. "regexp"
  4. "strings"
  5. "github.com/sagernet/sing-box/adapter"
  6. E "github.com/sagernet/sing/common/exceptions"
  7. F "github.com/sagernet/sing/common/format"
  8. )
  9. var _ RuleItem = (*DomainRegexItem)(nil)
  10. type DomainRegexItem struct {
  11. matchers []*regexp.Regexp
  12. description string
  13. }
  14. func NewDomainRegexItem(expressions []string) (*DomainRegexItem, error) {
  15. matchers := make([]*regexp.Regexp, 0, len(expressions))
  16. for i, regex := range expressions {
  17. matcher, err := regexp.Compile(regex)
  18. if err != nil {
  19. return nil, E.Cause(err, "parse expression ", i)
  20. }
  21. matchers = append(matchers, matcher)
  22. }
  23. description := "domain_regex="
  24. eLen := len(expressions)
  25. if eLen == 1 {
  26. description += expressions[0]
  27. } else if eLen > 3 {
  28. description += F.ToString("[", strings.Join(expressions[:3], " "), "]")
  29. } else {
  30. description += F.ToString("[", strings.Join(expressions, " "), "]")
  31. }
  32. return &DomainRegexItem{matchers, description}, nil
  33. }
  34. func (r *DomainRegexItem) Match(metadata *adapter.InboundContext) bool {
  35. var domainHost string
  36. if metadata.Domain != "" {
  37. domainHost = metadata.Domain
  38. } else {
  39. domainHost = metadata.Destination.Fqdn
  40. }
  41. if domainHost == "" {
  42. return false
  43. }
  44. domainHost = strings.ToLower(domainHost)
  45. for _, matcher := range r.matchers {
  46. if matcher.MatchString(domainHost) {
  47. return true
  48. }
  49. }
  50. return false
  51. }
  52. func (r *DomainRegexItem) String() string {
  53. return r.description
  54. }