JFLib

17. Network programs#

The building blocks of network programs -- servers, agents, command-line clients -- are library crates that any program can use (all no_std, no unsafe, see API.md):

  • netio::Server::start(&addr, ServerConfig, handler) -- an HTTP/1.1 server with a worker pool, keep-alive and limits; start_with(.., Some(wrap)) puts TLS (or anything else) under it and passes the identity it proved (a client certificate) to the handler. A slow client holds a worker only so long: the head within read_ms, a body at server::MIN_BODY_RATE (1 KiB a second) on average after a first read_ms; over TLS, records without data end a read after the stream's read timeout too.

  • netio::Client / client::Session -- requests with timeouts and size limits, kept-alive sessions; with_connector(netio::trust::connector(..)) for https to a server with its own CA (a CA file, a pinned fingerprint, or trust on first use). Bodies in gzip and br are asked for and decoded by default (decode; also zstd and deflate, max_body after decoding); the rest is switched on: with_redirects(n) (never from https to http; credentials stay with their origin; fetch gives the last URL), with_cookies(jar) (netpkt::cookie::Jar, the public suffix list deciding which Domain a site may set), with_pool(Pool::new()) (keep-alive), with_proxy(netio::proxy::Proxy::from_env()?) (HTTP proxies and CONNECT tunnels, NO_PROXY), deadline_ms for a whole request.

  • netio::tls -- TLS 1.3 servers and clients (ChaCha20-Poly1305, AES-GCM; X25519MLKEM768, X25519, P-256, P-384; Ed25519, ECDSA and RSA certificates and keys, mutual authentication), certificates by SNI (ServerConfig::identities, select), ALPN (ClientConfig::alpn, ServerConfig::alpn); Identity::from_pem(chain, key) reads what a CA hands out (PKCS #8, SEC 1, PKCS #1). Resumption with session tickets: ServerConfig::tickets (Arc<tls::Tickets>, one for all connections of a server) and ClientConfig::sessions (Arc<tls::Sessions>, a client's tickets); 0-RTT only where the server allows it (ServerConfig::early_data, tls::connect_early, TlsStream::read_early for data that may be a replay). netio::x509 builds and checks the certificates of a private CA (CertBuilder::sign_key with any key, sign_ext adds or replaces extensions: name constraints, a CA's purposes; x509::PrivateKey). The chain check honours name constraints for wildcards by the names they stand for and the extended key usage of every CA on the path (a CA for client certificates certifies no server). Trust::System(extra) connects to public servers: TLS 1.3 or TLS 1.2 with ECDHE, the chain built and checked by the system (Windows CryptoAPI and macOS / iOS's Security framework, with the stapled OCSP response; Linux against the distribution's CA bundle, or SSL_CERT_FILE / SSL_CERT_DIR), then the leaf by netio once more (x509::check_leaf); the system checks the extra CAs (a company CA) under its own policy (Linux where the bundle gives no path), and a refusal names its reason (expired, revoked, another name, unknown CA; netio::roots::verify_system answers it as roots::Reason); netio::trust::system_connector(extra) gives the connector for Client. OCSP stapling: ServerConfig::ocsp (Arc<tls::Staples>, kept current by netio::ocsp::refresh(&staples, &client, &chain, issuer), which says when to call it again) staples the CA's response; a client checking against CAs asks for one (ClientConfig::revocation: Stapled by default refuses a certificate the response calls revoked, Required one without a good response, Off); a must-staple certificate (RFC 7633) needs one. x509::ocsp checks and builds responses, x509::CsrBuilder / Csr write and read certificate requests.

  • netio::acme -- certificates from Let's Encrypt or another ACME CA (RFC 8555): Acme::new(client, acme::LETS_ENCRYPT), acme.account(key, &NewAccount { terms_agreed: true, .. }), account.issue(&[Identifier::parse("example.org")], &cert_key, &mut solver, &OrderOptions::default()) -> the chain (Issued::identity(&cert_key) for ServerConfig, or select for one renewed while the server runs). Solvers: acme::Http01 (its handler(site) on port 80), acme::TlsAlpn01 (setup(&mut tls_cfg) on port 443), dns-01 by the program's own Solver for its DNS provider (dns01_name, dns01_value; wildcards need it), Solvers to combine. When to renew: acme.renewal_info(&cert) (ARI), the new order with OrderOptions::replaces: acme::ari_id(&cert). Keep the account key (PrivateKey::to_pkcs8); test against acme::LETS_ENCRYPT_STAGING first, Let's Encrypt's rate limits are strict.

  • netio::smtp::send(&SmtpConfig, &Mail) -- e-mail (STARTTLS, TLS, or plain to any server with Security::None, e.g. a relay on port 25 inside a network; AUTH PLAIN / LOGIN only over TLS, a plain connection with a user name is refused; text and HTML parts, RFC 2047 subjects).

  • netio::ssh::Client -- run commands on a machine over SSH (curve25519, ssh-ed25519, chacha20-poly1305, strict key exchange), host key pinned by fingerprint.

  • netio::dns::resolve -- names to addresses (Linux: hosts file, resolv.conf, UDP and TCP). A name server on an IPv6 link-local address keeps its zone: nameserver fe80::1%eth0 (the interface by name, from /sys/class/net/NAME/ifindex, or by number, %2) becomes the socket address's sin6_scope_id (SocketAddr::scope); netio::dns::Config::system() on Windows takes the adapters' DNS servers with their scope (plat::net::dns_servers). plat::net::ip_scope_parse, if_index and local_addrs (the computer's own addresses) are the pieces; SocketAddr::parse and Display know [fe80::1%2]:53.

  • netio::dns::lookup(name, rtype) / dns::Resolver -- records of any type (MX, TXT, SRV, CAA, TLSA, HTTPS ...; netpkt::dns::TYPE_*) as Lookup { name, aliases, records, ttl }; a Resolver keeps answers as long as their TTL says (negative ones by their SOA). DNS over TLS and over HTTPS by Config::secure (then the plain servers are not asked):

    let cfg = dns::Config { secure: vec![dns::Server::tls(SocketAddr::new(IpAddr::V4([1, 1, 1, 1]), 853), "cloudflare-dns.com")],
                            ..dns::Config::default() };
    let r = dns::Resolver::new(cfg);
    for rr in r.lookup("gmail.com", netpkt::dns::TYPE_MX)?.records {
        plat::write_stdout(format!("{}\n", rr.data.text()).as_bytes());   // "5 gmail-smtp-in.l.google.com"
    }

    DNSSEC validation is off by default; Config::dnssec: Some(dns::Dnssec::root()) checks every answer up to the root zone's keys: Lookup::security says Secure or Insecure (an unsigned zone), a bogus answer is an error with code == dns::BOGUS. netio::dane::trust(&r, host, port) makes a TLS trust of the host's TLSA records when they are secure (Trust::Dane, RFC 7671), else the system's CAs:

    let r = dns::Resolver::new(dns::Config { dnssec: Some(dns::Dnssec::root()), ..dns::Config::system() });
    let trust = netio::dane::trust(&r, "www.example.org", 443)?;
    let tcp = plat::net::TcpStream::connect(&r.resolve("www.example.org", 443)?[0], 5000)?;
    let tls = netio::tls::connect(Box::new(tcp), netio::tls::ClientConfig::new(trust, "www.example.org"));
  • datastore::Store -- JSON collections in a crash-safe journal database with transactions; Journal for append-only logs. Secondary indexes in memory (add_index with Index::field or Index::by, unique() refusing what breaks it with StoreError::Conflict; find, find_one, range), and encryption at rest (Store::open_encrypted, Journal::open_encrypted with a 32-byte key, for example from plat::secret::secret_get; rekey encrypts, changes the key or decrypts).

  • cas::Repo -- content-addressed, deduplicated, encrypted repositories with signed snapshots: only trusted keys (CreateOptions::signer, trust_signer) save and load them (CasError::UntrustedSigner); the list is protected by the repository key, so it does not keep out someone who can open the repository. A repository lives in a folder (cas::Folder, Repo::open(path, ..)) or in any cas::Store, which keeps its objects by kind and name the way S3, SFTP or WebDAV do (Repo::create_in / open_in; writes atomic and durable, reads of chunks in ranges, one holder through Store::lock).

  • crypto -- hashes (SHA-2 incl. SHA-384, BLAKE2b, BLAKE3), MACs, KDFs, Argon2id, AEAD (ChaCha20-Poly1305, XChaCha, AES-GCM), X25519, P-256 key exchange, Ed25519, RSA (PKCS#1 v1.5, PSS) and ECDSA P-256 / P-384 verification (randomness comes from the caller: plat::random_bytes on Windows, Linux, macOS, iOS and Android; the browser has no system generator in plat, a web page takes crypto.getRandomValues). For protocols that are defined with them (WPA2 and WPA3): SHA-1 (sha1, Sha1, hmac_sha1; broken for collisions, new designs take SHA-256), PBKDF2 over any hash (pbkdf2::<H>, pbkdf2_sha1), the AES key wrap of RFC 3394 (aes_wrap / aes_unwrap, which checks the integrity value) and AES-CMAC of RFC 4493 (cmac_aes). For protocols defined with MD5 (RADIUS): MD5 (md5, Md5, md5_parts) and HMAC-MD5 (hmac_md5); broken for collisions, so new designs take SHA-256 (RFC 1321, 2104).

  • compress -- DEFLATE, zlib and gzip in both directions (compress::gzip::compress(data, level) / decompress(data, max_out); levels 0 to 9), Brotli, the br of HTTP (compress::brotli::compress(data, level) / decompress; levels 0 to 11, LEVEL_DEFAULT 5 for a web server's responses, 11 for files compressed once), LZ4 (lz4::compress_hc for smaller blocks) and zstd (compress::zstd::compress(data, level) / decompress; levels 1 to 19, single-segment frames with checksums), zstd dictionaries for small records (zstd::Dictionary::train(&samples, 16 << 10), compress_with_dict, in the format of zstd --train), CRC-32, Adler-32 and xxHash; Codec picks LZ4 or zstd by name. Each format also in pieces (compress::stream): gzip::Decoder::new().decode(input, out) takes input as it comes and writes at most out, with a window of the format's size as its only memory; gzip::Encoder, zstd::Encoder and the others with Flush::Sync for live data; stream::decode_all(dec, read, write, limit) pumps a whole file.

  • formats -- data formats as text, without a dependency: formats::json (strict bounded JSON, numbers kept as their exact token, parse_with_limits / stringify_pretty), formats::jmap (typed records, below), formats::xml (Reader, the strict pull reader with namespaces and offsets; Lenient, the forgiving one for files from editors; parse, a bounded tree of a subset that refuses a DTD, comments and mixed content) and formats::encoding (strict UTF-8 and UTF-16 by their byte-order mark; every encoding of the WHATWG Encoding Standard as browsers read and write it: Charset, the single-byte sets of the web and of DOS files, MultiByte, Shift_JIS, EUC-JP, ISO-2022-JP, GBK, gb18030, Big5 and EUC-KR with encode / encode_html; label("iso-8859-2"), from_code_page(932) and decode_label as the standard reads labels; Decoder for input in pieces). agent_core::json / jmap and base::xml / encoding are the same modules under their names until 0.2.1.

  • plat::watch::Watcher::new(&roots) / take(ms) -- the changed paths below folders (ReadDirectoryChangesW / inotify, recursive; overflow when events were lost; Android: inotify on the app's folders, /data, /documents ...). Every change after new returned is seen. A root that is deleted or moved away (Linux: also a folder that could not be watched or listed yet) is tried again every second; until it is watched again watching() is false and every take reports overflow after its wait, so a caller that rescans on overflow polls meanwhile.

  • plat::net::UnixListener::bind(path) / connect_unix(path, ms) -- Unix domain sockets (Linux, Windows 10 1803 and later) with the stream calls of TcpStream. bind removes only a socket file nobody listens on any more; a file, a folder or a socket that is listened on stays and bind fails. A dropped listener removes its socket file, not a name taken again meanwhile.

  • plat::process::Command { program, args, cwd, env }.spawn() -- a child process with pipes (no shell); dropping the Child ends its process tree, Child::id() gives its process id.

  • plat::process_alive(pid) -- whether a process with this id runs (the owner of a lock file, a helper started earlier; a process of another user counts too), on every target, false in the browser; plat::process_id() is this process's id. Ids are reused once a process ended, so a lock file should hold more than the id where that matters.

  • netpkt -- packets byte for byte, without I/O (written for JFNetworker's simulator): Mac, Ipv4, Ipv6 (RFC 5952 text), Prefix4 / Prefix6; the Internet checksum (checksum::sum / finish / verify, pseudo headers, update16 for incremental changes) and crc32; views that check lengths once (EthView, Ipv4View, TcpView, ...) and records that write headers in front of a payload (Pkt::push, Ipv4Hdr::push_onto, TcpHdr::push_v4); 802.1Q tags, ARP, ICMP errors with their quote, IPv4 fragmentation and Reassembly; decode::layers(frame) (fields with byte ranges for an inspector), decode::proto_mask (filters; decode::ip_mask and decode::stack_ip for packets without a link header, as on serial lines), decode::info (one-line summaries); pcapng::Writer / pcapng::read for Wireshark files; http::Parser for HTTP/1.1 in pieces of any size (push adds bytes and gives the next event -- More, Head, Data, End --, poll the ones after it, pipelined messages one after the other, finish at the end of the stream) and http::encode_request / encode_response / encode_chunked by the wire rules of netio::http. For address translation, nat::rewrite(pkt, Side::Src | Side::Dst, addr, Some(port)) changes a packet in place with every checksum it touches updated incrementally (IPv4 header, TCP and UDP with their pseudo header -- a UDP checksum of 0 stays 0 --, the identifier of an ICMP query; a later fragment changes its address only), nat::rewrite_quoted does the same to the packet an ICMP error quotes together with the error's own checksum (RFC 5508), nat::Flow::of / Flow::quoted give what translation and filters look at (addresses, ports or the ICMP identifier, type and code, TCP flags, fragment position), and checksum::update(ck, old, new) follows any changed run of bytes (RFC 1624).

    let mut p = Pkt::new(netpkt::pkt::HEADROOM, b"payload");
    UdpHdr::new(40000, 53).push_v4(&mut p, src, dst);
    Ipv4Hdr::new(src, dst, ipv4::PROTO_UDP, 64).push_onto(&mut p);
    EthHdr { dst: gw_mac, src: my_mac, ethertype: eth::ET_IPV4 }.push_onto(&mut p);
    let frame = p.into_vec();

    Application protocols: dhcp (RFC 2131 / 2132: DhcpView, Dhcp with typed options in their order, Opt::RelayInfo of RFC 3046, long options split and joined per RFC 3396, to_bytes(dhcp::BOOTP_MIN) pads to the usual 300 bytes), dns (RFC 1035: Message with header, questions and A, AAAA, NS, CNAME, PTR, MX, SOA and TXT records; names with compression pointers both ways, loops refused; to_bytes_max(512) leaves out whole records and sets TC; reverse_v4, is_subdomain), ntp (the 48-byte header, Ts timestamps that keep whole nanoseconds, offset_delay) and syslog (pri, the BSD and IOS message forms, parse). decode::layers and decode::info dissect all four ("DHCP Discover - Transaction ID 0x3d1d", "Standard query response 0x1234 A www.lab CNAME web.lab A 10.0.2.20").

    let mut m = Dhcp::new(dhcp::OP_REQUEST, xid, mac);
    m.set(Opt::MsgType(MsgType::Discover));
    m.set(Opt::Params(vec![1, 3, 6, 15]));
    let payload = m.to_bytes(dhcp::BOOTP_MIN);
    let q = dns::Message::query(id, "www.lab", dns::TYPE_A, true).to_bytes();
    let answer = dns::Message::parse(&reply)?;          // answers, authority, additional

    Spanning tree: stp has the BPDUs of STP and RSTP -- Configuration and TCN BPDUs of 802.1D-1998, RST BPDUs of 802.1D-2004 with their flags and port role (Role, F_PROPOSAL, F_AGREEMENT, ...), BridgeId (priority with the system ID extension, then the MAC; lower is better) and PortId (priority in steps of 16, port number), path_cost(kbps) after 802.1D-2004 Table 17-3 (1G 20 000, 10G 2 000, 100G 200). Bpdu::parse validates as 9.3.4 says (protocol identifier, type, length; an MST BPDU reads as an RST BPDU), Bpdu::frame(src) writes the 802.3 frame with LLC 42 42 03 to 01:80:c2:00:00:00, stp::of_frame reads one back. decode::layers shows every field and flag, decode::info sums a BPDU up as capture tools do ("RST. Root = 4096/0/02:4a:00:00:01:00 Cost = 0 Port = 0x8001").

    let t = Times { msg_age: 0, max_age: 20, hello: 2, fwd_delay: 15 };     // seconds
    let me = BridgeId::new(4096, mac);
    let b = Bpdu::rst(stp::F_PROPOSAL, me, 0, me, PortId::new(128, 1), t).with_role(Role::Designated);
    let frame = b.frame(port_mac);                      // 60 bytes, padded
    let back = stp::of_frame(&frame);                   // Some(b)

    Routing: rip (RFC 2453, version 1 after RFC 1058) -- RipView reads a message (command, version, the complete 20-byte entries, routes() without the authentication entry, auth() for that entry of RFC 2453 4.1, trailing() bytes), Rip writes one (response, request_all for the whole table, to_bytes; the sender splits at rip::MAX_ENTRIES), Rte::v2(prefix, next_hop, metric, tag) and Rte::v1(addr, metric) build entries, Rte::prefix() gives a version 2 destination (version 1 masks are the receiver's business), Auth::password / text() the plain-text password (keyed MD5 is recognised, not checked). decode::layers shows one field per entry with its bytes and the problems a receiver refuses (a must-be-zero field of version 1, metrics outside 1 to 16, masks with gaps, bytes after the last entry); decode::info sums it up ("RIPv2 Response, 3 routes", "RIPv1 Request for the whole table").

    let m = rip::Rip::response(2, vec![rip::Rte::v2(net, Ipv4::UNSPECIFIED, 2, 0)]);
    let mut p = Pkt::new(netpkt::pkt::HEADROOM, &m.to_bytes());
    UdpHdr::new(udp::PORT_RIP, udp::PORT_RIP).push_v4(&mut p, src, rip::GROUP);
    let heard = rip::RipView::parse(payload).map(|v| rip::Rip::read(&v));

    IPv6: ipv6 reads a packet with its extension headers (Ipv6View, ext_headers, upper_layer for the header that carries the payload), writes the fixed header (Ipv6Hdr::packet / push_onto), fragments as a sender does (fragment(packet, mtu, id): fragment headers of RFC 8200 4.5, pieces in multiples of 8 bytes; frag reads one back) and reassembles (Reassembly6::add: offsets and lengths checked, overlapping fragments refused as RFC 5722 says). icmpv6 has the messages of RFC 4443 and RFC 4861: Icmp6 (echo and the errors; error_quote fills the 1280-byte minimum MTU) with the checksum over the pseudo header, Nd for Neighbor Discovery (ns, na, rs, router advertisements with their flags and lifetimes, redirects; the options source and target link-layer address, prefix information, MTU and redirected header) with Nd::parse and check_ip, the validation of RFC 4861 6.1 and 7.1 (hop limit 255, code 0, option lengths, link-local sources of router advertisements, DAD only to a solicited-node group) as an NdErr. Ipv6::solicited_node, Ipv6::link_local_of(mac) / eui64_in(prefix, mac) (the interface identifier of RFC 4291 appendix A) and Mac::of_ipv6_multicast give the addresses Neighbor Discovery needs; decode::layers shows every field and option, decode::info sums a message up ("Neighbor Advertisement 2001:db8::5 (sol, ovr) is at 02:4a:00:00:01:01").

    let group = target.solicited_node();
    let msg = Nd::ns(target, Some(my_mac)).encode(src, group);      // with the checksum
    let pkt = Ipv6Hdr::new(src, group, ipv6::NH_ICMPV6, 255).packet(&msg);
    let nd = Nd::parse(&Icmp6View::parse(body)?).ok()?;            // then nd.check_ip(src, dst, hops)
    let parts = ipv6::fragment(&big, 1280, id)?;                    // 1280 bytes, then the rest

    And ospf (OSPF version 2, RFC 2328 appendix A) -- OspfView reads a packet (the 24-byte header: version, type, length, router ID, area, checksum, authentication type and field; checksum_ok() is the IP checksum without the authentication field, lsu_spans() the LSAs of an update), Packet::read / Packet::to_bytes turn it into a record and back (Header and Body::Hello, Dd, Lsr, Lsu with the LSAs byte for byte, Ack; to_bytes fills in the length and the checksum). Lsa::parse / Lsa::new(..).to_bytes() read and write an LSA (LsaHeader and LsaBody::Router, Network, Summary for types 3 and 4, External, Other) with the Fletcher checksum of 12.1.7 (lsa_checksum, lsa_checksum_ok; set_age changes the age outside it), compare tells which of two instances is more recent (13.1) and LsaKey names an LSA. The constants of appendix B (MAX_AGE, LS_REFRESH_TIME, MIN_LS_INTERVAL, MIN_LS_ARRIVAL ...), the option bits, DD flags, LSA and link types come with it. decode::layers shows every field and every LSA with its bytes and the problems (a checksum of the packet or of an LSA that does not fit, another version, lengths that do not add up); decode::info sums it up ("Hello Packet, DR 10.0.0.2, BDR 10.0.0.1, 3 neighbors", "LS Update, 2 LSAs").

    let hdr = ospf::Header { kind: ospf::T_HELLO, router: rid, area: 0, autype: ospf::AU_NULL, auth: [0; 8] };
    let bytes = ospf::Packet { hdr, body: ospf::Body::Hello(hello) }.to_bytes();
    let back = ospf::OspfView::parse(&bytes).filter(|v| v.checksum_ok()).map(|v| ospf::Packet::read(&v));
    let lsa = ospf::Lsa::new(ospf::LSA_ROUTER, rid, rid, ospf::INITIAL_SEQ, ospf::OPT_E, body).to_bytes();
    assert!(ospf::lsa_checksum_ok(&lsa));

    Address selection: addrsel orders the addresses a name resolves to as RFC 6724 6 says, given the source address each one would leave with (Dest::new(addr, Some(src)), None for one that cannot be reached; src_len is the source's prefix length, src_deprecated its preferred lifetime ended): unusable destinations last, matching scope, no deprecated source, matching label, higher precedence, smaller scope, the longest matching prefix between IPv6 destinations (capped at the source's prefix, as glibc does), else the given order (sort is stable). scope, precedence and label give the values of 3.1 / 3.2 and of the default policy table of 2.1 (an IPv4 address as ::ffff:a.b.c.d), so a host with a global IPv6 address tries IPv6 first and one with only a link-local address IPv4. Rules 4 and 7 (home addresses, native transport) need Mobile IPv6 and tunnels and are left out.

    let mut d = vec![addrsel::Dest::new(v4, Some(my_v4)), addrsel::Dest::new(v6, Some(my_v6))];
    addrsel::sort(&mut d);                              // v6 first: precedence 40 against 35

    WLAN security: eapol has the EAPOL frames of IEEE 802.1X-2004 (ethertype eth::ET_EAPOL, 0x888E) with the EAPOL-Key body of the 4-way handshake (IEEE 802.11-2020 12.7.2) -- EapolView reads the header, Key reads and writes the RSN key descriptor (Key Information bits KI_* with the descriptor version, replay counter, nonce, IV, RSC, MIC, key data) and tells which message of the handshake it is (message(): 1 to 4, None for group key messages and requests); mic_input gives what the MIC covers (the PDU with its MIC field zeroed) and set_mic writes one, so the caller computes it with its key (HMAC-SHA1-128 or AES-CMAC from crypto). Rsne writes and reads the RSN element of a personal network (CCMP, AKM PSK, PSK- SHA256 or SAE, management frame protection bits), kde_gtk / kde_igtk the key data encapsulations of message 3, kdes and elements read key data, pad_key_data pads it for the key wrap. decode::layers shows every field ("802.1X Authentication, EAPOL-Key (Message 3 of 4)", the bits of Key Information by name, the RSN element and the KDEs of plain key data), decode::info sums it up ("Key (Message 2 of 4)").

    let m1 = eapol::Key { info: eapol::KDV_SHA1 | eapol::KI_PAIRWISE | eapol::KI_ACK, key_len: 16, replay: 1, nonce: anonce, ..Default::default() };
    let frame = EthHdr { dst: sta, src: bssid, ethertype: eth::ET_EAPOL }.frame(&m1.pdu(eapol::VERSION_2004));
    let mut pdu = m2.pdu(1);                       // message 2 of the station: KI_MIC set
    let mic = crypto::hmac_sha1(&kck, &eapol::mic_input(&pdu).unwrap_or_default());
    eapol::set_mic(&mut pdu, mic[..16].try_into().unwrap_or(&[0; 16]));

    BGP: bgp has the BGP-4 messages of RFC 4271 -- frame(stream) says how long the first message of a TCP byte stream is once all of it is there (Ok(None): more bytes needed) after the header checks of 6.1; Message::read(bytes, as4) turns one into Open (version, AS -- AS_TRANS above 65535 with the real one in the 4-octet capability --, hold time, identifier, optional parameters with the capabilities of RFC 5492: Cap::Mp, RouteRefresh, As4, Other), Update (withdrawn routes, path attributes in their order with their flags -- AttrVal::Origin, AsPath with AS_SEQUENCE and AS_SET Segments in 2- or 4-octet form, NextHop, Med, LocalPref, AtomicAggregate, Aggregator, Communities of RFC 1997, As4Path, As4Aggregator, unknown ones as Other byte for byte -- and NLRI), Notification, Keepalive or RouteRefresh (RFC 2918), and to_bytes(as4) writes it back the same; as4 says whether the session agreed on 4-octet AS numbers. What a receiver refuses (6.1 to 6.3: marker, lengths, types, version, hold time, identifier, unknown parameters, attribute flags and lengths, a missing well-known attribute, ORIGIN, AS_PATH, prefixes) comes back as a BgpErr with the code, subcode and data of its NOTIFICATION (error_name, code_name, the Cease subcodes of RFC 4486). path_len counts an AS_SET as one AS, path_text writes "65002 {65010,65011}", Attr::new(val) gives a type its usual flags (the extended length bit when the value needs it). decode::layers shows every message of a TCP segment to or from port 179 field by field (each capability, attribute, withdrawn route and prefix; the rest of a message of an earlier segment as such), with what a receiver would answer with a NOTIFICATION as a problem; decode::info sums it up ("OPEN Message, AS 65001, hold time 180, ID 1.1.1.1, KEEPALIVE Message"); its bit is decode::P_BGP.

    let caps = vec![bgp::Cap::Mp { afi: bgp::AFI_IPV4, safi: bgp::SAFI_UNICAST }, bgp::Cap::RouteRefresh, bgp::Cap::As4(65001)];
    let open = bgp::Message::Open(bgp::Open::new(65001, 180, rid, caps)).to_bytes(true);
    while let Some(n) = bgp::frame(&stream)? {                  // Err: the NOTIFICATION to send
        let m = bgp::Message::read(&stream[..n], as4)?;
        stream.drain(..n);
    }

    File transfer: tftp has the packets of RFC 1350 with the option extension of RFC 2347 -- TftpView reads one (opcode, file, mode and options of RRQ / WRQ / OACK as NUL-terminated fields with their offsets, block and data, error code and message; Bad says what is wrong), Packet writes and reads them (Rrq, Wrq, Data, Ack, Error, Oack; opt("blksize") ignores case, error_of(code) takes the RFC's text), to_netascii / from_netascii convert line ends, and looks_like tells a packet of a running transfer by its shape, as a transfer leaves port 69 at once (RFC 1350 4). ftp has the control connection of RFC 959: Command::parse / to_line, Reply with the multi-line form of 4.2 (to_bytes, is_preliminary / is_ok / is_intermediate), Lines and ReplyReader for bytes in any pieces, host_port / fmt_host_port (PORT's argument and the six numbers of a 227 reply wherever they stand), eprt / fmt_eprt and epsv_port / fmt_epsv of RFC 2428. decode::layers shows every TFTP field (also between two ports above 1023) and each FTP line with its command or code (P_FTP, Proto::Ftp, Proto::FtpData for port 20); decode::info sums them up ("Data Packet, Block: 3 (last)", "Request: USER anna").

    let rrq = tftp::Packet::Rrq { file: "r1-config".into(), mode: "octet".into(), opts: vec![("blksize".into(), "1428".into())] };
    let ack = tftp::Packet::parse(payload)?;             // Packet::Ack { block: 1 }
    let mut replies = ftp::ReplyReader::new();
    for r in replies.push(&bytes) { /* r.code, r.text() */ }
    let (_, port) = ftp::host_port("Passive mode on (10,0,0,9,117,49).").unwrap_or_default();

    Mail: smtp has the commands and replies of RFC 5321 -- Command::parse / to_line, parse_path / fmt_path for MAIL FROM:<a@b> SIZE=345 and RCPT TO:<..> (the null reverse path is an empty address), Reply with the multi-line form (Reply::enh(550, "5.1.1", ..) puts the enhanced status code of RFC 3463 before the text, status() reads it back, is_positive / is_intermediate / is_transient / is_permanent), ReplyReader for a server's bytes in any pieces, Ehlo::of_reply with has("PIPELINING"), size_limit() and auth("PLAIN"); Stream is the server's side: line() while commands come (pipelined ones in their order), begin_data(max) after 354, data() once the line with the dot came (the dots undone, more than max counted but not kept); stuff writes the bytes after DATA, and auth_plain / plain_of and LOGIN_USER / LOGIN_PASS serve AUTH (RFC 4954, 4616). pop3 has RFC 1939: Command, Response (ok / err, with_body for a multi-line one, its lines dot-stuffed by to_bytes), multi_line(&cmd) (LIST and UIDL without an argument, RETR, TOP, CAPA) and Reader, which the client tells for each command whether a body may follow. imf is the message of RFC 5322 with the MIME a plain text needs: Message::parse (CRLF or LF, folded fields unfolded) with get / set / prepend and to_bytes (folded at 78 columns), subject(), from(), to(), date(), text() (quoted-printable, base64, the charset and the first text part of a multipart undone); Mailbox with display names (quoted, or encoded words of RFC 2047), parse_list, addr_ok; date / parse_date, message_id, qp_encode / qp_decode, b64_encode / b64_decode, split_multipart; Draft::to_bytes(eight_bit) writes a text in UTF-8 as 7bit, 8bit or quoted-printable. decode::layers shows each SMTP line with its command, code and enhanced code and the lines of a message after DATA, each POP3 line with its command or status indicator (P_MAIL, Proto::Smtp for ports 25 and 587, Proto::Pop3 for 110); decode::info sums them up ("C: EHLO pc1", "S: +OK 2 messages", "C: DATA fragment, 345 bytes").

    let mut rd = smtp::ReplyReader::new();
    for r in rd.push(&bytes) { /* r.code, r.status(): Some("5.1.1") */ }
    let mut st = smtp::Stream::new();
    st.push(&bytes);
    while let Some(line) = st.line() { /* a command; after DATA: st.begin_data(max) */ }
    if let Some(d) = st.data() { /* d.body (CRLF, unstuffed), d.size, d.over */ }
    let msg = imf::Draft { from, to, subject, date, id, text, ..Default::default() }.to_bytes(true);
    let wire = smtp::stuff(&msg);                            // the bytes after 354

    SNMP: ber reads and writes the Basic Encoding Rules as SNMP uses them (RFC 3417 8: definite lengths only, the simple types and SEQUENCE) -- Reader (seq, int, uint, octets, null, oid, value), Writer (begin(tag) / end() around a SEQUENCE), Oid (parse, starts_with, child; its order is SNMP's lexicographic one) and Value with every type of SNMPv2-SMI and the exceptions noSuchObject, noSuchInstance and endOfMibView; what it refuses comes back as ber::Bad (an indefinite length, an INTEGER without contents or beyond 64 bits, a value outside its type's range, an OID not in its shortest form, of more than 128 arcs or with an arc above 2^32 - 1, bytes after the end); writers use the shortest forms. snmp has the messages of SNMPv1 (RFC 1157) and SNMPv2c (RFC 1901, RFC 3416): Message::new(version, community, pdu), parse and to_bytes, Pdu for Get, GetNext, GetBulk (Pdu::bulk with non-repeaters and max-repetitions), Set, Response, SNMPv2-Trap, Inform and Report, TrapV1 for the trap of version 1, the error statuses with error_name and v1_error (RFC 3584 4.4), the generic traps with trap_oid / generic_of between version 1 traps and notification OIDs (RFC 3584 3.1) and the OIDs every notification carries (SYS_UPTIME_0, SNMP_TRAP_OID_0, ...). mib is a small MIB built in: the objects of SNMPv2-MIB (system, snmp, the notifications), IF-MIB (ifTable, ifXTable, linkDown, linkUp), IP-MIB (ipAddrTable) and IP-FORWARD-MIB (ipCidrRouteTable) with syntax, access and the names of enumerations; lookup reads "sysName.0", "IF-MIB::ifDescr.2" or dotted numbers, name_of writes "SNMPv2-MIB::sysName.0", show a binding as net-snmp prints it ("IF-MIB::ifOperStatus.3 = INTEGER: up(1)") and children gives the objects below a node (a tree of the MIB). decode::layers shows every field of a message to or from port 161 or 162 with the names of its objects and a BER error as a problem at its place, decode::info sums it up ("GetRequest 4660: SNMPv2-MIB::sysName.0"); its bit is decode::P_SNMP.

    let oid = mib::lookup("sysName.0").unwrap_or_default();
    let get = snmp::Message::new(snmp::Version::V2c, "public", snmp::Pdu::new(snmp::Kind::Get, 4660, vec![snmp::VarBind::null(oid)]));
    let answer = snmp::Message::parse(&payload)?;               // Err(snmp::Bad) for what is no SNMP
    let lines: Vec<String> = answer.varbinds().iter().map(|vb| mib::show(vb.oid.arcs(), &vb.value, false)).collect();
    let mut w = ber::Writer::new();
    w.begin(ber::T_SEQUENCE); w.int(5); w.octets(b"public"); w.end();

    Port access control: eap has the packets of RFC 3748 -- Packet (Request, Response, Success, Failure; identity_request, identity_response, nak, identity(), nak_types()), the data of EAP-MD5 (Md5Data, md5_value with lent MD5) and of EAP-PWD (Pwd: Id, Commit, Confirm), info for one line about a packet. eapol writes start, logoff and eap_pdu, PAE_GROUP is their address on a wire, AKM_8021X and AKM_8021X_SHA256 are the suites of enterprise networks. radius carries EAP: Packet::push_eap / eap (pieces of 253 bytes, RFC 3579 3.1), push_vlan / vlan (RFC 3580), push_msk / msk with mppe_seal / mppe_open (RFC 2548). The sums of EAP-PWD are crypto::eappwd on the group functions of crypto::p256 (y_for_x, mul_point, add_points, neg_point, scalar_add), and eapm holds the methods as state machines without I/O: Peer and Server take packets and give the next one, the caller carries the bytes, keeps timers and hands in randomness, so a run is the same byte for byte. decode::layers shows EAP as a layer under EAPOL and as a line in a RADIUS EAP-Message.

    let mut peer = eapm::Peer::new("anna", "secret", eapm::Method::Pwd);
    let mut server = eapm::Server::new("radius", &[eapm::Method::Pwd]);
    let lookup = |user: &str| (user == "anna").then(|| String::from("secret"));
    let mut request = eap::Packet::identity_request(1, "").to_bytes();
    loop {
        let eapm::PeerOut::Send(response) = peer.on_packet(&request, &mut rnd) else { break };
        match server.on_packet(&response, &lookup, &mut rnd) {
            eapm::ServerOut::Send(next) => request = next,
            eapm::ServerOut::Success { eap, msk, .. } => {
                peer.on_packet(&eap, &mut rnd); // now peer.msk() == msk.as_ref()
                break;
            }
            _ => break,
        }
    }

    Mail on a server: imap is IMAP without I/O (a subset of RFC 9051 and 3501) -- LineReader turns bytes in pieces into logical lines with their literals (Read::NeedLiteral tells a server to answer "+"), Command::parse and Response::parse read them, tokens gives the values (Item: atom, quoted, literal, list, NIL), ok / no / bad / untagged / cont write server lines, astring and quoted strings; SeqSet, parse_fetch (FetchItem, Section), parse_search (SearchKey) read what clients ask, envelope, internal_date, header_of, text_of and header_fields make the answers. decode::layers shows each line with its tag, command or status and response code (port 143, P_MAIL).

    Remote access: telnet has the NVT protocol of RFC 854 -- the commands after IAC, the options OPT_* (ECHO, SGA, ...), escape and to_nvt for a data stream, a Reader that turns bytes arriving in pieces into Items (data, a command, a negotiation, a subnegotiation), parse for one buffer, and Options (the loop-free Q method of RFC 1143: received gives the answer to send, enable_us / enable_him ask for a change). uri reads addresses as RFC 3986 does: Uri::parse(s) takes every text as a reference (scheme, authority, path, query, fragment; host(), port()), base.join(r) resolves a relative one (the examples of 5.4 are tests), remove_dot_segments, u.encoded() escapes what a URI cannot hold, percent_encode / percent_decode, and form_encode / form_decode are HTML's application/x-www-form-urlencoded; http::mime_of(path) gives a file's Content-Type. radius has the RADIUS packets of RFC 2865 / 2866 -- RadiusView and Packet with every attribute by number and name (A_*, attr_name, value_name; vendor-specific ones kept as bytes), hide_password / reveal_password (the User-Password hiding of 5.2), the Request and Response Authenticators (accounting_auth, response_auth) and the Message-Authenticator of RFC 3579; the caller lends MD5 and HMAC-MD5 (crypto::md5_parts, crypto::hmac_md5). decode::layers and decode::info dissect both (ports 23, 1812 / 1813 / 1645 / 1646; P_TELNET, P_RADIUS; a hidden password stays hidden).

    let mut r = telnet::Reader::new(true);
    for item in r.push(&bytes) { /* Item::Data / Opt / Cmd / Sub */ }
    let hidden = radius::hide_password(b"secret", key, &auth, crypto::md5_parts);
    let mut p = radius::Packet::new(radius::ACCESS_REQUEST, id, auth);
    p.push(radius::Attr::text(radius::A_USER_NAME, "admin"));

    SSH: ssh is SSH version 2 without I/O, for simulators and tests (netio::ssh::Client is the blocking client on real sockets). ssh::Core::client(cfg, &seed) and Core::server(cfg, keys, &seed) are one side of a connection: push what the connection brought, take_out what to send, take_events what happened; random bytes come from the seed, so the same seed gives the same bytes. It speaks curve25519-sha256, ssh-ed25519 and rsa-sha2-256, chacha20-poly1305@openssh.com, aes128-ctr and aes256-ctr with hmac-sha2-256, logins by none, password and publickey and session channels with windows. The embedder decides what the protocol leaves open: host_key_verdict answers Event::HostKey, auth_accept / auth_reject / auth_pk_ok answer Event::AuthRequest (later if a server must be asked), accept_channel, reply. KeyPair makes keys from the caller's random bytes, signs, and reads and writes OpenSSH's unencrypted key files; fingerprint, parse_public, verify, dissect (for inspectors; decode::layers shows the identification line, packets in the clear and "verschlüsselt" after them). crypto::rsa::PrivateKey generates and signs.

    let mut client = ssh::Core::client(ssh::Config::default(), &seed_a);
    let mut server = ssh::Core::server(ssh::Config::default(), vec![ssh::KeyPair::ed25519(&key)], &seed_b);
    loop {
        server.push(&client.take_out());
        client.push(&server.take_out());
        for e in client.take_events() {
            match e {
                ssh::Event::HostKey { blob, .. } => client.host_key_verdict(ssh::fingerprint(&blob) == pinned),
                ssh::Event::AuthReady => client.auth_password("admin", "secret"),
                ssh::Event::AuthSuccess => { client.open_session(); }
                _ => {}
            }
        }
        // ... the server's events the same way, until both are quiet
    }

    SNMPv3: snmpv3 has the message of RFC 3412 (V3, Usm, ScopedPdu) around the PDUs of snmp, and the USM: password_to_key and localize (RFC 3414 A.2), sign and check (HMAC-MD5-96, HMAC-SHA-96, the SHA-2 tags of RFC 7860), encrypt and decrypt (AES-128-CFB of RFC 3826), engine_id_mac, the counters of report PDUs (USM_STATS_*, report_pdu, report_name). decode shows msgFlags, the user and the scoped PDU, or "verschlüsselt".

    let kul = snmpv3::localize(AuthProto::Sha1, &snmpv3::password_to_key(AuthProto::Sha1, b"maplesyrup"), &engine);
    let mut bytes = message.to_bytes();         // msgAuthenticationParameters: zeros of tag_len()
    snmpv3::sign(&mut bytes, AuthProto::Sha1, &kul);
  • base::rng::Pcg32::new(seed, stream) / Pcg32::derive(seed, id) -- deterministic random numbers (the reference PCG32): the same seed gives the same run on every target. For keys and nonces use plat::random_bytes (not in the browser, see crypto above).

  • base::metrics -- measuring without keeping the values: Counter, Gauge (with its maximum), Hist (log-linear: exact below 32, then 32 steps per power of two, so a quantile is at most 1.6 % off; quantile(per_mille), p50 / p95 / p99, merge) and Window (n slots of a time span, e.g. Window::new(300, 1_000_000_000) for five minutes of seconds in nanoseconds: record(t, v), quantiles over what is still in the window, per_slot for charts). Integer arithmetic only, so every target computes the same numbers. Window::hist_between(from, to) merges the slots of a time span into one Hist: a time series takes a point per interval from it and the quantiles of any span (JFNetworker's jfn_sim::series, which samples every service on virtual time). A window makes its slots with the first value, so one that never got a value holds no memory; Window::bytes() is what it holds (JFNetworker's keyframes count it into their memory budget).

  • base::hashring -- consistent hashing: Ring::add(member, key, vnodes) puts a member's tokens on the ring (made from its key, so every device that knows the members builds the same ring), owner(hash64(key)) is the member of the first token at or after the hash, preference(h, n) the next n distinct members (the replicas of a key), preference_by skips members that are down or draining, shares() gives each member's part of the ring. Adding or removing a member moves only the keys of its own tokens.

  • base::lru::Lru -- a map that forgets the least recently used entries: limits on the number of entries and on their weight (bytes), insert returns what had to go, get counts as a use and peek does not. Ordered maps only, so it is deterministic.

  • base::pattern -- patterns of shells and grep: glob(pat, name) is fnmatch without flags (*, ?, [a-z], [!x], [[:digit:]], \x; callers match a path component by component and hide dot files themselves), has_glob(word) says whether a word needs expanding; Regex::new(pat, Syntax::Basic | Syntax::Extended, icase) compiles POSIX's BRE or ERE without back-references (classes, anchors, * + ? {m,n}, groups, alternatives, GNU's \w \s \< \> \b) and find / find_at give the leftmost-longest match as byte offsets. It runs a Pike VM, so (a|a)*b against a long text costs linear time instead of exponential; a refused pattern says why with ReErr::text() in GNU grep's words (JFNetworker's shell, apps/coretest group pattern).

  • formats::jmap -- typed JSON for protocols and files: record! { pub struct P { pub a: String, pub n: u32 } } declares the struct with to_json / from_json, wire_enum! an enum carried as a string; missing or mistyped members read as their defaults, unknown ones are ignored (old and new programs read each other's data). json::stringify_pretty(&v, limits, 2) writes indented JSON for files people read and diff (JFNetworker's .jfnet).

Source: docs/GUIDE.md in the JFLib repository.