-
Notifications
You must be signed in to change notification settings - Fork 6
/
server.go
302 lines (255 loc) · 7.21 KB
/
server.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
package main
import (
"context"
"fmt"
"net"
"net/http"
"net/http/httptest"
"path/filepath"
"sync"
"time"
"github.com/coredhcp/coredhcp/plugins/allocators"
"github.com/coredns/coredns/core/dnsserver"
"github.com/insomniacslk/dhcp/dhcpv4/server4"
"github.com/pin/tftp"
matchboxHttp "github.com/poseidon/matchbox/matchbox/http"
matchboxServer "github.com/poseidon/matchbox/matchbox/server"
"github.com/poseidon/matchbox/matchbox/storage"
)
type DHCPRecord struct {
IP net.IP
expires time.Time
}
// A Server boots machines using a Booter.
type Server struct {
ServerRoot string
IP net.IP
GWIP net.IP
Net *net.IPNet
ForwardDns []string
Intf string
Controlplane string
ProxyDHCP bool
DHCPLock sync.Mutex
DHCPRecords map[string]*DHCPRecord
DHCPAllocator allocators.Allocator
DNSRWLock sync.RWMutex
DNSRecordsv4 map[string][]net.IP
DNSRecordsv6 map[string][]net.IP
DNSRRecords map[string][]string
// These ports can technically be set for testing, but the
// protocols burned in firmware on the client side hardcode these,
// so if you change them in production, nothing will work.
DHCPPort int
TFTPPort int
PXEPort int
HTTPPort int
DNSPort int
errs chan error
// pointers to servers needed for shutdowns
serverHTTP *http.Server
serverTFTP *tftp.Server
serverDHCP *server4.Server
serverDNS *dnsserver.Server
// the PXE does not have server object just a socket that we close when Serve() exits
closeServers chan struct{}
tFTPStarted bool
}
// Serve listens for machines attempting to boot, and uses Booter to
// help them.
func (s *Server) Serve() error {
cTftp, err := net.ListenPacket("udp", fmt.Sprintf("%s:%d", s.IP, s.TFTPPort))
if err != nil {
return err
}
defer cTftp.Close()
cPxe, err := net.ListenPacket("udp4", fmt.Sprintf("%s:%d", s.IP, s.PXEPort))
if err != nil {
return err
}
defer cPxe.Close()
cHttp, err := net.Listen("tcp", fmt.Sprintf(":%d", s.HTTPPort))
if err != nil {
return err
}
defer cHttp.Close()
cDns, err := net.ListenPacket("udp", fmt.Sprintf("%s:%d", s.IP, s.DNSPort))
if err != nil {
return err
}
defer cDns.Close()
log.Info("Starting servers")
go func() { s.errs <- s.servePXE(cPxe) }()
go func() { s.errs <- s.serveTFTP(cTftp) }()
go func() { s.errs <- s.startMatchbox(cHttp) }()
go func() { s.errs <- s.serveDNS(cDns) }()
go func() { s.errs <- s.startDHCP() }()
// Wait for either a fatal error, or Shutdown().
err = <-s.errs
return err
}
// NewServer creates the talos-pxe server and prepares all the inner servers without starting them
func NewServer(ip net.IP, serverRoot, interfaceName, controlplane string) (*Server, error) {
var err error
s := &Server{
IP: ip,
ServerRoot: serverRoot,
Intf: interfaceName,
Controlplane: controlplane,
DHCPRecords: make(map[string]*DHCPRecord),
DNSRecordsv4: make(map[string][]net.IP),
DNSRecordsv6: make(map[string][]net.IP),
DNSRRecords: make(map[string][]string),
closeServers: make(chan struct{}),
// 6 buffer slots, one for each goroutine, plus one for
// Shutdown(). We only ever pull the first error out, but shutdown
// will likely generate some spurious errors from the other
// goroutines, and we want them to be able to dump them without
// blocking.
errs: make(chan error, 6),
DHCPPort: portDHCP,
TFTPPort: portTFTP,
PXEPort: portPXE,
HTTPPort: portHTTP,
}
// Configure MatchBox server
server := matchboxServer.NewServer(&matchboxServer.Config{
Store: storage.NewFileStore(&storage.Config{
Root: serverRoot,
}),
})
config := &matchboxHttp.Config{
Core: server,
Logger: log,
AssetsPath: filepath.Join(serverRoot, "assets"),
}
s.serverHTTP = &http.Server{
Handler: s.ipxeWrapperMenuHandler(matchboxHttp.NewServer(config).HTTPHandler()),
}
// Configure TFTP server
s.serverTFTP = tftp.NewServer(s.readHandlerTFTP, nil)
s.serverTFTP.SetHook(&TFTPHook{})
// Configure DHCP server
s.serverDHCP, err = server4.NewServer(
s.Intf,
nil,
s.handlerDHCP4(),
server4.WithLogger(DHCPLogger{}),
)
if err != nil {
return nil, err
}
if err := s.ConfigureDnsServer([]string{forwardDns}, portDNS); err != nil {
return nil, err
}
return s, nil
}
// ConfigureDnsServer is needed to overwrite default DNS configuration that is set up in NewServer()
func (s *Server) ConfigureDnsServer(forwardDns []string, port int) (err error) {
s.ForwardDns = forwardDns
s.DNSPort = port
dnsConfig := s.prepConfDNS()
s.serverDNS, err = dnsserver.NewServer(s.IP.String(), dnsConfig)
return err
}
// Shutdown causes Serve() to exit, cleaning up behind itself.
func (s *Server) Shutdown() {
close(s.closeServers)
if err := s.serverDHCP.Close(); err != nil {
log.Warnf("Error closing DHCP server: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
if err := s.serverHTTP.Shutdown(ctx); err != nil {
log.Warnf("Error closing HTTP server: %v", err)
}
if s.tFTPStarted {
s.serverTFTP.Shutdown()
}
if err := s.serverDNS.Stop(); err != nil {
log.Warnf("Error closing DNS server: %v", err)
}
select {
case s.errs <- nil:
default:
}
}
func (s *Server) startMatchbox(l net.Listener) error {
if err := s.serverHTTP.Serve(l); err != nil {
return fmt.Errorf("Matchbox server shut down: %s", err)
}
return nil
}
// ipxeWrapperMenuHandler
func (s *Server) ipxeWrapperMenuHandler(primaryHandler http.Handler) http.Handler {
fn := func(w http.ResponseWriter, req *http.Request) {
if req.URL.Path != "ipxe" && req.URL.Path != "/ipxe" {
primaryHandler.ServeHTTP(w, req)
return
}
rr := httptest.NewRecorder()
primaryHandler.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
log.Info("Serving menu")
if err := ipxeMenuTemplate.Execute(w, s); err != nil {
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
}
return
}
if err := req.ParseForm(); err != nil {
log.Errorf("Error ParseForm: %v", err)
return
}
machineType := req.Form.Get("type")
remoteIp := net.ParseIP(req.Form.Get("ip"))
log.Infof("Selecting %s for %s", machineType, remoteIp)
if machineType == "init" || machineType == "controlplane" {
s.registerDNSEntry(s.Controlplane, remoteIp)
}
for key, values := range rr.HeaderMap {
for _, value := range values {
w.Header().Add(key, value)
}
}
w.WriteHeader(rr.Code)
if _, err := w.Write(rr.Body.Bytes()); err != nil {
log.Errorf("Error wrtiting body bytes %v", err)
}
}
return http.HandlerFunc(fn)
}
func getPrivateAddress() (net.IP, error) {
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
return nil, err
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr).IP
return localAddr, nil
}
func getInterface(addr net.IP) (*net.Interface, net.IPMask, error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, nil, err
}
for _, iface := range ifaces {
ifaceAddrs, err := iface.Addrs()
if err != nil {
return nil, nil, err
}
for _, ifaceAddr := range ifaceAddrs {
switch v := ifaceAddr.(type) {
case *net.IPAddr:
if v.IP.Equal(addr) {
return &iface, v.IP.DefaultMask(), nil
}
case *net.IPNet:
if v.IP.Equal(addr) {
return &iface, v.Mask, nil
}
}
}
}
return nil, nil, fmt.Errorf("Could not find interface for address")
}