Expand description
Ergonomic in-process network testing, built on snare_interpose.
Write the code under test against plain std::net. In a test, create a Sim, run the code
inside it, and describe the peer it talks to with a Tester — the same shape as the original
snare’s connect_tester / then_action / with_cyclic_action / run_testers!.
use std::io::{BufRead, BufReader, Write};
use std::net::TcpStream;
use std::time::Duration;
use snare::{connect_tester, run_testers, Line, Sim, TesterAction};
let sim = Sim::new();
sim.run(|| {
let server = connect_tester::<Line>("127.0.0.2:9000")
.then_action(|msg, _from| TesterAction::Send(Line(format!("echo:{}", msg.0))))
.until_after(Duration::from_millis(200));
let client = std::thread::spawn(|| {
let mut stream = TcpStream::connect("127.0.0.2:9000").unwrap();
stream.write_all(b"hello\n").unwrap();
let mut line = String::new();
BufReader::new(stream).read_line(&mut line).unwrap();
line
});
run_testers!(server);
assert_eq!(client.join().unwrap(), "echo:hello\n");
});The code under test uses real TcpStream; its socket calls are serviced from process memory,
and the tester is the other end of the wire. Threads spawned inside Sim::run join the
simulation automatically.
Every resource or object used by the code under test must be created under its active
simulation, including dependency and worker initialization. real is reserved for the
harness and other-side emulation; it must not wrap the code under test or its constructors.
TCP (SOCK_STREAM) and UDP (SOCK_DGRAM) over IPv4/IPv6 are both serviced from memory, with
blocking or non-blocking sockets, poll, and readiness via epoll (Linux) or kqueue (macOS)
— so mio-based code runs on both. UDP covers bind/connect/sendto/recvfrom, blocking
cross-thread receive, broadcast, multicast and several addresses sharing a port.
This file holds only the public front: the unix Sim / SimBuilder (the Windows ones live
in win_host), the TimeHandle onto a sim’s clock, and the re-exports. Everything a sim
owns sits in one scope::SimShared, which every backend reaches either through the Sim
(from any thread) or through the calling thread’s scope (from inside Sim::run); the free
functions such as add_nic and add_host take the second route and panic off a sim.
Modules§
- prelude
- The items most tests use:
use snare::prelude::*;. - sched
- What each thread of a
Simis to the simulation, and what holds it busy.
Macros§
- run_
testers - Runs every tester until each one with a finish condition has finished, one thread per tester; testers without a finish condition run alongside as background peers and stop with the rest. The testers are borrowed, so their state and recordings can be read afterwards.
Structs§
- Bytes
- Every readable byte as one message, and back. A tester using this sees whatever chunks the stream delivers, with no framing of its own.
- Channels
- Queue counts and their maxima (
struct ethtool_channels,ethtool -l). - Coalesce
- Interrupt coalescing (
struct ethtool_coalesce,ethtool -c), field for field in the kernel’s order. - Coalesce
Params - The coalescing parameters a driver accepts: its
supported_coalesce_params, a set ofETHTOOL_COALESCE_*bits (include/linux/ethtool.h). Bitncovers wordnofCoalescein kernel order, soETHTOOL_SCOALESCEwith a non-zero value in an unsupported field isEOPNOTSUPP(ethtool_set_coalesce_supported). - Cr
- Frames end with
\r, as a Wenglor weCat3D scanner’s text commands do. - CrLf
- Frames end with
\r\n, as FANUC Remote Motion Interface JSON packets do (B-84184EN/03 §2.2, “Communication packets”). - Delimited
- A frame ended by
D’s delimiter, kept as the raw bytes it crossed the wire as, delimiter included. - DnsPolicy
- How the sim’s resolver answers one name, or every name without a policy of its own. Set with
set_dns_policyandset_default_dns_policy; the default answers at once and never fails. - Easy
Builder - A batteries-included
HostProfilebuilder. Start from a preset that matches the kind of machine your code expects, tweak if needed, thenbuild. Every preset ships a working NIC, soif_nametoindex,ethtool,getifaddrsand the/sys/class/netreads all succeed out of the box. - Eee
- Energy Efficient Ethernet (
struct ethtool_eee,ethtool --show-eee). Link modes are the legacySUPPORTED_*/ADVERTISED_*bits. - Fabric
- The
Netthe code under test’s sockets route through. - Flow
Rule - An n-tuple flow steering rule as the driver holds it (
ethtool -u). - FsBuilder
- Builds a
VirtualFs: declare virtual files and directories, the prefixes it owns, and glob patterns to pass through to (or deny at) the real OS. - Host
Profile - A test-configurable description of the simulated host. Build one, then attach it to a
SimwithSimBuilder::host. - IpNet
- An address with a prefix length: an interface address with its subnet, or a route’s destination.
- Length
Field - Where a
LengthPrefixedframe’s length field sits and how it gives the frame’s length. - Length
Prefixed - A frame whose length is read from a field in its header, kept as the raw bytes it crossed the wire as, header included.
- Lf
- Frames end with
\n. - Line
- A newline-delimited text message (the trailing
\nis not part of the value). - Link
Stats - Interface statistics reported through rtnetlink
IFLA_STATS64(a subset of the kernel’srtnl_link_stats64). Build withLinkStats { rx_packets: .., ..Default::default() }. They seed the topology’s liveNicCounters, which the sim then advances as traffic crosses the interface; sysfsstatistics/*and macOSNET_RT_IFLIST2report the same counters. - Membership
- A multicast group a socket joined: the group, the local interface address the join named (if any) and the interface index (0 when the join left it to the routing table).
- Nic
- A simulated network interface. Attach it to a
HostProfilewithHostProfile::nic; the code under test then resolves it by name (if_nametoindex) and queries it overethtool. - NicCounters
- An interface’s traffic counters. Frames count their Ethernet, IP and transport headers. The
fields are those of Linux’s
struct rtnl_link_stats(include/uapi/linux/if_link.h), whichgetifaddrs, netlink and sysfs report; macOS’sstruct if_data(<net/if_var.h>) shows the subset it has. The sim bumpstx_carrier_errors(if_link.h: “frame transmission errors due to loss of carrier”) for each frame sent while the link had no carrier, alongsidetx_dropped. It never setsrx_errors,tx_errorsorrx_nohandler(if_link.h: received “but dropped by the networking stack because the device is not designated to receive packets”); onlyset_nic_countersdoes. - NicEthtool
- What a
Nic’s driver can do and what has been set on it: theethtoolview of the interface. Read it back withSimHost::ethtool. ANoneoperation is one the driver lacks, so its commands fail withEOPNOTSUPP. - NicPolicy
- How the link behind one interface treats the traffic that crosses it (host to station and
station to station; never host-local traffic). Delays add to and losses compound with the
address’s
UdpPolicy; TCP takes the latency and jitter, in order, and never loses bytes. - NicSnapshot
- One interface as it is now.
- NicSpec
- One interface of the simulated host: its name, addresses, the station addresses on its
segment, and its link. Build with
NicSpec::newand add it withSimBuilder::nicoradd_nic. - Node
Times - Timestamps for a node an
FsBuilderdeclares. A field leftNonetakes the instant the sim the file system is handed to (SimBuilder::fs) is built at, on that sim’s clock. - Parse
IpNet Error - Why a string is not an
IpNet. - Pause
- Ethernet flow control (
struct ethtool_pauseparam,ethtool -a). - Pending
Signal - A signal
SignalHandle::raise_afterwill deliver. - Privileges
- What the code under test is allowed to do: whether it runs as root, the Linux capabilities
(capabilities(7)) it holds and the process resource limits (man 2 getrlimit) that let an
unprivileged process do some of the same. macOS gates on
rootandRLIMIT_MEMLOCKalone, Windows gates no socket call. - Proto
Counters - The host’s protocol counters, per address family, as the sim’s traffic drove them.
- PtpCaps
- What a PTP hardware clock’s driver offers (its
struct ptp_clock_info), which decides whatPTP_CLOCK_GETCAPSreports and which of the clock’s ioctls work (drivers/ptp/ptp_chardev.cptp_ioctl, Linux 7.0). The default is a bare clock: nothing to adjust (the sim’s PHC follows the virtual clock), no alarms, external timestamp channels, periodic outputs, PPS or pins, no cross-timestamping (getcrosststamp, as on igb’s I210), andgettimex64, soPTP_SYS_OFFSET_EXTENDEDworks. A profile copied from a real clock takes itsPTP_CLOCK_GETCAPSwords. - Recorded
Entry - One entry of the log: when it happened in sim time (see
Sim::time_value; real time since the sim was built on a sim without a virtual clock), its place in the log, and what happened. - Recorder
- What a tester received, shared with the code driving the test. Cheap to clone.
- Rings
- Descriptor ring sizes and their maxima (
struct ethtool_ringparam,ethtool -g). - Rlimit
- A resource limit as
getrlimit(2)reports it: the soft limit the kernel enforces (rlim_cur) and the ceiling an unprivileged process may raise it to (rlim_max), in the resource’s unit. Either may beRlimit::INFINITY. - Route
- A route: traffic to
destleaves throughnic, togatewaywhen it is off-link, fromsrcwhen the socket did not choose one. - Route
Choice - Where
route_lookupsends traffic: the interface, the source address it would carry and the next hop when it is not on-link. - Signal
Handle - Sends signals into one sim, from any thread: one of the sim’s own, or one outside it.
- Sim
- A running simulation: a
Domainwhose managed threads’ sockets are serviced by an in-memoryFabric, and whose file operations may be served by aVirtualFs. One per test. - SimBuilder
- Composes a
Simfrom a fabric plus optional backends. - SimHost
- A simulated host serving
fast-talker’s tuning calls from an in-memoryHostProfile. - Socket
Entry - A snapshot of one socket.
queued/deliveredcount datagrams for UDP and written chunks for TCP;sentcounts successful sends. Times are on the sim’s timeline (seeSim::time_value). - Socket
Id - One socket of a sim, numbered from 1 in creation order and never reused. Ids are per sim: two sims both start at 1, so an id only means something in the sim that issued it.
- SysLimits
- The host’s socket-buffer sysctls: the defaults a new socket gets, the most
SO_RCVBUF/SO_SNDBUFmay ask for, and the lowest port an unprivileged process may bind. A change applies to sockets created after it. The Linux knobs are documented in Documentation/admin-guide/sysctl/net.rst (net.core.*) and Documentation/networking/ip-sysctl.rst (net.ipv4.*). - TcpCounters
- A snapshot of one family’s TCP counters (see
proto_counters). - TcpPolicy
- How the simulated link delays a TCP connection’s bytes. Set with
set_tcp_policy; the default is an instant link. - Tester
- Plays the peer at an address the code under test talks to. Build it with
connect_testerorudp_tester, describe its behaviour, drive it withrun_testers!, then read back its state (inspect) or what it received (recorded). - Time
Handle - A handle to a
Sim’s virtual clock, usable from any thread — one running inside the sim, or one outside it driving time while every simulated thread waits. See theSimmethods of the same names. - Tracefs
- The tracefs a
HostProfileserves. The default is a kernel with everything: thenop,function,osnoiseandtimerlattracers, hist triggers, synthetic events and a snapshot buffer. - Tracefs
Sim - The test’s view of a sim’s tracefs, from
SimHost::tracefs: what the code under test registered, and the hooks that make the tracers report something. - UdpCounters
- A snapshot of one family’s UDP counters (see
proto_counters). - UdpPolicy
- How the simulated link treats datagrams to and from one address. Set with
set_udp_policy; the default is a perfect link. - Virtual
Fs - An in-memory file system serving the file plane of a
Sim; build one withFsBuilderand hand it toSimBuilder::fs.
Enums§
- Direction
- Which traffic a stall holds, as seen from the code under test’s address (see
quiesce). - DnsFailure
- How a lookup fails, as the host OS reports it.
- Endian
- Byte order of a multi-byte length field.
- Fault
- A fault injected into the code under test, as it took effect.
- Link
Fault - What a
UdpPolicydid to one datagram. - Listener
Behavior - How a TCP listening address answers connects, set with
set_listener_behavior. It applies to a tester’s listener and to one of the code under test alike, and to an address nothing listens on yet. - Recorded
Event - Something that happened at the edge of the code under test.
testeris the tester’s own address andpeerthe code under test’s end;lencounts bytes. - Signal
- A signal or console control event the code under test can be sent.
- Signal
Delivery - What delivering a signal did.
- Signal
Origin - Who sent a recorded signal.
- Socket
Kind - Tester
Action - What a tester does in response to a message, a new peer, or a cyclic tick.
- Toward
- Which side a tester kept traffic from while it was quiesced.
- Tracefs
Fault - Something the code under test did to tracefs that a real kernel would punish or that a test
should know about, from
TracefsSim::faultsand the sim’s recorded events. - Transport
- Which protocol a tester’s traffic used.
- Unmodelled
Option - A socket option or ioctl request the code under test used on a sim socket that the sim does
not model. Numbers are the host’s own (
<sys/socket.h>,<winsock2.h>).
Constants§
- CAP_
IPC_ LOCK CAP_IPC_LOCK(14):mlock/mlockallbeyondRLIMIT_MEMLOCK(man 7 capabilities, man 2 mlockall; include/uapi/linux/capability.h).- CAP_
NET_ ADMIN CAP_NET_ADMIN(12): interface configuration, includingSIOCSHWTSTAMP(man 7 capabilities; include/uapi/linux/capability.h).- CAP_
NET_ BIND_ SERVICE - Capability numbers (
<linux/capability.h>) the setters gate on. Exposed so tests can grant them by name.CAP_NET_BIND_SERVICE(10) permits binding a port below 1024 (man 7 capabilities; include/uapi/linux/capability.h). - CAP_
NET_ RAW CAP_NET_RAW(13): raw and packet sockets (man 7 capabilities; include/uapi/linux/capability.h).- CAP_
SYS_ NICE CAP_SYS_NICE(23): real-time scheduling policies and lowering the nice value (man 7 capabilities, man 7 sched; include/uapi/linux/capability.h).
Traits§
- Delimiter
- The byte string that ends each
Delimitedframe. Implement it on a marker type for a delimiter snare does not provide: - Frame
Length - Where the length field of
L’s frames sits; seeLengthPrefixed. - Packet
- A message type the tester reads from and writes to the code under test.
Functions§
- add_
host - Resolves
nametoaddrs, in that order, in the sim the calling thread runs in, replacing any addresses it had. Case and one trailing dot do not matter. A name added with no addresses is known but has none, which lookups report as the host OS reports such a name. - add_nic
- Adds an interface to the calling thread’s sim and returns its index. Fails if the name or index is taken. The first interface with an address ends the open sim: from then on the code under test can only bind the host’s addresses and its interfaces’ station addresses.
- add_
route - Adds a route through an existing interface.
- clear_
recorded_ events - Empties the log of the sim the calling thread runs in, so what follows can be read on its own. Sequence numbers carry on from where they were.
- closed_
sockets - The closed sockets of the calling thread’s sim, in the order they closed. Panics off a sim.
- connect_
tester - Registers a TCP tester as the peer the code under test will connect to at
addr. - inject_
icmp_ port_ unreachable - Delivers an ICMP port unreachable from
fromto the datagram sockets of the code under test bound atto, as the host kernel takes one: a socket connected tofromfails its next receive or send withECONNREFUSED(its next receive withWSAECONNRESETon Windows); a socket connected elsewhere ignores it; an unconnected one ignores it on macOS (xnu bsd/netinet/udp_usrreq.cudp_ctlinputfinds the socket with a non-wildcardin_pcblookup_hashon the datagram’s four-tuple, which only a socket connected tofrommatches) and on Linux unlessIP_RECVERRis on (net/ipv4/udp.c__udp4_lib_err,udp_errin mainline: withoutRECVERRonly a hard error on aTCP_ESTABLISHED, i.e. connected, socket setssk_err; man 2constIP_RECVERR), and on Windows fails its next receive withWSAECONNRESETunlessSIO_UDP_CONNRESETturned that off (Microsoft Learn: recvfrom,WSAECONNRESET; Microsoft Learn: Winsock IOCTLs,SIO_UDP_CONNRESET). Panics off a sim. - inject_
socket_ drops - Adds
nto the drop counter of open socketidin the calling thread’s sim, as drops the kernel made below the socket: they show inSO_RXQ_OVFLandSO_MEMINFOand inSocketEntry::drops.NotFoundwhen no such socket is open. Panics off a sim. - nic
- Interface
nameas it is now. - nic_
counters - Interface
name’s counters now. - nics
- Every interface, by index.
- privileges
- The privileges of the calling thread’s sim. Panics off a sim.
- proto_
counters - The protocol counters of the calling thread’s sim: the same numbers the code under test reads
from
/proc/net/snmp,net.inet.udp.statsorGetUdpStatistics. Panics off a sim. - quiesce
- Holds the traffic at
addr(every address it resolves to) forspanon the sim’s clock: what arrives there forDirection::Receive, what leaves it forDirection::Send, both forDirection::Both. TCP bytes in flight and written meanwhile, and a FIN, land in order once the stall ends, still counting against the receive window; bytes already received stay readable. Datagrams arrive once it ends. Panics off a sim. - raise_
socket_ error - Makes
errorthe pending error of every socket of the code under test ataddr(every address it resolves to): each stream whose local or peer address it is, and each datagram socket bound at or connected to it. The next call that reports errors fails with it, as the host kernel orders them: a send first everywhere (xnu bsd/kern/uipc_socket.csosendcheck; Linux net/ipv4/tcp.ctcp_sendmsg_lockedand net/core/sock.csock_alloc_send_pskb); a receive after the data already queued on macOS (soreceivejumps todontblockwhilesb_mbholds data), and on Linux for a stream (net/ipv4/tcp.ctcp_recvmsg_lockedreportssk_erronly once nothing was copied); before it on Linux for a datagram socket (net/ipv4/udp.c__skb_recv_udpcheckssock_errorbefore dequeuing) and on Windows (undocumented; tests/faults.rsraised_error_on_udp_orderingandraised_error_on_tcp_returns_buffered_data_firstpin the sim’s order). Reporting clears it, asgetsockopt(SO_ERROR)does (man 7 socket,SO_ERROR). A blocked call returns at once, and poll, epoll, kqueue,WSAPolland select report the socket. Panics off a sim, and for an error kind with no socket error code. - real
- Runs
fwith the calling thread’s OS calls going to the real OS, even inside aSim::run. Reserved for the test harness and other-side emulation that need real files, the real environment or real sockets. The code under test and all its resource construction must stay under the active simulation, outside this closure. Wrap an ordinary std call in it, e.g.snare::real(|| std::fs::read(path))orsnare::real(|| std::env::var("KEY")). Runsfwith the calling thread’s OS calls going to the OS, even on a managed thread. - recorded_
events - Everything the sim the calling thread runs in has recorded so far, oldest first. Panics off a
sim;
Sim::recorded_eventsreads it from anywhere. Scheduled link transitions that have come due are applied first, so their events are included. - remove_
host - Forgets
namein the sim the calling thread runs in. - remove_
nic - Removes an interface, its addresses and its routes; TCP bytes stalled on its link move again.
- remove_
route - Removes the configured routes to
dest; whether there were any. - route_
lookup - Where the host would send traffic to
dstfromsrc(or a source it picks), or the error a connect there fails with. - routes
- Every route, the connected subnets of the interfaces’ addresses first.
- schedule_
link - Gives or takes an interface’s carrier
afterfrom now on the sim’s clock. A thread blocked on traffic over the link wakes when it changes. - set_
default_ dns_ policy - Changes how the sim the calling thread runs in answers lookups of names without a policy of their own.
- set_
default_ route - Points the default routes (
0.0.0.0/0,::/0) atnic, or removes them. - set_
dns_ policy - Changes how the sim the calling thread runs in answers lookups of
name, known or not. - set_
link - Gives or takes an interface’s carrier now.
- set_
listener_ behavior - Makes
addr(every address it resolves to) answer connects asbehaviorsays, in the sim the calling thread runs in. The wildcard address covers every address on its port that has no behaviour of its own. Panics off a sim. - set_nic
- Edits an interface in place (not its name or index): addresses, stations, MTU, admin state, carrier, policy.
- set_
nic_ counters - Edits an interface’s live counters.
- set_
nic_ policy - Edits an interface’s link policy; see
NicPolicy. - set_
privileges - Changes the privileges of the calling thread’s sim, from then on. Panics off a sim.
- set_
socket_ device - Binds open socket
idof the calling thread’s sim to interfacenic, or unbinds it withNone, as the code under test would with LinuxSO_BINDTODEVICE, macOSIP_BOUND_IFor WindowsIP_UNICAST_IF: its sends leave throughnicand, where the host OS filters receives by device, it only receives what arrives there (docs/interfaces.mdgives each host’s rules). An unknown interface fails with the code the option gives for one:ENODEVon Linux (net/core/sock.csock_setbindtodevice),ENXIOon macOS (bsd/netinet/in_pcb.cinp_bindif) andWSAEINVALon Windows; a socket that is not open isNotFound. Unlike the option, it is never refused for want of privilege. Panics off a sim. - set_
sys_ limits - Changes the socket limits of the calling thread’s sim for sockets created from then on. Panics off a sim.
- set_
tcp_ policy - Changes the link policy for every TCP connection with
addrat either end — a listener the code under test connects to, a tester, or a known client address — in both directions. Callable from any thread of the test. - set_
udp_ policy - Changes the link policy for datagrams to and from
addrin the current sim — the address of a socket the code under test binds, or of a tester. Callable from any thread of the test. - socket_
entry - Socket
idof the calling thread’s sim, open or closed. Panics off a sim. - socket_
id - The id of
socketin the sim the calling thread runs in, orNonefor a socket the sim does not serve (a real OS socket) and off a sim. - socket_
table - The open sockets of the calling thread’s sim, oldest first. Panics off a sim.
- sockets_
bound - The open sockets of the calling thread’s sim whose local address is
local(any address it resolves to): bound datagram sockets, a listener and the streams accepted from it. Panics off a sim. - sys_
limits - The socket limits of the calling thread’s sim. Panics off a sim.
- time
- The clock of the
Simthe calling thread runs in — the test body or any thread it spawned. Panics off a sim, and on a sim with no controllable clock (seeSim::time). - udp_
tester - Binds a UDP tester at
addr: datagrams the code under test sends there reach its handlers, with their source address, and what it sends carriesaddras the source.