@k13engineering/raw-packet-socket
v0.0.5
Published
Raw AF_PACKET sockets as Node.js duplex streams
Maintainers
Readme
node-raw-packet-socket
Raw AF_PACKET sockets for Node.js on Linux, as duplex streams of ethernet frames, written in TypeScript.
- Streams. Every chunk you read is one frame received on the interface, every chunk you write is sent as one frame.
- No external tools. Offloads are disabled with
SIOCETHTOOLioctls the wayethtool -Kdoes it, not by runningethtool. - Errors are events. Problems with opening the socket or with the interface are emitted as
"error"on the stream.
Requirements
- Linux on x86_64 or arm64
- Node.js 24 or newer
CAP_NET_RAWto open packet sockets, andCAP_NET_ADMINto disable offloads
Installation
npm install @k13engineering/raw-packet-socketUsage
import {
createNodeDuplexByInterfaceIndex,
disableOffloadsUntilReboot,
findInterfaceIndexByName
} from "@k13engineering/raw-packet-socket";
const { error, ifindex } = findInterfaceIndexByName({ interfaceName: "eth0" });
if (error !== undefined) {
throw error;
}
const duplex = createNodeDuplexByInterfaceIndex({
ifindex,
// receive frames the way they are on the wire instead of merged by the kernel
disableGenericReceiveOffloadUntilReboot: true,
// also receive frames addressed to other hosts
enablePromiscuousMode: true,
});
duplex.on("error", (err) => {
console.error(err);
});
duplex.on("data", (frame: Buffer) => {
console.log(frame);
});
// broadcast, from a locally administered address, with an experimental ethertype
const frame = new Uint8Array(60);
frame.set([0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0, 0, 0, 0, 0x01, 0x88, 0xb5]);
duplex.write(frame);findInterfaceIndexByName() returns { error, ifindex } instead of throwing.
createNodeDuplexByInterfaceIndex() opens, sets up and binds the socket before it returns the stream, but emits errors in another task, so they reach the listeners attached after the call. Then the stream emits "open" and "ready". Destroy the stream to close the socket. Ending it is an error, as an ethernet interface cannot be half-closed.
Interface indexes belong to a network namespace. The socket is opened in the network namespace of the calling thread at the time of the call, so a caller may enter the namespace of an interface with setns(), look up its index, create the stream and leave the namespace again right away.
The options are:
| Option | Effect |
| --- | --- |
| disableTcpSegmentationOffloadUntilReboot | like ethtool -K <interface> tso off |
| disableGenericSegmentationOffloadUntilReboot | like ethtool -K <interface> gso off |
| disableGenericReceiveOffloadUntilReboot | like ethtool -K <interface> gro off |
| disableHardwareGenericReceiveOffloadUntilReboot | like ethtool -K <interface> rx-gro-hw off |
| disableLargeReceiveOffloadUntilReboot | like ethtool -K <interface> lro off |
| disableUdpSegmentationOffloadUntilReboot | like ethtool -K <interface> tx-udp-segmentation off |
| disableTransmitChecksumOffloadUntilReboot | like ethtool -K <interface> tx off |
| disableVlanFilterUntilReboot | like ethtool -K <interface> rx-vlan-filter off |
| enablePromiscuousMode | PACKET_MR_PROMISC membership for as long as the socket is open |
| ignoreOutgoingFrames | PACKET_IGNORE_OUTGOING, only receive the frames arriving on the interface, Linux 4.20 or newer |
| restoreVlanTags | put the VLAN tags back into the received frames, from PACKET_AUXDATA like libpcap |
Besides the frames arriving on the interface, the stream receives the frames the host sends on it, except the ones written to the stream itself. ignoreOutgoingFrames leaves them out.
The kernel takes the outermost VLAN tag out of every frame it receives before a packet socket sees it, also without hardware offload, and keeps it out of the frames it sends with VLAN offload. restoreVlanTags puts it back between the source address and the ethertype, with its TPID, e.g. 0x8100 for 802.1Q or 0x88a8 for 802.1ad.
The receive offloads merge frames before the socket sees them. The transmit offloads leave the outgoing frames of the host unfinished where the socket sees them: oversized with segmentation offloads, with unfinished checksums with checksum offload. Turning off checksum offload makes the kernel turn off TCP and UDP segmentation offload as well.
Many NICs filter VLANs in hardware and drop the frames of the VLANs the host has not set up, depending on the driver also in promiscuous mode. disableVlanFilterUntilReboot turns that filter off, so the stream receives the frames of every VLAN. Like ethtool, it leaves the filter of 802.1ad tags, rx-vlan-stag-filter, alone.
The offloads stay disabled until the interface goes away, e.g. on reboot. Like ethtool, the ioctls address the interface by name, so renaming it while the socket is set up affects the wrong interface or fails.
The stream reports the interface going down as Error("interface went down").
disableOffloadsUntilReboot() disables offloads of an interface without opening a socket on it. On a macvlan interface, for example, the frames are merged on its parent already:
const { error } = disableOffloadsUntilReboot({
ifindex: parentIfindex,
offloads: ["generic-receive-offload", "rx-gro-hw", "large-receive-offload"],
});It takes the names ethtool -k shows: tx-checksumming, tcp-segmentation-offload, tx-udp-segmentation, generic-segmentation-offload, generic-receive-offload, rx-gro-hw, large-receive-offload and rx-vlan-filter. Like findInterfaceIndexByName(), it returns { error } instead of throwing.
How it works
The library performs the syscalls with po6 and syscall-napi, pins buffers handed to the kernel with buffer2address, and waits for the socket in the event loop with @k13engineering/uv-poll. The kernel structures are described with ya-struct and compared with the C headers in the tests.
Disabling an offload works like do_sfeatures() in ethtool without netlink. It reads the feature names and their state, turns off the features matching the offload (e.g. tx-checksum-* or tx-tcp*-segmentation) that the device allows changing, and only fails if nothing changed while the offload is still on. Whether it is on comes from its legacy flag, e.g. ETHTOOL_GTSO, or from its features for rx-gro-hw, tx-udp-segmentation and rx-vlan-filter, which have none.
Development
npm ci
npm run build # transpile to dist/
npm run type-check
npm run test # mocha with c8, 100% coverage required
npm run lintcreateRawPacketSocketApi() in lib/raw-packet-socket-api.ts gets the kernel passed in, index.ts passes the one of the host (lib/kernel.ts). The kernel consists of the syscalls, the pinning of buffers and the polling of file descriptors.
The unit tests run against a fake kernel from lib/test-support/, which emulates interfaces, packet sockets and ethtool features. Some specs use the real kernel instead:
lib/kernel-abi.spec.tscompiles C programs to compare the structures and constants with the headers, so it needsgccand the kernel headerslib/kernel.spec.tsandlib/index.spec.tsuse unprivileged syscalls of the hostlib/build.spec.tsbuilds the package and type-checks a consumer against its declarationslib/end-to-end.spec.tsexchanges frames, also tagged ones, over a veth pair in a user and network namespace of its own, and opens streams on a veth pair of another network namespace it enters only for the call. It needsunshareandip, and skips where unprivileged user namespaces are not allowed.
License
LGPL-2.1, see LICENSE.
