-
Notifications
You must be signed in to change notification settings - Fork 12
/
client.go
379 lines (323 loc) · 8.92 KB
/
client.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
371
372
373
374
375
376
377
378
379
package dhclient
import (
"errors"
"fmt"
"log/slog"
"math/rand"
"net"
"sync"
"time"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/mdlayher/packet"
)
const responseTimeout = time.Second * 5
// Callback is a function called on certain events
type Callback func(*Lease)
// Client is a DHCP client instance
type Client struct {
Hostname string
Iface *net.Interface
Lease *Lease // The current lease
OnBound Callback // On renew or rebound
OnExpire Callback // On expiration of a lease
DHCPOptions []Option // List of options to send on discovery and requests
Logger *slog.Logger
conn *packet.Conn // Raw socket
xid uint32 // Transaction ID
rebind bool
shutdown bool
notify chan struct{} // Is closed on shutdown
wg sync.WaitGroup // For graceful shutdown
}
// Lease is an assignment by the DHCP server
type Lease struct {
ServerID net.IP
FixedAddress net.IP
Netmask net.IPMask
NextServer net.IP
Broadcast net.IP
Router []net.IP
DNS []net.IP
TimeServer []net.IP
DomainName string
MTU uint16
// Other options
OtherOptions []Option
Bound time.Time
Renew time.Time
Rebind time.Time
Expire time.Time
}
// DefaultParamsRequestList is a list of params to be requested from the server
var DefaultParamsRequestList = []layers.DHCPOpt{
layers.DHCPOptSubnetMask, // Subnet Mask
layers.DHCPOptRouter, // Router
layers.DHCPOptTimeServer, // Time Server
layers.DHCPOptDNS, // Domain Name Server
layers.DHCPOptDomainName, // Domain Name
layers.DHCPOptInterfaceMTU, // Interface MTU
layers.DHCPOptNTPServers, // Network Time Protocol Servers
}
// AddOption adds an DHCP option
func (client *Client) AddOption(optType layers.DHCPOpt, data []byte) {
client.DHCPOptions = append(client.DHCPOptions, Option{optType, data})
}
// AddParamRequest adds an parameter to parameter request list, if not included yet.
func (client *Client) AddParamRequest(dhcpOpt layers.DHCPOpt) {
// search for existing parameter request list
for i := range client.DHCPOptions {
if client.DHCPOptions[i].Type == layers.DHCPOptParamsRequest {
// extend existing list
client.DHCPOptions[i].AddByte(byte(dhcpOpt))
return
}
}
// option not added yet
client.AddOption(layers.DHCPOptParamsRequest, []byte{byte(dhcpOpt)})
}
// Start starts the client
func (client *Client) Start() {
if client.Logger == nil {
client.Logger = slog.New(&discardHandler{})
}
// Add default DHCP options if none added yet.
if client.DHCPOptions == nil {
for _, param := range DefaultParamsRequestList {
client.AddParamRequest(param)
}
client.AddOption(layers.DHCPOptHostname, []byte(client.Hostname))
}
if client.notify != nil {
panic(fmt.Sprintf("client for %s already started", client.Iface.Name))
}
client.notify = make(chan struct{})
client.wg.Add(1)
go client.run()
}
// Stop stops the client
func (client *Client) Stop() {
slog.Info("shutting down dhclient")
client.shutdown = true
close(client.notify)
client.wg.Wait()
}
// Renew triggers the renewal of the current lease
func (client *Client) Renew() {
select {
case client.notify <- struct{}{}:
default:
}
}
// Rebind forgets the current lease and triggers acquirement of a new one
func (client *Client) Rebind() {
client.rebind = true
client.Lease = nil
client.Renew()
}
func (client *Client) run() {
for !client.shutdown {
client.runOnce()
}
client.wg.Done()
}
func (client *Client) runOnce() {
var err error
if client.Lease == nil || client.rebind {
// request new lease
err = client.withConnection(client.discoverAndRequest)
if err == nil {
// try to renew the lease in the future
client.rebind = false
}
} else {
// renew existing lease
err = client.withConnection(client.renew)
}
if err != nil {
client.Logger.Error("failed to acquire lease", "error", err)
// delay for a second
select {
case <-client.notify:
case <-time.After(time.Second):
}
return
}
select {
case <-client.notify:
return
case <-time.After(time.Until(client.Lease.Expire)):
// remove lease and request a new one
client.unbound()
case <-time.After(time.Until(client.Lease.Rebind)):
// keep lease and request a new one
client.rebind = true
case <-time.After(time.Until(client.Lease.Renew)):
// renew the lease
}
}
// unbound removes the lease
func (client *Client) unbound() {
if cb := client.OnExpire; cb != nil {
cb(client.Lease)
}
client.Lease = nil
}
func (client *Client) withConnection(f func() error) error {
conn, err := packet.Listen(client.Iface, packet.Raw, int(layers.EthernetTypeIPv4), nil)
if err != nil {
return err
}
client.conn = conn
client.xid = rand.Uint32()
defer func() {
client.conn.Close()
client.conn = nil
}()
return f()
}
func (client *Client) discoverAndRequest() error {
lease, err := client.discover()
if err != nil {
return err
}
return client.request(lease)
}
func (client *Client) renew() error {
return client.request(client.Lease)
}
func (client *Client) discover() (*Lease, error) {
err := client.sendPacket(layers.DHCPMsgTypeDiscover, client.DHCPOptions)
if err != nil {
return nil, err
}
_, lease, err := client.waitForResponse(layers.DHCPMsgTypeOffer)
if err != nil {
return nil, err
}
return lease, nil
}
func (client *Client) request(lease *Lease) error {
err := client.sendPacket(layers.DHCPMsgTypeRequest, append(client.DHCPOptions,
Option{layers.DHCPOptRequestIP, []byte(lease.FixedAddress)},
Option{layers.DHCPOptServerID, []byte(lease.ServerID)},
))
if err != nil {
return err
}
msgType, lease, err := client.waitForResponse(layers.DHCPMsgTypeAck, layers.DHCPMsgTypeNak)
if err != nil {
return err
}
switch msgType {
case layers.DHCPMsgTypeAck:
if lease.Expire.IsZero() {
err = errors.New("expire value is zero")
break
}
// support DHCP servers that do not send option 58 and 59
// this is using the Microsoft suggested defaults
if lease.Renew.IsZero() {
lease.Renew = lease.Bound.Add(lease.Expire.Sub(lease.Bound) / 2)
}
if lease.Rebind.IsZero() {
lease.Rebind = lease.Bound.Add(lease.Expire.Sub(lease.Bound) / 1000 * 875)
}
client.Lease = lease
// call the handler
if cb := client.OnBound; cb != nil {
cb(lease)
}
case layers.DHCPMsgTypeNak:
err = errors.New("received NAK")
client.unbound()
default:
err = fmt.Errorf("unexpected response: %s", msgType.String())
}
return err
}
// sendPacket creates and sends a DHCP packet
func (client *Client) sendPacket(msgType layers.DHCPMsgType, options []Option) error {
client.Logger.Debug("sending packet", "type", msgType)
return client.sendMulticast(client.newPacket(msgType, options))
}
// newPacket creates a DHCP packet
func (client *Client) newPacket(msgType layers.DHCPMsgType, options []Option) *layers.DHCPv4 {
packet := layers.DHCPv4{
Operation: layers.DHCPOpRequest,
HardwareType: layers.LinkTypeEthernet,
ClientHWAddr: client.Iface.HardwareAddr,
Xid: client.xid, // Transaction ID
}
packet.Options = append(packet.Options, layers.DHCPOption{
Type: layers.DHCPOptMessageType,
Data: []byte{byte(msgType)},
Length: 1,
})
// append DHCP options
for _, option := range options {
packet.Options = append(packet.Options, layers.DHCPOption{
Type: option.Type,
Data: option.Data,
Length: uint8(len(option.Data)),
})
}
return &packet
}
func (client *Client) sendMulticast(dhcp *layers.DHCPv4) error {
eth := layers.Ethernet{
EthernetType: layers.EthernetTypeIPv4,
SrcMAC: client.Iface.HardwareAddr,
DstMAC: layers.EthernetBroadcast,
}
ip := layers.IPv4{
Version: 4,
TTL: 64,
SrcIP: []byte{0, 0, 0, 0},
DstIP: []byte{255, 255, 255, 255},
Protocol: layers.IPProtocolUDP,
}
udp := layers.UDP{
SrcPort: 68,
DstPort: 67,
}
// Serialize packet
buf := gopacket.NewSerializeBuffer()
opts := gopacket.SerializeOptions{
ComputeChecksums: true,
FixLengths: true,
}
udp.SetNetworkLayerForChecksum(&ip)
err := gopacket.SerializeLayers(buf, opts, ð, &ip, &udp, dhcp)
if err != nil {
return err
}
// Send packet
_, err = client.conn.WriteTo(buf.Bytes(), &packet.Addr{HardwareAddr: eth.DstMAC})
return err
}
// waitForResponse waits for a DHCP packet with matching transaction ID and the given message type
func (client *Client) waitForResponse(msgTypes ...layers.DHCPMsgType) (layers.DHCPMsgType, *Lease, error) {
client.conn.SetReadDeadline(time.Now().Add(responseTimeout))
recvBuf := make([]byte, 1500)
for {
_, _, err := client.conn.ReadFrom(recvBuf)
if err != nil {
return 0, nil, err
}
packet := parsePacket(recvBuf)
if packet == nil {
continue
}
if packet.Xid == client.xid && packet.Operation == layers.DHCPOpReply {
msgType, res := newLease(packet)
// do we have the expected message type?
for _, t := range msgTypes {
if t == msgType {
client.Logger.Debug("received packet", "type", msgType)
return msgType, &res, nil
}
}
}
}
}