github.com/inazumav/sing-box@v0.0.0-20230926072359-ab51429a14f1/route/rule_item_domain_keyword.go (about)

     1  package route
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/inazumav/sing-box/adapter"
     7  )
     8  
     9  var _ RuleItem = (*DomainKeywordItem)(nil)
    10  
    11  type DomainKeywordItem struct {
    12  	keywords []string
    13  }
    14  
    15  func NewDomainKeywordItem(keywords []string) *DomainKeywordItem {
    16  	return &DomainKeywordItem{keywords}
    17  }
    18  
    19  func (r *DomainKeywordItem) Match(metadata *adapter.InboundContext) bool {
    20  	var domainHost string
    21  	if metadata.Domain != "" {
    22  		domainHost = metadata.Domain
    23  	} else {
    24  		domainHost = metadata.Destination.Fqdn
    25  	}
    26  	if domainHost == "" {
    27  		return false
    28  	}
    29  	domainHost = strings.ToLower(domainHost)
    30  	for _, keyword := range r.keywords {
    31  		if strings.Contains(domainHost, keyword) {
    32  			return true
    33  		}
    34  	}
    35  	return false
    36  }
    37  
    38  func (r *DomainKeywordItem) String() string {
    39  	kLen := len(r.keywords)
    40  	if kLen == 1 {
    41  		return "domain_keyword=" + r.keywords[0]
    42  	} else if kLen > 3 {
    43  		return "domain_keyword=[" + strings.Join(r.keywords[:3], " ") + "...]"
    44  	} else {
    45  		return "domain_keyword=[" + strings.Join(r.keywords, " ") + "]"
    46  	}
    47  }