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 withinread_ms, a body atserver::MIN_BODY_RATE(1 KiB a second) on average after a firstread_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_bodyafter decoding); the rest is switched on:with_redirects(n)(never from https to http; credentials stay with their origin;fetchgives 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_msfor 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) andClientConfig::sessions(Arc<tls::Sessions>, a client's tickets); 0-RTT only where the server allows it (ServerConfig::early_data,tls::connect_early,TlsStream::read_earlyfor data that may be a replay).netio::x509builds and checks the certificates of a private CA (CertBuilder::sign_keywith any key,sign_extadds 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, orSSL_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_systemanswers it asroots::Reason);netio::trust::system_connector(extra)gives the connector forClient. OCSP stapling:ServerConfig::ocsp(Arc<tls::Staples>, kept current bynetio::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:Stapledby default refuses a certificate the response calls revoked,Requiredone without a good response,Off); a must-staple certificate (RFC 7633) needs one.x509::ocspchecks and builds responses,x509::CsrBuilder/Csrwrite 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)forServerConfig, orselectfor one renewed while the server runs). Solvers:acme::Http01(itshandler(site)on port 80),acme::TlsAlpn01(setup(&mut tls_cfg)on port 443), dns-01 by the program's ownSolverfor its DNS provider (dns01_name,dns01_value; wildcards need it),Solversto combine. When to renew:acme.renewal_info(&cert)(ARI), the new order withOrderOptions::replaces: acme::ari_id(&cert). Keep the account key (PrivateKey::to_pkcs8); test againstacme::LETS_ENCRYPT_STAGINGfirst, Let's Encrypt's rate limits are strict.netio::smtp::send(&SmtpConfig, &Mail)-- e-mail (STARTTLS, TLS, or plain to any server withSecurity::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'ssin6_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_indexandlocal_addrs(the computer's own addresses) are the pieces;SocketAddr::parseandDisplayknow[fe80::1%2]:53.netio::dns::lookup(name, rtype)/dns::Resolver-- records of any type (MX, TXT, SRV, CAA, TLSA, HTTPS ...;netpkt::dns::TYPE_*) asLookup { name, aliases, records, ttl }; aResolverkeeps answers as long as their TTL says (negative ones by their SOA). DNS over TLS and over HTTPS byConfig::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::securitysaysSecureorInsecure(an unsigned zone), a bogus answer is an error withcode == 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;Journalfor append-only logs. Secondary indexes in memory (add_indexwithIndex::fieldorIndex::by,unique()refusing what breaks it withStoreError::Conflict;find,find_one,range), and encryption at rest (Store::open_encrypted,Journal::open_encryptedwith a 32-byte key, for example fromplat::secret::secret_get;rekeyencrypts, 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 anycas::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 throughStore::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_byteson Windows, Linux, macOS, iOS and Android; the browser has no system generator inplat, a web page takescrypto.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, thebrof HTTP (compress::brotli::compress(data, level)/decompress; levels 0 to 11,LEVEL_DEFAULT5 for a web server's responses, 11 for files compressed once), LZ4 (lz4::compress_hcfor 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 ofzstd --train), CRC-32, Adler-32 and xxHash;Codecpicks 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 mostout, with a window of the format's size as its only memory;gzip::Encoder,zstd::Encoderand the others withFlush::Syncfor 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) andformats::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 withencode/encode_html;label("iso-8859-2"),from_code_page(932)anddecode_labelas the standard reads labels;Decoderfor input in pieces).agent_core::json/jmapandbase::xml/encodingare 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;overflowwhen events were lost; Android: inotify on the app's folders,/data,/documents...). Every change afternewreturned 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 againwatching()is false and everytakereportsoverflowafter its wait, so a caller that rescans onoverflowpolls meanwhile.plat::net::UnixListener::bind(path)/connect_unix(path, ms)-- Unix domain sockets (Linux, Windows 10 1803 and later) with the stream calls ofTcpStream.bindremoves only a socket file nobody listens on any more; a file, a folder or a socket that is listened on stays andbindfails. 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 theChildends 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,update16for incremental changes) andcrc32; 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 andReassembly;decode::layers(frame)(fields with byte ranges for an inspector),decode::proto_mask(filters;decode::ip_maskanddecode::stack_ipfor packets without a link header, as on serial lines),decode::info(one-line summaries);pcapng::Writer/pcapng::readfor Wireshark files;http::Parserfor HTTP/1.1 in pieces of any size (pushadds bytes and gives the next event --More,Head,Data,End--,pollthe ones after it, pipelined messages one after the other,finishat the end of the stream) andhttp::encode_request/encode_response/encode_chunkedby the wire rules ofnetio::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_quoteddoes the same to the packet an ICMP error quotes together with the error's own checksum (RFC 5508),nat::Flow::of/Flow::quotedgive what translation and filters look at (addresses, ports or the ICMP identifier, type and code, TCP flags, fragment position), andchecksum::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,Dhcpwith typed options in their order,Opt::RelayInfoof RFC 3046, long options split and joined per RFC 3396,to_bytes(dhcp::BOOTP_MIN)pads to the usual 300 bytes),dns(RFC 1035:Messagewith 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,Tstimestamps that keep whole nanoseconds,offset_delay) andsyslog(pri, the BSD and IOS message forms,parse).decode::layersanddecode::infodissect 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, additionalSpanning tree:
stphas 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) andPortId(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::parsevalidates 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_framereads one back.decode::layersshows every field and flag,decode::infosums 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) --RipViewreads 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),Ripwrites one (response,request_allfor the whole table,to_bytes; the sender splits atrip::MAX_ENTRIES),Rte::v2(prefix, next_hop, metric, tag)andRte::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::layersshows 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::infosums 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:
ipv6reads a packet with its extension headers (Ipv6View,ext_headers,upper_layerfor 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;fragreads one back) and reassembles (Reassembly6::add: offsets and lengths checked, overlapping fragments refused as RFC 5722 says).icmpv6has the messages of RFC 4443 and RFC 4861:Icmp6(echo and the errors;error_quotefills the 1280-byte minimum MTU) with the checksum over the pseudo header,Ndfor 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) withNd::parseandcheck_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 anNdErr.Ipv6::solicited_node,Ipv6::link_local_of(mac)/eui64_in(prefix, mac)(the interface identifier of RFC 4291 appendix A) andMac::of_ipv6_multicastgive the addresses Neighbor Discovery needs;decode::layersshows every field and option,decode::infosums 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 restAnd
ospf(OSPF version 2, RFC 2328 appendix A) --OspfViewreads 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_bytesturn it into a record and back (HeaderandBody::Hello,Dd,Lsr,Lsuwith the LSAs byte for byte,Ack;to_bytesfills in the length and the checksum).Lsa::parse/Lsa::new(..).to_bytes()read and write an LSA (LsaHeaderandLsaBody::Router,Network,Summaryfor types 3 and 4,External,Other) with the Fletcher checksum of 12.1.7 (lsa_checksum,lsa_checksum_ok;set_agechanges the age outside it),comparetells which of two instances is more recent (13.1) andLsaKeynames 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::layersshows 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::infosums 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:
addrselorders 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)),Nonefor one that cannot be reached;src_lenis the source's prefix length,src_deprecatedits 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 (sortis stable).scope,precedenceandlabelgive 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 35WLAN security:
eapolhas the EAPOL frames of IEEE 802.1X-2004 (ethertypeeth::ET_EAPOL, 0x888E) with the EAPOL-Key body of the 4-way handshake (IEEE 802.11-2020 12.7.2) --EapolViewreads the header,Keyreads and writes the RSN key descriptor (Key Information bitsKI_*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_inputgives what the MIC covers (the PDU with its MIC field zeroed) andset_micwrites one, so the caller computes it with its key (HMAC-SHA1-128 or AES-CMAC fromcrypto).Rsnewrites and reads the RSN element of a personal network (CCMP, AKM PSK, PSK- SHA256 or SAE, management frame protection bits),kde_gtk/kde_igtkthe key data encapsulations of message 3,kdesandelementsread key data,pad_key_datapads it for the key wrap.decode::layersshows 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::infosums 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:
bgphas 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 intoOpen(version, AS --AS_TRANSabove 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,AsPathwith AS_SEQUENCE and AS_SETSegments in 2- or 4-octet form,NextHop,Med,LocalPref,AtomicAggregate,Aggregator,Communitiesof RFC 1997,As4Path,As4Aggregator, unknown ones asOtherbyte for byte -- and NLRI),Notification,KeepaliveorRouteRefresh(RFC 2918), andto_bytes(as4)writes it back the same;as4says 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 aBgpErrwith the code, subcode and data of its NOTIFICATION (error_name,code_name, the Cease subcodes of RFC 4486).path_lencounts an AS_SET as one AS,path_textwrites "65002 {65010,65011}",Attr::new(val)gives a type its usual flags (the extended length bit when the value needs it).decode::layersshows 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::infosums it up ("OPEN Message, AS 65001, hold time 180, ID 1.1.1.1, KEEPALIVE Message"); its bit isdecode::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:
tftphas the packets of RFC 1350 with the option extension of RFC 2347 --TftpViewreads one (opcode, file, mode and options of RRQ / WRQ / OACK as NUL-terminated fields with their offsets, block and data, error code and message;Badsays what is wrong),Packetwrites and reads them (Rrq,Wrq,Data,Ack,Error,Oack;opt("blksize")ignores case,error_of(code)takes the RFC's text),to_netascii/from_netasciiconvert line ends, andlooks_liketells a packet of a running transfer by its shape, as a transfer leaves port 69 at once (RFC 1350 4).ftphas the control connection of RFC 959:Command::parse/to_line,Replywith the multi-line form of 4.2 (to_bytes,is_preliminary/is_ok/is_intermediate),LinesandReplyReaderfor 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_eprtandepsv_port/fmt_epsvof RFC 2428.decode::layersshows every TFTP field (also between two ports above 1023) and each FTP line with its command or code (P_FTP,Proto::Ftp,Proto::FtpDatafor port 20);decode::infosums 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:
smtphas the commands and replies of RFC 5321 --Command::parse/to_line,parse_path/fmt_pathforMAIL FROM:<a@b> SIZE=345andRCPT TO:<..>(the null reverse path is an empty address),Replywith 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),ReplyReaderfor a server's bytes in any pieces,Ehlo::of_replywithhas("PIPELINING"),size_limit()andauth("PLAIN");Streamis 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 thanmaxcounted but not kept);stuffwrites the bytes after DATA, andauth_plain/plain_ofandLOGIN_USER/LOGIN_PASSserve AUTH (RFC 4954, 4616).pop3has RFC 1939:Command,Response(ok/err,with_bodyfor a multi-line one, its lines dot-stuffed byto_bytes),multi_line(&cmd)(LIST and UIDL without an argument, RETR, TOP, CAPA) andReader, which the client tells for each command whether a body may follow.imfis the message of RFC 5322 with the MIME a plain text needs:Message::parse(CRLF or LF, folded fields unfolded) withget/set/prependandto_bytes(folded at 78 columns),subject(),from(),to(),date(),text()(quoted-printable, base64, the charset and the first text part of a multipart undone);Mailboxwith 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::layersshows 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::Smtpfor ports 25 and 587,Proto::Pop3for 110);decode::infosums 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 354SNMP:
berreads 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) andValuewith every type of SNMPv2-SMI and the exceptions noSuchObject, noSuchInstance and endOfMibView; what it refuses comes back asber::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.snmphas the messages of SNMPv1 (RFC 1157) and SNMPv2c (RFC 1901, RFC 3416):Message::new(version, community, pdu),parseandto_bytes,Pdufor Get, GetNext, GetBulk (Pdu::bulkwith non-repeaters and max-repetitions), Set, Response, SNMPv2-Trap, Inform and Report,TrapV1for the trap of version 1, the error statuses witherror_nameandv1_error(RFC 3584 4.4), the generic traps withtrap_oid/generic_ofbetween version 1 traps and notification OIDs (RFC 3584 3.1) and the OIDs every notification carries (SYS_UPTIME_0,SNMP_TRAP_OID_0, ...).mibis 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;lookupreads "sysName.0", "IF-MIB::ifDescr.2" or dotted numbers,name_ofwrites "SNMPv2-MIB::sysName.0",showa binding as net-snmp prints it ("IF-MIB::ifOperStatus.3 = INTEGER: up(1)") andchildrengives the objects below a node (a tree of the MIB).decode::layersshows 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::infosums it up ("GetRequest 4660: SNMPv2-MIB::sysName.0"); its bit isdecode::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:
eaphas 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_valuewith lent MD5) and of EAP-PWD (Pwd:Id,Commit,Confirm),infofor one line about a packet.eapolwritesstart,logoffandeap_pdu,PAE_GROUPis their address on a wire,AKM_8021XandAKM_8021X_SHA256are the suites of enterprise networks.radiuscarries EAP:Packet::push_eap/eap(pieces of 253 bytes, RFC 3579 3.1),push_vlan/vlan(RFC 3580),push_msk/mskwithmppe_seal/mppe_open(RFC 2548). The sums of EAP-PWD arecrypto::eappwdon the group functions ofcrypto::p256(y_for_x,mul_point,add_points,neg_point,scalar_add), andeapmholds the methods as state machines without I/O:PeerandServertake 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::layersshows 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:
imapis IMAP without I/O (a subset of RFC 9051 and 3501) --LineReaderturns bytes in pieces into logical lines with their literals (Read::NeedLiteraltells a server to answer "+"),Command::parseandResponse::parseread them,tokensgives the values (Item: atom, quoted, literal, list, NIL),ok/no/bad/untagged/contwrite server lines,astringandquotedstrings;SeqSet,parse_fetch(FetchItem,Section),parse_search(SearchKey) read what clients ask,envelope,internal_date,header_of,text_ofandheader_fieldsmake the answers.decode::layersshows each line with its tag, command or status and response code (port 143,P_MAIL).Remote access:
telnethas the NVT protocol of RFC 854 -- the commands afterIAC, the optionsOPT_*(ECHO,SGA, ...),escapeandto_nvtfor a data stream, aReaderthat turns bytes arriving in pieces intoItems (data, a command, a negotiation, a subnegotiation),parsefor one buffer, andOptions(the loop-free Q method of RFC 1143:receivedgives the answer to send,enable_us/enable_himask for a change).urireads 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, andform_encode/form_decodeare HTML'sapplication/x-www-form-urlencoded;http::mime_of(path)gives a file's Content-Type.radiushas the RADIUS packets of RFC 2865 / 2866 --RadiusViewandPacketwith 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::layersanddecode::infodissect 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:
sshis SSH version 2 without I/O, for simulators and tests (netio::ssh::Clientis the blocking client on real sockets).ssh::Core::client(cfg, &seed)andCore::server(cfg, keys, &seed)are one side of a connection:pushwhat the connection brought,take_outwhat to send,take_eventswhat 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_verdictanswersEvent::HostKey,auth_accept/auth_reject/auth_pk_okanswerEvent::AuthRequest(later if a server must be asked),accept_channel,reply.KeyPairmakes 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::layersshows the identification line, packets in the clear and "verschlüsselt" after them).crypto::rsa::PrivateKeygenerates 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:
snmpv3has the message of RFC 3412 (V3,Usm,ScopedPdu) around the PDUs ofsnmp, and the USM:password_to_keyandlocalize(RFC 3414 A.2),signandcheck(HMAC-MD5-96, HMAC-SHA-96, the SHA-2 tags of RFC 7860),encryptanddecrypt(AES-128-CFB of RFC 3826),engine_id_mac, the counters of report PDUs (USM_STATS_*,report_pdu,report_name).decodeshows 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 useplat::random_bytes(not in the browser, seecryptoabove).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) andWindow(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_slotfor charts). Integer arithmetic only, so every target computes the same numbers.Window::hist_between(from, to)merges the slots of a time span into oneHist: a time series takes a point per interval from it and the quantiles of any span (JFNetworker'sjfn_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_byskips 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),insertreturns what had to go,getcounts as a use andpeekdoes 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) andfind/find_atgive the leftmost-longest match as byte offsets. It runs a Pike VM, so(a|a)*bagainst a long text costs linear time instead of exponential; a refused pattern says why withReErr::text()in GNU grep's words (JFNetworker's shell,apps/coretestgrouppattern).formats::jmap-- typed JSON for protocols and files:record! { pub struct P { pub a: String, pub n: u32 } }declares the struct withto_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).