-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathdns.go
126 lines (106 loc) · 2.29 KB
/
dns.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package main
import (
"fmt"
"io/ioutil"
"net"
"os"
"strings"
"github.com/miekg/dns"
)
type DNS struct {
daemon *Daemon
server *dns.Server
}
func (d *DNS) handleRequest(w dns.ResponseWriter, r *dns.Msg) {
msg := &dns.Msg{}
msg.SetReply(r)
if d.daemon.VM == nil {
msg.SetRcode(r, dns.RcodeNameError)
w.WriteMsg(msg)
return
}
userPath := getPath(*d.daemon.VM.Owner)
cfg, err := readConfig(userPath)
if err != nil {
msg.SetRcode(r, dns.RcodeServerFailure)
w.WriteMsg(msg)
return
}
hostname := fmt.Sprintf("%s.", cfg.Hostname)
domain := fmt.Sprintf("%s.", getDomain(cfg.Hostname))
q := r.Question[0]
if q.Qtype != dns.TypeA {
msg.SetRcode(r, dns.RcodeNotImplemented)
} else {
if !strings.HasSuffix(q.Name, domain) {
msg.SetRcode(r, dns.RcodeNameError)
w.WriteMsg(msg)
return
}
if q.Name == hostname {
ip, err := d.daemon.VM.IP()
if err != nil {
msg.SetRcode(r, dns.RcodeNameError)
w.WriteMsg(msg)
return
}
record := &dns.A{
Hdr: dns.RR_Header{
Name: q.Name,
Rrtype: dns.TypeA,
Class: dns.ClassINET,
Ttl: 0,
},
A: net.ParseIP(ip).To4(),
}
msg.Answer = append(msg.Answer, record)
} else if cfg.Route {
cleaned := strings.TrimSuffix(q.Name, fmt.Sprintf(".%s", domain))
ip, err := d.daemon.VM.findContainer(cleaned)
if err != nil {
msg.SetRcode(r, dns.RcodeNameError)
w.WriteMsg(msg)
return
}
record := &dns.A{
Hdr: dns.RR_Header{
Name: q.Name,
Rrtype: dns.TypeA,
Class: dns.ClassINET,
Ttl: 0,
},
A: net.ParseIP(ip).To4(),
}
msg.Answer = append(msg.Answer, record)
} else {
msg.SetRcode(r, dns.RcodeNameError)
}
}
w.WriteMsg(msg)
}
func (d *DNS) Start() error {
dns.HandleFunc(".", d.handleRequest)
d.server = &dns.Server{
Addr: ":1053",
Net: "udp",
}
return d.server.ListenAndServe()
}
func (d *DNS) Stop() error {
return d.server.Shutdown()
}
func NewDNS(daemon *Daemon) *DNS {
return &DNS{
daemon: daemon,
}
}
func installResolver(hostname string) error {
err := os.MkdirAll("/etc/resolver", 0755)
if err != nil {
return err
}
domain := getDomain(hostname)
file := fmt.Sprintf("/etc/resolver/%s", domain)
resolver := "nameserver 127.0.0.1\nport 1053"
return ioutil.WriteFile(file, []byte(resolver), 0644)
}