-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
setup.go
88 lines (72 loc) · 1.7 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
package loop
import (
"math/rand"
"net"
"strconv"
"time"
"github.com/coredns/coredns/core/dnsserver"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/pkg/dnsutil"
"github.com/caddyserver/caddy"
)
func init() { plugin.Register("loop", setup) }
func setup(c *caddy.Controller) error {
l, err := parse(c)
if err != nil {
return plugin.Error("loop", err)
}
dnsserver.GetConfig(c).AddPlugin(func(next plugin.Handler) plugin.Handler {
l.Next = next
return l
})
// Send query to ourselves and see if it end up with us again.
c.OnStartup(func() error {
// Another Go function, otherwise we block startup and can't send the packet.
go func() {
deadline := time.Now().Add(30 * time.Second)
conf := dnsserver.GetConfig(c)
lh := conf.ListenHosts[0]
addr := net.JoinHostPort(lh, conf.Port)
for time.Now().Before(deadline) {
l.setAddress(addr)
if _, err := l.exchange(addr); err != nil {
l.reset()
time.Sleep(1 * time.Second)
continue
}
go func() {
time.Sleep(2 * time.Second)
l.setDisabled()
}()
break
}
l.setDisabled()
}()
return nil
})
return nil
}
func parse(c *caddy.Controller) (*Loop, error) {
i := 0
zone := "."
for c.Next() {
if i > 0 {
return nil, plugin.ErrOnce
}
i++
if c.NextArg() {
return nil, c.ArgErr()
}
if len(c.ServerBlockKeys) > 0 {
zone = plugin.Host(c.ServerBlockKeys[0]).Normalize()
}
}
return New(zone), nil
}
// qname returns a random name. <rand.Int()>.<rand.Int().<zone>.
func qname(zone string) string {
l1 := strconv.Itoa(r.Int())
l2 := strconv.Itoa(r.Int())
return dnsutil.Join(l1, l2, zone)
}
var r = rand.New(rand.NewSource(time.Now().UnixNano()))