Pull request 2617: 4923-gopacket-dhcp-vol.22

Squashed commit of the following:

commit 36ae171ca61d8b35b92a3803ed22375ea670a9c7
Merge: 4ccc60b51 1d491ad0f
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Mon Apr 6 15:37:37 2026 +0300

    Merge branch 'master' into 4923-gopacket-dhcp-vol.22

commit 4ccc60b51747b3e4684543880a43ba6ba651f900
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Mon Apr 6 13:27:58 2026 +0300

    dhcpsvc: imp code, names

commit e7b3accdfe9819d3399d70fa2644763c21a72b68
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Fri Apr 3 18:32:09 2026 +0300

    dhcpsvc: imp tests & docs

commit d4982a3dfd5c1714b9e67abe4f3d9798f271ff4f
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Wed Apr 1 21:14:10 2026 +0300

    dhcpsvc: imp rfc compliance
This commit is contained in:
Eugene Burkov committed 2026-04-06 12:59:36 +00:00
1 parent 1d491ad0f3
commit 6344ecce8a
7 files changed
+384 -439

No files matched your search

+53 -48
View File
@@ -83,6 +83,47 @@ func (iface *dhcpInterfaceV4) handleDHCPv4(
return nil
}
// handleDiscover handles messages of type DHCPDISCOVER. req must be a
// DHCPDISCOVER message, fd must not be nil.
func (iface *dhcpInterfaceV4) handleDiscover(
ctx context.Context,
req *layers.DHCPv4,
fd *frameData,
) {
l := iface.common.logger
mac := req.ClientHWAddr
mk := macToKey(mac)
idOpt := clientIdentifier4(req)
// Check if there's an existing lease for this MAC address.
iface.common.indexMu.Lock()
defer iface.common.indexMu.Unlock()
lease, hasLease := iface.common.leases[mk]
if hasLease {
reqIP, hasReqIP := requestedIPv4(req)
if hasReqIP && reqIP != lease.IP {
l.DebugContext(ctx, "different requested ip", "requested", reqIP, "lease", lease.IP)
}
lease.updateExpiry(iface.clock, iface.common.leaseTTL)
iface.respondOffer(ctx, req, fd, lease, idOpt)
return
}
lease, err := iface.allocateLease(ctx, mac)
if err != nil {
l.ErrorContext(ctx, "allocating a lease", slogutil.KeyError, err)
return
}
// Send DHCPOFFER with new lease.
iface.respondOffer(ctx, req, fd, lease, idOpt)
}
// handleRequest handles the DHCPv4 message of DHCPREQUEST type. req must be a
// DHCPREQUEST message. req and fd must not be nil.
//
@@ -118,7 +159,7 @@ func (iface *dhcpInterfaceV4) handleRequest(
// If the DHCP server detects that the client is on the wrong net
// then the server SHOULD send a DHCPNAK message to the client.
l.DebugContext(ctx, "declining init-reboot request", "requestedip", reqIP)
iface.respondNAK(ctx, req, fd)
iface.respondNAK(ctx, req, fd, clientIdentifier4(req))
return
}
@@ -139,45 +180,6 @@ func (iface *dhcpInterfaceV4) handleRequest(
}
}
// handleDiscover handles messages of type DHCPDISCOVER. req must be a
// DHCPDISCOVER message, fd must not be nil.
func (iface *dhcpInterfaceV4) handleDiscover(
ctx context.Context,
req *layers.DHCPv4,
fd *frameData,
) {
l := iface.common.logger
mac := req.ClientHWAddr
mk := macToKey(mac)
// Check if there's an existing lease for this MAC address.
iface.common.indexMu.Lock()
defer iface.common.indexMu.Unlock()
lease, hasLease := iface.common.leases[mk]
if hasLease {
reqIP, hasReqIP := requestedIPv4(req)
if hasReqIP && reqIP != lease.IP {
l.DebugContext(ctx, "different requested ip", "requested", reqIP, "lease", lease.IP)
}
lease.updateExpiry(iface.clock, iface.common.leaseTTL)
iface.respondOffer(ctx, req, fd, lease)
return
}
lease, err := iface.allocateLease(ctx, mac)
if err != nil {
l.ErrorContext(ctx, "allocating a lease", slogutil.KeyError, err)
return
}
// Send DHCPOFFER with new lease.
iface.respondOffer(ctx, req, fd, lease)
}
// handleSelecting handles messages of type DHCPREQUEST in SELECTING state. req
// must be a DHCPREQUEST message, reqIP must be a valid IPv4 address, fd must
// not be nil.
@@ -198,6 +200,7 @@ func (iface *dhcpInterfaceV4) handleSelecting(
mac := req.ClientHWAddr
mk := macToKey(mac)
idOpt := clientIdentifier4(req)
iface.common.indexMu.Lock()
defer iface.common.indexMu.Unlock()
@@ -205,14 +208,14 @@ func (iface *dhcpInterfaceV4) handleSelecting(
lease, hasLease := iface.common.leases[mk]
if !hasLease {
l.DebugContext(ctx, "no reserved lease", "clienthwaddr", mac)
iface.respondNAK(ctx, req, fd)
iface.respondNAK(ctx, req, fd, idOpt)
return
}
if lease.IP != reqIP {
l.DebugContext(ctx, "selecting request mismatched", "requested", reqIP, "lease", lease.IP)
iface.respondNAK(ctx, req, fd)
iface.respondNAK(ctx, req, fd, idOpt)
return
}
@@ -222,12 +225,12 @@ func (iface *dhcpInterfaceV4) handleSelecting(
err := iface.updateLease(ctx, lease)
if err != nil {
l.ErrorContext(ctx, "selecting request failed", slogutil.KeyError, err)
iface.respondNAK(ctx, req, fd)
iface.respondNAK(ctx, req, fd, idOpt)
return
}
iface.respondACK(ctx, req, fd, lease)
iface.respondACK(ctx, req, fd, lease, idOpt)
}
// handleInitReboot handles messages of type DHCPREQUEST in INIT-REBOOT state.
@@ -253,6 +256,7 @@ func (iface *dhcpInterfaceV4) handleInitReboot(
// Check if the lease exists and matches.
mac := req.ClientHWAddr
mk := macToKey(mac)
idOpt := clientIdentifier4(req)
iface.common.indexMu.Lock()
defer iface.common.indexMu.Unlock()
@@ -268,12 +272,12 @@ func (iface *dhcpInterfaceV4) handleInitReboot(
if lease.IP != reqIP {
l.WarnContext(ctx, "init-reboot request mismatched", "requested", reqIP, "lease", lease.IP)
iface.respondNAK(ctx, req, fd)
iface.respondNAK(ctx, req, fd, idOpt)
return
}
iface.updateAndRespond(ctx, l, req, lease, fd)
iface.updateAndRespond(ctx, l, req, lease, fd, idOpt)
}
// handleRenew handles messages of type DHCPREQUEST in RENEWING or REBINDING
@@ -290,6 +294,7 @@ func (iface *dhcpInterfaceV4) handleRenew(
// Check if the lease exists and matches.
mac := req.ClientHWAddr
mk := macToKey(mac)
idOpt := clientIdentifier4(req)
iface.common.indexMu.Lock()
defer iface.common.indexMu.Unlock()
@@ -306,12 +311,12 @@ func (iface *dhcpInterfaceV4) handleRenew(
if lease.IP != ip {
l.DebugContext(ctx, "renew request mismatched", "ciaddr", ip, "lease", lease.IP)
iface.respondNAK(ctx, req, fd)
iface.respondNAK(ctx, req, fd, idOpt)
return
}
iface.updateAndRespond(ctx, l, req, lease, fd)
iface.updateAndRespond(ctx, l, req, lease, fd, idOpt)
}
// handleDecline handles messages of type DHCPDECLINE. req must be a
+154 -259
View File
@@ -29,47 +29,81 @@ var testIPv4InterfacesConf = map[string]*dhcpsvc.InterfaceConfig{
},
}
// Lease hostnames for test cases.
//
// NOTE: Keep in sync with testdata.
const (
// testLeaseHostnameStatic is the test hostname for the static lease.
testLeaseHostnameStatic = "static4"
// testLeaseHostnameDynamic is the test hostname for the dynamic lease.
testLeaseHostnameDynamic = "dynamic4"
// testLeaseHostnameExpired is the test hostname for the expired lease.
testLeaseHostnameExpired = "expired4"
)
// Hardware addresses for test cases.
//
// NOTE: Keep in sync with testdata.
var (
// testHWUnknown is the test MAC address for an unknown client.
testHWUnknown = net.HardwareAddr{0x0, 0x1, 0x2, 0x3, 0x4, 0x5}
// testHWStatic is the test MAC address for a known static lease.
testHWStatic = net.HardwareAddr{0x1, 0x2, 0x3, 0x4, 0x5, 0x6}
// testHWDynamic is the test MAC address for a known dynamic lease.
testHWDynamic = net.HardwareAddr{0x2, 0x3, 0x4, 0x5, 0x6, 0x7}
// testHWExpired is the test MAC address for a known expired lease.
testHWExpired = net.HardwareAddr{0x3, 0x4, 0x5, 0x6, 0x7, 0x8}
// testHWAnother is the test MAC address for a lease with another IP.
testHWAnother = net.HardwareAddr{0x4, 0x5, 0x6, 0x7, 0x8, 0x9}
)
// IP addresses for test cases.
//
// NOTE: Keep in sync with testdata.
var (
// testIPUnknown is the test IP address for an unknown client.
testIPUnknown = netip.MustParseAddr("192.0.2.142")
// testIPStatic is the test IP address for a known static lease.
testIPStatic = netip.MustParseAddr("192.0.2.101")
// testIPDynamic is the test IP address for a known dynamic lease.
testIPDynamic = netip.MustParseAddr("192.0.2.102")
// testIPOtherSubnet is the test IP address for a client on another subnet.
testIPOtherSubnet = netip.MustParseAddr(testAnotherGatewayIPv4Str)
// testIPRelayAgent is the test IP address of the relay agent.
testIPRelayAgent = netip.MustParseAddr("10.0.0.1")
)
// Time-related variables for test cases.
//
// NOTE: Keep in sync with testdata.
var (
// testExpiryDynamicLease is the test expiry time for a dynamic lease.
testExpiryDynamicLease = time.Date(2025, 1, 1, 10, 1, 1, 0, time.UTC)
// testTTLDynamicLease is the test TTL for the dynamic lease.
testTTLDynamicLease = testExpiryDynamicLease.Sub(testCurrentTime)
)
func TestDHCPServer_ServeEther4_discover(t *testing.T) {
t.Parallel()
// NOTE: Keep in sync with testdata.
const (
// leaseHostnameStatic is the hostname for the static lease.
leaseHostnameStatic = "static4"
// leaseHostnameDynamic is the hostname for the dynamic lease.
leaseHostnameDynamic = "dynamic4"
// leaseHostnameExpired is the hostname for the expired lease.
leaseHostnameExpired = "expired4"
)
// NOTE: Keep in sync with testdata.
var (
// hwAddrUnknown is the MAC address for an unknown client.
hwAddrUnknown = net.HardwareAddr{0x0, 0x1, 0x2, 0x3, 0x4, 0x5}
// hwAddrStatic is the MAC address for a known static lease.
hwAddrStatic = net.HardwareAddr{0x1, 0x2, 0x3, 0x4, 0x5, 0x6}
// hwAddrDynamic is the MAC address for a known dynamic lease.
hwAddrDynamic = net.HardwareAddr{0x2, 0x3, 0x4, 0x5, 0x6, 0x7}
// hwAddrExpired is the MAC address for a known expired lease.
hwAddrExpired = net.HardwareAddr{0x3, 0x4, 0x5, 0x6, 0x7, 0x8}
)
// NOTE: Keep in sync with testdata.
dynamicLeaseExpiry := time.Date(2025, 1, 1, 10, 1, 1, 0, time.UTC)
dynamicLeaseTTL := dynamicLeaseExpiry.Sub(testCurrentTime)
testCases := []struct {
name string
in gopacket.Packet
wantOpts layers.DHCPOptions
}{{
name: "new",
in: newDHCPDISCOVER(t, hwAddrUnknown),
in: newDHCPDISCOVER(t, testHWUnknown),
wantOpts: layers.DHCPOptions{
newOptMessageType(t, layers.DHCPMsgTypeOffer),
newOptServerID(t, testIfaceAddr),
@@ -77,30 +111,30 @@ func TestDHCPServer_ServeEther4_discover(t *testing.T) {
},
}, {
name: "existing_static",
in: newDHCPDISCOVER(t, hwAddrStatic),
in: newDHCPDISCOVER(t, testHWStatic),
wantOpts: layers.DHCPOptions{
newOptMessageType(t, layers.DHCPMsgTypeOffer),
newOptServerID(t, testIfaceAddr),
newOptLeaseTime(t, testLeaseTTL),
newOptHostname(t, leaseHostnameStatic),
newOptHostname(t, testLeaseHostnameStatic),
},
}, {
name: "existing_dynamic",
in: newDHCPDISCOVER(t, hwAddrDynamic),
in: newDHCPDISCOVER(t, testHWDynamic),
wantOpts: layers.DHCPOptions{
newOptMessageType(t, layers.DHCPMsgTypeOffer),
newOptServerID(t, testIfaceAddr),
newOptLeaseTime(t, dynamicLeaseTTL),
newOptHostname(t, leaseHostnameDynamic),
newOptLeaseTime(t, testTTLDynamicLease),
newOptHostname(t, testLeaseHostnameDynamic),
},
}, {
name: "existing_dynamic_expired",
in: newDHCPDISCOVER(t, hwAddrExpired),
in: newDHCPDISCOVER(t, testHWExpired),
wantOpts: layers.DHCPOptions{
newOptMessageType(t, layers.DHCPMsgTypeOffer),
newOptServerID(t, testIfaceAddr),
newOptLeaseTime(t, testLeaseTTL),
newOptHostname(t, leaseHostnameExpired),
newOptHostname(t, testLeaseHostnameExpired),
},
}}
@@ -121,10 +155,7 @@ func TestDHCPServer_ServeEther4_discover(t *testing.T) {
testutil.RequireSend(t, inCh, tc.in, testTimeout)
respData, ok := testutil.RequireReceive(t, outCh, testTimeout)
require.True(t, ok)
assertValidOffer(t, req, respData, tc.wantOpts)
assertValidResponse(t, req, outCh, tc.wantOpts)
})
}
}
@@ -132,13 +163,7 @@ func TestDHCPServer_ServeEther4_discover(t *testing.T) {
func TestDHCPServer_ServeEther4_discoverExpired(t *testing.T) {
t.Parallel()
// hwAddrUnknown is the MAC address for an unknown client, not related to
// any existing lease.
//
// NOTE: Keep in sync with testdata.
hwAddrUnknown := net.HardwareAddr{0x0, 0x1, 0x2, 0x3, 0x4, 0x5}
pkt := newDHCPDISCOVER(t, hwAddrUnknown)
pkt := newDHCPDISCOVER(t, testHWUnknown)
req := testutil.RequireTypeAssert[*layers.DHCPv4](t, pkt.Layer(layers.LayerTypeDHCPv4))
ndMgr, inCh, outCh := newTestNetworkDeviceManager(t, testIfaceName, testIfaceAddr)
@@ -152,10 +177,7 @@ func TestDHCPServer_ServeEther4_discoverExpired(t *testing.T) {
testutil.RequireSend(t, inCh, pkt, testTimeout)
respData, ok := testutil.RequireReceive(t, outCh, testTimeout)
require.True(t, ok)
assertValidOffer(t, req, respData, layers.DHCPOptions{
assertValidResponse(t, req, outCh, layers.DHCPOptions{
newOptMessageType(t, layers.DHCPMsgTypeOffer),
newOptServerID(t, testIfaceAddr),
newOptLeaseTime(t, testLeaseTTL),
@@ -165,47 +187,21 @@ func TestDHCPServer_ServeEther4_discoverExpired(t *testing.T) {
func TestDHCPServer_ServeEther4_release(t *testing.T) {
t.Parallel()
// NOTE: Keep in sync with testdata.
leaseExpiry := time.Date(2025, 1, 1, 10, 1, 1, 0, time.UTC)
// NOTE: Keep in sync with testdata.
var (
// hwAddrSuccess is the MAC address for a lease to be released
// successfully.
hwAddrSuccess = net.HardwareAddr{0x02, 0x03, 0x04, 0x05, 0x06, 0x07}
// ipSuccess matches the lease IP.
ipSuccess = netip.MustParseAddr("192.0.2.102")
// ipMismatch is the IP of the lease used in the mismatch cases.
ipMismatch = netip.MustParseAddr("192.0.2.103")
// hwAddrMismatch is the MAC address for a lease with mismatched IP.
hwAddrMismatch = net.HardwareAddr{0x03, 0x04, 0x05, 0x06, 0x07, 0x08}
// ipMismatchReq is the IP requested for release, which differs from the
// lease IP.
ipMismatchReq = netip.MustParseAddr("192.0.2.104")
// hwAddrUnknown is an unknown MAC.
hwAddrUnknown = net.HardwareAddr{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}
)
anotherSubnetAddr := netip.MustParseAddr(testAnotherGatewayIPv4Str)
var (
leaseSuccess = &dhcpsvc.Lease{
Expiry: leaseExpiry,
IP: ipSuccess,
Hostname: "success",
HWAddr: hwAddrSuccess,
Expiry: testExpiryDynamicLease,
IP: testIPDynamic,
Hostname: "dynamic",
HWAddr: testHWDynamic,
IsStatic: false,
}
ipAnother = testIPDynamic.Next()
leaseMismatch = &dhcpsvc.Lease{
Expiry: leaseExpiry,
IP: ipMismatch,
Expiry: testExpiryDynamicLease,
IP: ipAnother,
Hostname: "mismatch",
HWAddr: hwAddrMismatch,
HWAddr: testHWAnother,
IsStatic: false,
}
)
@@ -216,27 +212,27 @@ func TestDHCPServer_ServeEther4_release(t *testing.T) {
wantLeases []*dhcpsvc.Lease
}{{
name: "success",
req: newDHCPRELEASE(t, hwAddrSuccess, ipSuccess, testIfaceHWAddr, testIfaceAddr),
req: newDHCPRELEASE(t, testHWDynamic, testIPDynamic, testIfaceHWAddr, testIfaceAddr),
wantLeases: []*dhcpsvc.Lease{
leaseMismatch,
},
}, {
name: "not_found",
req: newDHCPRELEASE(t, hwAddrUnknown, ipSuccess, testIfaceHWAddr, testIfaceAddr),
req: newDHCPRELEASE(t, testHWUnknown, testIPDynamic, testIfaceHWAddr, testIfaceAddr),
wantLeases: []*dhcpsvc.Lease{
leaseSuccess,
leaseMismatch,
},
}, {
name: "mismatch_ip",
req: newDHCPRELEASE(t, hwAddrMismatch, ipMismatchReq, testIfaceHWAddr, testIfaceAddr),
req: newDHCPRELEASE(t, testHWAnother, ipAnother.Next(), testIfaceHWAddr, testIfaceAddr),
wantLeases: []*dhcpsvc.Lease{
leaseSuccess,
leaseMismatch,
},
}, {
name: "bad_subnet",
req: newDHCPRELEASE(t, hwAddrSuccess, anotherSubnetAddr, testIfaceHWAddr, testIfaceAddr),
req: newDHCPRELEASE(t, testHWDynamic, testIPOtherSubnet, testIfaceHWAddr, testIfaceAddr),
wantLeases: []*dhcpsvc.Lease{
leaseSuccess,
leaseMismatch,
@@ -272,30 +268,19 @@ func TestDHCPServer_ServeEther4_release(t *testing.T) {
func TestDHCPServer_ServeEther4_requestSelecting(t *testing.T) {
t.Parallel()
// NOTE: Keep in sync with testdata.
var (
hwAddrUnknown = net.HardwareAddr{0x0, 0x1, 0x2, 0x3, 0x4, 0x5}
hwAddrStatic = net.HardwareAddr{0x1, 0x2, 0x3, 0x4, 0x5, 0x6}
ipStatic = netip.MustParseAddr("192.0.2.101")
ipWrong = netip.MustParseAddr("192.0.2.200")
ipOtherSubnet = netip.MustParseAddr(testAnotherGatewayIPv4Str)
)
testCases := []struct {
discover gopacket.Packet
request gopacket.Packet
name string
wantOpts layers.DHCPOptions
}{{
discover: newDHCPDISCOVER(t, hwAddrUnknown),
discover: newDHCPDISCOVER(t, testHWUnknown),
request: newDHCPREQUEST(t, &dhcpRequestConfig{
options: layers.DHCPOptions{
newOptRequestIP(t, testIPv4Conf.RangeStart),
newOptServerID(t, testIfaceAddr),
},
clientHWAddr: hwAddrUnknown,
clientHWAddr: testHWUnknown,
flags: dhcpsvc.FlagsBroadcast,
}),
name: "success",
@@ -305,13 +290,13 @@ func TestDHCPServer_ServeEther4_requestSelecting(t *testing.T) {
newOptLeaseTime(t, testLeaseTTL),
},
}, {
discover: newDHCPDISCOVER(t, hwAddrStatic),
discover: newDHCPDISCOVER(t, testHWStatic),
request: newDHCPREQUEST(t, &dhcpRequestConfig{
options: layers.DHCPOptions{
newOptRequestIP(t, ipStatic),
newOptServerID(t, ipOtherSubnet),
newOptRequestIP(t, testIPStatic),
newOptServerID(t, testIPOtherSubnet),
},
clientHWAddr: hwAddrStatic,
clientHWAddr: testHWStatic,
flags: dhcpsvc.FlagsBroadcast,
}),
name: "wrong_server_id",
@@ -320,41 +305,41 @@ func TestDHCPServer_ServeEther4_requestSelecting(t *testing.T) {
discover: nil,
request: newDHCPREQUEST(t, &dhcpRequestConfig{
options: layers.DHCPOptions{
newOptRequestIP(t, ipWrong),
newOptRequestIP(t, testIPv4Conf.RangeEnd.Next()),
newOptServerID(t, testIfaceAddr),
},
clientHWAddr: hwAddrUnknown,
clientHWAddr: testHWUnknown,
flags: dhcpsvc.FlagsBroadcast,
}),
name: "no_lease",
wantOpts: layers.DHCPOptions{
newOptMessageType(t, layers.DHCPMsgTypeNak),
newOptServerID(t, testIPv4Conf.GatewayIP),
newOptServerID(t, testIfaceAddr),
},
}, {
discover: newDHCPDISCOVER(t, hwAddrStatic),
discover: newDHCPDISCOVER(t, testHWStatic),
request: newDHCPREQUEST(t, &dhcpRequestConfig{
options: layers.DHCPOptions{
newOptRequestIP(t, ipWrong),
newOptRequestIP(t, testIPv4Conf.RangeEnd.Next()),
newOptServerID(t, testIfaceAddr),
},
clientHWAddr: hwAddrStatic,
clientHWAddr: testHWStatic,
flags: dhcpsvc.FlagsBroadcast,
}),
name: "wrong_ip",
wantOpts: layers.DHCPOptions{
newOptMessageType(t, layers.DHCPMsgTypeNak),
newOptServerID(t, testIPv4Conf.GatewayIP),
newOptServerID(t, testIfaceAddr),
},
}, {
discover: newDHCPDISCOVER(t, hwAddrStatic),
discover: newDHCPDISCOVER(t, testHWStatic),
request: newDHCPREQUEST(t, &dhcpRequestConfig{
options: layers.DHCPOptions{
newOptRequestIP(t, ipStatic),
newOptRequestIP(t, testIPStatic),
newOptServerID(t, testIfaceAddr),
},
clientHWAddr: hwAddrStatic,
clientIP: ipStatic,
clientHWAddr: testHWStatic,
clientIP: testIPStatic,
flags: dhcpsvc.FlagsBroadcast,
}),
name: "nonzero_ciaddr",
@@ -393,22 +378,6 @@ func TestDHCPServer_ServeEther4_requestSelecting(t *testing.T) {
func TestDHCPServer_ServeEther4_requestInitReboot(t *testing.T) {
t.Parallel()
// NOTE: Keep in sync with testdata.
const (
leaseHostnameStatic = "static4"
)
// NOTE: Keep in sync with testdata.
var (
hwAddrUnknown = net.HardwareAddr{0x0, 0x1, 0x2, 0x3, 0x4, 0x5}
hwAddrStatic = net.HardwareAddr{0x1, 0x2, 0x3, 0x4, 0x5, 0x6}
ipStatic = netip.MustParseAddr("192.0.2.101")
ipDynamic = netip.MustParseAddr("192.0.2.102")
ipOtherSubnet = netip.MustParseAddr(testAnotherGatewayIPv4Str)
)
testCases := []struct {
req gopacket.Packet
name string
@@ -416,62 +385,62 @@ func TestDHCPServer_ServeEther4_requestInitReboot(t *testing.T) {
}{{
name: "success",
req: newDHCPREQUEST(t, &dhcpRequestConfig{
options: layers.DHCPOptions{newOptRequestIP(t, ipStatic)},
clientHWAddr: hwAddrStatic,
options: layers.DHCPOptions{newOptRequestIP(t, testIPStatic)},
clientHWAddr: testHWStatic,
flags: dhcpsvc.FlagsBroadcast,
}),
wantOpts: layers.DHCPOptions{
newOptMessageType(t, layers.DHCPMsgTypeAck),
newOptServerID(t, testIfaceAddr),
newOptLeaseTime(t, testLeaseTTL),
newOptHostname(t, leaseHostnameStatic),
newOptHostname(t, testLeaseHostnameStatic),
},
}, {
name: "wrong_subnet",
req: newDHCPREQUEST(t, &dhcpRequestConfig{
options: layers.DHCPOptions{newOptRequestIP(t, ipOtherSubnet)},
clientHWAddr: hwAddrStatic,
options: layers.DHCPOptions{newOptRequestIP(t, testIPOtherSubnet)},
clientHWAddr: testHWStatic,
flags: dhcpsvc.FlagsBroadcast,
}),
wantOpts: layers.DHCPOptions{
newOptMessageType(t, layers.DHCPMsgTypeNak),
newOptServerID(t, testIPv4Conf.GatewayIP),
newOptServerID(t, testIfaceAddr),
},
}, {
name: "no_lease",
req: newDHCPREQUEST(t, &dhcpRequestConfig{
options: layers.DHCPOptions{newOptRequestIP(t, ipStatic)},
clientHWAddr: hwAddrUnknown,
options: layers.DHCPOptions{newOptRequestIP(t, testIPStatic)},
clientHWAddr: testHWUnknown,
flags: dhcpsvc.FlagsBroadcast,
}),
wantOpts: nil,
}, {
name: "wrong_ip",
req: newDHCPREQUEST(t, &dhcpRequestConfig{
options: layers.DHCPOptions{newOptRequestIP(t, ipDynamic)},
clientHWAddr: hwAddrStatic,
options: layers.DHCPOptions{newOptRequestIP(t, testIPDynamic)},
clientHWAddr: testHWStatic,
flags: dhcpsvc.FlagsBroadcast,
}),
wantOpts: layers.DHCPOptions{
newOptMessageType(t, layers.DHCPMsgTypeNak),
newOptServerID(t, testIPv4Conf.GatewayIP),
newOptServerID(t, testIfaceAddr),
},
}, {
name: "wrong_ip_no_broadcast",
req: newDHCPREQUEST(t, &dhcpRequestConfig{
options: layers.DHCPOptions{newOptRequestIP(t, ipDynamic)},
clientHWAddr: hwAddrStatic,
options: layers.DHCPOptions{newOptRequestIP(t, testIPDynamic)},
clientHWAddr: testHWStatic,
}),
wantOpts: layers.DHCPOptions{
newOptMessageType(t, layers.DHCPMsgTypeNak),
newOptServerID(t, testIPv4Conf.GatewayIP),
newOptServerID(t, testIfaceAddr),
},
}, {
name: "nonzero_ciaddr",
req: newDHCPREQUEST(t, &dhcpRequestConfig{
options: layers.DHCPOptions{newOptRequestIP(t, ipStatic)},
clientHWAddr: hwAddrStatic,
clientIP: ipStatic,
options: layers.DHCPOptions{newOptRequestIP(t, testIPStatic)},
clientHWAddr: testHWStatic,
clientIP: testIPStatic,
flags: dhcpsvc.FlagsBroadcast,
}),
wantOpts: nil,
@@ -501,27 +470,6 @@ func TestDHCPServer_ServeEther4_requestInitReboot(t *testing.T) {
func TestDHCPServer_ServeEther4_requestRenewSuccess(t *testing.T) {
t.Parallel()
// NOTE: Keep in sync with testdata.
const (
leaseHostnameStatic = "static4"
leaseHostnameDynamic = "dynamic4"
)
// NOTE: Keep in sync with testdata.
var (
hwAddrStatic = net.HardwareAddr{0x1, 0x2, 0x3, 0x4, 0x5, 0x6}
hwAddrDynamic = net.HardwareAddr{0x2, 0x3, 0x4, 0x5, 0x6, 0x7}
ipStatic = netip.MustParseAddr("192.0.2.101")
ipDynamic = netip.MustParseAddr("192.0.2.102")
ipRelayAgent = netip.MustParseAddr("10.0.0.1")
)
// NOTE: Keep in sync with testdata.
dynamicLeaseExpiry := time.Date(2025, 1, 1, 10, 1, 1, 0, time.UTC)
dynamicLeaseTTL := dynamicLeaseExpiry.Sub(testCurrentTime)
testCases := []struct {
name string
req gopacket.Packet
@@ -529,53 +477,53 @@ func TestDHCPServer_ServeEther4_requestRenewSuccess(t *testing.T) {
}{{
name: "success",
req: newDHCPREQUEST(t, &dhcpRequestConfig{
clientHWAddr: hwAddrDynamic,
clientIP: ipDynamic,
clientHWAddr: testHWDynamic,
clientIP: testIPDynamic,
flags: dhcpsvc.FlagsBroadcast,
}),
wantOpts: layers.DHCPOptions{
newOptMessageType(t, layers.DHCPMsgTypeAck),
newOptServerID(t, testIfaceAddr),
newOptLeaseTime(t, dynamicLeaseTTL),
newOptHostname(t, leaseHostnameDynamic),
newOptLeaseTime(t, testTTLDynamicLease),
newOptHostname(t, testLeaseHostnameDynamic),
},
}, {
name: "static",
req: newDHCPREQUEST(t, &dhcpRequestConfig{
clientHWAddr: hwAddrStatic,
clientIP: ipStatic,
clientHWAddr: testHWStatic,
clientIP: testIPStatic,
flags: dhcpsvc.FlagsBroadcast,
}),
wantOpts: layers.DHCPOptions{
newOptMessageType(t, layers.DHCPMsgTypeAck),
newOptServerID(t, testIfaceAddr),
newOptLeaseTime(t, testLeaseTTL),
newOptHostname(t, leaseHostnameStatic),
newOptHostname(t, testLeaseHostnameStatic),
},
}, {
name: "relay_agent",
req: newDHCPREQUEST(t, &dhcpRequestConfig{
clientHWAddr: hwAddrDynamic,
clientIP: ipDynamic,
relayAgentIP: ipRelayAgent,
clientHWAddr: testHWDynamic,
clientIP: testIPDynamic,
relayAgentIP: testIPRelayAgent,
}),
wantOpts: layers.DHCPOptions{
newOptMessageType(t, layers.DHCPMsgTypeAck),
newOptServerID(t, testIfaceAddr),
newOptLeaseTime(t, dynamicLeaseTTL),
newOptHostname(t, leaseHostnameDynamic),
newOptLeaseTime(t, testTTLDynamicLease),
newOptHostname(t, testLeaseHostnameDynamic),
},
}, {
name: "ciaddr_unicast",
req: newDHCPREQUEST(t, &dhcpRequestConfig{
clientHWAddr: hwAddrDynamic,
clientIP: ipDynamic,
clientHWAddr: testHWDynamic,
clientIP: testIPDynamic,
}),
wantOpts: layers.DHCPOptions{
newOptMessageType(t, layers.DHCPMsgTypeAck),
newOptServerID(t, testIfaceAddr),
newOptLeaseTime(t, dynamicLeaseTTL),
newOptHostname(t, leaseHostnameDynamic),
newOptLeaseTime(t, testTTLDynamicLease),
newOptHostname(t, testLeaseHostnameDynamic),
},
}}
@@ -603,17 +551,6 @@ func TestDHCPServer_ServeEther4_requestRenewSuccess(t *testing.T) {
func TestDHCPServer_ServeEther4_requestRenewFail(t *testing.T) {
t.Parallel()
// NOTE: Keep in sync with testdata.
var (
hwAddrUnknown = net.HardwareAddr{0x0, 0x1, 0x2, 0x3, 0x4, 0x5}
hwAddrStatic = net.HardwareAddr{0x1, 0x2, 0x3, 0x4, 0x5, 0x6}
ipStatic = netip.MustParseAddr("192.0.2.101")
ipDynamic = netip.MustParseAddr("192.0.2.102")
ipOtherSubnet = netip.MustParseAddr(testAnotherGatewayIPv4Str)
)
testCases := []struct {
name string
req gopacket.Packet
@@ -621,29 +558,29 @@ func TestDHCPServer_ServeEther4_requestRenewFail(t *testing.T) {
}{{
name: "wrong_subnet",
req: newDHCPREQUEST(t, &dhcpRequestConfig{
clientHWAddr: hwAddrStatic,
clientIP: ipOtherSubnet,
clientHWAddr: testHWStatic,
clientIP: testIPOtherSubnet,
flags: dhcpsvc.FlagsBroadcast,
}),
wantOpts: nil,
}, {
name: "no_lease",
req: newDHCPREQUEST(t, &dhcpRequestConfig{
clientHWAddr: hwAddrUnknown,
clientIP: ipStatic,
clientHWAddr: testHWUnknown,
clientIP: testIPStatic,
flags: dhcpsvc.FlagsBroadcast,
}),
wantOpts: nil,
}, {
name: "wrong_ip",
req: newDHCPREQUEST(t, &dhcpRequestConfig{
clientHWAddr: hwAddrStatic,
clientIP: ipDynamic,
clientHWAddr: testHWStatic,
clientIP: testIPDynamic,
flags: dhcpsvc.FlagsBroadcast,
}),
wantOpts: layers.DHCPOptions{
newOptMessageType(t, layers.DHCPMsgTypeNak),
newOptServerID(t, testIPv4Conf.GatewayIP),
newOptServerID(t, testIfaceAddr),
},
}}
@@ -671,50 +608,28 @@ func TestDHCPServer_ServeEther4_requestRenewFail(t *testing.T) {
func TestDHCPServer_ServeEther4_decline(t *testing.T) {
t.Parallel()
// NOTE: Keep in sync with testdata.
var (
// hwAddrSuccess is the MAC address for a lease to be declined
// successfully.
hwAddrSuccess = net.HardwareAddr{0x02, 0x03, 0x04, 0x05, 0x06, 0x07}
// ipSuccess matches the lease IP.
ipSuccess = netip.MustParseAddr("192.0.2.102")
// hwAddrMismatch is the MAC address for a lease with mismatched IP.
hwAddrMismatch = net.HardwareAddr{0x03, 0x04, 0x05, 0x06, 0x07, 0x08}
// ipMismatchReq is the IP requested for decline, which differs from
// the lease IP.
ipMismatchReq = netip.MustParseAddr("192.0.2.104")
// hwAddrUnknown is an unknown MAC.
hwAddrUnknown = net.HardwareAddr{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}
)
anotherSubnetAddr := netip.MustParseAddr(testAnotherGatewayIPv4Str)
testCases := []struct {
req gopacket.Packet
name string
wantChange bool
}{{
req: newDHCPDECLINE(t, hwAddrSuccess, ipSuccess),
req: newDHCPDECLINE(t, testHWDynamic, testIPDynamic),
name: "success",
wantChange: true,
}, {
req: newDHCPDECLINE(t, hwAddrUnknown, ipSuccess),
req: newDHCPDECLINE(t, testHWUnknown, testIPDynamic),
name: "not_found",
wantChange: false,
}, {
req: newDHCPDECLINE(t, hwAddrMismatch, ipMismatchReq),
req: newDHCPDECLINE(t, testHWAnother, testIPUnknown),
name: "mismatch_ip",
wantChange: false,
}, {
req: newDHCPDECLINE(t, hwAddrSuccess, anotherSubnetAddr),
req: newDHCPDECLINE(t, testHWDynamic, testIPOtherSubnet),
name: "bad_subnet",
wantChange: false,
}, {
req: newDHCPDECLINE(t, hwAddrSuccess, netip.Addr{}),
req: newDHCPDECLINE(t, testHWDynamic, netip.Addr{}),
name: "no_requested_ip",
wantChange: false,
}}
@@ -992,28 +907,6 @@ func requireEthernet(
return types
}
// assertValidOffer asserts that respData contains a complete DHCPOFFER response
// with the expected options, wrapped with all layers down to Ethernet.
func assertValidOffer(
tb testing.TB,
discover *layers.DHCPv4,
respData []byte,
wantOpts layers.DHCPOptions,
) {
tb.Helper()
resp := &layers.DHCPv4{}
types := requireEthernet(tb, respData, &layers.Ethernet{}, &layers.IPv4{}, &layers.UDP{}, resp)
require.Equal(tb, fullLayersStack, types)
assert.Equal(tb, layers.DHCPOpReply, resp.Operation, "operation")
assert.Equal(tb, discover.HardwareType, resp.HardwareType, "hardware type")
assert.Equal(tb, discover.HardwareLen, resp.HardwareLen, "hardware length")
assert.Equal(tb, discover.Xid, resp.Xid, "xid")
assert.Equal(tb, discover.ClientHWAddr, resp.ClientHWAddr, "client hardware address")
assert.Equal(tb, wantOpts, resp.Options, "options")
}
// assertValidResponse asserts that recvCh eventually gets the response with
// wantOpts for request. If wantOpts is nil, asserts that no response is sent.
// request and recvCh must not be nil.
@@ -1042,6 +935,8 @@ func assertValidResponse(
assertValidDHCPv4(tb, request, resp, ip, udp)
// TODO(e.burkov): Consider comparing the whole message instead of separate
// fields.
assert.Equal(tb, layers.DHCPOpReply, resp.Operation, "operation")
assert.Equal(tb, request.HardwareType, resp.HardwareType, "hardware type")
assert.Equal(tb, request.HardwareLen, resp.HardwareLen, "hardware length")
@@ -1057,7 +952,7 @@ func assertValidDHCPv4(tb testing.TB, req, resp *layers.DHCPv4, ip *layers.IPv4,
case !req.RelayAgentIP.IsUnspecified():
assert.Equal(tb, req.RelayAgentIP.To4(), ip.DstIP)
assert.Equal(tb, dhcpsvc.ServerPortV4, udp.DstPort)
case !req.ClientIP.IsUnspecified() && req.Flags&dhcpsvc.FlagsBroadcast == 0:
case !req.ClientIP.IsUnspecified():
assert.Equal(tb, req.ClientIP.To4(), ip.DstIP)
case req.Flags&dhcpsvc.FlagsBroadcast != 0:
assert.Equal(tb, net.IPv4bcast.To4(), ip.DstIP)
+3 -3
View File
@@ -16,14 +16,14 @@ import (
// macKey contains hardware address as byte array of 6, 8, or 20 bytes.
//
// TODO(e.burkov): Move to aghnet or even to netutil.
//
// TODO(e.burkov): Identify the client by the hardware address and the client
// identifier from the DHCP messages.
type macKey any
// macToKey converts mac into macKey, which is used as the key for the lease
// maps. mac must be a valid hardware address of length 6, 8, or 20 bytes, see
// [netutil.ValidateMAC].
//
// TODO(e.burkov): Identify the client by the hardware address and the client
// identifier from the DHCP messages.
func macToKey(mac net.HardwareAddr) (key macKey) {
switch len(mac) {
case 6:
+83 -14
View File
@@ -13,6 +13,23 @@ import (
"github.com/google/gopacket/layers"
)
// msgTypeOptions4 contains preallocated DHCPv4 message type options mapped by
// their type.
var msgTypeOptions4 = map[layers.DHCPMsgType]layers.DHCPOption{
layers.DHCPMsgTypeAck: layers.NewDHCPOption(
layers.DHCPOptMessageType,
[]byte{byte(layers.DHCPMsgTypeAck)},
),
layers.DHCPMsgTypeNak: layers.NewDHCPOption(
layers.DHCPOptMessageType,
[]byte{byte(layers.DHCPMsgTypeNak)},
),
layers.DHCPMsgTypeOffer: layers.NewDHCPOption(
layers.DHCPOptMessageType,
[]byte{byte(layers.DHCPMsgTypeOffer)},
),
}
// implicitOptions returns the implicit options for the interface, sorted by
// code.
func (c *IPv4Config) implicitOptions() (opts layers.DHCPOptions) {
@@ -247,11 +264,14 @@ func compareV4OptionCodes(a, b layers.DHCPOption) (res int) {
return int(a.Type) - int(b.Type)
}
// updateOptions updates the options of the response in accordance with the
// requested parameters. req and resp must not be nil.
// appendRequestedOptions adds the options to opts in accordance with the
// requested parameters. req must not be nil.
//
// See https://datatracker.ietf.org/doc/html/rfc2131#section-4.3.1.
func (iface *dhcpInterfaceV4) updateOptions(req, resp *layers.DHCPv4) {
func (iface *dhcpInterfaceV4) appendRequestedOptions(
opts layers.DHCPOptions,
req *layers.DHCPv4,
) (res layers.DHCPOptions) {
// If the server recognizes the parameter as a parameter defined in the Host
// Requirements Document, the server MUST include the default value for that
// parameter.
@@ -260,13 +280,13 @@ func (iface *dhcpInterfaceV4) updateOptions(req, resp *layers.DHCPv4) {
optWithCode.Type = code
i, has := slices.BinarySearchFunc(iface.implicitOpts, optWithCode, compareV4OptionCodes)
if has {
// The client MAY list the options in order of preference. The DHCP
// The client MAY list the options in order of preference. The DHCP
// server is not required to return the options in the requested
// order, but MUST try to insert the requested options in the order
// requested by the client.
//
// See https://datatracker.ietf.org/doc/html/rfc2132#section-9.8.
resp.Options = append(resp.Options, iface.implicitOpts[i])
opts = append(opts, iface.implicitOpts[i])
}
}
@@ -274,23 +294,47 @@ func (iface *dhcpInterfaceV4) updateOptions(req, resp *layers.DHCPv4) {
// parameter or the parameter has a non-default value on the client's
// subnet, the server MUST include that value in an appropriate option.
for _, opt := range iface.explicitOpts {
if opt.Data != nil {
resp.Options = append(resp.Options, opt)
if len(opt.Data) > 0 {
opts = append(opts, opt)
continue
}
// Remove options explicitly configured to be removed, in case they are
// already set.
resp.Options = slices.DeleteFunc(resp.Options, func(o layers.DHCPOption) (ok bool) {
opts = slices.DeleteFunc(opts, func(o layers.DHCPOption) (ok bool) {
return o.Type == opt.Type
})
}
return opts
}
// appendLeaseTime appends the lease time option to the response. lease must
// newRespOptions creates the basic options for a DHCP response. fd must not be
// nil, mt must be a valid DHCP response message type. idOpt is an optional
// client identifier from the corresponding request.
func newRespOptions(mt layers.DHCPMsgType, fd *frameData, idOpt []byte) (opts layers.DHCPOptions) {
opts = layers.DHCPOptions{
msgTypeOptions4[mt],
layers.NewDHCPOption(layers.DHCPOptServerID, fd.localAddr.AsSlice()),
}
if len(idOpt) > 0 {
opts = append(opts, layers.NewDHCPOption(layers.DHCPOptClientID, idOpt))
}
return opts
}
// appendTimeOptions adds the lease time option to the response. lease must
// not be nil.
func (iface *dhcpInterfaceV4) appendLeaseTime(resp *layers.DHCPv4, lease *Lease) {
//
// TODO(e.burkov): Add also renewal (T1) and rebinding (T2) time options, see
// RFC 2131 Section 4.4.5, and RFC 2132 Sections 9.11 and 9.12.
func (iface *dhcpInterfaceV4) appendTimeOptions(
opts layers.DHCPOptions,
lease *Lease,
) (res layers.DHCPOptions) {
var dur time.Duration
if lease.IsStatic {
dur = iface.common.leaseTTL
@@ -298,14 +342,28 @@ func (iface *dhcpInterfaceV4) appendLeaseTime(resp *layers.DHCPv4, lease *Lease)
dur = lease.Expiry.Sub(iface.clock.Now())
}
leaseTimeData := binary.BigEndian.AppendUint32(nil, uint32(dur.Seconds()))
leaseTimeOpt := [4]byte{}
binary.BigEndian.PutUint32(leaseTimeOpt[:], uint32(dur.Seconds()))
resp.Options = append(
resp.Options,
layers.NewDHCPOption(layers.DHCPOptLeaseTime, leaseTimeData),
return append(
opts,
layers.NewDHCPOption(layers.DHCPOptLeaseTime, leaseTimeOpt[:]),
)
}
// appendHostnameOption appends the hostname option to the response, if it's
// provided.
//
// TODO(e.burkov): Lease should always has a hostname, investigate when it
// isn't the case.
func appendHostnameOption(opts layers.DHCPOptions, hostname string) (res layers.DHCPOptions) {
if hostname == "" {
return opts
}
return append(opts, layers.NewDHCPOption(layers.DHCPOptHostname, []byte(hostname)))
}
// msg4Type returns the message type of msg, if it's present within the options.
func msg4Type(msg *layers.DHCPv4) (typ layers.DHCPMsgType, ok bool) {
for _, opt := range msg.Options {
@@ -353,6 +411,17 @@ func hostname4(msg *layers.DHCPv4) (hostname string) {
return ""
}
// clientIdentifier4 returns a client identifier from msg, if any.
func clientIdentifier4(msg *layers.DHCPv4) (id []byte) {
for _, opt := range msg.Options {
if opt.Type == layers.DHCPOptClientID && len(opt.Data) > 0 {
return opt.Data
}
}
return nil
}
// requestedOptions returns the list of options requested in DHCPv4 message, if
// any.
//
@@ -3,7 +3,7 @@
{
"expires": "2025-01-01T10:01:01Z",
"ip": "192.0.2.102",
"hostname": "success",
"hostname": "dynamic",
"mac": "02:03:04:05:06:07",
"static": false
},
@@ -11,7 +11,7 @@
"expires": "2025-01-01T10:01:01Z",
"ip": "192.0.2.103",
"hostname": "mismatch",
"mac": "03:04:05:06:07:08",
"mac": "04:05:06:07:08:09",
"static": false
}
],
@@ -3,7 +3,7 @@
{
"expires": "2025-01-01T10:01:01Z",
"ip": "192.0.2.102",
"hostname": "success",
"hostname": "dynamic",
"mac": "02:03:04:05:06:07",
"static": false
},
@@ -11,7 +11,7 @@
"expires": "2025-01-01T10:01:01Z",
"ip": "192.0.2.103",
"hostname": "mismatch",
"mac": "03:04:05:06:07:08",
"mac": "04:05:06:07:08:09",
"static": false
}
],
+87 -111
View File
@@ -200,32 +200,39 @@ func (srv *DHCPServer) newDHCPInterfaceV4(
return iface
}
// updateLease updates l in the database. l must be valid and not expired.
func (iface *dhcpInterfaceV4) updateLease(
ctx context.Context,
l *Lease,
) (err error) {
return iface.common.index.update(ctx, iface.common.logger, l, iface.common)
// updateLease updates lease in the database. lease must be valid and not
// expired.
func (iface *dhcpInterfaceV4) updateLease(ctx context.Context, lease *Lease) (err error) {
return iface.common.index.update(ctx, iface.common.logger, lease, iface.common)
}
// respondOffer sends a DHCPOFFER message to the client. req, fd, and l must
// not be nil.
// respondOffer sends a DHCPOFFER message to the client. idOpt is expected to
// be the value of the DHCP option Client Identifier, nil if not present. req,
// fd, and lease must not be nil.
//
// TODO(e.burkov): Consider merging with [respondACK].
func (iface *dhcpInterfaceV4) respondOffer(
ctx context.Context,
req *layers.DHCPv4,
fd *frameData,
l *Lease,
lease *Lease,
idOpt []byte,
) {
resp := iface.buildResponse(req, l, fd.device, layers.DHCPMsgTypeOffer)
opts := newRespOptions(layers.DHCPMsgTypeOffer, fd, idOpt)
opts = iface.appendTimeOptions(opts, lease)
opts = appendHostnameOption(opts, lease.Hostname)
opts = iface.appendRequestedOptions(opts, req)
resp := buildResponse(req, lease.IP, net.IPv4zero, req.Flags, opts)
err := respond4(fd, req, resp)
if err != nil {
iface.common.logger.ErrorContext(ctx, "writing offer", "error", err)
}
}
// respondACK sends a DHCPACK message to the client. req, fd, and l must not be
// nil.
// respondACK sends a DHCPACK message to the client. idOpt is expected to be
// the value of the DHCP option Client Identifier, nil if not present. req, fd,
// and lease must not be nil.
//
// TODO(e.burkov): Implement according to RFC, answer to DHCPINFORM
// differently, when it's supported.
@@ -233,107 +240,75 @@ func (iface *dhcpInterfaceV4) respondACK(
ctx context.Context,
req *layers.DHCPv4,
fd *frameData,
l *Lease,
lease *Lease,
idOpt []byte,
) {
resp := iface.buildResponse(req, l, fd.device, layers.DHCPMsgTypeAck)
opts := newRespOptions(layers.DHCPMsgTypeAck, fd, idOpt)
opts = iface.appendTimeOptions(opts, lease)
opts = iface.appendRequestedOptions(opts, req)
opts = appendHostnameOption(opts, lease.Hostname)
resp := buildResponse(req, lease.IP, req.ClientIP, req.Flags, opts)
err := respond4(fd, req, resp)
if err != nil {
iface.common.logger.ErrorContext(ctx, "writing ack", "error", err)
}
}
// v4OptionMessageTypeNAK is a DHCP option for DHCPNAK message type.
var v4OptionMessageTypeNAK = layers.NewDHCPOption(
layers.DHCPOptMessageType,
[]byte{byte(layers.DHCPMsgTypeNak)},
)
// respondNAK constructs and sends a DHCPNAK message to the client. req, fd,
// and resp must not be nil.
// respondNAK constructs and sends a DHCPNAK message to the client. idOpt is
// expected to be the value of the DHCP option Client Identifier, nil if not
// present. req, fd, and resp must not be nil.
//
// See https://datatracker.ietf.org/doc/html/rfc2131#section-4.3.1.
func (iface *dhcpInterfaceV4) respondNAK(
ctx context.Context,
req *layers.DHCPv4,
fd *frameData,
idOpt []byte,
) {
// TODO(e.burkov): According to RFC 2131 we should add a message.
opts := newRespOptions(layers.DHCPMsgTypeNak, fd, idOpt)
// If 'giaddr' is set in the DHCPREQUEST message, the client is on a
// different subnet. The server MUST set the broadcast bit in the DHCPNAK,
// so that the relay agent will broadcast the DHCPNAK to the client, because
// the client may not have a correct network address or subnet mask, and the
// client may not be answering ARP requests.
var flags uint16
if !isSpecified(req.RelayAgentIP) {
flags = FlagsBroadcast
}
resp := &layers.DHCPv4{
Operation: layers.DHCPOpReply,
HardwareType: layers.LinkTypeEthernet,
HardwareLen: uint8(len(req.ClientHWAddr)),
Xid: req.Xid,
Secs: 0,
Flags: flags,
ClientIP: req.ClientIP,
RelayAgentIP: req.RelayAgentIP,
ClientHWAddr: req.ClientHWAddr,
Options: layers.DHCPOptions{
v4OptionMessageTypeNAK,
layers.NewDHCPOption(layers.DHCPOptServerID, iface.gateway.AsSlice()),
// TODO(e.burkov): According to RFC 2131 we should add a message.
},
flags := req.Flags
if isSpecified(req.RelayAgentIP) {
flags = flags | FlagsBroadcast
}
resp := buildResponse(req, netip.Addr{}, net.IPv4zero, flags, opts)
err := respond4(fd, req, resp)
if err != nil {
iface.common.logger.ErrorContext(ctx, "writing nak", "error", err)
}
}
// buildResponse builds a DHCP response message with the given message type.
// req and l must not be nil. msgType must be one of:
// - [layers.DHCPMsgTypeOffer]
// - [layers.DHCPMsgTypeAck]
func (iface *dhcpInterfaceV4) buildResponse(
// buildResponse constructs a DHCPv4 response message. req must not be nil.
// Note that in order to be a valid response, opts must contain some mandatory
// options, e.g. a message type.
func buildResponse(
req *layers.DHCPv4,
l *Lease,
nd NetworkDevice,
msgType layers.DHCPMsgType,
yiaddr netip.Addr,
ciaddr net.IP,
flags uint16,
opts layers.DHCPOptions,
) (resp *layers.DHCPv4) {
resp = &layers.DHCPv4{
return &layers.DHCPv4{
Operation: layers.DHCPOpReply,
HardwareType: layers.LinkTypeEthernet,
HardwareLen: uint8(len(req.ClientHWAddr)),
Xid: req.Xid,
Secs: 0,
Flags: req.Flags,
ClientIP: req.ClientIP,
Flags: flags,
ClientIP: ciaddr,
RelayAgentIP: req.RelayAgentIP,
ClientHWAddr: req.ClientHWAddr,
YourClientIP: l.IP.AsSlice(),
YourClientIP: yiaddr.AsSlice(),
Options: opts,
}
resp.Options = append(
resp.Options,
layers.NewDHCPOption(layers.DHCPOptMessageType, []byte{byte(msgType)}),
layers.NewDHCPOption(layers.DHCPOptServerID, nd.Addresses()[0].AsSlice()),
)
iface.appendLeaseTime(resp, l)
iface.updateOptions(req, resp)
// Add hostname option if the lease has a hostname.
//
// TODO(e.burkov): Lease should always has a hostname, investigate when
// it isn't the case.
if l.Hostname != "" {
resp.Options = append(
resp.Options,
layers.NewDHCPOption(layers.DHCPOptHostname, []byte(l.Hostname)),
)
}
return resp
}
// dhcpInterfacesV4 is a slice of network interfaces of IPv4 address family.
@@ -353,74 +328,74 @@ func (ifaces dhcpInterfacesV4) find(ip netip.Addr) (iface4 *netInterface, ok boo
}
// allocateLease allocates a new lease for the MAC address. If there are no IP
// addresses left, both l and err are nil. mac must be a valid according to
// addresses left, both lease and err are nil. mac must be a valid according to
// [netutil.ValidateMAC].
//
// TODO(e.burkov): Pass the precalculated macKey.
func (iface *dhcpInterfaceV4) allocateLease(
ctx context.Context,
mac net.HardwareAddr,
) (l *Lease, err error) {
) (lease *Lease, err error) {
for {
l, err = iface.reserveLease(ctx, mac)
lease, err = iface.reserveLease(ctx, mac)
if err != nil {
return nil, err
}
var ok bool
ok, err = iface.addrChecker.IsAvailable(l.IP)
ok, err = iface.addrChecker.IsAvailable(lease.IP)
if err != nil {
return nil, fmt.Errorf("checking address availability: %w", err)
}
if ok {
iface.common.leases[macToKey(mac)] = l
iface.common.leases[macToKey(mac)] = lease
off, _ := iface.common.addrSpace.offset(l.IP)
off, _ := iface.common.addrSpace.offset(lease.IP)
iface.common.leasedOffsets.set(off, true)
return l, nil
return lease, nil
}
iface.common.logger.DebugContext(ctx, "address not available", "ip", l.IP)
iface.common.logger.DebugContext(ctx, "address not available", "ip", lease.IP)
err = iface.common.blockLease(ctx, l, iface.clock)
err = iface.common.blockLease(ctx, lease, iface.clock)
if err != nil {
return nil, fmt.Errorf("blocking unavailable address: %w", err)
}
}
}
// reserveLease reserves a lease for a client by its MAC-address. l is nil if a
// new lease can't be allocated. mac must be a valid according to
// reserveLease reserves a lease for a client by its MAC-address. lease is nil
// if a new lease can't be allocated. mac must be a valid according to
// [netutil.ValidateMAC]. index mutex must be locked.
func (iface *dhcpInterfaceV4) reserveLease(
ctx context.Context,
mac net.HardwareAddr,
) (l *Lease, err error) {
) (lease *Lease, err error) {
nextIP := iface.common.nextIP()
if nextIP != (netip.Addr{}) {
l = &Lease{
lease = &Lease{
HWAddr: slices.Clone(mac),
IP: nextIP,
Expiry: iface.clock.Now().Add(iface.common.leaseTTL),
}
return l, nil
return lease, nil
}
l = iface.common.findExpiredLease(iface.clock.Now())
if l == nil {
lease = iface.common.findExpiredLease(iface.clock.Now())
if lease == nil {
return nil, errors.Error("no addresses available to lease")
}
// TODO(e.burkov): Move validation from index methods into server's
// methods and use index here.
delete(iface.common.leases, macToKey(l.HWAddr))
delete(iface.common.leases, macToKey(lease.HWAddr))
idx := iface.common.index
delete(idx.byAddr, l.IP)
delete(idx.byName, strings.ToLower(l.Hostname))
delete(idx.byAddr, lease.IP)
delete(idx.byName, strings.ToLower(lease.Hostname))
err = idx.dbStore(ctx, iface.common.logger)
if err != nil {
@@ -428,37 +403,39 @@ func (iface *dhcpInterfaceV4) reserveLease(
return nil, err
}
l.HWAddr = slices.Clone(mac)
l.Hostname = ""
l.IsStatic = false
l.updateExpiry(iface.clock, iface.common.leaseTTL)
lease.HWAddr = slices.Clone(mac)
lease.Hostname = ""
lease.IsStatic = false
lease.updateExpiry(iface.clock, iface.common.leaseTTL)
iface.common.leases[macToKey(mac)] = l
iface.common.leases[macToKey(mac)] = lease
return l, nil
return lease, nil
}
// updateAndRespond updates the lease and sends a DHCPACK or DHCPNAK response to
// the client according to the update result. req must be a DHCPREQUEST
// message, lease, l, and fd must not be nil.
// the client according to the update result. idOpt is an expected to be the
// value of the DHCP option Client Identifier, nil if not present. req must be
// a DHCPREQUEST message, lease, l, and fd must not be nil.
func (iface *dhcpInterfaceV4) updateAndRespond(
ctx context.Context,
l *slog.Logger,
req *layers.DHCPv4,
lease *Lease,
fd *frameData,
idOpt []byte,
) {
lease.Hostname = cmp.Or(hostname4(req), lease.Hostname)
err := iface.updateLease(ctx, lease)
if err != nil {
l.ErrorContext(ctx, "init-reboot request failed", slogutil.KeyError, err)
iface.respondNAK(ctx, req, fd)
iface.respondNAK(ctx, req, fd, idOpt)
return
}
iface.respondACK(ctx, req, fd, lease)
iface.respondACK(ctx, req, fd, lease, idOpt)
}
const (
@@ -511,19 +488,18 @@ func respond4(fd *frameData, req, resp *layers.DHCPv4) (err error) {
return fd.device.WritePacketData(buf.Bytes())
}
// newIPv4UDPLayers creates new UDP and IP layers for DHCP v4 response. fd,
// req, and res must not be nil.
// newIPv4UDPLayers creates new UDP and IP layers for DHCPv4 response. fd, req,
// and resp must not be nil.
func newIPv4UDPLayers(fd *frameData, req, resp *layers.DHCPv4) (ip *layers.IPv4, udp *layers.UDP) {
var dstIP net.IP
dstPort := ClientPortV4
switch {
case isSpecified(req.RelayAgentIP):
case isSpecified(req.RelayAgentIP.To4()):
// If the 'giaddr' field in a DHCP message from a client is non-zero,
// the server sends any return messages to the 'DHCP server' port on the
// BOOTP relay agent whose address appears in 'giaddr'.
dstIP = req.RelayAgentIP.To4()
dstPort = ServerPortV4
case isSpecified(req.ClientIP) && resp.Flags&FlagsBroadcast == 0:
dstIP, dstPort = req.RelayAgentIP.To4(), ServerPortV4
case isSpecified(req.ClientIP.To4()):
// If the 'giaddr' field is zero and the 'ciaddr' field is nonzero, then
// the server unicasts DHCPOFFER and DHCPACK messages to the address in
// 'ciaddr'.