feat(core): DHCP in the simulation core, as in Swift
engine.ts ports Swift's "DHCP server and automatic client": an active server listens on port 67 from the start and offers a static assignment before its range, round from the address after the last one offered; offers last 10 s, dynamic leases a day, and a server whose offer another server beat blacklists that address for a while. A client starts as an event: DISCOVER, OFFER, a check by ARP, DECLINE, REQUEST, ACK or NAK, 2.5 s per wait, and after ten failures its old address back. The snapshot carries the DHCP settings of clients and servers. Four scenarios match the Swift engine. One Swift error is named in the oracle test: a client run directly is advanced a second time, to FINISH, by the server's answer within its own DISCOVER, and the outer run then writes back its stale copy of the status (Swift's value types); the address and every trace agree, only the reported status is wrong in Swift. Swift's three DHCP engine tests are ported, with tests for stopping and the message format. 15 mutation probes, 14 caught; the other concerns the home router, which runs only once NAT is ported. Two departures from Java remain, to be fixed next: from the event queue the client's ARP check does not wait, so an address conflict is never found, and each answer that wakes the client makes it send its state's message again (a second DISCOVER and REQUEST, the second answered with NAK). Java waits a round trip and sends once per attempt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,12 +1,17 @@
|
||||
// Ported from filius-ipad ios/FiliusPadTests/TopologyNetworkRuntimeEngineTests.swift:
|
||||
// the event queue, the virtual clock, Java-compatible randomness, restart,
|
||||
// Ethernet/switch/ARP/IPv4/ICMP, routing errors, the firewall, packet loss
|
||||
// and trace retention, UDP and TCP sockets. The remaining Swift tests (DHCP,
|
||||
// DNS, RIP, NAT, remote link, packet viewer) follow with their protocol
|
||||
// and trace retention, UDP and TCP sockets, DHCP. The remaining Swift tests
|
||||
// (DNS, RIP, NAT, remote link, packet viewer) follow with their protocol
|
||||
// slices.
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
decodeDhcpMessage,
|
||||
DHCP_DYNAMIC_LEASE_LIFETIME_MILLISECONDS,
|
||||
deviceConfiguration,
|
||||
dhcpServerConfiguration,
|
||||
encodeDhcpMessage,
|
||||
EMPTY_TOPOLOGY_SNAPSHOT,
|
||||
ETHERNET_BROADCAST_MAC_ADDRESS,
|
||||
firewallConfiguration,
|
||||
@@ -26,6 +31,8 @@ import {
|
||||
topologySnapshot,
|
||||
traceRetentionPolicy,
|
||||
UNSPECIFIED_MAC_ADDRESS,
|
||||
type DeviceConfiguration,
|
||||
type DhcpServerConfiguration,
|
||||
type EthernetFrame,
|
||||
type EthernetPayload,
|
||||
type FirewallConfiguration,
|
||||
@@ -212,6 +219,36 @@ describe('event queue and virtual clock', () => {
|
||||
expect(engine.bindUdpSocket(nodeId, { localPort: 7 })).toBe(uuid(1));
|
||||
});
|
||||
|
||||
it('forgets DHCP leases and client state on stop', () => {
|
||||
const [serverId, serverPortId, clientId, clientPortId] = [0x31, 0x32, 0x33, 0x34].map(uuid) as [string, string, string, string];
|
||||
const engine = startedEngine({
|
||||
nodes: [pc(serverId, serverPortId), pc(clientId, clientPortId)],
|
||||
links: [link(serverId, serverPortId, clientId, clientPortId)],
|
||||
deviceConfigurations: new Map([
|
||||
[serverId, device('10.4.0.1')],
|
||||
[clientId, device('0.0.0.0')],
|
||||
]),
|
||||
dhcpClientConfigurationsByNodeId: new Map([[clientId, { isEnabled: true }]]),
|
||||
dhcpServerConfigurationsByNodeId: new Map([
|
||||
[serverId, dhcpServerConfiguration({ isActive: true, lowerBoundIPAddress: '10.4.0.20', upperBoundIPAddress: '10.4.0.29' })],
|
||||
]),
|
||||
});
|
||||
engine.handle({ type: 'advance', toMilliseconds: 1_000 });
|
||||
expect(engine.state.dhcpLeasesByIPAddress.size).toBe(1);
|
||||
|
||||
engine.handle({ type: 'stop' });
|
||||
const state = engine.state;
|
||||
expect([
|
||||
state.dhcpOffersByIPAddress.size,
|
||||
state.dhcpLeasesByIPAddress.size,
|
||||
state.dhcpBlacklistByServerNodeId.size,
|
||||
state.dhcpLastOfferedAddressByServerNodeId.size,
|
||||
state.dhcpServerSocketIdsByNodeId.size,
|
||||
state.dhcpClientStatusesByNodeId.size,
|
||||
state.dhcpClientContextsByNodeId.size,
|
||||
]).toEqual([0, 0, 0, 0, 0, 0, 0]);
|
||||
});
|
||||
|
||||
it('forgets TCP sessions and accepted sockets on stop', () => {
|
||||
const [clientId, clientPortId, serverId, serverPortId] = [0x21, 0x22, 0x23, 0x24].map(uuid) as [string, string, string, string];
|
||||
const engine = startedEngine({
|
||||
@@ -867,3 +904,108 @@ describe('TCP sockets', () => {
|
||||
expect(engine.state.socketsById.get(listenerId)?.tcpState).toBe('LISTEN');
|
||||
});
|
||||
});
|
||||
|
||||
describe('DHCP', () => {
|
||||
const serverAndClient = (first: number, serverIp: string, client: DeviceConfiguration, server: Partial<DhcpServerConfiguration>) => {
|
||||
const [serverId, serverPortId, clientId, clientPortId] = [first, first + 1, first + 2, first + 3].map(uuid) as [string, string, string, string];
|
||||
const engine = startedEngine(
|
||||
{
|
||||
nodes: [pc(serverId, serverPortId), pc(clientId, clientPortId)],
|
||||
links: [link(serverId, serverPortId, clientId, clientPortId)],
|
||||
deviceConfigurations: new Map([
|
||||
[serverId, device(serverIp)],
|
||||
[clientId, client],
|
||||
]),
|
||||
dhcpClientConfigurationsByNodeId: new Map([[clientId, { isEnabled: true }]]),
|
||||
dhcpServerConfigurationsByNodeId: new Map([[serverId, dhcpServerConfiguration({ isActive: true, ...server })]]),
|
||||
},
|
||||
16,
|
||||
);
|
||||
return { engine, clientId, clientPortId };
|
||||
};
|
||||
|
||||
it('completes DISCOVER, OFFER, REQUEST and ACK and applies the configuration', () => {
|
||||
const { engine, clientId } = serverAndClient(0x1601, '192.168.50.1', device('169.254.1.2', { mask: '0.0.0.0' }), {
|
||||
lowerBoundIPAddress: '192.168.50.20',
|
||||
upperBoundIPAddress: '192.168.50.29',
|
||||
gatewayIPAddress: '192.168.50.1',
|
||||
dnsServerIPAddress: '192.168.50.53',
|
||||
useOwnSettings: true,
|
||||
});
|
||||
|
||||
engine.handle({ type: 'advance', toMilliseconds: 1_000 });
|
||||
|
||||
expect(engine.state.topologySnapshot.deviceConfigurations.get(clientId)).toEqual(
|
||||
deviceConfiguration('192.168.50.20', '255.255.255.0', '192.168.50.1', '192.168.50.53'),
|
||||
);
|
||||
const status = engine.state.dhcpClientStatusesByNodeId.get(clientId);
|
||||
expect([status?.state, status?.errorCount, status?.succeeded]).toEqual(['FINISH', 0, true]);
|
||||
const leaseExpiry = [...engine.state.dhcpLeasesByIPAddress.values()][0]?.expiresAtMilliseconds;
|
||||
expect(leaseExpiry).toBeGreaterThan(engine.state.currentTimeMilliseconds);
|
||||
expect(leaseExpiry! - engine.state.currentTimeMilliseconds).toBeLessThanOrEqual(DHCP_DYNAMIC_LEASE_LIFETIME_MILLISECONDS);
|
||||
const details = engine.state.packetTraces.map((trace) => trace.detail);
|
||||
for (const message of ['DHCPDISCOVER', 'DHCPOFFER', 'DHCPREQUEST', 'DHCPACK']) expect(details).toContain(message);
|
||||
});
|
||||
|
||||
it('matches a static assignment regardless of case, with a lease that does not expire', () => {
|
||||
const clientPortId = uuid(0x1611 + 3);
|
||||
const { engine, clientId } = serverAndClient(0x1611, '10.0.0.1', device('0.0.0.0'), {
|
||||
lowerBoundIPAddress: '10.0.0.20',
|
||||
upperBoundIPAddress: '10.0.0.20',
|
||||
staticAssignments: [{ id: 'static', macAddress: stableMacAddress(clientPortId).toLowerCase(), ipAddress: '10.0.0.99' }],
|
||||
});
|
||||
|
||||
engine.handle({ type: 'advance', toMilliseconds: 1_000 });
|
||||
|
||||
expect(engine.state.topologySnapshot.deviceConfigurations.get(clientId)?.ipAddress).toBe('10.0.0.99');
|
||||
expect([...engine.state.dhcpLeasesByIPAddress.values()][0]?.expiresAtMilliseconds).toBeUndefined();
|
||||
});
|
||||
|
||||
it('retries ten timeouts and gives back only the old address', () => {
|
||||
const clientId = uuid(0x1621);
|
||||
const oldConfiguration = deviceConfiguration('169.254.5.7', '255.255.0.0', '169.254.0.1', '169.254.0.53');
|
||||
const engine = startedEngine(
|
||||
{
|
||||
nodes: [pc(clientId, uuid(0x1622))],
|
||||
links: [],
|
||||
deviceConfigurations: new Map([[clientId, oldConfiguration]]),
|
||||
dhcpClientConfigurationsByNodeId: new Map([[clientId, { isEnabled: true }]]),
|
||||
},
|
||||
16,
|
||||
);
|
||||
|
||||
engine.handle({ type: 'advance', toMilliseconds: 0 });
|
||||
expect(engine.state.topologySnapshot.deviceConfigurations.get(clientId)?.ipAddress).toBe('0.0.0.0');
|
||||
expect(engine.state.dhcpClientStatusesByNodeId.get(clientId)?.state).toBe('DISCOVER');
|
||||
expect(engine.state.dhcpClientStatusesByNodeId.get(clientId)?.errorCount).toBe(0);
|
||||
|
||||
engine.handle({ type: 'advance', toMilliseconds: 25_000 });
|
||||
|
||||
const status = engine.state.dhcpClientStatusesByNodeId.get(clientId);
|
||||
expect([status?.state, status?.errorCount, status?.succeeded]).toEqual(['FINISH', 10, false]);
|
||||
expect(engine.state.topologySnapshot.deviceConfigurations.get(clientId)).toEqual(oldConfiguration);
|
||||
expect(engine.state.dhcpClientContextsByNodeId.has(clientId)).toBe(false);
|
||||
expect(engine.state.socketsById.size).toBe(0);
|
||||
});
|
||||
|
||||
it("writes and reads a message in Swift's text format", () => {
|
||||
const message = {
|
||||
type: 'DHCPOFFER' as const,
|
||||
yourIPAddress: '10.0.0.5',
|
||||
clientMacAddress: '02:00:00:00:00:01',
|
||||
subnetMask: '255.255.255.0',
|
||||
routerIPAddress: '10.0.0.1',
|
||||
dnsServerIPAddress: '10.0.0.53',
|
||||
requestedIPAddress: '',
|
||||
serverIdentifier: '10.0.0.1',
|
||||
};
|
||||
const text = new TextDecoder().decode(encodeDhcpMessage(message));
|
||||
expect(text).toBe(
|
||||
'DHCPOFFER\nyiaddr=10.0.0.5\nchaddr=02:00:00:00:00:01\nrouter=10.0.0.1\nsubnetmask=255.255.255.0\ndnsserver=10.0.0.53\nserverident=10.0.0.1',
|
||||
);
|
||||
const { requestedIPAddress: _empty, ...withoutEmpty } = message;
|
||||
expect(decodeDhcpMessage(new TextEncoder().encode(text))).toEqual(withoutEmpty);
|
||||
expect(decodeDhcpMessage(new TextEncoder().encode('dhcpack\nyiaddr=1.2.3.4\nnoise'))).toEqual({ type: 'DHCPACK', yourIPAddress: '1.2.3.4' });
|
||||
expect(decodeDhcpMessage(new TextEncoder().encode('HELLO'))).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user