-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetup.go
105 lines (92 loc) · 2.39 KB
/
setup.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package better_template
import (
"net"
"strconv"
"strings"
"github.com/coredns/caddy"
"github.com/coredns/coredns/core/dnsserver"
"github.com/coredns/coredns/plugin"
"github.com/v2fly/v2ray-core/v5/common/strmatcher"
)
func init() { plugin.Register("better_template", setup) }
func setup(c *caddy.Controller) error {
domainMatcher := strmatcher.NewMphIndexMatcher()
lookup := make(map[uint32]*entry)
c.Next()
for c.Val() != "" {
if c.Val() == "better_template" {
if c.Next() && c.Val() != "{" {
return plugin.Error("better_template", c.SyntaxErr("{"))
}
c.Next()
}
m := c.Val()
if c.Next() && c.Val() != "{" {
return plugin.Error("better_template", c.SyntaxErr("{"))
}
if !c.Next() {
return plugin.Error("better_template", c.ArgErr())
}
e := &entry{make([]addressTtl, 0), make([]addressTtl, 0), ""}
for {
dst := c.Val()
if dst == "}" {
c.NextLine()
break
}
ip := net.ParseIP(dst)
if ip == nil {
return plugin.Error("better_template", c.ArgErr())
}
ttl := uint32(60)
if c.NextArg() {
tmp, err := strconv.Atoi(c.Val())
if err != nil {
return plugin.Error("better_template", err)
}
if tmp > 2147483647 || ttl < 0 {
return plugin.Error("better_template", c.Err("Invalid TTL"))
}
ttl = uint32(tmp)
}
if temp := ip.To4(); temp != nil {
e.ipv4 = append(e.ipv4, addressTtl{temp, ttl})
} else {
e.ipv6 = append(e.ipv6, addressTtl{ip, ttl})
}
if !c.NextLine() {
return plugin.Error("better_template", c.ArgErr())
}
}
t := strmatcher.Full
if strings.HasPrefix(m, "regexp:") {
t = strmatcher.Regex
m = m[7:]
} else if strings.HasPrefix(m, "keyword:") {
t = strmatcher.Substr
m = m[8:]
} else if strings.HasPrefix(m, "subdomain:") {
t = strmatcher.Domain
m = m[10:]
e.isSubdomainMatch = m
} else if strings.HasPrefix(m, "domain:") {
t = strmatcher.Domain
m = m[7:]
}
matcher, err := t.New(m)
if err != nil {
return plugin.Error("better_template", err)
}
lookup[domainMatcher.Add(matcher)] = e
if c.Val() == "}" && !c.Next() {
break
}
}
domainMatcher.Build()
// Add the Plugin to CoreDNS, so Servers can use it in their plugin chain.
dnsserver.GetConfig(c).AddPlugin(func(next plugin.Handler) plugin.Handler {
return &BetterTemplate{Next: next, lookup: lookup, matcher: domainMatcher}
})
// All OK, return a nil error.
return nil
}