/** * @license * Copyright 2022-2026 Matter.js Authors * SPDX-License-Identifier: Apache-2.0 */ import { Cache, InterfaceType, isIPv6, Lifetime, Logger, Minutes, Network, NetworkError, NetworkInterface, NetworkInterfaceDetails, onSameNetwork, TCP_CONNECTION_TIMEOUT_MS, TcpConnection, TcpConnectOptions, TcpListener, TcpListenerOptions, UdpSocket, UdpSocketOptions, } from "@matter/general"; import { createConnection } from "node:net"; // Called through the module object so tests can replace networkInterfaces in every runtime, Bun included import os, { NetworkInterfaceInfo } from "node:os"; import { NodeJsTcpConnection } from "./NodeJsTcpConnection.js"; import { NodeJsTcpListener } from "./NodeJsTcpListener.js"; import { NodeJsUdpSocket } from "./NodeJsUdpSocket.js"; const logger = Logger.get("NetworkNode"); export class NodeJsNetwork extends Network { protected override clearInterfaceCaches() { return NodeJsNetwork.netInterfaces.clear(); } static getMulticastInterfaceIpv4(netInterface: string): string | undefined { const netInterfaceInfo = os.networkInterfaces()[netInterface]; if (netInterfaceInfo === undefined) throw new NetworkError(`Unknown interface: ${netInterface}`); for (const info of netInterfaceInfo) { if (familyIs(4, info)) { return info.address; } } return undefined; } static getMembershipMulticastInterfaces( netInterfaceOrZone: string | undefined, ipv4: boolean, ): (string | undefined)[] { if (ipv4) { if (netInterfaceOrZone === undefined) { return [undefined]; } // IPv4 group memberships select the interface by one of its addresses; joining without one lets the // kernel use the default-route interface, which on a multi-homed host is not the configured one const multicastInterfaces = Object.entries(os.networkInterfaces()).flatMap(([netIf, netIfInfo]) => { if (netIfInfo === undefined) { return []; } if (this.getNetInterfaceZoneIpv6Internal(netIf, netIfInfo) !== netInterfaceOrZone) { return []; } const ipv4Info = netIfInfo.find(info => familyIs(4, info)); return ipv4Info === undefined ? [] : [ipv4Info.address]; }); if (multicastInterfaces.length === 0) { logger.warn(`No IPv4 multicast interface found for interface ${netInterfaceOrZone}.`); } return multicastInterfaces; } else { const multicastInterfaces = Object.entries(os.networkInterfaces()).flatMap(([netIf, netIfInfo]) => { if (netIfInfo === undefined) { return []; } const zone = this.getNetInterfaceZoneIpv6Internal(netIf, netIfInfo); if (zone === undefined) { return []; } // zone is either the interface scope id (windows) or the interface name (linux, macos) // The potentially provided interface follows the same logic because it was pre-processed if (netInterfaceOrZone !== undefined && netInterfaceOrZone !== zone) { return []; } return [`::%${zone}`]; }); if (multicastInterfaces.length === 0) { logger.warn( `No IPv6 multicast interface found${ netInterfaceOrZone !== undefined ? ` for interface ${netInterfaceOrZone}` : "" }.`, ); } return multicastInterfaces; } } static getNetInterfaceZoneIpv6(netInterface: string): string | undefined { const netInterfaceInfo = os.networkInterfaces()[netInterface]; if (netInterfaceInfo === undefined) throw new NetworkError(`Unknown interface: ${netInterface}`); return this.getNetInterfaceZoneIpv6Internal(netInterface, netInterfaceInfo); } /** * Returns the zone-scoped name of the first non-internal IPv6 interface. * Used as a fallback for multicast sends when no interface has been observed * from inbound traffic (e.g. when all sessions run over TCP). */ static getDefaultNetInterface(): string | undefined { const interfaces = os.networkInterfaces(); for (const name in interfaces) { const infos = interfaces[name] as NetworkInterfaceInfo[]; if (infos.some(info => familyIs(6, info) && !info.internal)) { return this.getNetInterfaceZoneIpv6Internal(name, infos); } } return undefined; } static getNetInterfaceForIp(ip: string) { // Finding the local interface on the same interface is complex and won't change // So let's cache the results for 5mn return this.netInterfaces.get(ip); } private static readonly netInterfaces = new Cache( "Network interface", Lifetime.process, (ip: string) => this.getNetInterfaceForRemoteAddress(ip), Minutes(5), ); override async close() { await super.close(); // The cache is static and shared by every instance, so it must stay open await NodeJsNetwork.netInterfaces.clear(); } private static getNetInterfaceForRemoteAddress(ip: string) { if (ip.includes("%")) { // IPv6 address with scope return ip.split("%")[1]; } else { const interfaces = os.networkInterfaces(); for (const name in interfaces) { const netInterfaces = interfaces[name] as NetworkInterfaceInfo[]; for (const { address, netmask } of netInterfaces) { if (onSameNetwork(ip, address, netmask)) { return this.getNetInterfaceZoneIpv6Internal(name, netInterfaces); } } } if (isIPv6(ip)) { if (ip.startsWith("fd")) { // IPv6 address is an ULA return ""; // consider it as being ok and using the "Default interface" } } return undefined; } } private static getNetInterfaceZoneIpv6Internal( netInterface: string, netInterfaceInfos: NetworkInterfaceInfo[] | undefined, ): string | undefined { if (process.platform !== "win32") { return netInterface; } if (netInterfaceInfos === undefined) return undefined; return netInterfaceInfos .find(info => familyIs(6, info) && info.address.startsWith("fe80::")) ?.scopeid?.toString(); } /** * Get all network interfaces. * The optional configuration parameter allows to map interface names to types if this mapping is known. * Each network interface which has no mapped type is returned as Ethernet for now. * * @param configuration - An array of objects with the name and type properties. */ getNetInterfaces(configuration: NetworkInterface[] = []): NetworkInterface[] { const result = new Array(); const interfaces = os.networkInterfaces(); for (const name in interfaces) { const netInterfaces = interfaces[name] as NetworkInterfaceInfo[]; if (netInterfaces.length === 0) continue; if (netInterfaces[0].internal) continue; let type = InterfaceType.Ethernet; if (configuration.length > 0) { const nameType = configuration.find(({ name: mapName }) => name === mapName); if (nameType !== undefined && nameType.type !== undefined) { type = nameType.type; } } result.push({ name, type }); } return result; } getIpMac(netInterface: string): NetworkInterfaceDetails | undefined { const netInterfaceInfo = os.networkInterfaces()[netInterface]; if (netInterfaceInfo === undefined) return undefined; const ipV4 = netInterfaceInfo.filter(info => familyIs(4, info)).map(({ address }) => address); const ipV6 = netInterfaceInfo.filter(info => familyIs(6, info)).map(({ address }) => address); return { mac: netInterfaceInfo[0].mac, ipV4, ipV6 }; } override createUdpSocket(options: UdpSocketOptions): Promise { return NodeJsUdpSocket.create(options); } override createTcpListener(options: TcpListenerOptions): Promise { return NodeJsTcpListener.create(options); } override async connectTcp(host: string, port: number, options?: TcpConnectOptions): Promise { if (options?.abort?.aborted) { throw new NetworkError("TCP connect aborted"); } return new Promise((resolve, reject) => { let settled = false; // Captured by reference so settle() can detach the listener regardless of which path settles first. let abortListener: (() => void) | undefined; const detachAbort = () => { if (abortListener !== undefined) { options?.abort?.removeEventListener("abort", abortListener); abortListener = undefined; } }; const settle = (fn: () => void) => { if (settled) return; settled = true; detachAbort(); fn(); }; const socket = createConnection({ host, port, noDelay: true }, () => { socket.setTimeout(0); socket.off("error", rejectOnce); settle(() => resolve(new NodeJsTcpConnection(socket))); }); const rejectOnce = (error: Error) => settle(() => { socket.destroy(); reject(error); }); abortListener = () => rejectOnce(new NetworkError("TCP connect aborted")); socket.setTimeout(options?.timeout ?? TCP_CONNECTION_TIMEOUT_MS); socket.once("timeout", () => { socket.destroy(); settle(() => reject(new NetworkError("TCP connection timeout"))); }); socket.on("error", rejectOnce); options?.abort?.addEventListener("abort", abortListener, { once: true }); }); } } function familyIs(version: number, { family }: NetworkInterfaceInfo) { return family === `IPv${version}`; }