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

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