Skip to content

Commit

Permalink
Fix: domain trie should backtrack to parent if match fail (#758)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kr328 authored Jun 24, 2020
1 parent 5f3db72 commit 3dfff84
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 27 deletions.
46 changes: 19 additions & 27 deletions component/trie/domain.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,45 +96,37 @@ func (t *DomainTrie) Search(domain string) *Node {
return nil
}

n := t.root
var dotWildcardNode *Node
var wildcardNode *Node
for i := len(parts) - 1; i >= 0; i-- {
part := parts[i]
n := t.search(t.root, parts)

if node := n.getChild(dotWildcard); node != nil {
dotWildcardNode = node
}
if n.Data == nil {
return nil
}

child := n.getChild(part)
if child == nil && wildcardNode != nil {
child = wildcardNode.getChild(part)
}
wildcardNode = n.getChild(wildcard)
return n
}

n = child
if n == nil {
n = wildcardNode
wildcardNode = nil
}
func (t *DomainTrie) search(node *Node, parts []string) *Node {
if len(parts) == 0 {
return node
}

if n == nil {
break
if c := node.getChild(parts[len(parts)-1]); c != nil {
if n := t.search(c, parts[:len(parts)-1]); n != nil {
return n
}
}

if n == nil {
if dotWildcardNode != nil {
return dotWildcardNode
if c := node.getChild(wildcard); c != nil {
if n := t.search(c, parts[:len(parts)-1]); n != nil {
return n
}
return nil
}

if n.Data == nil {
return nil
if c := node.getChild(dotWildcard); c != nil {
return c
}

return n
return nil
}

// New returns a new, empty Trie.
Expand Down
5 changes: 5 additions & 0 deletions component/trie/domain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ func TestTrie_Wildcard(t *testing.T) {
".example.net",
".apple.*",
"+.foo.com",
"+.stun.*.*",
"+.stun.*.*.*",
"+.stun.*.*.*.*",
"stun.l.google.com",
}

for _, domain := range domains {
Expand All @@ -52,6 +56,7 @@ func TestTrie_Wildcard(t *testing.T) {
assert.NotNil(t, tree.Search("test.apple.com"))
assert.NotNil(t, tree.Search("test.foo.com"))
assert.NotNil(t, tree.Search("foo.com"))
assert.NotNil(t, tree.Search("global.stun.website.com"))
assert.Nil(t, tree.Search("foo.sub.example.com"))
assert.Nil(t, tree.Search("foo.example.dev"))
assert.Nil(t, tree.Search("example.com"))
Expand Down

0 comments on commit 3dfff84

Please sign in to comment.