feat(core): event queue, Ethernet, switch, ARP, IPv4, ICMP, routing and firewall
First slice of the TypeScript port of the filius-ipad runtime engine, with 29 tests ported from the Swift suite. Parts not ported yet throw NotPortedError instead of guessing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"name": "@mdg-filius/core",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"license": "GPL-3.0-only",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Ported from filius-ipad (GPLv2/GPLv3), ios/FiliusPad/TopologyEditor.
|
||||
// Swift orders identifiers by `UUID.uuidString`, which is upper case. Every
|
||||
// deterministic ordering in the runtime depends on it, so identifiers are
|
||||
// compared the same way here whatever case they were written in.
|
||||
|
||||
/** A node, port, link or socket identifier: a UUID string. */
|
||||
export type Id = string;
|
||||
|
||||
/** `lhs.uuidString < rhs.uuidString` in Swift. */
|
||||
export function idLess(lhs: Id, rhs: Id): boolean {
|
||||
return lhs.toUpperCase() < rhs.toUpperCase();
|
||||
}
|
||||
|
||||
/** Comparator for `Array.prototype.sort` with the Swift ordering. */
|
||||
export function compareIds(lhs: Id, rhs: Id): number {
|
||||
const left = lhs.toUpperCase();
|
||||
const right = rhs.toUpperCase();
|
||||
return left < right ? -1 : left > right ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Public surface of the simulation core.
|
||||
export * from './ids.js';
|
||||
export * from './model/node.js';
|
||||
export * from './runtime/config.js';
|
||||
export * from './runtime/engine.js';
|
||||
export * from './runtime/ipv4.js';
|
||||
export * from './runtime/packets.js';
|
||||
export * from './runtime/random.js';
|
||||
export * from './runtime/routeTable.js';
|
||||
export * from './runtime/snapshot.js';
|
||||
export * from './runtime/speed.js';
|
||||
export * from './runtime/trace.js';
|
||||
export * from './util/equal.js';
|
||||
@@ -0,0 +1,102 @@
|
||||
// Ported from filius-ipad (GPLv2/GPLv3):
|
||||
// ios/FiliusPad/TopologyEditor/Model/TopologyNode.swift
|
||||
// Java counterpart: filius.hardware.knoten.* (port counts per device kind).
|
||||
|
||||
import type { Id } from '../ids.js';
|
||||
|
||||
export type NodeKind =
|
||||
| 'pc'
|
||||
| 'notebook'
|
||||
| 'networkSwitch'
|
||||
| 'router'
|
||||
| 'gateway'
|
||||
| 'remoteLink'
|
||||
| 'unsupported';
|
||||
|
||||
export function isPcClassEndpoint(kind: NodeKind): boolean {
|
||||
return kind === 'pc' || kind === 'notebook';
|
||||
}
|
||||
|
||||
export type HostLabelPolicy = 'manual' | 'ipAddress' | 'macAddress' | 'ipAndMAC';
|
||||
|
||||
export interface PortMetadata {
|
||||
readonly id: Id;
|
||||
label: string;
|
||||
isOccupied: boolean;
|
||||
/** Canonical (upper case, colon separated) or undefined. */
|
||||
readonly importedMacAddress?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The MAC address of a port nobody gave one: `02:` followed by the last ten
|
||||
* hex digits of the port's UUID — stable across saves, locally administered.
|
||||
*/
|
||||
export function stableGeneratedMacAddress(portId: Id): string {
|
||||
const compact = portId.toUpperCase().replaceAll('-', '');
|
||||
const suffix = compact.slice(-10);
|
||||
const octets = ['02'];
|
||||
for (let offset = 0; offset < suffix.length; offset += 2) {
|
||||
octets.push(suffix.slice(offset, offset + 2).toUpperCase());
|
||||
}
|
||||
return octets.join(':');
|
||||
}
|
||||
|
||||
/** Six colon-separated pairs of hex digits, upper-cased; anything else is undefined. */
|
||||
export function canonicalMacAddress(value: string | undefined | null): string | undefined {
|
||||
if (value === undefined || value === null) return undefined;
|
||||
const segments = value.trim().split(':');
|
||||
if (segments.length !== 6) return undefined;
|
||||
if (!segments.every((segment) => /^[0-9A-Fa-f]{2}$/.test(segment))) return undefined;
|
||||
return segments.map((segment) => segment.toUpperCase()).join(':');
|
||||
}
|
||||
|
||||
export function effectiveMacAddress(port: PortMetadata): string {
|
||||
return port.importedMacAddress ?? stableGeneratedMacAddress(port.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* The name a new device gets. These are the Java FILIUS device names; the
|
||||
* editor shows them translated (packages/editor i18n), the model keeps them
|
||||
* as they appear in a Java .fls file.
|
||||
*/
|
||||
export function defaultDisplayName(kind: NodeKind): string {
|
||||
switch (kind) {
|
||||
case 'pc':
|
||||
return 'Rechner';
|
||||
case 'notebook':
|
||||
return 'Notebook';
|
||||
case 'networkSwitch':
|
||||
return 'Switch';
|
||||
case 'router':
|
||||
return 'Vermittlungsrechner';
|
||||
case 'gateway':
|
||||
return 'Gateway';
|
||||
case 'remoteLink':
|
||||
return 'Remote Link';
|
||||
case 'unsupported':
|
||||
return 'Unbekanntes Gerät';
|
||||
}
|
||||
}
|
||||
|
||||
/** Labels of the ports a new device of this kind has, in order. */
|
||||
export function defaultPortLabels(kind: NodeKind): string[] {
|
||||
switch (kind) {
|
||||
case 'pc':
|
||||
case 'notebook':
|
||||
return ['eth0'];
|
||||
case 'networkSwitch':
|
||||
// Java Switch constructs exactly 24 physical ports.
|
||||
return Array.from({ length: 24 }, (_, index) => `sw${index + 1}`);
|
||||
case 'router':
|
||||
// Java Vermittlungsrechner starts with one configurable network interface.
|
||||
return ['rt1'];
|
||||
case 'gateway':
|
||||
// Java Gateway has fixed WAN (index 0) and LAN (index 1) interfaces.
|
||||
return ['wan0', 'lan0'];
|
||||
case 'remoteLink':
|
||||
// One local physical attachment, matching the Java Modem.
|
||||
return ['remote0'];
|
||||
case 'unsupported':
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
// Ported from filius-ipad (GPLv2/GPLv3):
|
||||
// State/TopologyEditorState.swift (runtime configuration value types)
|
||||
|
||||
import type { Id } from '../ids.js';
|
||||
import { maskAddress, parseIPv4 } from './ipv4.js';
|
||||
|
||||
/** The IP settings of a PC or notebook (its single interface) — and a router's gateway. */
|
||||
export interface DeviceConfiguration {
|
||||
readonly ipAddress: string;
|
||||
readonly subnetMask: string;
|
||||
readonly defaultGateway: string;
|
||||
readonly dnsServer: string;
|
||||
}
|
||||
|
||||
export function deviceConfiguration(
|
||||
ipAddress: string,
|
||||
subnetMask: string,
|
||||
defaultGateway = '',
|
||||
dnsServer = '',
|
||||
): DeviceConfiguration {
|
||||
return { ipAddress, subnetMask, defaultGateway, dnsServer };
|
||||
}
|
||||
|
||||
/** One interface of a router or gateway. */
|
||||
export interface InterfaceConfiguration {
|
||||
readonly ipAddress: string;
|
||||
readonly subnetMask: string;
|
||||
}
|
||||
|
||||
/** Map key for an interface: node and port. */
|
||||
export type InterfaceKey = string;
|
||||
|
||||
export function interfaceKey(nodeId: Id, portId: Id): InterfaceKey {
|
||||
return `${nodeId}/${portId}`;
|
||||
}
|
||||
|
||||
/** A row of the manual routing table (Java `Weiterleitungstabelle`). */
|
||||
export interface ManualRoute {
|
||||
readonly destinationNetwork: string;
|
||||
readonly subnetMask: string;
|
||||
readonly gateway: string;
|
||||
readonly interfaceIPAddress: string;
|
||||
}
|
||||
|
||||
/** Longest numeric mask wins; on a tie the first row stays. */
|
||||
export function bestMatchingManualRoute(
|
||||
targetIPAddress: string,
|
||||
routes: readonly ManualRoute[],
|
||||
): ManualRoute | undefined {
|
||||
const target = parseIPv4(targetIPAddress);
|
||||
if (target === undefined) return undefined;
|
||||
let best: ManualRoute | undefined;
|
||||
let bestMask: number | undefined;
|
||||
for (const route of routes) {
|
||||
const destination = parseIPv4(route.destinationNetwork);
|
||||
const mask = parseIPv4(route.subnetMask);
|
||||
if (destination === undefined || mask === undefined) continue;
|
||||
if (destination !== maskAddress(target, mask)) continue;
|
||||
if (bestMask !== undefined && mask <= bestMask) continue;
|
||||
bestMask = mask;
|
||||
best = route;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
export interface SwitchConfiguration {
|
||||
readonly ssid: string;
|
||||
readonly retentionTimeMilliseconds: number;
|
||||
}
|
||||
|
||||
/** Java SwitchFirmware keeps a learned MAC address for five minutes. */
|
||||
export const DEFAULT_SWITCH_RETENTION_MILLISECONDS = 300_000;
|
||||
|
||||
export function switchConfiguration(
|
||||
ssid: string,
|
||||
retentionTimeMilliseconds = DEFAULT_SWITCH_RETENTION_MILLISECONDS,
|
||||
): SwitchConfiguration {
|
||||
return { ssid, retentionTimeMilliseconds };
|
||||
}
|
||||
|
||||
/** The first six hex digits of the node's UUID, lower case. */
|
||||
export function defaultSwitchConfiguration(nodeId: Id): SwitchConfiguration {
|
||||
const compact = nodeId.replaceAll('-', '').toLowerCase();
|
||||
return switchConfiguration(compact.slice(0, 6));
|
||||
}
|
||||
|
||||
// ── Firewall (Java filius.software.firewall.Firewall, FirewallRule) ─────────
|
||||
|
||||
export const FIREWALL_PROTOCOL = { all: -1, icmp: 1, tcp: 6, udp: 17 } as const;
|
||||
export type FirewallProtocol = keyof typeof FIREWALL_PROTOCOL;
|
||||
|
||||
export type FirewallAction = 'drop' | 'accept';
|
||||
|
||||
/** Java writes this as the source of a rule that means "any directly connected network". */
|
||||
export const DIRECTLY_CONNECTED_SOURCE_MARKER = '999.999.999.999';
|
||||
export const ALL_PORTS = -1;
|
||||
|
||||
export interface FirewallRule {
|
||||
readonly sourceIPAddress: string;
|
||||
readonly sourceSubnetMask: string;
|
||||
readonly destinationIPAddress: string;
|
||||
readonly destinationSubnetMask: string;
|
||||
/** A port number or ALL_PORTS. */
|
||||
readonly port: number;
|
||||
readonly protocol: FirewallProtocol;
|
||||
readonly action: FirewallAction;
|
||||
}
|
||||
|
||||
export function firewallRule(fields: Partial<FirewallRule> = {}): FirewallRule {
|
||||
return {
|
||||
sourceIPAddress: fields.sourceIPAddress ?? '',
|
||||
sourceSubnetMask: fields.sourceSubnetMask ?? '',
|
||||
destinationIPAddress: fields.destinationIPAddress ?? '',
|
||||
destinationSubnetMask: fields.destinationSubnetMask ?? '',
|
||||
port: fields.port ?? ALL_PORTS,
|
||||
protocol: fields.protocol ?? 'tcp',
|
||||
action: fields.action ?? 'drop',
|
||||
};
|
||||
}
|
||||
|
||||
export interface FirewallConfiguration {
|
||||
readonly isActive: boolean;
|
||||
readonly defaultPolicy: FirewallAction;
|
||||
readonly dropIcmp: boolean;
|
||||
readonly filterSynSegmentsOnly: boolean;
|
||||
readonly filterUdp: boolean;
|
||||
readonly rules: readonly FirewallRule[];
|
||||
}
|
||||
|
||||
/** What a router or gateway has without a firewall configured: inactive. */
|
||||
export function firewallConfiguration(fields: Partial<FirewallConfiguration> = {}): FirewallConfiguration {
|
||||
return {
|
||||
isActive: fields.isActive ?? false,
|
||||
defaultPolicy: fields.defaultPolicy ?? 'drop',
|
||||
dropIcmp: fields.dropIcmp ?? false,
|
||||
filterSynSegmentsOnly: fields.filterSynSegmentsOnly ?? true,
|
||||
filterUdp: fields.filterUdp ?? true,
|
||||
rules: fields.rules ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
/** What Java installs as the personal firewall of a PC: active, drop by default. */
|
||||
export const JAVA_PERSONAL_FIREWALL_DEFAULTS: FirewallConfiguration = firewallConfiguration({
|
||||
isActive: true,
|
||||
defaultPolicy: 'drop',
|
||||
dropIcmp: false,
|
||||
filterSynSegmentsOnly: true,
|
||||
filterUdp: true,
|
||||
rules: [],
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,48 @@
|
||||
// Ported from filius-ipad (GPLv2/GPLv3):
|
||||
// State/TopologyNetworkRuntimeEngine.swift (parseIPv4, sameSubnet)
|
||||
// State/TopologyEditorState.swift (TopologyRuntimeManualRoute.parseIPv4)
|
||||
//
|
||||
// Two parsers exist on purpose, as in the Swift source: the runtime reads an
|
||||
// octet the way Swift's `UInt8(String)` does, the route editor the way Java
|
||||
// FILIUS validates its table cells (see routeTable.ts).
|
||||
|
||||
/**
|
||||
* Swift `UInt8(segment)`: an optional sign, then decimal digits, value 0…255.
|
||||
* Leading zeros are allowed ("007" is 7), whitespace is not.
|
||||
*/
|
||||
function parseSwiftOctet(segment: string): number | undefined {
|
||||
if (!/^[+-]?[0-9]+$/.test(segment)) return undefined;
|
||||
const value = Number(segment);
|
||||
if (!Number.isInteger(value) || value < 0 || value > 255) return undefined;
|
||||
return Object.is(value, -0) ? 0 : value;
|
||||
}
|
||||
|
||||
/** Dotted quad to an unsigned 32-bit number, or undefined. */
|
||||
export function parseIPv4(value: string): number | undefined {
|
||||
const segments = value.split('.');
|
||||
if (segments.length !== 4) return undefined;
|
||||
let address = 0;
|
||||
for (const segment of segments) {
|
||||
const octet = parseSwiftOctet(segment);
|
||||
if (octet === undefined) return undefined;
|
||||
address = ((address << 8) | octet) >>> 0;
|
||||
}
|
||||
return address;
|
||||
}
|
||||
|
||||
export function formatIPv4(address: number): string {
|
||||
return [24, 16, 8, 0].map((shift) => String((address >>> shift) & 0xff)).join('.');
|
||||
}
|
||||
|
||||
export function sameSubnet(lhs: string, rhs: string, mask: string): boolean {
|
||||
const left = parseIPv4(lhs);
|
||||
const right = parseIPv4(rhs);
|
||||
const netmask = parseIPv4(mask);
|
||||
if (left === undefined || right === undefined || netmask === undefined) return false;
|
||||
return ((left & netmask) >>> 0) === ((right & netmask) >>> 0);
|
||||
}
|
||||
|
||||
/** `address & mask` as an unsigned number. */
|
||||
export function maskAddress(address: number, mask: number): number {
|
||||
return (address & mask) >>> 0;
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// Ported from filius-ipad (GPLv2/GPLv3):
|
||||
// State/TopologyNetworkRuntimeEngine.swift ("Java-observable packet and route models")
|
||||
// Frames and packets are typed values, not bytes — what the Java packet viewer
|
||||
// shows, not what a real wire would carry.
|
||||
|
||||
export interface EthernetFrame {
|
||||
readonly identity: number;
|
||||
readonly sourceMacAddress: string;
|
||||
readonly destinationMacAddress: string;
|
||||
readonly payload: EthernetPayload;
|
||||
}
|
||||
|
||||
export type EthernetPayload =
|
||||
| { readonly kind: 'arp'; readonly packet: ArpPacket }
|
||||
| { readonly kind: 'ipv4'; readonly packet: IPv4Packet };
|
||||
|
||||
export type ArpOperation = 'request' | 'reply';
|
||||
|
||||
export interface ArpPacket {
|
||||
readonly operation: ArpOperation;
|
||||
readonly senderMacAddress: string;
|
||||
readonly senderIPAddress: string;
|
||||
readonly targetMacAddress: string;
|
||||
readonly targetIPAddress: string;
|
||||
}
|
||||
|
||||
export const IPV4_PROTOCOL = { icmp: 1, tcp: 6, udp: 17 } as const;
|
||||
export type IPv4Protocol = keyof typeof IPV4_PROTOCOL;
|
||||
|
||||
export interface IPv4Packet {
|
||||
readonly identity: number;
|
||||
readonly senderIPAddress: string;
|
||||
readonly receiverIPAddress: string;
|
||||
/** 0…255 */
|
||||
readonly timeToLive: number;
|
||||
readonly protocol: IPv4Protocol;
|
||||
readonly payload: IPv4Payload;
|
||||
}
|
||||
|
||||
export type IPv4Payload =
|
||||
| { readonly kind: 'icmp'; readonly message: IcmpMessage }
|
||||
| { readonly kind: 'tcp'; readonly segment: TcpSegment }
|
||||
| { readonly kind: 'udp'; readonly datagram: UdpDatagram };
|
||||
|
||||
/** The same packet one hop further: identity kept, TTL lowered, never below 0. */
|
||||
export function forwardingClone(packet: IPv4Packet, decrementingTtlBy = 1): IPv4Packet {
|
||||
return {
|
||||
...packet,
|
||||
timeToLive: decrementingTtlBy >= packet.timeToLive ? 0 : packet.timeToLive - decrementingTtlBy,
|
||||
};
|
||||
}
|
||||
|
||||
export type IcmpMessageKind =
|
||||
| 'echoRequest'
|
||||
| 'echoReply'
|
||||
| 'destinationNetworkUnreachable'
|
||||
| 'destinationHostUnreachable'
|
||||
| 'timeExceeded';
|
||||
|
||||
export interface IcmpMessage {
|
||||
readonly kind: IcmpMessageKind;
|
||||
/** 0…65535 */
|
||||
readonly identifier: number;
|
||||
/** 0…65535 */
|
||||
readonly sequenceNumber: number;
|
||||
readonly data: Uint8Array;
|
||||
readonly embeddedOriginalPacket?: IPv4Packet;
|
||||
}
|
||||
|
||||
export function icmpMessage(
|
||||
kind: IcmpMessageKind,
|
||||
fields: Partial<Omit<IcmpMessage, 'kind'>> = {},
|
||||
): IcmpMessage {
|
||||
const message: IcmpMessage = {
|
||||
kind,
|
||||
identifier: fields.identifier ?? 0,
|
||||
sequenceNumber: fields.sequenceNumber ?? 0,
|
||||
data: fields.data ?? new Uint8Array(),
|
||||
};
|
||||
return fields.embeddedOriginalPacket === undefined
|
||||
? message
|
||||
: { ...message, embeddedOriginalPacket: fields.embeddedOriginalPacket };
|
||||
}
|
||||
|
||||
export const TCP_FLAG = {
|
||||
finish: 1 << 0,
|
||||
synchronize: 1 << 1,
|
||||
reset: 1 << 2,
|
||||
push: 1 << 3,
|
||||
acknowledgement: 1 << 4,
|
||||
} as const;
|
||||
|
||||
export type TcpSocketState =
|
||||
| 'CLOSED'
|
||||
| 'LISTEN'
|
||||
| 'SYN_RCVD'
|
||||
| 'SYN_SENT'
|
||||
| 'ESTABLISHED'
|
||||
| 'CLOSE_WAIT'
|
||||
| 'LAST_ACK'
|
||||
| 'FIN_WAIT_1'
|
||||
| 'FIN_WAIT_2'
|
||||
| 'CLOSING'
|
||||
| 'TIME_WAIT';
|
||||
|
||||
export interface TcpSegment {
|
||||
readonly sourcePort: number;
|
||||
readonly destinationPort: number;
|
||||
readonly sequenceNumber: number;
|
||||
readonly acknowledgementNumber: number;
|
||||
/** Bit set of TCP_FLAG values. */
|
||||
readonly flags: number;
|
||||
readonly payload: Uint8Array;
|
||||
}
|
||||
|
||||
export interface UdpDatagram {
|
||||
readonly sourcePort: number;
|
||||
readonly destinationPort: number;
|
||||
readonly payload: Uint8Array;
|
||||
}
|
||||
|
||||
export function packetIdentityInFrame(frame: EthernetFrame): number | undefined {
|
||||
return frame.payload.kind === 'ipv4' ? frame.payload.packet.identity : undefined;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// Ported from filius-ipad (GPLv2/GPLv3):
|
||||
// State/TopologyNetworkRuntimeEngine.swift (TopologyJavaCompatibleRandom)
|
||||
// A bit-exact java.util.Random: the 48-bit linear congruential generator
|
||||
// Java FILIUS draws its RIP beacon jitter and ephemeral ports from. BigInt
|
||||
// keeps the 48-bit arithmetic exact; a double would lose the low bits.
|
||||
|
||||
const MULTIPLIER = 0x5deece66dn;
|
||||
const ADDEND = 0xbn;
|
||||
const MASK = (1n << 48n) - 1n;
|
||||
const INT32_MAX = 2147483647n;
|
||||
|
||||
export class JavaCompatibleRandom {
|
||||
private state: bigint;
|
||||
|
||||
constructor(seed: bigint | number) {
|
||||
this.state = (BigInt.asUintN(64, BigInt(seed)) ^ MULTIPLIER) & MASK;
|
||||
}
|
||||
|
||||
/** The internal 48-bit state, for tests and for copying a generator. */
|
||||
get seed(): bigint {
|
||||
return this.state;
|
||||
}
|
||||
|
||||
clone(): JavaCompatibleRandom {
|
||||
const copy = new JavaCompatibleRandom(0);
|
||||
copy.state = this.state;
|
||||
return copy;
|
||||
}
|
||||
|
||||
next(bits: number): number {
|
||||
if (!(bits > 0 && bits <= 32)) throw new RangeError(`bits out of range: ${bits}`);
|
||||
this.state = (this.state * MULTIPLIER + ADDEND) & MASK;
|
||||
return Number(this.state >> BigInt(48 - bits));
|
||||
}
|
||||
|
||||
nextInt(upperBound: number): number {
|
||||
if (!(upperBound > 0)) throw new RangeError(`upperBound must be positive: ${upperBound}`);
|
||||
const bound = BigInt(upperBound);
|
||||
if ((upperBound & -upperBound) === upperBound) {
|
||||
return Number((bound * BigInt(this.next(31))) >> 31n);
|
||||
}
|
||||
for (;;) {
|
||||
const bits = BigInt(this.next(31));
|
||||
const value = bits % bound;
|
||||
if (bits - value + (bound - 1n) <= INT32_MAX) return Number(value);
|
||||
}
|
||||
}
|
||||
|
||||
nextFloat(): number {
|
||||
return Math.fround(this.next(24) / (1 << 24));
|
||||
}
|
||||
|
||||
/** Java RIP: 30 s · (f/3 + 0.84), truncated — somewhere between 25.2 s and 35.2 s. */
|
||||
nextRipJitterMilliseconds(): number {
|
||||
const javaFloat = this.nextFloat();
|
||||
return Math.trunc(30_000.0 * (javaFloat / 3.0 + 0.84));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
// Ported from filius-ipad (GPLv2/GPLv3):
|
||||
// State/TopologyJavaRouteTable.swift (row projection, validation, drafts)
|
||||
// Java counterpart: filius.software.vermittlungsschicht.Weiterleitungstabelle
|
||||
// (holeTabelle: the order of the generated rows).
|
||||
// The Swift file also carries table geometry for SwiftUI; that belongs to the
|
||||
// editor and is not ported here.
|
||||
|
||||
import { formatIPv4, maskAddress } from './ipv4.js';
|
||||
import type { InterfaceConfiguration, ManualRoute } from './config.js';
|
||||
|
||||
export type RouteOrigin = 'localHost' | 'connected' | 'localhost' | 'manual' | 'defaultGateway' | 'rip';
|
||||
|
||||
export interface RouteRow {
|
||||
readonly destinationNetwork: string;
|
||||
readonly subnetMask: string;
|
||||
readonly nextHop: string;
|
||||
readonly interfaceIPAddress: string;
|
||||
readonly origin: RouteOrigin;
|
||||
readonly isEditable: boolean;
|
||||
readonly metric?: number;
|
||||
readonly expiresAtMilliseconds?: number;
|
||||
}
|
||||
|
||||
export type RouteTableColumn = 'destination' | 'subnetMask' | 'nextGateway' | 'interface';
|
||||
|
||||
/**
|
||||
* A Java table octet: digits only, leading zeros allowed, at most three
|
||||
* significant digits, 0…255 ("001" is valid, " 1" and "+1" are not).
|
||||
*/
|
||||
function parseJavaOctet(segment: string): number | undefined {
|
||||
if (segment.length === 0 || !/^[0-9]+$/.test(segment)) return undefined;
|
||||
const significant = segment.replace(/^0+/, '');
|
||||
if (significant.length === 0) return 0;
|
||||
if (significant.length > 3) return undefined;
|
||||
const value = Number(significant);
|
||||
return value <= 255 ? value : undefined;
|
||||
}
|
||||
|
||||
function parseJavaIPv4(value: string): number | undefined {
|
||||
const segments = value.split('.');
|
||||
if (segments.length !== 4) return undefined;
|
||||
let address = 0;
|
||||
for (const segment of segments) {
|
||||
const octet = parseJavaOctet(segment);
|
||||
if (octet === undefined) return undefined;
|
||||
address = ((address << 8) | octet) >>> 0;
|
||||
}
|
||||
return address;
|
||||
}
|
||||
|
||||
export function isValidJavaIPAddress(value: string): boolean {
|
||||
return parseJavaIPv4(value) !== undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* FILIUS uses `musterSubNetz`, a dotted-decimal syntax check. It deliberately
|
||||
* accepts non-contiguous masks in the route editor.
|
||||
*/
|
||||
export function isValidJavaSubnetMask(value: string): boolean {
|
||||
return parseJavaIPv4(value) !== undefined;
|
||||
}
|
||||
|
||||
export function isValidRouteCell(value: string, column: RouteTableColumn): boolean {
|
||||
return column === 'subnetMask' ? isValidJavaSubnetMask(value) : isValidJavaIPAddress(value);
|
||||
}
|
||||
|
||||
function sameNetwork(lhs: string, rhs: string, mask: string): boolean {
|
||||
const left = parseJavaIPv4(lhs);
|
||||
const right = parseJavaIPv4(rhs);
|
||||
const netmask = parseJavaIPv4(mask);
|
||||
if (left === undefined || right === undefined || netmask === undefined) return false;
|
||||
return maskAddress(left, netmask) === maskAddress(right, netmask);
|
||||
}
|
||||
|
||||
function networkAddress(ipAddress: string, subnetMask: string): string | undefined {
|
||||
const address = parseJavaIPv4(ipAddress);
|
||||
const mask = parseJavaIPv4(subnetMask);
|
||||
if (address === undefined || mask === undefined) return undefined;
|
||||
return formatIPv4(maskAddress(address, mask));
|
||||
}
|
||||
|
||||
/**
|
||||
* The static table as Java shows it: the interfaces' own addresses (newest
|
||||
* first), their networks, loopback, the manual rows, then the default route.
|
||||
*/
|
||||
export function routeTableRows(
|
||||
interfaceConfigurations: readonly InterfaceConfiguration[],
|
||||
manualRoutes: readonly ManualRoute[],
|
||||
defaultGateway: string | undefined,
|
||||
): RouteRow[] {
|
||||
const validInterfaces = interfaceConfigurations.filter(
|
||||
(configuration) =>
|
||||
parseJavaIPv4(configuration.ipAddress) !== undefined &&
|
||||
parseJavaIPv4(configuration.subnetMask) !== undefined,
|
||||
);
|
||||
|
||||
const result: RouteRow[] = manualRoutes.map((route) => ({
|
||||
destinationNetwork: route.destinationNetwork,
|
||||
subnetMask: route.subnetMask,
|
||||
nextHop: route.gateway,
|
||||
interfaceIPAddress: route.interfaceIPAddress,
|
||||
origin: 'manual',
|
||||
isEditable: true,
|
||||
}));
|
||||
|
||||
result.unshift({
|
||||
destinationNetwork: '127.0.0.0',
|
||||
subnetMask: '255.0.0.0',
|
||||
nextHop: '127.0.0.1',
|
||||
interfaceIPAddress: '127.0.0.1',
|
||||
origin: 'localhost',
|
||||
isEditable: false,
|
||||
});
|
||||
|
||||
for (const configuration of validInterfaces) {
|
||||
const network = networkAddress(configuration.ipAddress, configuration.subnetMask);
|
||||
if (network === undefined) continue;
|
||||
result.unshift({
|
||||
destinationNetwork: network,
|
||||
subnetMask: configuration.subnetMask,
|
||||
nextHop: configuration.ipAddress,
|
||||
interfaceIPAddress: configuration.ipAddress,
|
||||
origin: 'connected',
|
||||
isEditable: false,
|
||||
});
|
||||
}
|
||||
|
||||
for (const configuration of validInterfaces) {
|
||||
result.unshift({
|
||||
destinationNetwork: configuration.ipAddress,
|
||||
subnetMask: '255.255.255.255',
|
||||
nextHop: '127.0.0.1',
|
||||
interfaceIPAddress: '127.0.0.1',
|
||||
origin: 'localHost',
|
||||
isEditable: false,
|
||||
});
|
||||
}
|
||||
|
||||
const trimmedGateway = defaultGateway?.trim() ?? '';
|
||||
const primaryInterface = validInterfaces[0];
|
||||
if (parseJavaIPv4(trimmedGateway) !== undefined && primaryInterface !== undefined) {
|
||||
let selectedInterface = primaryInterface.ipAddress;
|
||||
for (const configuration of validInterfaces) {
|
||||
if (sameNetwork(trimmedGateway, configuration.ipAddress, configuration.subnetMask)) {
|
||||
selectedInterface = configuration.ipAddress;
|
||||
}
|
||||
}
|
||||
result.push({
|
||||
destinationNetwork: '0.0.0.0',
|
||||
subnetMask: '0.0.0.0',
|
||||
nextHop: trimmedGateway,
|
||||
interfaceIPAddress: selectedInterface,
|
||||
origin: 'defaultGateway',
|
||||
isEditable: false,
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function visibleRouteRows(rows: readonly RouteRow[], showAllEntries: boolean): RouteRow[] {
|
||||
return showAllEntries ? [...rows] : rows.filter((row) => row.isEditable);
|
||||
}
|
||||
|
||||
/** One row being edited in the route editor. */
|
||||
export interface RouteDraft {
|
||||
readonly id: string;
|
||||
destinationNetwork: string;
|
||||
subnetMask: string;
|
||||
nextGateway: string;
|
||||
interfaceIPAddress: string;
|
||||
isPendingInsertion: boolean;
|
||||
}
|
||||
|
||||
export function blankRouteDraft(id: string): RouteDraft {
|
||||
return {
|
||||
id,
|
||||
destinationNetwork: '',
|
||||
subnetMask: '',
|
||||
nextGateway: '',
|
||||
interfaceIPAddress: '',
|
||||
isPendingInsertion: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function routeDraftFromRoute(id: string, route: ManualRoute): RouteDraft {
|
||||
return {
|
||||
id,
|
||||
destinationNetwork: route.destinationNetwork,
|
||||
subnetMask: route.subnetMask,
|
||||
nextGateway: route.gateway,
|
||||
interfaceIPAddress: route.interfaceIPAddress,
|
||||
isPendingInsertion: false,
|
||||
};
|
||||
}
|
||||
|
||||
/** The route a draft stands for — only once all four cells are valid. */
|
||||
export function manualRouteFromDraft(draft: RouteDraft): ManualRoute | undefined {
|
||||
if (
|
||||
!isValidRouteCell(draft.destinationNetwork, 'destination') ||
|
||||
!isValidRouteCell(draft.subnetMask, 'subnetMask') ||
|
||||
!isValidRouteCell(draft.nextGateway, 'nextGateway') ||
|
||||
!isValidRouteCell(draft.interfaceIPAddress, 'interface')
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
destinationNetwork: draft.destinationNetwork,
|
||||
subnetMask: draft.subnetMask,
|
||||
gateway: draft.nextGateway,
|
||||
interfaceIPAddress: draft.interfaceIPAddress,
|
||||
};
|
||||
}
|
||||
|
||||
/** At most one blank row waits at the end of the editor. */
|
||||
export function appendingBlankDraftIfNeeded(
|
||||
drafts: readonly RouteDraft[],
|
||||
newId: () => string,
|
||||
): RouteDraft[] {
|
||||
if (drafts.some((draft) => draft.isPendingInsertion)) return [...drafts];
|
||||
return [...drafts, blankRouteDraft(newId())];
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// Ported from filius-ipad (GPLv2/GPLv3):
|
||||
// State/TopologyNetworkRuntimeEngine.swift (TopologyNetworkRuntimeTopologySnapshot)
|
||||
// What the runtime starts from: the topology and every configuration, frozen
|
||||
// at the moment the simulation starts. Later protocol slices add their
|
||||
// configuration maps here (DHCP, NAT, remote link, wireless).
|
||||
|
||||
import { compareIds, type Id } from '../ids.js';
|
||||
import type { NodeKind } from '../model/node.js';
|
||||
import { canonicalMacAddress } from '../model/node.js';
|
||||
import type {
|
||||
DeviceConfiguration,
|
||||
FirewallConfiguration,
|
||||
InterfaceConfiguration,
|
||||
InterfaceKey,
|
||||
ManualRoute,
|
||||
SwitchConfiguration,
|
||||
} from './config.js';
|
||||
|
||||
export interface PortSnapshot {
|
||||
readonly id: Id;
|
||||
readonly label: string;
|
||||
/** Canonical, or undefined for a port whose MAC address is derived from its id. */
|
||||
readonly macAddress?: string;
|
||||
}
|
||||
|
||||
export function portSnapshot(id: Id, label: string, macAddress?: string): PortSnapshot {
|
||||
const canonical = canonicalMacAddress(macAddress);
|
||||
return canonical === undefined ? { id, label } : { id, label, macAddress: canonical };
|
||||
}
|
||||
|
||||
export interface NodeSnapshot {
|
||||
readonly id: Id;
|
||||
readonly kind: NodeKind;
|
||||
readonly ports: readonly PortSnapshot[];
|
||||
}
|
||||
|
||||
export interface LinkSnapshot {
|
||||
readonly id: Id;
|
||||
readonly sourceNodeId: Id;
|
||||
readonly sourcePortId: Id;
|
||||
readonly targetNodeId: Id;
|
||||
readonly targetPortId: Id;
|
||||
}
|
||||
|
||||
export interface TopologySnapshot {
|
||||
/** Sorted by id (Swift `uuidString` order). */
|
||||
readonly nodes: readonly NodeSnapshot[];
|
||||
/** Sorted by id (Swift `uuidString` order). */
|
||||
readonly links: readonly LinkSnapshot[];
|
||||
readonly deviceConfigurations: ReadonlyMap<Id, DeviceConfiguration>;
|
||||
readonly interfaceConfigurations: ReadonlyMap<InterfaceKey, InterfaceConfiguration>;
|
||||
readonly manualRoutesByNodeId: ReadonlyMap<Id, readonly ManualRoute[]>;
|
||||
readonly ripEnabledByNodeId: ReadonlyMap<Id, boolean>;
|
||||
readonly firewallConfigurationsByNodeId: ReadonlyMap<Id, FirewallConfiguration>;
|
||||
readonly switchConfigurationsByNodeId: ReadonlyMap<Id, SwitchConfiguration>;
|
||||
}
|
||||
|
||||
export interface TopologySnapshotInput {
|
||||
nodes: readonly NodeSnapshot[];
|
||||
links: readonly LinkSnapshot[];
|
||||
deviceConfigurations?: ReadonlyMap<Id, DeviceConfiguration>;
|
||||
interfaceConfigurations?: ReadonlyMap<InterfaceKey, InterfaceConfiguration>;
|
||||
manualRoutesByNodeId?: ReadonlyMap<Id, readonly ManualRoute[]>;
|
||||
ripEnabledByNodeId?: ReadonlyMap<Id, boolean>;
|
||||
firewallConfigurationsByNodeId?: ReadonlyMap<Id, FirewallConfiguration>;
|
||||
switchConfigurationsByNodeId?: ReadonlyMap<Id, SwitchConfiguration>;
|
||||
}
|
||||
|
||||
export function topologySnapshot(input: TopologySnapshotInput): TopologySnapshot {
|
||||
return {
|
||||
nodes: [...input.nodes].sort((lhs, rhs) => compareIds(lhs.id, rhs.id)),
|
||||
links: [...input.links].sort((lhs, rhs) => compareIds(lhs.id, rhs.id)),
|
||||
deviceConfigurations: input.deviceConfigurations ?? new Map(),
|
||||
interfaceConfigurations: input.interfaceConfigurations ?? new Map(),
|
||||
manualRoutesByNodeId: input.manualRoutesByNodeId ?? new Map(),
|
||||
ripEnabledByNodeId: input.ripEnabledByNodeId ?? new Map(),
|
||||
firewallConfigurationsByNodeId: input.firewallConfigurationsByNodeId ?? new Map(),
|
||||
switchConfigurationsByNodeId: input.switchConfigurationsByNodeId ?? new Map(),
|
||||
};
|
||||
}
|
||||
|
||||
/** The same snapshot with some fields replaced (Swift rebuilds it field by field). */
|
||||
export function withSnapshot(
|
||||
snapshot: TopologySnapshot,
|
||||
changes: Partial<TopologySnapshotInput>,
|
||||
): TopologySnapshot {
|
||||
return topologySnapshot({ ...snapshot, ...changes });
|
||||
}
|
||||
|
||||
export const EMPTY_TOPOLOGY_SNAPSHOT: TopologySnapshot = topologySnapshot({ nodes: [], links: [] });
|
||||
@@ -0,0 +1,33 @@
|
||||
// Ported from filius-ipad (GPLv2/GPLv3):
|
||||
// State/TopologyNetworkRuntimeEngine.swift (TopologyNetworkRuntimeSpeed)
|
||||
// Java counterpart: filius.hardware.Verbindung (MIN_VERZOEGERUNG_IN_MILLIS,
|
||||
// verzoegerungsFaktor) and GUIMainMenu.updateLatency.
|
||||
|
||||
export const MINIMUM_SPEED_PERCENT = 1;
|
||||
export const MAXIMUM_SPEED_PERCENT = 100;
|
||||
export const DEFAULT_SPEED_PERCENT = 90;
|
||||
export const JAVA_MINIMUM_LINK_DELAY_MILLISECONDS = 5;
|
||||
|
||||
export class RuntimeSpeed {
|
||||
readonly percent: number;
|
||||
|
||||
constructor(percent: number = DEFAULT_SPEED_PERCENT) {
|
||||
this.percent = Math.min(MAXIMUM_SPEED_PERCENT, Math.max(MINIMUM_SPEED_PERCENT, Math.trunc(percent)));
|
||||
}
|
||||
|
||||
/** Java's delay factor: 1 at full speed, 100 at the slowest. */
|
||||
get javaDelayFactor(): number {
|
||||
return MAXIMUM_SPEED_PERCENT - this.percent + 1;
|
||||
}
|
||||
|
||||
/** How long a frame travels over one cable. */
|
||||
get linkTransmissionDelayMilliseconds(): number {
|
||||
return JAVA_MINIMUM_LINK_DELAY_MILLISECONDS * this.javaDelayFactor;
|
||||
}
|
||||
|
||||
/** A base delay scaled like a cable, or undefined past the safe integer range. */
|
||||
scaledLinkDelay(baseMilliseconds: number): number | undefined {
|
||||
const delay = baseMilliseconds * this.javaDelayFactor;
|
||||
return Number.isSafeInteger(delay) ? delay : undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// Ported from filius-ipad (GPLv2/GPLv3):
|
||||
// State/TopologyNetworkRuntimeEngine.swift (packet trace model)
|
||||
// Java counterpart: filius.rahmenprogramm.nachrichten.Lauscher — here every
|
||||
// step a frame or packet takes is one trace event; the packet viewer groups them.
|
||||
|
||||
import type { Id } from '../ids.js';
|
||||
|
||||
export type TraceDirection = 'inbound' | 'outbound' | 'local';
|
||||
|
||||
export type TraceLayer = 'application' | 'transport' | 'network' | 'dataLink' | 'physical';
|
||||
|
||||
export type TraceOperation =
|
||||
| 'created'
|
||||
| 'sent'
|
||||
| 'received'
|
||||
| 'forwarded'
|
||||
| 'accepted'
|
||||
| 'dropped'
|
||||
| 'rewritten'
|
||||
| 'retransmitted'
|
||||
| 'compatibilityAdapter';
|
||||
|
||||
export interface HeaderField {
|
||||
readonly name: string;
|
||||
readonly value: string;
|
||||
}
|
||||
|
||||
export interface TraceEvent {
|
||||
readonly id: number;
|
||||
readonly timeMilliseconds: number;
|
||||
readonly frameIdentity?: number;
|
||||
readonly packetIdentity?: number;
|
||||
readonly nodeId: Id;
|
||||
readonly interfaceId?: Id;
|
||||
readonly direction: TraceDirection;
|
||||
readonly layer: TraceLayer;
|
||||
readonly operation: TraceOperation;
|
||||
readonly beforeHeaders: readonly HeaderField[];
|
||||
readonly afterHeaders: readonly HeaderField[];
|
||||
readonly detail?: string;
|
||||
}
|
||||
|
||||
/** How many trace events the runtime keeps, and how many it drops at once when full. */
|
||||
export interface TraceRetentionPolicy {
|
||||
readonly maximumEventCount: number;
|
||||
readonly evictionBatchSize: number;
|
||||
}
|
||||
|
||||
export function traceRetentionPolicy(maximumEventCount: number, evictionBatchSize: number): TraceRetentionPolicy {
|
||||
if (!(maximumEventCount > 0)) throw new RangeError('Packet-trace retention must keep at least one event');
|
||||
if (!(evictionBatchSize > 0)) throw new RangeError('Packet-trace eviction must remove at least one event');
|
||||
if (evictionBatchSize > maximumEventCount) {
|
||||
throw new RangeError('Packet-trace eviction cannot exceed the retention limit');
|
||||
}
|
||||
return { maximumEventCount, evictionBatchSize };
|
||||
}
|
||||
|
||||
export const PRODUCTION_TRACE_RETENTION = traceRetentionPolicy(10_000, 1_000);
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Structural equality for the runtime's value types — what Swift's synthesized
|
||||
* `Equatable` gives a struct or enum for free. Handles plain objects, arrays,
|
||||
* `Uint8Array`, `Map` and `Set`; everything else is compared with `Object.is`.
|
||||
*/
|
||||
export function deepEqual(lhs: unknown, rhs: unknown): boolean {
|
||||
if (Object.is(lhs, rhs)) return true;
|
||||
if (typeof lhs !== 'object' || typeof rhs !== 'object' || lhs === null || rhs === null) {
|
||||
return false;
|
||||
}
|
||||
if (lhs instanceof Uint8Array || rhs instanceof Uint8Array) {
|
||||
if (!(lhs instanceof Uint8Array && rhs instanceof Uint8Array)) return false;
|
||||
return lhs.length === rhs.length && lhs.every((byte, index) => byte === rhs[index]);
|
||||
}
|
||||
if (Array.isArray(lhs) || Array.isArray(rhs)) {
|
||||
if (!(Array.isArray(lhs) && Array.isArray(rhs)) || lhs.length !== rhs.length) return false;
|
||||
return lhs.every((item, index) => deepEqual(item, rhs[index]));
|
||||
}
|
||||
if (lhs instanceof Map || rhs instanceof Map) {
|
||||
if (!(lhs instanceof Map && rhs instanceof Map) || lhs.size !== rhs.size) return false;
|
||||
for (const [key, value] of lhs) {
|
||||
if (!rhs.has(key) || !deepEqual(value, rhs.get(key))) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (lhs instanceof Set || rhs instanceof Set) {
|
||||
if (!(lhs instanceof Set && rhs instanceof Set) || lhs.size !== rhs.size) return false;
|
||||
for (const value of lhs) if (!rhs.has(value)) return false;
|
||||
return true;
|
||||
}
|
||||
const leftKeys = Object.keys(lhs).filter((key) => (lhs as Record<string, unknown>)[key] !== undefined);
|
||||
const rightKeys = Object.keys(rhs).filter((key) => (rhs as Record<string, unknown>)[key] !== undefined);
|
||||
if (leftKeys.length !== rightKeys.length) return false;
|
||||
return leftKeys.every((key) =>
|
||||
deepEqual((lhs as Record<string, unknown>)[key], (rhs as Record<string, unknown>)[key]),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,631 @@
|
||||
// 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. The remaining Swift tests (UDP, TCP, DHCP, DNS, RIP,
|
||||
// NAT, remote link, packet viewer) follow with their protocol slices.
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
EMPTY_TOPOLOGY_SNAPSHOT,
|
||||
ETHERNET_BROADCAST_MAC_ADDRESS,
|
||||
firewallConfiguration,
|
||||
firewallRule,
|
||||
DIRECTLY_CONNECTED_SOURCE_MARKER,
|
||||
forwardingClone,
|
||||
icmpMessage,
|
||||
interfaceKey,
|
||||
JavaCompatibleRandom,
|
||||
NetworkRuntimeEngine,
|
||||
portSnapshot,
|
||||
stableMacAddress,
|
||||
switchConfiguration,
|
||||
TCP_FLAG,
|
||||
topologySnapshot,
|
||||
traceRetentionPolicy,
|
||||
UNSPECIFIED_MAC_ADDRESS,
|
||||
type EthernetFrame,
|
||||
type EthernetPayload,
|
||||
type FirewallConfiguration,
|
||||
type IPv4Packet,
|
||||
type NodeSnapshot,
|
||||
type RuntimeOutput,
|
||||
type ScheduledEventKind,
|
||||
} from '../src/index.js';
|
||||
import { device, link, pc, startedEngine, uuid } from './fixtures.js';
|
||||
|
||||
const marker = (label: string): ScheduledEventKind => ({ kind: 'parityMarker', label });
|
||||
|
||||
function firedKinds(outputs: RuntimeOutput[]): ScheduledEventKind[] {
|
||||
return outputs.flatMap((output) => (output.kind.type === 'fired' ? [output.kind.event.kind] : []));
|
||||
}
|
||||
|
||||
function routedTopology() {
|
||||
const sourceNodeId = uuid(0x1451);
|
||||
const sourcePortId = uuid(0x1461);
|
||||
const routerNodeId = uuid(0x1452);
|
||||
const routerPortA = uuid(0x1462);
|
||||
const routerPortB = uuid(0x1463);
|
||||
const targetNodeId = uuid(0x1453);
|
||||
const targetPortId = uuid(0x1464);
|
||||
const router: NodeSnapshot = {
|
||||
id: routerNodeId,
|
||||
kind: 'router',
|
||||
ports: [portSnapshot(routerPortA, 'rt1'), portSnapshot(routerPortB, 'rt2')],
|
||||
};
|
||||
const snapshot = topologySnapshot({
|
||||
nodes: [pc(sourceNodeId, sourcePortId), router, pc(targetNodeId, targetPortId)],
|
||||
links: [
|
||||
link(sourceNodeId, sourcePortId, routerNodeId, routerPortA),
|
||||
link(routerNodeId, routerPortB, targetNodeId, targetPortId),
|
||||
],
|
||||
deviceConfigurations: new Map([
|
||||
[sourceNodeId, device('10.0.0.2', { gateway: '10.0.0.1' })],
|
||||
[routerNodeId, device('10.0.0.1')],
|
||||
[targetNodeId, device('20.0.0.2', { gateway: '20.0.0.1' })],
|
||||
]),
|
||||
interfaceConfigurations: new Map([
|
||||
[interfaceKey(routerNodeId, routerPortA), { ipAddress: '10.0.0.1', subnetMask: '255.255.255.0' }],
|
||||
[interfaceKey(routerNodeId, routerPortB), { ipAddress: '20.0.0.1', subnetMask: '255.255.255.0' }],
|
||||
]),
|
||||
});
|
||||
const engine = new NetworkRuntimeEngine(14);
|
||||
engine.handle({ type: 'start', snapshot, seed: 14, initialTimeMilliseconds: 0 });
|
||||
return { engine, sourceNodeId, routerNodeId };
|
||||
}
|
||||
|
||||
function firewallEngine(configuration: FirewallConfiguration) {
|
||||
const routerId = uuid(0x1802);
|
||||
const portId = uuid(0x1812);
|
||||
const engine = startedEngine(
|
||||
{
|
||||
nodes: [{ id: routerId, kind: 'router', ports: [portSnapshot(portId, 'rt1')] }],
|
||||
links: [],
|
||||
interfaceConfigurations: new Map([
|
||||
[interfaceKey(routerId, portId), { ipAddress: '10.0.0.1', subnetMask: '255.255.255.0' }],
|
||||
]),
|
||||
firewallConfigurationsByNodeId: new Map([[routerId, configuration]]),
|
||||
},
|
||||
18,
|
||||
);
|
||||
return { engine, routerId };
|
||||
}
|
||||
|
||||
function tcpPacket(identity: number, destinationPort: number, flags: number): IPv4Packet {
|
||||
return {
|
||||
identity,
|
||||
senderIPAddress: '203.0.113.10',
|
||||
receiverIPAddress: '10.0.0.1',
|
||||
timeToLive: 64,
|
||||
protocol: 'tcp',
|
||||
payload: {
|
||||
kind: 'tcp',
|
||||
segment: {
|
||||
sourcePort: 50_000,
|
||||
destinationPort,
|
||||
sequenceNumber: identity,
|
||||
acknowledgementNumber: 0,
|
||||
flags,
|
||||
payload: new Uint8Array(),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('event queue and virtual clock', () => {
|
||||
it('orders events by deadline, then by insertion sequence', () => {
|
||||
const engine = new NetworkRuntimeEngine(42);
|
||||
engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 42, initialTimeMilliseconds: 0 });
|
||||
engine.handle({ type: 'schedule', deadlineMilliseconds: 100, kind: marker('first-at-100') });
|
||||
engine.handle({ type: 'schedule', deadlineMilliseconds: 50, kind: marker('at-50') });
|
||||
engine.handle({ type: 'schedule', deadlineMilliseconds: 100, kind: marker('second-at-100') });
|
||||
|
||||
const outputs = engine.handle({ type: 'advance', toMilliseconds: 100 });
|
||||
|
||||
expect(firedKinds(outputs)).toEqual([marker('at-50'), marker('first-at-100'), marker('second-at-100')]);
|
||||
expect(engine.state.currentTimeMilliseconds).toBe(100);
|
||||
expect(engine.state.pendingEvents).toEqual([]);
|
||||
});
|
||||
|
||||
it('rejects a past time without changing the clock', () => {
|
||||
const engine = new NetworkRuntimeEngine(7);
|
||||
engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 7, initialTimeMilliseconds: 10 });
|
||||
engine.handle({ type: 'advance', toMilliseconds: 25 });
|
||||
|
||||
const outputs = engine.handle({ type: 'advance', toMilliseconds: 24 });
|
||||
|
||||
expect(outputs.map((output) => output.kind)).toEqual([{ type: 'advanceRejectedPastTime' }]);
|
||||
expect(engine.state.currentTimeMilliseconds).toBe(25);
|
||||
});
|
||||
|
||||
it('rejects a past deadline without using up a sequence number', () => {
|
||||
const engine = new NetworkRuntimeEngine(8);
|
||||
engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 8, initialTimeMilliseconds: 25 });
|
||||
|
||||
const outputs = engine.handle({ type: 'schedule', deadlineMilliseconds: 24, kind: marker('past') });
|
||||
|
||||
expect(outputs.map((output) => output.kind)).toEqual([
|
||||
{ type: 'scheduleRejectedPastTime', deadlineMilliseconds: 24 },
|
||||
]);
|
||||
expect(engine.state.pendingEvents).toEqual([]);
|
||||
expect(engine.state.nextEventSequenceNumber).toBe(0);
|
||||
expect(engine.state.currentTimeMilliseconds).toBe(25);
|
||||
});
|
||||
|
||||
it('replays a named scenario straight to a stable state', () => {
|
||||
const finalState = NetworkRuntimeEngine.run({
|
||||
name: 'equal-deadline-order',
|
||||
seed: 1,
|
||||
advanceToMilliseconds: 1_000,
|
||||
scheduledEvents: [
|
||||
{ deadlineMilliseconds: 500, kind: marker('a') },
|
||||
{ deadlineMilliseconds: 500, kind: marker('b') },
|
||||
],
|
||||
});
|
||||
|
||||
expect(finalState.currentTimeMilliseconds).toBe(1_000);
|
||||
expect(finalState.pendingEvents).toEqual([]);
|
||||
expect(finalState.seed).toBe(1n);
|
||||
});
|
||||
|
||||
it('clears transient state on restart and numbers packets from one again', () => {
|
||||
const nodeId = uuid(0x12);
|
||||
const engine = new NetworkRuntimeEngine(12);
|
||||
engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 12, initialTimeMilliseconds: 0 });
|
||||
engine.handle({ type: 'schedule', deadlineMilliseconds: 40, kind: marker('stale') });
|
||||
expect(engine.allocateFrameIdentity()).toBe(1);
|
||||
expect(engine.allocatePacketIdentity()).toBe(1);
|
||||
engine.recordTrace({ packetIdentity: 1, nodeId, direction: 'local', layer: 'application', operation: 'created' });
|
||||
engine.handle({ type: 'stop' });
|
||||
|
||||
engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 12, initialTimeMilliseconds: 0 });
|
||||
|
||||
const state = engine.state;
|
||||
expect(state.pendingEvents).toEqual([]);
|
||||
expect(state.packetTraces).toEqual([]);
|
||||
expect(state.arpCachesByNodeId.size).toBe(0);
|
||||
expect(state.switchForwardingTablesByNodeId.size).toBe(0);
|
||||
expect(state.switchSeenFrameIdentitiesByNodeId.size).toBe(0);
|
||||
expect(state.deliveredIPv4PacketsByNodeId.size).toBe(0);
|
||||
expect(state.icmpObservationsByNodeId.size).toBe(0);
|
||||
expect(state.firewallDecisions).toEqual([]);
|
||||
expect(engine.allocateFrameIdentity()).toBe(1);
|
||||
expect(engine.allocatePacketIdentity()).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Java-compatible randomness', () => {
|
||||
it('draws the same RIP jitter as java.util.Random', () => {
|
||||
const random = new JavaCompatibleRandom(42);
|
||||
|
||||
expect(Array.from({ length: 5 }, () => random.nextRipJitterMilliseconds())).toEqual([
|
||||
32_475, 25_746, 32_032, 25_679, 28_287,
|
||||
]);
|
||||
});
|
||||
|
||||
it('matches java.util.Random.nextInt for bounded and power-of-two ranges', () => {
|
||||
// Measured on OpenJDK 21 (29.09.2026): new java.util.Random(42),
|
||||
// nextInt(100) three times, then nextInt(16) three times.
|
||||
const random = new JavaCompatibleRandom(42);
|
||||
|
||||
expect([random.nextInt(100), random.nextInt(100), random.nextInt(100)]).toEqual([30, 63, 48]);
|
||||
expect([random.nextInt(16), random.nextInt(16), random.nextInt(16)]).toEqual([0, 4, 15]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('IPv4 packets', () => {
|
||||
it('keeps the identity and lowers the TTL when forwarding', () => {
|
||||
const packet: IPv4Packet = {
|
||||
identity: 99,
|
||||
senderIPAddress: '192.168.0.10',
|
||||
receiverIPAddress: '192.168.1.20',
|
||||
timeToLive: 2,
|
||||
protocol: 'icmp',
|
||||
payload: { kind: 'icmp', message: icmpMessage('echoRequest', { identifier: 3, sequenceNumber: 4 }) },
|
||||
};
|
||||
|
||||
const forwarded = forwardingClone(packet);
|
||||
const expired = forwardingClone(forwarded);
|
||||
|
||||
expect(forwarded).toMatchObject({ identity: 99, timeToLive: 1 });
|
||||
expect(expired).toMatchObject({ identity: 99, timeToLive: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('Ethernet, ARP and ICMP', () => {
|
||||
it('fills both ARP caches with one request and reply over a direct cable', () => {
|
||||
const sourceNodeId = uuid(0x1401);
|
||||
const sourcePortId = uuid(0x1411);
|
||||
const targetNodeId = uuid(0x1402);
|
||||
const targetPortId = uuid(0x1412);
|
||||
const engine = startedEngine({
|
||||
nodes: [pc(sourceNodeId, sourcePortId), pc(targetNodeId, targetPortId)],
|
||||
links: [link(sourceNodeId, sourcePortId, targetNodeId, targetPortId)],
|
||||
deviceConfigurations: new Map([
|
||||
[sourceNodeId, device('192.168.0.10')],
|
||||
[targetNodeId, device('192.168.0.20')],
|
||||
]),
|
||||
});
|
||||
|
||||
const resolved = engine.resolveMacAddress(sourceNodeId, '192.168.0.20');
|
||||
|
||||
expect(resolved).toBe(stableMacAddress(targetPortId));
|
||||
expect(engine.state.arpCachesByNodeId.get(sourceNodeId)?.get('192.168.0.20')?.macAddress).toBe(resolved);
|
||||
expect(engine.state.arpCachesByNodeId.get(targetNodeId)?.get('192.168.0.10')?.macAddress).toBe(
|
||||
stableMacAddress(sourcePortId),
|
||||
);
|
||||
});
|
||||
|
||||
it('pings across a switch with Ethernet, ARP and ICMP packets', () => {
|
||||
const sourceNodeId = uuid(0x1421);
|
||||
const sourcePortId = uuid(0x1431);
|
||||
const switchNodeId = uuid(0x1422);
|
||||
const switchPortA = uuid(0x1432);
|
||||
const switchPortB = uuid(0x1433);
|
||||
const targetNodeId = uuid(0x1423);
|
||||
const targetPortId = uuid(0x1434);
|
||||
const switchNode: NodeSnapshot = {
|
||||
id: switchNodeId,
|
||||
kind: 'networkSwitch',
|
||||
ports: [portSnapshot(switchPortA, 'sw1'), portSnapshot(switchPortB, 'sw2')],
|
||||
};
|
||||
const engine = startedEngine({
|
||||
nodes: [pc(sourceNodeId, sourcePortId), switchNode, pc(targetNodeId, targetPortId)],
|
||||
links: [
|
||||
link(sourceNodeId, sourcePortId, switchNodeId, switchPortA),
|
||||
link(switchNodeId, switchPortB, targetNodeId, targetPortId),
|
||||
],
|
||||
deviceConfigurations: new Map([
|
||||
[sourceNodeId, device('192.168.0.10')],
|
||||
[targetNodeId, device('192.168.0.20')],
|
||||
]),
|
||||
});
|
||||
|
||||
const result = engine.sendIcmpEcho(sourceNodeId, '192.168.0.20', { identifier: 14, sequenceNumber: 1 });
|
||||
|
||||
expect(result.type).toBe('delivered');
|
||||
expect(engine.state.icmpObservationsByNodeId.get(sourceNodeId)?.at(-1)?.message.kind).toBe('echoReply');
|
||||
expect(engine.state.switchForwardingTablesByNodeId.get(switchNodeId)?.size).toBe(2);
|
||||
expect(engine.state.packetTraces.some((trace) => trace.detail === 'ARP request for 192.168.0.20')).toBe(true);
|
||||
expect(
|
||||
engine.state.packetTraces.some((trace) => trace.packetIdentity !== undefined && trace.layer === 'network'),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('answers an expired TTL at the router with time exceeded and the original packet', () => {
|
||||
const topology = routedTopology();
|
||||
|
||||
const result = topology.engine.sendIcmpEcho(topology.sourceNodeId, '20.0.0.2', {
|
||||
timeToLive: 1,
|
||||
identifier: 140,
|
||||
sequenceNumber: 1,
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({ type: 'icmpError', kind: 'timeExceeded' });
|
||||
const observation = topology.engine.state.icmpObservationsByNodeId.get(topology.sourceNodeId)?.at(-1);
|
||||
expect(observation?.message.kind).toBe('timeExceeded');
|
||||
expect(observation?.message.embeddedOriginalPacket?.timeToLive).toBe(1);
|
||||
expect(observation?.message.embeddedOriginalPacket?.receiverIPAddress).toBe('20.0.0.2');
|
||||
});
|
||||
|
||||
it('keeps the packet identity and lowers the TTL when a router forwards', () => {
|
||||
const topology = routedTopology();
|
||||
|
||||
const result = topology.engine.sendIcmpEcho(topology.sourceNodeId, '20.0.0.2', {
|
||||
timeToLive: 8,
|
||||
identifier: 141,
|
||||
sequenceNumber: 1,
|
||||
});
|
||||
|
||||
expect(result.type).toBe('delivered');
|
||||
const forwardingTrace = topology.engine.state.packetTraces.find(
|
||||
(trace) =>
|
||||
trace.nodeId === topology.routerNodeId && trace.operation === 'forwarded' && trace.detail === 'TTL decremented',
|
||||
);
|
||||
expect(forwardingTrace?.packetIdentity).toBeDefined();
|
||||
expect(forwardingTrace?.beforeHeaders.find((field) => field.name === 'ttl')?.value).toBe('8');
|
||||
expect(forwardingTrace?.afterHeaders.find((field) => field.name === 'ttl')?.value).toBe('7');
|
||||
});
|
||||
|
||||
it('reports network unreachable when the router has no route', () => {
|
||||
const topology = routedTopology();
|
||||
const snapshot = topology.engine.state.topologySnapshot;
|
||||
const sourceToRouter = snapshot.links.find(
|
||||
(candidate) => candidate.sourceNodeId === topology.sourceNodeId || candidate.targetNodeId === topology.sourceNodeId,
|
||||
);
|
||||
const engine = new NetworkRuntimeEngine(14);
|
||||
engine.handle({
|
||||
type: 'start',
|
||||
snapshot: topologySnapshot({
|
||||
nodes: snapshot.nodes,
|
||||
links: sourceToRouter === undefined ? [] : [sourceToRouter],
|
||||
deviceConfigurations: snapshot.deviceConfigurations,
|
||||
interfaceConfigurations: snapshot.interfaceConfigurations,
|
||||
manualRoutesByNodeId: snapshot.manualRoutesByNodeId,
|
||||
}),
|
||||
seed: 14,
|
||||
initialTimeMilliseconds: 0,
|
||||
});
|
||||
|
||||
const result = engine.sendIcmpEcho(topology.sourceNodeId, '30.0.0.2', { identifier: 142, sequenceNumber: 1 });
|
||||
|
||||
expect(result).toMatchObject({ type: 'icmpError', kind: 'destinationNetworkUnreachable' });
|
||||
});
|
||||
|
||||
it('reports host unreachable when a connected target never answers ARP', () => {
|
||||
const sourceNodeId = uuid(0x1481);
|
||||
const sourcePortId = uuid(0x1491);
|
||||
const engine = startedEngine({
|
||||
nodes: [pc(sourceNodeId, sourcePortId)],
|
||||
links: [],
|
||||
deviceConfigurations: new Map([[sourceNodeId, device('192.168.50.10')]]),
|
||||
});
|
||||
|
||||
const result = engine.sendIcmpEcho(sourceNodeId, '192.168.50.99', { identifier: 143, sequenceNumber: 1 });
|
||||
|
||||
expect(result).toMatchObject({ type: 'icmpError', kind: 'destinationHostUnreachable' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('switch', () => {
|
||||
it('learns, floods, forwards, filters and ages its address table', () => {
|
||||
const hostAId = uuid(0x1a01);
|
||||
const hostAPortId = uuid(0x1a11);
|
||||
const hostBId = uuid(0x1a02);
|
||||
const hostBPortId = uuid(0x1a12);
|
||||
const hostCId = uuid(0x1a03);
|
||||
const hostCPortId = uuid(0x1a13);
|
||||
const switchId = uuid(0x1a04);
|
||||
const switchPorts = [1, 2, 3].map((index) => portSnapshot(uuid(0x1a20 + index), `sw${index}`));
|
||||
const engine = startedEngine(
|
||||
{
|
||||
nodes: [
|
||||
pc(hostAId, hostAPortId),
|
||||
pc(hostBId, hostBPortId),
|
||||
pc(hostCId, hostCPortId),
|
||||
{ id: switchId, kind: 'networkSwitch', ports: switchPorts },
|
||||
],
|
||||
links: [
|
||||
link(hostAId, hostAPortId, switchId, switchPorts[0]!.id),
|
||||
link(hostBId, hostBPortId, switchId, switchPorts[1]!.id),
|
||||
link(hostCId, hostCPortId, switchId, switchPorts[2]!.id),
|
||||
],
|
||||
switchConfigurationsByNodeId: new Map([[switchId, switchConfiguration('Classroom', 1_000)]]),
|
||||
},
|
||||
20,
|
||||
);
|
||||
const macA = stableMacAddress(hostAPortId);
|
||||
const macB = stableMacAddress(hostBPortId);
|
||||
const payload: EthernetPayload = {
|
||||
kind: 'arp',
|
||||
packet: {
|
||||
operation: 'request',
|
||||
senderMacAddress: macA,
|
||||
senderIPAddress: '192.0.2.1',
|
||||
targetMacAddress: UNSPECIFIED_MAC_ADDRESS,
|
||||
targetIPAddress: '192.0.2.200',
|
||||
},
|
||||
};
|
||||
const frame = (sourceMacAddress: string, destinationMacAddress: string): EthernetFrame => ({
|
||||
identity: engine.allocateFrameIdentity(),
|
||||
sourceMacAddress,
|
||||
destinationMacAddress,
|
||||
payload,
|
||||
});
|
||||
const switchTraces = (detail: string) =>
|
||||
engine.state.packetTraces.filter((trace) => trace.nodeId === switchId && trace.detail === detail);
|
||||
|
||||
engine.sendEthernetFrame(hostAId, hostAPortId, frame(macA, '02:00:00:00:00:FE'));
|
||||
expect(switchTraces('switch unknown unicast flooding')).toHaveLength(2);
|
||||
|
||||
engine.sendEthernetFrame(hostBId, hostBPortId, frame(macB, macA));
|
||||
expect(switchTraces('switch learned unicast forwarding')).toHaveLength(1);
|
||||
|
||||
engine.sendEthernetFrame(hostAId, hostAPortId, frame(macA, macA));
|
||||
expect(switchTraces('switch filtered destination on incoming port').length).toBeGreaterThan(0);
|
||||
expect(engine.switchSatEntries(switchId)).toHaveLength(2);
|
||||
|
||||
const retention = 1_000;
|
||||
const updateTimes = [...engine.state.switchForwardingUpdatedAtMillisecondsByNodeId.get(switchId)!.values()];
|
||||
const expirationDeadlines = updateTimes.map((time) => time + retention);
|
||||
const firstExpiration = Math.min(...expirationDeadlines);
|
||||
const lastExpiration = Math.max(...expirationDeadlines);
|
||||
|
||||
engine.handle({ type: 'advance', toMilliseconds: firstExpiration - 1 });
|
||||
expect(engine.switchSatEntries(switchId)).toHaveLength(2);
|
||||
engine.handle({ type: 'advance', toMilliseconds: lastExpiration });
|
||||
expect(engine.switchSatEntries(switchId)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('firewall', () => {
|
||||
it('accepts when inactive, and an active ICMP drop bypasses the ordered rules', () => {
|
||||
const routerId = uuid(0x1801);
|
||||
const portId = uuid(0x1811);
|
||||
const router: NodeSnapshot = { id: routerId, kind: 'router', ports: [portSnapshot(portId, 'rt1')] };
|
||||
const packet: IPv4Packet = {
|
||||
identity: 18,
|
||||
senderIPAddress: '203.0.113.10',
|
||||
receiverIPAddress: '10.0.0.1',
|
||||
timeToLive: 64,
|
||||
protocol: 'icmp',
|
||||
payload: { kind: 'icmp', message: icmpMessage('echoRequest') },
|
||||
};
|
||||
const interfaces = new Map([
|
||||
[interfaceKey(routerId, portId), { ipAddress: '10.0.0.1', subnetMask: '255.255.255.0' }],
|
||||
]);
|
||||
|
||||
const inactive = startedEngine(
|
||||
{
|
||||
nodes: [router],
|
||||
links: [],
|
||||
interfaceConfigurations: interfaces,
|
||||
firewallConfigurationsByNodeId: new Map([[routerId, firewallConfiguration()]]),
|
||||
},
|
||||
18,
|
||||
);
|
||||
expect(inactive.evaluateFirewall(packet, routerId).accepted).toBe(true);
|
||||
|
||||
const active = startedEngine(
|
||||
{
|
||||
nodes: [router],
|
||||
links: [],
|
||||
interfaceConfigurations: interfaces,
|
||||
firewallConfigurationsByNodeId: new Map([
|
||||
[
|
||||
routerId,
|
||||
firewallConfiguration({
|
||||
isActive: true,
|
||||
defaultPolicy: 'accept',
|
||||
dropIcmp: true,
|
||||
rules: [firewallRule({ protocol: 'icmp', action: 'accept' })],
|
||||
}),
|
||||
],
|
||||
]),
|
||||
},
|
||||
18,
|
||||
);
|
||||
expect(active.evaluateFirewall(packet, routerId).accepted).toBe(false);
|
||||
expect(active.state.firewallDecisions.at(-1)?.ruleIndex).toBeUndefined();
|
||||
expect(active.state.packetTraces.at(-1)?.operation).toBe('dropped');
|
||||
});
|
||||
|
||||
it('lets the first matching TCP rule win, and established traffic bypasses SYN-only rules', () => {
|
||||
const { engine, routerId } = firewallEngine(
|
||||
firewallConfiguration({
|
||||
isActive: true,
|
||||
defaultPolicy: 'drop',
|
||||
filterSynSegmentsOnly: true,
|
||||
rules: [
|
||||
firewallRule({ port: 443, protocol: 'tcp', action: 'accept' }),
|
||||
firewallRule({ port: 443, protocol: 'tcp', action: 'drop' }),
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const synDecision = engine.evaluateFirewall(tcpPacket(181, 443, TCP_FLAG.synchronize), routerId);
|
||||
expect(synDecision.accepted).toBe(true);
|
||||
expect(synDecision.ruleIndex).toBe(0);
|
||||
expect(engine.evaluateFirewall(tcpPacket(182, 22, TCP_FLAG.acknowledgement), routerId).accepted).toBe(true);
|
||||
});
|
||||
|
||||
it('matches a UDP response by its explicit source port and the direct-network marker', () => {
|
||||
const { engine, routerId } = firewallEngine(
|
||||
firewallConfiguration({
|
||||
isActive: true,
|
||||
defaultPolicy: 'drop',
|
||||
rules: [
|
||||
firewallRule({
|
||||
sourceIPAddress: DIRECTLY_CONNECTED_SOURCE_MARKER,
|
||||
destinationIPAddress: '8.8.8.8',
|
||||
destinationSubnetMask: '255.255.255.255',
|
||||
port: 53,
|
||||
protocol: 'udp',
|
||||
action: 'accept',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
);
|
||||
const udp = (identity: number, sender: string, receiver: string, sourcePort: number, destinationPort: number): IPv4Packet => ({
|
||||
identity,
|
||||
senderIPAddress: sender,
|
||||
receiverIPAddress: receiver,
|
||||
timeToLive: 64,
|
||||
protocol: 'udp',
|
||||
payload: { kind: 'udp', datagram: { sourcePort, destinationPort, payload: new Uint8Array() } },
|
||||
});
|
||||
|
||||
expect(engine.evaluateFirewall(udp(183, '10.0.0.20', '8.8.8.8', 50_001, 53), routerId).accepted).toBe(true);
|
||||
expect(engine.evaluateFirewall(udp(184, '8.8.8.8', '10.0.0.20', 53, 50_001), routerId).accepted).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('packet loss and trace retention', () => {
|
||||
it('drops every physical delivery while global packet loss is on', () => {
|
||||
const firstNodeId = uuid(0x101);
|
||||
const firstPortId = uuid(0x102);
|
||||
const secondNodeId = uuid(0x103);
|
||||
const secondPortId = uuid(0x104);
|
||||
const engine = startedEngine({
|
||||
nodes: [pc(firstNodeId, firstPortId), pc(secondNodeId, secondPortId)],
|
||||
links: [link(firstNodeId, firstPortId, secondNodeId, secondPortId)],
|
||||
deviceConfigurations: new Map([
|
||||
[firstNodeId, device('10.0.0.1')],
|
||||
[secondNodeId, device('10.0.0.2')],
|
||||
]),
|
||||
});
|
||||
const frame: EthernetFrame = {
|
||||
identity: engine.allocateFrameIdentity(),
|
||||
sourceMacAddress: stableMacAddress(firstPortId),
|
||||
destinationMacAddress: ETHERNET_BROADCAST_MAC_ADDRESS,
|
||||
payload: {
|
||||
kind: 'arp',
|
||||
packet: {
|
||||
operation: 'request',
|
||||
senderMacAddress: stableMacAddress(firstPortId),
|
||||
senderIPAddress: '10.0.0.1',
|
||||
targetMacAddress: UNSPECIFIED_MAC_ADDRESS,
|
||||
targetIPAddress: '10.0.0.2',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
engine.setGlobalPacketLossEnabled(true);
|
||||
engine.sendEthernetFrame(firstNodeId, firstPortId, frame);
|
||||
|
||||
expect(engine.state.globalPacketLossEnabled).toBe(true);
|
||||
expect(engine.state.arpCachesByNodeId.get(secondNodeId)?.size ?? 0).toBe(0);
|
||||
expect(
|
||||
engine.state.packetTraces.some(
|
||||
(trace) =>
|
||||
trace.frameIdentity === frame.identity &&
|
||||
trace.nodeId === secondNodeId &&
|
||||
trace.operation === 'dropped' &&
|
||||
trace.detail === 'global packet-loss simulation',
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
engine.setGlobalPacketLossEnabled(false);
|
||||
engine.sendEthernetFrame(firstNodeId, firstPortId, frame);
|
||||
|
||||
expect(engine.state.globalPacketLossEnabled).toBe(false);
|
||||
expect(engine.state.arpCachesByNodeId.get(secondNodeId)?.get('10.0.0.1')?.macAddress).toBe(
|
||||
stableMacAddress(firstPortId),
|
||||
);
|
||||
});
|
||||
|
||||
it('resets packet loss across stop and restart', () => {
|
||||
const engine = new NetworkRuntimeEngine(42);
|
||||
engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 42, initialTimeMilliseconds: 0 });
|
||||
engine.setGlobalPacketLossEnabled(true);
|
||||
expect(engine.state.globalPacketLossEnabled).toBe(true);
|
||||
|
||||
engine.handle({ type: 'stop' });
|
||||
expect(engine.state.globalPacketLossEnabled).toBe(false);
|
||||
|
||||
engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 42, initialTimeMilliseconds: 0 });
|
||||
expect(engine.state.globalPacketLossEnabled).toBe(false);
|
||||
});
|
||||
|
||||
it('evicts the oldest trace events in configured batches', () => {
|
||||
const nodeId = uuid(0x2001);
|
||||
const interfaceId = uuid(0x2002);
|
||||
const engine = new NetworkRuntimeEngine(20, traceRetentionPolicy(3, 2));
|
||||
|
||||
for (let identity = 1; identity <= 6; identity += 1) {
|
||||
engine.recordTrace({
|
||||
frameIdentity: identity,
|
||||
nodeId,
|
||||
interfaceId,
|
||||
direction: 'outbound',
|
||||
layer: 'dataLink',
|
||||
operation: 'sent',
|
||||
detail: `trace-${identity}`,
|
||||
});
|
||||
}
|
||||
|
||||
expect(engine.state.packetTraces.map((trace) => trace.id)).toEqual([5, 6]);
|
||||
expect(engine.state.packetTraces.map((trace) => trace.detail)).toEqual(['trace-5', 'trace-6']);
|
||||
expect(engine.state.discardedPacketTraceCount).toBe(4);
|
||||
expect(engine.state.nextTraceIdentity).toBe(7);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
// Test fixtures, ported from the private helpers of
|
||||
// filius-ipad ios/FiliusPadTests/TopologyNetworkRuntimeEngineTests.swift.
|
||||
|
||||
import {
|
||||
deviceConfiguration,
|
||||
NetworkRuntimeEngine,
|
||||
portSnapshot,
|
||||
topologySnapshot,
|
||||
type DeviceConfiguration,
|
||||
type Id,
|
||||
type LinkSnapshot,
|
||||
type NodeSnapshot,
|
||||
type TopologySnapshotInput,
|
||||
} from '../src/index.js';
|
||||
|
||||
let linkCounter = 0;
|
||||
|
||||
/** Swift uses a fresh `UUID()` per link; a counter keeps runs reproducible. */
|
||||
export function link(sourceNodeId: Id, sourcePortId: Id, targetNodeId: Id, targetPortId: Id): LinkSnapshot {
|
||||
linkCounter += 1;
|
||||
return {
|
||||
id: `ffffffff-0000-0000-0000-${linkCounter.toString(16).padStart(12, '0')}`,
|
||||
sourceNodeId,
|
||||
sourcePortId,
|
||||
targetNodeId,
|
||||
targetPortId,
|
||||
};
|
||||
}
|
||||
|
||||
export function pc(nodeId: Id, portId: Id): NodeSnapshot {
|
||||
return { id: nodeId, kind: 'pc', ports: [portSnapshot(portId, 'eth0')] };
|
||||
}
|
||||
|
||||
export function device(ipAddress: string, options: { mask?: string; gateway?: string } = {}): DeviceConfiguration {
|
||||
return deviceConfiguration(ipAddress, options.mask ?? '255.255.255.0', options.gateway ?? '');
|
||||
}
|
||||
|
||||
export function startedEngine(
|
||||
input: TopologySnapshotInput,
|
||||
seed: number = 14,
|
||||
): NetworkRuntimeEngine {
|
||||
const engine = new NetworkRuntimeEngine(seed);
|
||||
engine.handle({ type: 'start', snapshot: topologySnapshot(input), seed, initialTimeMilliseconds: 0 });
|
||||
return engine;
|
||||
}
|
||||
|
||||
/** `00000000-0000-0000-0000-` followed by twelve hex digits. */
|
||||
export function uuid(suffix: number): Id {
|
||||
return `00000000-0000-0000-0000-${suffix.toString(16).toUpperCase().padStart(12, '0')}`;
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// Ported from filius-ipad ios/FiliusPadTests/TopologyJavaRouteTableTests.swift.
|
||||
// Left out: column titles and geometry (editor), and the reducer tests
|
||||
// (they move with the document layer, packages/doc).
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
appendingBlankDraftIfNeeded,
|
||||
bestMatchingManualRoute,
|
||||
blankRouteDraft,
|
||||
isValidJavaIPAddress,
|
||||
isValidJavaSubnetMask,
|
||||
manualRouteFromDraft,
|
||||
routeTableRows,
|
||||
visibleRouteRows,
|
||||
type ManualRoute,
|
||||
} from '../src/index.js';
|
||||
|
||||
function route(destinationNetwork: string, subnetMask: string, gateway: string, interfaceIPAddress: string): ManualRoute {
|
||||
return { destinationNetwork, subnetMask, gateway, interfaceIPAddress };
|
||||
}
|
||||
|
||||
describe('Java route table', () => {
|
||||
it('projects multiple interfaces in Java order with Java values', () => {
|
||||
const rows = routeTableRows(
|
||||
[
|
||||
{ ipAddress: '10.0.0.1', subnetMask: '255.255.255.0' },
|
||||
{ ipAddress: '192.168.0.1', subnetMask: '255.255.255.0' },
|
||||
],
|
||||
[
|
||||
route('172.16.0.0', '255.255.0.0', '10.0.0.2', '10.0.0.1'),
|
||||
route('203.0.113.0', '255.255.255.0', '192.168.0.2', '192.168.0.1'),
|
||||
],
|
||||
'10.0.0.254',
|
||||
);
|
||||
|
||||
expect(rows.map((row) => row.destinationNetwork)).toEqual([
|
||||
'192.168.0.1', '10.0.0.1',
|
||||
'192.168.0.0', '10.0.0.0',
|
||||
'127.0.0.0',
|
||||
'172.16.0.0', '203.0.113.0',
|
||||
'0.0.0.0',
|
||||
]);
|
||||
expect(rows.map((row) => row.origin)).toEqual([
|
||||
'localHost', 'localHost', 'connected', 'connected', 'localhost', 'manual', 'manual', 'defaultGateway',
|
||||
]);
|
||||
expect(rows.map((row) => row.isEditable)).toEqual([false, false, false, false, false, true, true, false]);
|
||||
expect(rows[0]).toMatchObject({ subnetMask: '255.255.255.255', nextHop: '127.0.0.1', interfaceIPAddress: '127.0.0.1' });
|
||||
expect(rows[2]?.nextHop).toBe('192.168.0.1');
|
||||
expect(rows[4]?.nextHop).toBe('127.0.0.1');
|
||||
expect(rows.at(-1)).toMatchObject({ nextHop: '10.0.0.254', interfaceIPAddress: '10.0.0.1' });
|
||||
});
|
||||
|
||||
it('puts the default route on the last matching interface and falls back to the primary one', () => {
|
||||
const interfaces = [
|
||||
{ ipAddress: '10.0.0.1', subnetMask: '255.0.0.0' },
|
||||
{ ipAddress: '10.1.0.1', subnetMask: '255.0.0.0' },
|
||||
];
|
||||
|
||||
const matching = routeTableRows(interfaces, [], '10.2.0.1');
|
||||
expect(matching.at(-1)).toMatchObject({ origin: 'defaultGateway', interfaceIPAddress: '10.1.0.1' });
|
||||
|
||||
const fallback = routeTableRows(interfaces, [], '192.168.0.1');
|
||||
expect(fallback.at(-1)?.interfaceIPAddress).toBe('10.0.0.1');
|
||||
});
|
||||
|
||||
it('shows only manual rows when generated rows are hidden', () => {
|
||||
const rows = routeTableRows(
|
||||
[{ ipAddress: '10.0.0.1', subnetMask: '255.255.255.0' }],
|
||||
[route('172.16.0.0', '255.255.0.0', '10.0.0.2', '10.0.0.1')],
|
||||
'10.0.0.254',
|
||||
);
|
||||
|
||||
expect(visibleRouteRows(rows, false).map((row) => row.origin)).toEqual(['manual']);
|
||||
expect(visibleRouteRows(rows, true)).toEqual(rows);
|
||||
});
|
||||
|
||||
it('accepts leading zeros and non-contiguous masks like Java', () => {
|
||||
expect(isValidJavaIPAddress('001.002.003.004')).toBe(true);
|
||||
expect(isValidJavaSubnetMask('255.0.255.0')).toBe(true);
|
||||
expect(isValidJavaIPAddress('256.0.0.1')).toBe(false);
|
||||
expect(isValidJavaSubnetMask('255.255.255')).toBe(false);
|
||||
expect(isValidJavaIPAddress(' 10.0.0.1')).toBe(false);
|
||||
});
|
||||
|
||||
it('commits a draft only when all four cells are valid', () => {
|
||||
const draft = blankRouteDraft('00000000-0000-0000-0000-000000000013');
|
||||
draft.destinationNetwork = '10.0.0.0';
|
||||
draft.subnetMask = '255.0.255.0';
|
||||
draft.nextGateway = '10.0.0.2';
|
||||
|
||||
expect(manualRouteFromDraft(draft)).toBeUndefined();
|
||||
|
||||
draft.interfaceIPAddress = '10.0.0.1';
|
||||
expect(manualRouteFromDraft(draft)).toEqual(route('10.0.0.0', '255.0.255.0', '10.0.0.2', '10.0.0.1'));
|
||||
});
|
||||
|
||||
it('keeps at most one pending blank draft', () => {
|
||||
let counter = 0;
|
||||
const newId = () => `draft-${(counter += 1)}`;
|
||||
const first = appendingBlankDraftIfNeeded([], newId);
|
||||
const second = appendingBlankDraftIfNeeded(first, newId);
|
||||
|
||||
expect(first).toHaveLength(1);
|
||||
expect(second).toEqual(first);
|
||||
expect(second[0]?.isPendingInsertion).toBe(true);
|
||||
});
|
||||
|
||||
it('picks the greatest numeric mask and keeps the first row on a tie', () => {
|
||||
const broad = route('10.0.0.0', '255.0.0.0', '1.1.1.1', '10.0.0.1');
|
||||
const firstSpecific = route('10.1.0.0', '255.255.0.0', '2.2.2.2', '10.0.0.1');
|
||||
const tiedSpecific = route('10.1.0.0', '255.255.0.0', '3.3.3.3', '10.0.0.1');
|
||||
|
||||
expect(bestMatchingManualRoute('10.1.2.3', [broad, firstSpecific, tiedSpecific])).toBe(firstSpecific);
|
||||
});
|
||||
|
||||
it('never includes learned RIP rows in the static projection', () => {
|
||||
const rows = routeTableRows([{ ipAddress: '10.0.0.1', subnetMask: '255.255.255.0' }], [], undefined);
|
||||
|
||||
expect(rows.some((row) => row.origin === 'rip')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".",
|
||||
"outDir": "dist",
|
||||
"types": []
|
||||
},
|
||||
"include": ["src", "test"]
|
||||
}
|
||||
Reference in New Issue
Block a user