forked from tinkerbell/dhcp
/
handler.go
289 lines (252 loc) · 9.13 KB
/
handler.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
package reservation
import (
"context"
"errors"
"fmt"
"github.com/go-logr/logr"
"github.com/insomniacslk/dhcp/dhcpv4"
"github.com/raunovv/dhcp/backend/noop"
"github.com/raunovv/dhcp/data"
oteldhcp "github.com/raunovv/dhcp/otel"
"github.com/tinkerbell/tink/api/v1alpha1"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"net"
"strings"
)
const tracerName = "github.com/raunovv/dhcp/server"
// setDefaults will update the Handler struct to have default values so as
// to avoid panic for nil pointers and such.
func (h *Handler) setDefaults() {
if h.Backend == nil {
h.Backend = noop.Handler{}
}
if h.Log.GetSink() == nil {
h.Log = logr.Discard()
}
}
// Handle responds to DHCP messages with DHCP server options.
func (h *Handler) Handle(conn net.PacketConn, peer net.Addr, pkt *dhcpv4.DHCPv4) {
h.setDefaults()
if pkt == nil {
h.Log.Error(errors.New("incoming packet is nil"), "not able to respond when the incoming packet is nil")
return
}
log := h.Log.WithValues("mac", pkt.ClientHWAddr.String())
log.Info("received DHCP packet", "type", pkt.MessageType().String())
tracer := otel.Tracer(tracerName)
ctx, span := tracer.Start(context.Background(),
fmt.Sprintf("DHCP Packet Received: %v", pkt.MessageType().String()),
trace.WithAttributes(h.encodeToAttributes(pkt, "request")...),
trace.WithAttributes(attribute.String("DHCP.peer", peer.String())),
)
defer span.End()
var reply *dhcpv4.DHCPv4
switch mt := pkt.MessageType(); mt {
case dhcpv4.MessageTypeDiscover:
d, n, err := h.readBackend(ctx, pkt.ClientHWAddr)
if err != nil {
log.Error(err, "error reading from backend")
span.SetStatus(codes.Error, err.Error())
if h.AutoRegister {
h.registerHw(ctx, pkt.ClientHWAddr)
}
return
}
reply = h.updateMsg(ctx, pkt, d, n, dhcpv4.MessageTypeOffer)
log = log.WithValues("type", dhcpv4.MessageTypeOffer.String())
case dhcpv4.MessageTypeRequest:
d, n, err := h.readBackend(ctx, pkt.ClientHWAddr)
if err != nil {
log.Error(err, "error reading from backend")
span.SetStatus(codes.Error, err.Error())
return
}
reply = h.updateMsg(ctx, pkt, d, n, dhcpv4.MessageTypeAck)
log = log.WithValues("type", dhcpv4.MessageTypeAck.String())
case dhcpv4.MessageTypeRelease:
// Since the design of this DHCP server is that all IP addresses are
// Host reservations, when a client releases an address, the server
// doesn't have anything to do. This case is included for clarity of this
// design decision.
log.Info("received release, no response required")
span.SetStatus(codes.Ok, "received release, no response required")
return
default:
log.Info("received unknown message type")
span.SetStatus(codes.Error, "received unknown message type")
return
}
if _, err := conn.WriteTo(reply.ToBytes(), peer); err != nil {
log.Error(err, "failed to send DHCP")
span.SetStatus(codes.Error, err.Error())
return
}
log.Info("sent DHCP response")
log.Info("repaly msg", reply)
span.SetAttributes(h.encodeToAttributes(reply, "reply")...)
span.SetStatus(codes.Ok, "sent DHCP response")
}
// readBackend encapsulates the backend read and opentelemetry handling.
func (h *Handler) readBackend(ctx context.Context, mac net.HardwareAddr) (*data.DHCP, *data.Netboot, error) {
h.setDefaults()
tracer := otel.Tracer(tracerName)
ctx, span := tracer.Start(ctx, "Hardware data get")
defer span.End()
d, n, err := h.Backend.GetByMac(ctx, mac)
if err != nil {
h.Log.Info("error getting DHCP data from backend", "mac", mac, "error", err)
span.SetStatus(codes.Error, err.Error())
return nil, nil, err
}
span.SetAttributes(d.EncodeToAttributes()...)
span.SetAttributes(n.EncodeToAttributes()...)
span.SetStatus(codes.Ok, "done reading from backend")
return d, n, nil
}
// registerHw encapsulates the registration of all dhcp discoveries
func (h *Handler) registerHw(ctx context.Context, mac net.HardwareAddr) error {
h.setDefaults()
tracer := otel.Tracer(tracerName)
ctx, span := tracer.Start(ctx, "Hardware data get")
defer span.End()
hwObject := v1alpha1.Hardware{
TypeMeta: v1.TypeMeta{
Kind: "Hardware",
APIVersion: "tinkerbell.org/v1alpha1",
},
ObjectMeta: v1.ObjectMeta{
Name: "node-" + strings.Replace(mac.String(), ":", "", -1),
Namespace: "default",
},
Spec: v1alpha1.HardwareSpec{
Interfaces: []v1alpha1.Interface{
{
Netboot: &v1alpha1.Netboot{
AllowPXE: &[]bool{false}[0],
AllowWorkflow: &[]bool{false}[0],
},
DHCP: &v1alpha1.DHCP{
Arch: "x86_64",
Hostname: "sm01",
IP: &v1alpha1.IP{
Address: "127.0.0.5",
Gateway: "127.0.0.1",
Netmask: "255.255.255.0",
},
LeaseTime: 86400,
MAC: mac.String(),
NameServers: []string{"1.1.1.1"},
UEFI: false,
},
},
},
},
}
h.Log.Info("auto registering hw information", "hw", hwObject)
err := h.Backend.RegisterHw(ctx, hwObject)
if err != nil {
h.Log.Info("error registering DHCP data to backend", "mac", mac, "error", err)
span.SetStatus(codes.Error, err.Error())
return err
}
//span.SetAttributes(d.EncodeToAttributes()...)
//span.SetAttributes(n.EncodeToAttributes()...)
span.SetStatus(codes.Ok, "done reading from backend")
return nil
}
func GenerateHwName() string {
/*rng, err := codename.DefaultRNG()
if err != nil {
panic(err)
}
return codename.Generate(rng, 0) */
return ""
}
// updateMsg handles updating DHCP packets with the data from the backend.
func (h *Handler) updateMsg(ctx context.Context, pkt *dhcpv4.DHCPv4, d *data.DHCP, n *data.Netboot, msgType dhcpv4.MessageType) *dhcpv4.DHCPv4 {
h.setDefaults()
mods := []dhcpv4.Modifier{
dhcpv4.WithMessageType(msgType),
dhcpv4.WithGeneric(dhcpv4.OptionServerIdentifier, h.IPAddr.AsSlice()),
dhcpv4.WithServerIP(h.IPAddr.AsSlice()),
}
mods = append(mods, h.setDHCPOpts(ctx, pkt, d)...)
if h.Netboot.Enabled && h.isNetbootClient(pkt) {
mods = append(mods, h.setNetworkBootOpts(ctx, pkt, n))
}
reply, err := dhcpv4.NewReplyFromRequest(pkt, mods...)
if err != nil {
return nil
}
return reply
}
// isNetbootClient returns true if the client is a valid netboot client.
//
// A valid netboot client will have the following in its DHCP request:
// 1. is a DHCP discovery/request message type.
// 2. option 93 is set.
// 3. option 94 is set.
// 4. option 97 is correct length.
// 5. option 60 is set with this format: "PXEClient:Arch:xxxxx:UNDI:yyyzzz" or "HTTPClient:Arch:xxxxx:UNDI:yyyzzz".
//
// See: http://www.pix.net/software/pxeboot/archive/pxespec.pdf
//
// See: https://www.rfc-editor.org/rfc/rfc4578.html
func (h *Handler) isNetbootClient(pkt *dhcpv4.DHCPv4) bool {
h.setDefaults()
// only response to DISCOVER and REQUEST packets
if pkt.MessageType() != dhcpv4.MessageTypeDiscover && pkt.MessageType() != dhcpv4.MessageTypeRequest {
h.Log.Info("not a netboot client", "reason", "message type must be either Discover or Request", "mac", pkt.ClientHWAddr.String(), "message type", pkt.MessageType())
return false
}
// option 60 must be set
if !pkt.Options.Has(dhcpv4.OptionClassIdentifier) {
h.Log.Info("not a netboot client", "reason", "option 60 not set", "mac", pkt.ClientHWAddr.String())
return false
}
// option 60 must start with PXEClient or HTTPClient
opt60 := pkt.GetOneOption(dhcpv4.OptionClassIdentifier)
if !strings.HasPrefix(string(opt60), string(pxeClient)) && !strings.HasPrefix(string(opt60), string(httpClient)) {
h.Log.Info("not a netboot client", "reason", "option 60 not PXEClient or HTTPClient", "mac", pkt.ClientHWAddr.String(), "option 60", string(opt60))
return false
}
// option 93 must be set
if !pkt.Options.Has(dhcpv4.OptionClientSystemArchitectureType) {
h.Log.Info("not a netboot client", "reason", "option 93 not set", "mac", pkt.ClientHWAddr.String())
return false
}
// option 94 must be set
if !pkt.Options.Has(dhcpv4.OptionClientNetworkInterfaceIdentifier) {
h.Log.Info("not a netboot client", "reason", "option 94 not set", "mac", pkt.ClientHWAddr.String())
return false
}
// option 97 must be have correct length or not be set
guid := pkt.GetOneOption(dhcpv4.OptionClientMachineIdentifier)
switch len(guid) {
case 0:
// A missing GUID is invalid according to the spec, however
// there are PXE ROMs in the wild that omit the GUID and still
// expect to boot. The only thing we do with the GUID is
// mirror it back to the client if it's there, so we might as
// well accept these buggy ROMs.
case 17:
if guid[0] != 0 {
h.Log.Info("not a netboot client", "reason", "option 97 does not start with 0", "mac", pkt.ClientHWAddr.String(), "option 97", string(guid))
return false
}
default:
h.Log.Info("not a netboot client", "reason", "option 97 has invalid length (0 or 17)", "mac", pkt.ClientHWAddr.String(), "option 97", string(guid))
return false
}
return true
}
// encodeToAttributes takes a DHCP packet and returns opentelemetry key/value attributes.
func (h *Handler) encodeToAttributes(d *dhcpv4.DHCPv4, namespace string) []attribute.KeyValue {
h.setDefaults()
a := &oteldhcp.Encoder{Log: h.Log}
return a.Encode(d, namespace, oteldhcp.AllEncoders()...)
}