diff --git a/component/trie/domain.go b/component/trie/domain.go index f790d666f..723020c44 100644 --- a/component/trie/domain.go +++ b/component/trie/domain.go @@ -175,6 +175,11 @@ func (t *DomainTrie[T]) Optimize() { t.root.optimize() } +// Foreach iterates over the stored domain patterns and their associated values +// in unspecified order. Patterns use lowercase labels, "*" for a single-label +// wildcard, and a leading "." for subdomain-only matching. Exact and suffix-only +// patterns are separate entries; "+." shorthand is not emitted. Each pattern +// and its value can be passed to Insert independently to reproduce the mappings. func (t *DomainTrie[T]) Foreach(fn func(domain string, data T) bool) { for key, data := range t.root.getChildren() { recursion([]string{key}, data, fn) @@ -198,9 +203,6 @@ func recursion[T any](items []string, node *Node[T], fn func(domain string, data newItems := append([]string{key}, items...) if !data.isEmpty() { domain := joinDomain(newItems) - if domain[0] == domainStepByte { - domain = complexWildcard + domain - } if !fn(domain, data.Data()) { return false } diff --git a/component/trie/domain_set.go b/component/trie/domain_set.go index 574237599..cc4cccded 100644 --- a/component/trie/domain_set.go +++ b/component/trie/domain_set.go @@ -82,6 +82,11 @@ func (b *DomainSetBuilder) Build() *DomainSet { func (t *DomainTrie[T]) NewDomainSet() *DomainSet { keys := make([]string, 0) t.Foreach(func(domain string, _ T) bool { + if domain[0] == domainStepByte { + // Suffix-only patterns need an explicit '+' wildcard marker in + // the internal key; a leading dot alone is only a label separator. + domain = complexWildcard + domain + } keys = append(keys, utils.Reverse(domain)) return true }) @@ -267,9 +272,16 @@ func (ss *DomainSet) keys(f func(key string) bool) { return } +// Foreach iterates over the stored domain patterns in unspecified order. +// Patterns use lowercase labels, "*" for a single-label wildcard, and a leading +// "." for subdomain-only matching. Exact and suffix-only patterns are separate +// entries; "+." shorthand is not emitted. Each pattern can be passed to +// DomainSetBuilder.Insert independently to reproduce the set. func (ss *DomainSet) Foreach(f func(key string) bool) { ss.keys(func(key string) bool { - return f(utils.Reverse(key)) + // Internal keys are reversed, with a trailing '+' for suffix wildcards. + // Removing that marker leaves the leading-dot syntax after reversal. + return f(utils.Reverse(strings.TrimSuffix(key, complexWildcard))) }) } diff --git a/component/trie/domain_set_test.go b/component/trie/domain_set_test.go index 4eff4362f..fa64d4998 100644 --- a/component/trie/domain_set_test.go +++ b/component/trie/domain_set_test.go @@ -61,6 +61,33 @@ func TestDomainSet(t *testing.T) { testDump(t, tree, set) } +func TestDomainSetForeach(test *testing.T) { + var builder trie.DomainSetBuilder + for _, domain := range []string{".example.com", "+.example.org", "example.net"} { + assert.NoError(test, builder.Insert(domain)) + } + set := builder.Build() + var keys []string + set.Foreach(func(key string) bool { + keys = append(keys, key) + assert.NoError(test, builder.Insert(key)) + return true + }) + assert.ElementsMatch(test, []string{".example.com", ".example.org", "example.org", "example.net"}, keys) + for _, set := range []*trie.DomainSet{set, builder.Build()} { + for domain, expected := range map[string]bool{ + "example.com": false, + "www.example.com": true, + "example.org": true, + "www.example.org": true, + "example.net": true, + "www.example.net": false, + } { + assert.Equal(test, expected, set.Has(domain), domain) + } + } +} + func TestDomainSetBuilderLifecycle(t *testing.T) { var builder trie.DomainSetBuilder assert.True(t, builder.IsEmpty()) @@ -82,7 +109,7 @@ func TestDomainSetBuilderLifecycle(t *testing.T) { return true }) slices.Sort(keys) - assert.Equal(t, []string{"+.example.com", "example.com"}, keys) + assert.Equal(t, []string{".example.com", "example.com"}, keys) assert.NoError(t, builder.Insert("other.example")) set = builder.Build() diff --git a/component/trie/domain_test.go b/component/trie/domain_test.go index 6eef9c932..010aaf7ef 100644 --- a/component/trie/domain_test.go +++ b/component/trie/domain_test.go @@ -199,7 +199,7 @@ func TestTrie_ValidAndSplitDomain(t *testing.T) { } func TestTrie_Foreach(t *testing.T) { - tree := trie.New[netip.Addr]() + tree := trie.New[int]() domainList := []string{ "google.com", "stun.*.*.*", @@ -207,14 +207,37 @@ func TestTrie_Foreach(t *testing.T) { "+.baidu.com", "*.baidu.com", "*.*.baidu.com", + "baidu.com", + ".example.org", } - for _, domain := range domainList { - assert.NoError(t, tree.Insert(domain, localIP)) + for index, domain := range domainList { + assert.NoError(t, tree.Insert(domain, index)) } - count := 0 - tree.Foreach(func(domain string, data netip.Addr) bool { - count++ + rebuilt := trie.New[int]() + values := make(map[string]int) + tree.Foreach(func(domain string, data int) bool { + assert.NotContains(t, values, domain) + values[domain] = data + assert.NoError(t, rebuilt.Insert(domain, data)) return true }) - assert.Equal(t, 7, count) + assert.Equal(t, map[string]int{ + "google.com": 0, + "stun.*.*.*": 1, + "test.*.google.com": 2, + ".baidu.com": 3, + "*.baidu.com": 4, + "*.*.baidu.com": 5, + "baidu.com": 6, + ".example.org": 7, + }, values) + for _, tree := range []*trie.DomainTrie[int]{tree, rebuilt} { + for domain, expected := range map[string]int{"google.com": 0, "baidu.com": 6, "a.b.c.baidu.com": 3, "www.example.org": 7} { + node := tree.Search(domain) + if assert.NotNil(t, node, domain) { + assert.Equal(t, expected, node.Data(), domain) + } + } + assert.Nil(t, tree.Search("example.org")) + } } diff --git a/rules/provider/domain_strategy.go b/rules/provider/domain_strategy.go index 46c63d6f2..be473b909 100644 --- a/rules/provider/domain_strategy.go +++ b/rules/provider/domain_strategy.go @@ -71,6 +71,9 @@ func (d *domainStrategy) WriteMrs(w io.Writer) error { return d.domainSet.WriteBin(w) } +// DumpMrs emits a compact domain rule list in lexicographical order through f. +// A "domain" entry and a ".domain" entry are represented by one "+.domain" rule; +// either entry alone is emitted unchanged. Returning false from f stops iteration. func (d *domainStrategy) DumpMrs(f func(key string) bool) { if d.domainSet != nil { var keys []string @@ -80,10 +83,23 @@ func (d *domainStrategy) DumpMrs(f func(key string) bool) { }) slices.Sort(keys) + // Keep keys unchanged for binary searches; sort the compact rules separately. + rules := make([]string, 0, len(keys)) for _, key := range keys { - if _, ok := slices.BinarySearch(keys, "+."+key); ok { - continue // ignore the rules added by trie internal processing + if strings.HasPrefix(key, ".") { + if _, ok := slices.BinarySearch(keys, key[1:]); ok { + // Both the domain itself and its subdomains are covered by one "+." rule. + key = "+" + key + } + } else if _, ok := slices.BinarySearch(keys, "."+key); ok { + // The paired suffix entry represents this exact entry in the combined rule. + continue } + rules = append(rules, key) + } + slices.Sort(rules) + + for _, key := range rules { if !f(key) { return } diff --git a/rules/provider/domain_strategy_test.go b/rules/provider/domain_strategy_test.go new file mode 100644 index 000000000..7292c0886 --- /dev/null +++ b/rules/provider/domain_strategy_test.go @@ -0,0 +1,79 @@ +package provider_test + +import ( + "testing" + + "github.com/metacubex/mihomo/constant" + "github.com/metacubex/mihomo/rules/provider" + "github.com/stretchr/testify/assert" +) + +func TestDomainStrategyDumpMrs(test *testing.T) { + tests := []struct { + name string + domains []string + expected []string + queries map[string]bool + }{ + { + "suffix-only", + []string{".example.com"}, + []string{".example.com"}, + map[string]bool{"example.com": false, "www.example.com": true}, + }, + { + "exact-only", + []string{"example.com"}, + []string{"example.com"}, + map[string]bool{"example.com": true, "www.example.com": false}, + }, + { + "merge-terminals", + []string{"example.com", ".example.com"}, + []string{"+.example.com"}, + map[string]bool{"example.com": true, "www.example.com": true}, + }, + { + "deduplicate", + []string{"+.example.com", "+.example.com", "example.com", ".example.com"}, + []string{"+.example.com"}, + map[string]bool{"example.com": true, "www.example.com": true}, + }, + { + "mixed", + []string{".example.com", "example.net", "example.org", ".example.org"}, + []string{"+.example.org", ".example.com", "example.net"}, + map[string]bool{ + "example.com": false, + "www.example.com": true, + "example.net": true, + "www.example.net": false, + "example.org": true, + "www.example.org": true, + }, + }, + } + for _, testCase := range tests { + test.Run(testCase.name, func(test *testing.T) { + strategy := provider.NewDomainStrategy() + for _, domain := range testCase.domains { + strategy.Insert(domain) + } + strategy.FinishInsert() + rebuilt := provider.NewDomainStrategy() + var domains []string + strategy.DumpMrs(func(domain string) bool { + domains = append(domains, domain) + rebuilt.Insert(domain) + return true + }) + rebuilt.FinishInsert() + assert.Equal(test, testCase.expected, domains) + for domain, expected := range testCase.queries { + metadata := &constant.Metadata{Host: domain} + assert.Equal(test, expected, strategy.Match(metadata, constant.RuleMatchHelper{}), domain) + assert.Equal(test, expected, rebuilt.Match(metadata, constant.RuleMatchHelper{}), domain) + } + }) + } +}