cmd_geosite_matcher.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package main
  2. import (
  3. "regexp"
  4. "strings"
  5. "github.com/sagernet/sing-box/common/geosite"
  6. )
  7. type searchGeositeMatcher struct {
  8. domainMap map[string]bool
  9. suffixList []string
  10. keywordList []string
  11. regexList []string
  12. }
  13. func newSearchGeositeMatcher(items []geosite.Item) (*searchGeositeMatcher, error) {
  14. options := geosite.Compile(items)
  15. domainMap := make(map[string]bool)
  16. for _, domain := range options.Domain {
  17. domainMap[domain] = true
  18. }
  19. rule := &searchGeositeMatcher{
  20. domainMap: domainMap,
  21. suffixList: options.DomainSuffix,
  22. keywordList: options.DomainKeyword,
  23. regexList: options.DomainRegex,
  24. }
  25. return rule, nil
  26. }
  27. func (r *searchGeositeMatcher) Match(domain string) string {
  28. if r.domainMap[domain] {
  29. return "domain=" + domain
  30. }
  31. for _, suffix := range r.suffixList {
  32. if strings.HasSuffix(domain, suffix) {
  33. return "domain_suffix=" + suffix
  34. }
  35. }
  36. for _, keyword := range r.keywordList {
  37. if strings.Contains(domain, keyword) {
  38. return "domain_keyword=" + keyword
  39. }
  40. }
  41. for _, regexStr := range r.regexList {
  42. regex, err := regexp.Compile(regexStr)
  43. if err != nil {
  44. continue
  45. }
  46. if regex.MatchString(domain) {
  47. return "domain_regex=" + regexStr
  48. }
  49. }
  50. return ""
  51. }