forked from u-root/u-root
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dhclient.go
332 lines (296 loc) · 9.06 KB
/
dhclient.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
// Copyright 2017 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// dhclient sets up DHCP.
//
// Synopsis:
// dhclient [OPTIONS...]
//
// Options:
// -timeout: lease timeout in seconds
// -renewals: number of DHCP renewals before exiting
// -verbose: verbose output
package main
import (
"crypto/rand"
"encoding/binary"
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"os"
"regexp"
"sync"
"time"
"github.com/d2g/dhcp4"
"github.com/d2g/dhcp4client"
"github.com/u-root/dhcp6"
"github.com/vishvananda/netlink"
)
const (
// slop is the slop in our lease time.
slop = 10 * time.Second
linkUpAttempt = 30 * time.Second
)
var (
ifName = "^e.*"
leasetimeout = flag.Int("timeout", 15, "Lease timeout in seconds")
retry = flag.Int("retry", -1, "Max number of attempts for DHCP clients to send requests. -1 means infinity")
renewals = flag.Int("renewals", -1, "Number of DHCP renewals before exiting. -1 means infinity")
verbose = flag.Bool("verbose", false, "Verbose output")
ipv4 = flag.Bool("ipv4", true, "use IPV4")
ipv6 = flag.Bool("ipv6", true, "use IPV6")
test = flag.Bool("test", false, "Test mode")
debug = func(string, ...interface{}) {}
)
func ifup(ifname string) (netlink.Link, error) {
debug("Try bringing up %v", ifname)
start := time.Now()
for time.Since(start) < linkUpAttempt {
// Note that it may seem odd to keep trying the
// LinkByName operation, by consider that a hotplug
// device such as USB ethernet can just vanish.
iface, err := netlink.LinkByName(ifname)
debug("LinkByName(%v) returns (%v, %v)", ifname, iface, err)
if err != nil {
return nil, fmt.Errorf("cannot get interface by name %v: %v", ifname, err)
}
if iface.Attrs().OperState == netlink.OperUp {
debug("Link %v is up", ifname)
return iface, nil
}
if err := netlink.LinkSetUp(iface); err != nil {
return nil, fmt.Errorf("%v: %v can't make it up: %v", ifname, iface, err)
}
time.Sleep(1 * time.Second)
}
return nil, fmt.Errorf("Link %v still down after %d seconds", ifname, linkUpAttempt)
}
func dhclient4(iface netlink.Link, numRenewals int, timeout time.Duration, retry int) error {
mac := iface.Attrs().HardwareAddr
conn, err := dhcp4client.NewPacketSock(iface.Attrs().Index)
if err != nil {
return fmt.Errorf("client connection generation: %v", err)
}
client, err := dhcp4client.New(dhcp4client.HardwareAddr(mac), dhcp4client.Connection(conn), dhcp4client.Timeout(timeout))
if err != nil {
return fmt.Errorf("error: %v", err)
}
var packet dhcp4.Packet
needsRequest := true
for i := 0; numRenewals < 0 || i < numRenewals+1; i++ {
debug("Start getting or renewing DHCPv4 lease")
var success bool
for i := 0; i < retry || retry < 0; i++ {
if i > 0 {
if needsRequest {
debug("Resending DHCPv4 request...\n")
} else {
debug("Resending DHCPv4 renewal")
}
}
if needsRequest {
success, packet, err = client.Request()
} else {
success, packet, err = client.Renew(packet)
}
if err != nil {
if err0, ok := err.(net.Error); ok && err0.Timeout() {
log.Printf("%s: timeout contacting DHCP server", mac)
} else {
log.Printf("%s: error: %v", mac, err)
}
} else {
// Client needs renew after no matter what state it is now.
needsRequest = false
break
}
}
debug("Success on %s: %v\n", mac, success)
debug("Packet: %v\n", packet)
debug("Lease is %v seconds\n", packet.Secs())
if !success {
return fmt.Errorf("%s: we didn't successfully get a DHCP lease", mac)
}
debug("IP Received: %v\n", packet.YIAddr().String())
// We got here because we got a good packet.
o := packet.ParseOptions()
debug("Options: %v", o)
netmask, ok := o[dhcp4.OptionSubnetMask]
if ok {
debug("OptionSubnetMask is %v\n", netmask)
} else {
// If they did not offer a subnet mask, we
// choose the most restrictive option, namely,
// our IP address. This could happen on,
// e.g., a point to point link.
netmask = packet.YIAddr()
debug("No OptionSubnetMask; default to %v\n", netmask)
}
dst := &netlink.Addr{IPNet: &net.IPNet{IP: packet.YIAddr(), Mask: netmask}, Label: ""}
// Add the address to the iface.
if *test == false {
if err := netlink.AddrReplace(iface, dst); err != nil {
if os.IsExist(err) {
return fmt.Errorf("add/replace %v to %v: %v", dst, iface, err)
}
}
if gwData, ok := o[dhcp4.OptionRouter]; ok {
debug("router %v", gwData)
routerName := net.IP(gwData).String()
debug("routerName %v", routerName)
r := &netlink.Route{
LinkIndex: iface.Attrs().Index,
Gw: net.IP(gwData),
}
if err := netlink.RouteAdd(r); err != nil {
if os.IsExist(err) {
if err := netlink.RouteReplace(r); err != nil {
return fmt.Errorf("%s: add %s: %v", iface.Attrs().Name, r.String(), routerName)
}
} else {
return fmt.Errorf("%s: add %s: %v", iface.Attrs().Name, r.String(), routerName)
}
}
}
if ip, ok := o[dhcp4.OptionDomainNameServer]; ok {
rc := ""
// multiples of 4 octets.
for i := 0; i < len(ip); i += 4 {
// Don't let broken servers cause us to die.
if len(ip[i:]) < 4 {
log.Printf("dhcp4.OptionDomainNameServer: short length for last adddress: %v", ip[i:])
continue
}
rc = fmt.Sprintf("%snameserver %s\n", rc, net.IP(ip[i:i+4]))
}
if err := ioutil.WriteFile("/etc/resolv.conf", []byte(rc), 0644); err != nil {
return err
}
}
}
if binary.BigEndian.Uint16(packet.Secs()) == 0 {
debug("%v: server returned infinite lease.", iface.Attrs().Name)
break
}
// We can not assume the server will give us any grace time. So
// sleep for just a tiny bit less than the minimum.
time.Sleep(timeout - slop)
}
return nil
}
// dhcp6 support in go is hard to find. This function represents our best current
// guess based on reading and testing.
func dhclient6(iface netlink.Link, numRenewals int, timeout time.Duration, retry int) error {
conn, err := dhcp6.NewPacketSock(iface.Attrs().Index)
if err != nil {
return fmt.Errorf("client connection generation: %v", err)
}
client := dhcp6.New(iface.Attrs().HardwareAddr, conn, timeout, retry)
for i := 0; numRenewals < 0 || i < numRenewals+1; i++ {
debug("Start getting or renewing DHCPv6 lease")
iaAddrs, packet, err := client.Solicit()
if err != nil {
return fmt.Errorf("error: %v", err)
}
debug("Packet: %+v\n\n", packet)
debug("IAAddrs: %v\n", iaAddrs)
if *test == false {
dst := &netlink.Addr{
IPNet: &net.IPNet{IP: iaAddrs[0].IP},
PreferedLft: int(iaAddrs[0].PreferredLifetime.Seconds()),
ValidLft: int(iaAddrs[0].ValidLifetime.Seconds()),
Label: "",
}
if err := netlink.AddrReplace(iface, dst); err != nil {
if os.IsExist(err) {
return fmt.Errorf("add/replace %v to %v: %v", dst, iface, err)
}
}
}
time.Sleep(timeout - slop)
}
return nil
}
func main() {
flag.Parse()
if *verbose {
debug = log.Printf
}
// if we boot quickly enough, the random number generator
// may not be ready, and the dhcp package panics in that case.
// Worse, /dev/urandom, which the Go package falls back to,
// might not be there. Still worse, the Go package is "sticky"
// in that once it decides to use /dev/urandom, it won't go back,
// even if the system call would subsequently work.
// You're screwed. Exit.
// Wouldn't it be nice if we could just do the blocking system
// call? But that comes with its own giant set of headaches.
// Maybe we'll end up in a loop, sleeping, and just running
// ourselves.
if n, err := rand.Read([]byte{0}); err != nil || n != 1 {
log.Fatalf("We're sorry, the random number generator is not up. Please file a ticket")
}
if len(flag.Args()) > 1 {
log.Fatalf("only one re")
}
if len(flag.Args()) > 0 {
ifName = flag.Args()[0]
}
ifRE := regexp.MustCompilePOSIX(ifName)
ifnames, err := netlink.LinkList()
if err != nil {
log.Fatalf("Can't get list of link names: %v", err)
}
timeout := time.Duration(*leasetimeout) * time.Second
// if timeout is < slop, it's too short.
if timeout < slop {
timeout = 2 * slop
log.Printf("increased lease timeout to %s", timeout)
}
var wg sync.WaitGroup
done := make(chan error)
for _, i := range ifnames {
if !ifRE.MatchString(i.Attrs().Name) {
continue
}
wg.Add(1)
go func(ifname string) {
defer wg.Done()
iface, err := ifup(ifname)
if err != nil {
done <- err
return
}
if *ipv4 {
wg.Add(1)
done <- dhclient4(iface, *renewals, timeout, *retry)
wg.Done()
}
if *ipv6 {
wg.Add(1)
done <- dhclient6(iface, *renewals, timeout, *retry)
wg.Done()
}
debug("Done dhclient for %v", ifname)
}(i.Attrs().Name)
}
go func() {
wg.Wait()
close(done)
}()
// Wait for all goroutines to finish.
var nif int
for err := range done {
debug("err from done %v", err)
if err != nil {
log.Print(err)
}
nif++
}
if nif == 0 {
log.Fatalf("No interfaces match %v\n", ifName)
}
fmt.Printf("%d dhclient attempts were sent", nif)
}