Skip to main content

Crate snare

Crate snare 

Source
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 Sim is 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.
CoalesceParams
The coalescing parameters a driver accepts: its supported_coalesce_params, a set of ETHTOOL_COALESCE_* bits (include/linux/ethtool.h). Bit n covers word n of Coalesce in kernel order, so ETHTOOL_SCOALESCE with a non-zero value in an unsupported field is EOPNOTSUPP (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_policy and set_default_dns_policy; the default answers at once and never fails.
EasyBuilder
A batteries-included HostProfile builder. Start from a preset that matches the kind of machine your code expects, tweak if needed, then build. Every preset ships a working NIC, so if_nametoindex, ethtool, getifaddrs and the /sys/class/net reads all succeed out of the box.
Eee
Energy Efficient Ethernet (struct ethtool_eee, ethtool --show-eee). Link modes are the legacy SUPPORTED_*/ADVERTISED_* bits.
Fabric
The Net the code under test’s sockets route through.
FlowRule
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.
HostProfile
A test-configurable description of the simulated host. Build one, then attach it to a Sim with SimBuilder::host.
IpNet
An address with a prefix length: an interface address with its subnet, or a route’s destination.
LengthField
Where a LengthPrefixed frame’s length field sits and how it gives the frame’s length.
LengthPrefixed
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 \n is not part of the value).
LinkStats
Interface statistics reported through rtnetlink IFLA_STATS64 (a subset of the kernel’s rtnl_link_stats64). Build with LinkStats { rx_packets: .., ..Default::default() }. They seed the topology’s live NicCounters, which the sim then advances as traffic crosses the interface; sysfs statistics/* and macOS NET_RT_IFLIST2 report 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 HostProfile with HostProfile::nic; the code under test then resolves it by name (if_nametoindex) and queries it over ethtool.
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), which getifaddrs, netlink and sysfs report; macOS’s struct if_data (<net/if_var.h>) shows the subset it has. The sim bumps tx_carrier_errors (if_link.h: “frame transmission errors due to loss of carrier”) for each frame sent while the link had no carrier, alongside tx_dropped. It never sets rx_errors, tx_errors or rx_nohandler (if_link.h: received “but dropped by the networking stack because the device is not designated to receive packets”); only set_nic_counters does.
NicEthtool
What a Nic’s driver can do and what has been set on it: the ethtool view of the interface. Read it back with SimHost::ethtool. A None operation is one the driver lacks, so its commands fail with EOPNOTSUPP.
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::new and add it with SimBuilder::nic or add_nic.
NodeTimes
Timestamps for a node an FsBuilder declares. A field left None takes the instant the sim the file system is handed to (SimBuilder::fs) is built at, on that sim’s clock.
ParseIpNetError
Why a string is not an IpNet.
Pause
Ethernet flow control (struct ethtool_pauseparam, ethtool -a).
PendingSignal
A signal SignalHandle::raise_after will 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 root and RLIMIT_MEMLOCK alone, Windows gates no socket call.
ProtoCounters
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 what PTP_CLOCK_GETCAPS reports and which of the clock’s ioctls work (drivers/ptp/ptp_chardev.c ptp_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), and gettimex64, so PTP_SYS_OFFSET_EXTENDED works. A profile copied from a real clock takes its PTP_CLOCK_GETCAPS words.
RecordedEntry
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 be Rlimit::INFINITY.
Route
A route: traffic to dest leaves through nic, to gateway when it is off-link, from src when the socket did not choose one.
RouteChoice
Where route_lookup sends traffic: the interface, the source address it would carry and the next hop when it is not on-link.
SignalHandle
Sends signals into one sim, from any thread: one of the sim’s own, or one outside it.
Sim
A running simulation: a Domain whose managed threads’ sockets are serviced by an in-memory Fabric, and whose file operations may be served by a VirtualFs. One per test.
SimBuilder
Composes a Sim from a fabric plus optional backends.
SimHost
A simulated host serving fast-talker’s tuning calls from an in-memory HostProfile.
SocketEntry
A snapshot of one socket. queued/delivered count datagrams for UDP and written chunks for TCP; sent counts successful sends. Times are on the sim’s timeline (see Sim::time_value).
SocketId
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_SNDBUF may 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_tester or udp_tester, describe its behaviour, drive it with run_testers!, then read back its state (inspect) or what it received (recorded).
TimeHandle
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 the Sim methods of the same names.
Tracefs
The tracefs a HostProfile serves. The default is a kernel with everything: the nop, function, osnoise and timerlat tracers, hist triggers, synthetic events and a snapshot buffer.
TracefsSim
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.
VirtualFs
An in-memory file system serving the file plane of a Sim; build one with FsBuilder and hand it to SimBuilder::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.
LinkFault
What a UdpPolicy did to one datagram.
ListenerBehavior
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.
RecordedEvent
Something that happened at the edge of the code under test. tester is the tester’s own address and peer the code under test’s end; len counts bytes.
Signal
A signal or console control event the code under test can be sent.
SignalDelivery
What delivering a signal did.
SignalOrigin
Who sent a recorded signal.
SocketKind
TesterAction
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.
TracefsFault
Something the code under test did to tracefs that a real kernel would punish or that a test should know about, from TracefsSim::faults and the sim’s recorded events.
Transport
Which protocol a tester’s traffic used.
UnmodelledOption
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/mlockall beyond RLIMIT_MEMLOCK (man 7 capabilities, man 2 mlockall; include/uapi/linux/capability.h).
CAP_NET_ADMIN
CAP_NET_ADMIN (12): interface configuration, including SIOCSHWTSTAMP (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 Delimited frame. Implement it on a marker type for a delimiter snare does not provide:
FrameLength
Where the length field of L’s frames sits; see LengthPrefixed.
Packet
A message type the tester reads from and writes to the code under test.

Functions§

add_host
Resolves name to addrs, 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 from to the datagram sockets of the code under test bound at to, as the host kernel takes one: a socket connected to from fails its next receive or send with ECONNREFUSED (its next receive with WSAECONNRESET on Windows); a socket connected elsewhere ignores it; an unconnected one ignores it on macOS (xnu bsd/netinet/udp_usrreq.c udp_ctlinput finds the socket with a non-wildcard in_pcblookup_hash on the datagram’s four-tuple, which only a socket connected to from matches) and on Linux unless IP_RECVERR is on (net/ipv4/udp.c __udp4_lib_err, udp_err in mainline: without RECVERR only a hard error on a TCP_ESTABLISHED, i.e. connected, socket sets sk_err; man 2const IP_RECVERR), and on Windows fails its next receive with WSAECONNRESET unless SIO_UDP_CONNRESET turned that off (Microsoft Learn: recvfrom, WSAECONNRESET; Microsoft Learn: Winsock IOCTLs, SIO_UDP_CONNRESET). Panics off a sim.
inject_socket_drops
Adds n to the drop counter of open socket id in the calling thread’s sim, as drops the kernel made below the socket: they show in SO_RXQ_OVFL and SO_MEMINFO and in SocketEntry::drops. NotFound when no such socket is open. Panics off a sim.
nic
Interface name as 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.stats or GetUdpStatistics. Panics off a sim.
quiesce
Holds the traffic at addr (every address it resolves to) for span on the sim’s clock: what arrives there for Direction::Receive, what leaves it for Direction::Send, both for Direction::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 error the pending error of every socket of the code under test at addr (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.c sosendcheck; Linux net/ipv4/tcp.c tcp_sendmsg_locked and net/core/sock.c sock_alloc_send_pskb); a receive after the data already queued on macOS (soreceive jumps to dontblock while sb_mb holds data), and on Linux for a stream (net/ipv4/tcp.c tcp_recvmsg_locked reports sk_err only once nothing was copied); before it on Linux for a datagram socket (net/ipv4/udp.c __skb_recv_udp checks sock_error before dequeuing) and on Windows (undocumented; tests/faults.rs raised_error_on_udp_ordering and raised_error_on_tcp_returns_buffered_data_first pin the sim’s order). Reporting clears it, as getsockopt(SO_ERROR) does (man 7 socket, SO_ERROR). A blocked call returns at once, and poll, epoll, kqueue, WSAPoll and select report the socket. Panics off a sim, and for an error kind with no socket error code.
real
Runs f with the calling thread’s OS calls going to the real OS, even inside a Sim::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)) or snare::real(|| std::env::var("KEY")). Runs f with 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_events reads it from anywhere. Scheduled link transitions that have come due are applied first, so their events are included.
remove_host
Forgets name in 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 dst from src (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 after from 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) at nic, 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 as behavior says, 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 id of the calling thread’s sim to interface nic, or unbinds it with None, as the code under test would with Linux SO_BINDTODEVICE, macOS IP_BOUND_IF or Windows IP_UNICAST_IF: its sends leave through nic and, where the host OS filters receives by device, it only receives what arrives there (docs/interfaces.md gives each host’s rules). An unknown interface fails with the code the option gives for one: ENODEV on Linux (net/core/sock.c sock_setbindtodevice), ENXIO on macOS (bsd/netinet/in_pcb.c inp_bindif) and WSAEINVAL on Windows; a socket that is not open is NotFound. 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 addr at 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 addr in 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 id of the calling thread’s sim, open or closed. Panics off a sim.
socket_id
The id of socket in the sim the calling thread runs in, or None for 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 Sim the calling thread runs in — the test body or any thread it spawned. Panics off a sim, and on a sim with no controllable clock (see Sim::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 carries addr as the source.