This repository has been archived by the owner on Jun 16, 2023. It is now read-only.
forked from Mirantis/virtlet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
370 lines (322 loc) · 9.54 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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/*
Copyright 2016-2017 Mirantis
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Parts of this file are copied from https://github.com/google/netboot/blob/8e5c0d07937f8c1dea6e5f218b64f6b95c32ada3/pixiecore/dhcp.go
*/
package dhcp
import (
"bytes"
"errors"
"fmt"
"io"
"net"
"strings"
cnicurrent "github.com/containernetworking/cni/pkg/types/current"
"github.com/golang/glog"
"go.universe.tf/netboot/dhcp4"
"github.com/Mirantis/virtlet/pkg/network"
)
const (
serverPort = 67
// option 121 is for static routes as defined in rfc3442
classlessRouteOption = 121
)
var (
defaultDNS = []byte{8, 8, 8, 8}
)
// Server implements a DHCP server that runs in the container network namespace.
type Server struct {
config *network.ContainerSideNetwork
listener *dhcp4.Conn
}
// NewServer returns an initialized instance of Server.
func NewServer(config *network.ContainerSideNetwork) *Server {
return &Server{config: config}
}
// SetupListener sets up a DHCP4 listener that listens on the default DHCP
// port and the specified IP address.
func (s *Server) SetupListener(laddr string) error {
var listener *dhcp4.Conn
var err error
if listener, err = dhcp4.NewConn(fmt.Sprintf("%s:%d", laddr, serverPort)); err != nil {
return err
}
s.listener = listener
return nil
}
// Close shuts down DHCP listener.
func (s *Server) Close() error {
return s.listener.Close()
}
// Serve waits in an endless loop for DHCP requests and answers them.
func (s *Server) Serve() error {
for {
pkt, intf, err := s.listener.RecvDHCP()
if err != nil {
return fmt.Errorf("receiving DHCP packet: %v", err)
}
if intf == nil {
return fmt.Errorf("received DHCP packet with no interface information - please fill a bug to https://github.com/google/netboot")
}
glog.V(2).Infof("Received dhcp packet from: %s", pkt.HardwareAddr.String())
serverIP, err := interfaceIP(intf)
if err != nil {
glog.Warningf("Want to respond to %s on %s, but couldn't get a source address: %s", pkt.HardwareAddr.String(), intf.Name, err)
continue
}
var resp *dhcp4.Packet
switch pkt.Type {
case dhcp4.MsgDiscover:
resp, err = s.offerDHCP(pkt, serverIP)
if err != nil {
glog.Warningf("Failed to construct DHCP offer for %s: %s", pkt.HardwareAddr.String(), err)
continue
}
case dhcp4.MsgRequest:
resp, err = s.ackDHCP(pkt, serverIP)
if err != nil {
glog.Warningf("Failed to construct DHCP ACK for %s: %s", pkt.HardwareAddr.String(), err)
continue
}
default:
glog.Warningf("Ignoring packet from %s: packet is %s", pkt.HardwareAddr.String(), pkt.Type.String())
continue
}
if resp != nil {
glog.V(2).Infof("Sending %s packet to %s", resp.Type.String(), pkt.HardwareAddr.String())
glog.V(3).Info(resp.DebugString())
if err = s.listener.SendDHCP(resp, intf); err != nil {
glog.Warningf("Failed to send DHCP offer for %s: %s", pkt.HardwareAddr.String(), err)
}
}
}
}
func interfaceIP(intf *net.Interface) (net.IP, error) {
addrs, err := intf.Addrs()
if err != nil {
return nil, err
}
// Try to find an IPv4 address to use, in the following order:
// global unicast (includes rfc1918), link-local unicast,
// loopback.
fs := [](func(net.IP) bool){
net.IP.IsGlobalUnicast,
net.IP.IsLinkLocalUnicast,
net.IP.IsLoopback,
}
for _, f := range fs {
for _, a := range addrs {
ipaddr, ok := a.(*net.IPNet)
if !ok {
continue
}
ip := ipaddr.IP.To4()
if ip == nil {
continue
}
if f(ip) {
return ip, nil
}
}
}
return nil, errors.New("no usable unicast address configured on interface")
}
func (s *Server) getInterfaceNo(hwAddr net.HardwareAddr) int {
addr := hwAddr.String()
for i, permitted := range s.config.Result.Interfaces {
if permitted.Mac == addr {
return i
}
}
return -1
}
func (s *Server) prepareResponse(pkt *dhcp4.Packet, serverIP net.IP, mt dhcp4.MessageType) (*dhcp4.Packet, error) {
interfaceNo := s.getInterfaceNo(pkt.HardwareAddr)
if interfaceNo < 0 {
return nil, fmt.Errorf("unexpected packet from %v", pkt.HardwareAddr)
}
var cfg *cnicurrent.IPConfig
for _, curCfg := range s.config.Result.IPs {
if curCfg.Version == "4" && curCfg.Interface == interfaceNo {
cfg = curCfg
}
}
var mtu uint16
for _, iface := range s.config.Interfaces {
if bytes.Compare(pkt.HardwareAddr, iface.HardwareAddr) == 0 {
mtu = iface.MTU
}
}
if mtu == 0 {
return nil, fmt.Errorf("packet from mac address %s not found in CSN", pkt.HardwareAddr.String())
}
if cfg == nil {
return nil, fmt.Errorf("IPv4 config for interface %s is not specified in CNI config", pkt.HardwareAddr.String())
}
p := &dhcp4.Packet{
Type: mt,
TransactionID: pkt.TransactionID,
Broadcast: true,
HardwareAddr: pkt.HardwareAddr,
RelayAddr: pkt.RelayAddr,
ServerAddr: serverIP,
Options: make(dhcp4.Options),
}
p.Options[dhcp4.OptServerIdentifier] = serverIP
// if guid was sent, copy it
if pkt.Options[97] != nil {
p.Options[97] = pkt.Options[97]
}
p.YourAddr = cfg.Address.IP
p.Options[dhcp4.OptSubnetMask] = cfg.Address.Mask
// MTU option
p.Options[26] = []byte{uint8(mtu >> 8), uint8(mtu & 0xff)}
router, routeData, err := s.getStaticRoutes(cfg.Address)
if err != nil {
glog.Warningf("Can not transform static routes for mac %v: %v", pkt.HardwareAddr, err)
}
if router != nil {
p.Options[dhcp4.OptRouters] = router
}
if routeData != nil {
p.Options[classlessRouteOption] = routeData
}
// 86400 - full 24h
p.Options[dhcp4.OptLeaseTime] = []byte{0, 1, 81, 128}
// 43200 - 12h
p.Options[dhcp4.OptRenewalTime] = []byte{0, 0, 168, 192}
// 64800 - 18h
p.Options[dhcp4.OptRebindingTime] = []byte{0, 0, 253, 32}
// TODO: include more dns options
if len(s.config.Result.DNS.Nameservers) == 0 {
p.Options[dhcp4.OptDNSServers] = defaultDNS
} else {
var b bytes.Buffer
for _, nsIP := range s.config.Result.DNS.Nameservers {
ip := net.ParseIP(nsIP).To4()
if ip == nil {
glog.Warningf("failed to parse nameserver ip %q", nsIP)
} else {
b.Write(ip)
}
}
if b.Len() > 0 {
p.Options[dhcp4.OptDNSServers] = b.Bytes()
} else {
p.Options[dhcp4.OptDNSServers] = defaultDNS
}
}
if len(s.config.Result.DNS.Search) != 0 {
// https://tools.ietf.org/search/rfc3397
p.Options[119], err = compressedDomainList(s.config.Result.DNS.Search)
if err != nil {
return nil, err
}
}
return p, nil
}
func (s *Server) offerDHCP(pkt *dhcp4.Packet, serverIP net.IP) (*dhcp4.Packet, error) {
return s.prepareResponse(pkt, serverIP, dhcp4.MsgOffer)
}
func (s *Server) ackDHCP(pkt *dhcp4.Packet, serverIP net.IP) (*dhcp4.Packet, error) {
return s.prepareResponse(pkt, serverIP, dhcp4.MsgAck)
}
func (s *Server) getStaticRoutes(ip net.IPNet) (router, routes []byte, err error) {
if len(s.config.Result.Routes) == 0 {
return nil, nil, nil
}
var b bytes.Buffer
for _, route := range s.config.Result.Routes {
if route.Dst.IP == nil {
return nil, nil, fmt.Errorf("invalid route: %#v", route)
}
dstIP := route.Dst.IP.To4()
gw := route.GW
if gw == nil {
// FIXME: this should not be really needed for newer CNI
var cfg *cnicurrent.IPConfig
for _, curCfg := range s.config.Result.IPs {
if curCfg.Version == "4" {
cfg = curCfg
}
}
gw = cfg.Gateway.To4()
if gw == nil && cfg.Gateway != nil {
return nil, nil, fmt.Errorf("unexpected IPv6 gateway address: %#v", gw)
}
} else {
gw = gw.To4()
}
if !ip.Contains(gw) {
continue
}
if gw != nil && dstIP.Equal(net.IPv4zero) {
if s, _ := route.Dst.Mask.Size(); s == 0 {
router = gw
continue
}
}
writeRoute(&b, route.Dst, gw)
}
// XXX: classless routes apparently cause a problem:
// https://askubuntu.com/questions/767002/dhcp-connection-does-not-set-default-gateway-automatically
if b.Len() != 0 && router != nil {
writeRoute(&b, net.IPNet{
IP: net.IPv4zero,
Mask: net.IPv4Mask(0, 0, 0, 0),
}, router)
router = nil
}
routes = b.Bytes()
return
}
// toDestinationDescriptor returns calculated destination descriptor according to rfc3442 (page 3)
// warning: there is no check if ipnet is in required ipv4 type
func toDestinationDescriptor(network net.IPNet) []byte {
s, _ := network.Mask.Size()
ipAsBytes := []byte(network.IP.To4())
return append(
[]byte{byte(s)},
ipAsBytes[:widthOfMaskToSignificantOctets(s)]...,
)
}
func writeRoute(w io.Writer, dst net.IPNet, gw net.IP) {
w.Write(toDestinationDescriptor(dst))
if gw != nil {
w.Write(gw)
} else {
w.Write([]byte{0, 0, 0, 0})
}
}
func widthOfMaskToSignificantOctets(mask int) int {
return (mask + 7) / 8
}
func compressedDomainList(domainList []string) ([]byte, error) {
// https://tools.ietf.org/search/rfc1035#section-4.1.4
// simplified version, only encoding, without real compression
var b bytes.Buffer
for n, domain := range domainList {
// add '\0' between entries
if n > 0 {
b.WriteByte(0)
}
// encode domain parts as (single byte length)(string)
parts := strings.Split(domain, ".")
for _, part := range parts {
if len(part) > 254 {
return nil, fmt.Errorf("domain name element '%s' exceeds 254 length limit", part)
}
b.WriteByte(byte(len(part)))
b.WriteString(part)
}
}
return b.Bytes(), nil
}