forked from krolaw/dhcp4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
84 lines (78 loc) · 2.48 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
package dhcp4
import (
"net"
"strconv"
)
type Handler interface {
ServeDHCP(req Packet, msgType MessageType, options Options) Packet
}
// ServeConn is the bare minimum connection functions required by Serve()
// It allows you to create custom connections for greater control,
// such as ServeIfConn (see serverif.go), which locks to a given interface.
type ServeConn interface {
ReadFrom(b []byte) (n int, addr net.Addr, err error)
WriteTo(b []byte, addr net.Addr) (n int, err error)
}
// Serve takes a ServeConn (such as a net.PacketConn) that it uses for both
// reading and writing DHCP packets. Every packet is passed to the handler,
// which processes it and optionally return a response packet for writing back
// to the network.
//
// To capture limited broadcast packets (sent to 255.255.255.255), you must
// listen on a socket bound to IP_ADDRANY (0.0.0.0). This means that broadcast
// packets sent to any interface on the system may be delivered to this
// socket. See: https://code.google.com/p/go/issues/detail?id=7106
//
// Additionally, response packets may not return to the same
// interface that the request was received from. Writing a custom ServeConn,
// or using ServeIf() can provide a workaround to this problem.
func Serve(conn ServeConn, handler Handler) error {
buffer := make([]byte, 1500)
for {
n, addr, err := conn.ReadFrom(buffer)
if err != nil {
return err
}
if n < 240 { // Packet too small to be DHCP
continue
}
req := Packet(buffer[:n])
if req.HLen() > 16 { // Invalid size
continue
}
options := req.ParseOptions()
var reqType MessageType
if t := options[OptionDHCPMessageType]; len(t) != 1 {
continue
} else {
reqType = MessageType(t[0])
if reqType < Discover || reqType > Inform {
continue
}
}
if res := handler.ServeDHCP(req, reqType, options); res != nil {
// If IP not available, broadcast
ipStr, portStr, err := net.SplitHostPort(addr.String())
if err != nil {
return err
}
if net.ParseIP(ipStr).Equal(net.IPv4zero) || req.Broadcast() {
port, _ := strconv.Atoi(portStr)
addr = &net.UDPAddr{IP: net.IPv4bcast, Port: port}
}
if _, e := conn.WriteTo(res, addr); e != nil {
return e
}
}
}
}
// ListenAndServe listens on the UDP network address addr and then calls
// Serve with handler to handle requests on incoming packets.
func ListenAndServe(handler Handler) error {
l, err := net.ListenPacket("udp4", ":67")
if err != nil {
return err
}
defer l.Close()
return Serve(l, handler)
}