Something went wrong. Try again.
A port of FlightAware's dump1090, a Mode S and ADS-B decoder for software defined radios, to Zig 0.16.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968// SPDX-FileCopyrightText: © 2014-2026 FlightAware LLC// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: GPL-2.0-or-later
//! FlightAware's adept protocol: the uplink PiAware speaks.//!//! PiAware is two things wearing one name. One is a small protocol client//! that logs in to FlightAware over TLS and forwards tracks. The other is a//! machine manager: it runs a decoder as a child process, restarts services,//! rewrites network configuration, reboots, and accepts commands from the//! server to update itself. Only the first is wanted here, so only the first//! is ported, and the parts of the protocol that exist to drive the second//! are answered with a refusal rather than implemented.//!//! The format is a pleasant surprise. A message is one line of tab-separated//! key and value, alternating, with the key `type` saying what it is — which//! is the format the tracks are already in. PiAware's own forwarding path is//! two lines: split a line from `faup1090` on tabs, hand the resulting array//! to the uplink. So `src/fatsv.zig` does not merely feed this; what it//! writes *is* the payload, and the two formats never have to be converted//! between.//!//! What this module is, then, is the envelope around that: the pinned//! certificate, the line codec, and the conversation — log in, be told a//! feeder identifier, keep the connection alive, and reconnect when it//! drops.
const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;const Certificate = std.crypto.Certificate;const testing = std.testing;
/// FlightAware's root certificate, embedded from PiAware at the commit named/// in `build.zig.zon`.////// Their adept server presents a certificate from a private authority, so/// there is nothing in the system trust store that will vouch for it and the/// root has to be pinned. Pinning *this* certificate and no more is/// deliberate: PiAware also carries the intermediate, but the copy in their/// tree expired on 2025-12-06 while the server has long since rotated to a/// replacement, so a client that insisted on the bundled intermediate would/// have stopped working. The root runs to 2035 and the intermediate arrives/// in the handshake, which is how the chain is meant to be built anyway.pub const root_ca_pem = @embedFile("flightaware_root_ca");
/// Where the uplink lives.pub const default_host = "piaware.flightaware.com";pub const default_port: u16 = 1200;
/// The certificate names FlightAware's server is allowed to present.////// The leaf carries `DNS:*.flightaware.com` as a subject alternative name, so/// ordinary wildcard matching against the host being dialled is enough and is/// what this port does. PiAware instead accepts any of four common names and/// does no host matching at all, which is weaker than it looks: it would take/// a certificate issued for `eyes.flightaware.com` as proof of having reached/// `piaware.flightaware.com`.pub const expected_host_suffix = ".flightaware.com";
/// Build a certificate bundle holding the pinned root and nothing else.////// The caller owns it and must `deinit` it. Verification against this bundle/// therefore succeeds only for certificates that chain to FlightAware's root/// — the system trust store is not consulted, so a public authority that has/// been persuaded to issue for `flightaware.com` is not enough.////// Fails with `PinnedRootExpired` rather than handing back an empty bundle./// The standard library drops an expired certificate from a bundle without/// saying so, which is right for a system trust store of many and wrong for a/// pin of one: it would turn "the certificate this program trusts ran out" —/// in December 2035, and it will — into a handshake failing much later for/// want of an issuer, which is a far harder thing to read.pub fn rootBundle(gpa: Allocator, now_sec: i64) !Certificate.Bundle { var bundle: Certificate.Bundle = .empty; errdefer bundle.deinit(gpa); try addCertsFromPem(&bundle, gpa, root_ca_pem, now_sec); if (bundle.map.count() == 0) return error.PinnedRootExpired; return bundle;}
/// Add every certificate in a PEM document to a bundle.////// The standard library can fill a bundle from a file or a directory but not/// from bytes already in hand, which is what an embedded certificate is. This/// is that missing case, and follows `Bundle.addCertsFromFile` closely enough/// that the two can be compared side by side: reserve room for the decoded/// output *and* a scratch copy of the encoded input, then decode each/// `BEGIN`/`END` pair in place.pub fn addCertsFromPem( bundle: *Certificate.Bundle, gpa: Allocator, pem: []const u8, now_sec: i64,) !void { const decoder = std.base64.standard.decoderWithIgnore(" \t\r\n");
const decoded_size_upper_bound = pem.len / 4 * 3; const needed = std.math.cast(u32, decoded_size_upper_bound + pem.len) orelse return error.CertificateAuthorityBundleTooBig; try bundle.bytes.ensureUnusedCapacity(gpa, needed);
const begin_marker = "-----BEGIN CERTIFICATE-----"; const end_marker = "-----END CERTIFICATE-----";
var start_index: usize = 0; while (std.mem.findPos(u8, pem, start_index, begin_marker)) |begin_start| { const cert_start = begin_start + begin_marker.len; const cert_end = std.mem.findPos(u8, pem, cert_start, end_marker) orelse return error.MissingEndCertificateMarker; start_index = cert_end + end_marker.len;
const encoded = std.mem.trim(u8, pem[cert_start..cert_end], " \t\r\n"); const decoded_start: u32 = @intCast(bundle.bytes.items.len); const dest = bundle.bytes.allocatedSlice()[decoded_start..]; bundle.bytes.items.len += try decoder.decode(dest, encoded); try bundle.parseCert(gpa, decoded_start, now_sec); }}
// ---- The line codec ----
/// One key and its value. Neither is owned.pub const Field = struct { key: []const u8, value: []const u8,};
/// The most fields a single message is allowed to carry.////// A track line is the widest thing that goes over this link and the FATSV/// writer caps one at `fatsv.max_line` bytes, which cannot hold anywhere near/// this many `key\tvalue` pairs. The limit exists so that decoding a hostile/// line cannot be made to allocate.pub const max_fields = 128;
/// Longest line this will encode or decode, matching what PiAware's Tcl will/// read in one go.pub const max_line = 8192;
pub const ParseError = error{ /// An odd number of tab-separated parts: a key with no value. PiAware's /// `array set` raises on this too, and the connection is dropped. OddFieldCount, /// More than `max_fields` pairs. TooManyFields,};
/// Split an adept line into its fields, writing them into `out`.////// Returns the prefix of `out` that was filled. Nothing is copied: every key/// and value points into `line`.////// Values are *not* unescaped, which looks like an omission and is not —/// PiAware does the same, splitting the line and using the parts as they/// come. An escape written by one side is therefore only unwound by the/// other's parser if that parser chooses to, and matching the reference/// client matters more here than being tidy.pub fn parseLine(line: []const u8, out: []Field) ParseError![]Field { if (line.len == 0) return out[0..0];
var n: usize = 0; var it = std.mem.splitScalar(u8, line, '\t'); while (it.next()) |key| { const value = it.next() orelse return error.OddFieldCount; if (n == out.len or n == max_fields) return error.TooManyFields; out[n] = .{ .key = key, .value = value }; n += 1; } return out[0..n];}
/// Look a field up by key, or null if the message does not carry it.pub fn find(fields: []const Field, key: []const u8) ?[]const u8 { for (fields) |f| { if (std.mem.eql(u8, f.key, key)) return f.value; } return null;}
/// Write fields as one adept line, terminated with a newline.////// `fields` is sorted in place by key, because PiAware sorts before sending/// and a byte-identical line is one less thing to wonder about when a message/// is refused. Nothing is known to require it: the far side reads the line/// into an associative array, which has no order.////// Only values are escaped, and only for the two characters that would/// otherwise end a field or the line. Keys are written through untouched, as/// PiAware writes them — every key in this protocol is a bare identifier, and/// a caller passing something else is making a mistake this will not hide.pub fn writeLine(w: *Io.Writer, fields: []Field) Io.Writer.Error!void { std.mem.sort(Field, fields, {}, lessByKey); for (fields, 0..) |f, i| { if (i != 0) try w.writeByte('\t'); try w.writeAll(f.key); try w.writeByte('\t'); try writeEscaped(w, f.value); } try w.writeByte('\n');}
fn lessByKey(_: void, a: Field, b: Field) bool { return std.mem.order(u8, a.key, b.key) == .lt;}
/// Write a value with the field and line separators made harmless.pub fn writeEscaped(w: *Io.Writer, value: []const u8) Io.Writer.Error!void { var rest = value; while (std.mem.indexOfAny(u8, rest, "\t\n")) |i| { try w.writeAll(rest[0..i]); try w.writeAll(if (rest[i] == '\t') "\\t" else "\\n"); rest = rest[i + 1 ..]; } try w.writeAll(rest);}
test "a line round trips through parse" { var fields: [max_fields]Field = undefined; const parsed = try parseLine("type\tlogin\tmac\t00:11:22:33:44:55", &fields);
try testing.expectEqual(@as(usize, 2), parsed.len); try testing.expectEqualStrings("type", parsed[0].key); try testing.expectEqualStrings("login", parsed[0].value); try testing.expectEqualStrings("00:11:22:33:44:55", find(parsed, "mac").?); try testing.expectEqual(@as(?[]const u8, null), find(parsed, "absent"));}
test "a key with no value is refused rather than half read" { var fields: [max_fields]Field = undefined; try testing.expectError(error.OddFieldCount, parseLine("type\tlogin\tmac", &fields));}
test "an empty line parses as no fields" { var fields: [max_fields]Field = undefined; try testing.expectEqual(@as(usize, 0), (try parseLine("", &fields)).len);}
test "an empty value is a value, not a missing field" { var fields: [max_fields]Field = undefined; const parsed = try parseLine("type\talive\toffset\t", &fields); try testing.expectEqual(@as(usize, 2), parsed.len); try testing.expectEqualStrings("", find(parsed, "offset").?);}
test "a line too wide for the caller's buffer is refused" { var small: [2]Field = undefined; try testing.expectError( error.TooManyFields, parseLine("a\t1\tb\t2\tc\t3", &small), );}
test "fields are written sorted by key" { var buf: [256]u8 = undefined; var w: Io.Writer = .fixed(&buf);
var fields = [_]Field{ .{ .key = "type", .value = "login" }, .{ .key = "mac", .value = "001122334455" }, .{ .key = "clock", .value = "1600000000" }, }; try writeLine(&w, &fields);
try testing.expectEqualStrings( "clock\t1600000000\tmac\t001122334455\ttype\tlogin\n", w.buffered(), );}
test "tabs and newlines in a value cannot end the field or the line" { var buf: [256]u8 = undefined; var w: Io.Writer = .fixed(&buf);
var fields = [_]Field{ .{ .key = "message", .value = "one\ttwo\nthree\n" }, }; try writeLine(&w, &fields);
try testing.expectEqualStrings( "message\tone\\ttwo\\nthree\\n\n", w.buffered(), );
// And the result is still one line of an even number of fields, which is // the property the escaping exists to preserve. var fields_back: [max_fields]Field = undefined; const line = w.buffered(); const parsed = try parseLine(line[0 .. line.len - 1], &fields_back); try testing.expectEqual(@as(usize, 1), parsed.len);}
test "a track line from the FATSV writer is already a valid adept message" { // Not a conversion: this is what `src/fatsv.zig` emits, parsed as an // adept message. PiAware forwards these by splitting on tabs and sending // the parts, which is exactly what happens here. const fatsv_line = "_v\t9E\tclock\t1600000000\thexid\t4840D6\talt\t35000 0 A";
var fields: [max_fields]Field = undefined; const parsed = try parseLine(fatsv_line, &fields);
try testing.expectEqualStrings("9E", find(parsed, "_v").?); try testing.expectEqualStrings("1600000000", find(parsed, "clock").?); try testing.expectEqualStrings("4840D6", find(parsed, "hexid").?); try testing.expectEqualStrings("35000 0 A", find(parsed, "alt").?);}
test "the pinned root parses, and is one certificate" { // A fixed instant inside the certificate's validity, so that the parse is // being tested and not the clock. const during_2026: i64 = 1_767_225_600; // 2026-01-01T00:00:00Z
var bundle = try rootBundle(testing.allocator, during_2026); defer bundle.deinit(testing.allocator);
try testing.expect(bundle.bytes.items.len > 0); try testing.expectEqual(@as(u32, 1), bundle.map.count());}
test "the pinned root has not expired" { // Separate from the parse above, and deliberately against the real clock: // this certificate runs out in December 2035, and when it does the thing // that should say so is a test rather than a feed that silently stops. const now = Io.Timestamp.now(testing.io, .real).toSeconds();
var bundle = rootBundle(testing.allocator, now) catch |err| { try testing.expect(err == error.PinnedRootExpired); return error.FlightAwareRootCertificateHasExpired; }; defer bundle.deinit(testing.allocator);}
// ---- Messages ----
/// Where the receiver is, as the login and health messages carry it.pub const Position = struct { latitude: f64, longitude: f64, /// Feet. altitude: f64 = 0, /// What the altitude is measured from. PiAware sends the string through /// untouched, and the two values it ever sends are these. reference: enum { barometric, geometric } = .geometric,
fn referenceName(self: Position) []const u8 { return switch (self.reference) { .barometric => "barometric", .geometric => "geometric", }; }};
/// What the uplink needs to know about this receiver.pub const Options = struct { host: []const u8 = default_host, port: u16 = default_port,
/// The identity every message is stamped with, and required. /// /// It is not, on its own, what identifies a site: two logins from the /// same MAC with no feeder identifier were given two different /// identifiers and two sites. What carries a site across restarts is /// `feeder_id`, so it is that which has to be kept. mac: []const u8,
/// The identifier the server issued at a previous login, if there has /// been one. Absent on a first connection; the server sends one back and /// it should be written down and offered next time. feeder_id: ?[]const u8 = null,
/// Where that identifier came from, which is sent beside it. /// /// This is not bookkeeping. FlightAware will not create a site for a /// client that does not say this, refusing the login with "creation of /// new feeder sites requires a newer PiAware client that supports feeder /// IDs" — the word is how the server knows the client can *keep* an /// identifier it is given. A first login therefore says `cache` with no /// identifier, which is the request for one. feeder_id_source: FeederIdSource = .none,
/// Where the antenna is. FlightAware needs this to make sense of the /// tracks, and multilateration is not possible without it. position: ?Position = null,
/// What to call this software in the login message. program: []const u8 = "zig-dump1090", version: []const u8,
/// Whether to let FlightAware update software on this machine. /// /// Always false, and present as a field rather than a constant because it /// should read as a decision rather than an omission. PiAware advertises /// these two capabilities at login and the server only sends /// `request_auto_update` and `request_manual_update` to a client that /// said yes; declaring no is what stops them being sent at all, and the /// handler that refuses them is the second line of defence rather than /// the first. allow_auto_update: bool = false, allow_manual_update: bool = false,
/// The codec version to declare, or null to declare none. /// /// PiAware always names its newest codec here, and the server then /// expects the compact encoding: recognised fields packed into a single /// `!` entry behind a bitfield header, with anything unrecognised left /// plain beside it. That codec is a substantial piece of work and is not /// implemented, so this defaults to declaring nothing and sending every /// field in the clear — which the encoding already has to allow for, /// since it is what happens to any field the codec does not know. /// /// Whether the server *accepts* a client that declares nothing is the one /// question this port cannot answer by reading PiAware: their codec /// registry documents a no-op codec but no longer registers one. It is /// settled by logging in and reading the reply, which is why the login /// response is reported rather than merely checked. compression_version: ?[]const u8 = null,};
/// Where a feeder identifier came from, in PiAware's vocabulary.pub const FeederIdSource = enum { /// Written into the configuration by hand. config, /// Read from a file this program can also write, so a newly issued one /// will be kept. cache, /// Read from a file that cannot be written back. cache_ro, /// Nowhere to keep one. none,};
/// The fixed part of a login message.////// PiAware sends a great deal more: the output of `uname -a`, the versions of/// every installed package matching `*piaware*` and `*dump1090*`, the OS/// release fields, the local IP address and interface. None of it is required/// — every one of those is gathered inside a `catch` in `login.tcl`, so a/// machine where the lookup fails logs in perfectly well without it — and all/// of it describes a host this program has no business describing. What is/// left is what identifies the feed and what the server needs to place it.pub fn loginFields(buf: []Field, options: Options, scratch: *LoginScratch) []Field { var n: usize = 0; const add = struct { fn f(list: []Field, i: *usize, key: []const u8, value: []const u8) void { if (i.* == list.len) return; list[i.*] = .{ .key = key, .value = value }; i.* += 1; } }.f;
add(buf, &n, "type", "login"); add(buf, &n, "mac", options.mac); add(buf, &n, "connected_host", options.host);
// The format on the wire is faup1090's, because it is: `src/fatsv.zig` // writes what faup1090 writes. Saying so is more useful to the far end // than naming a program it has never heard of. add(buf, &n, "transprogram", "faup1090"); add(buf, &n, "adsbprogram", options.program); add(buf, &n, "piaware_version", options.version); add(buf, &n, "piaware_version_full", scratch.versionFull(options)); add(buf, &n, "image_type", "zig_dump1090");
add(buf, &n, "local_auto_update_enable", if (options.allow_auto_update) "1" else "0"); add(buf, &n, "local_manual_update_enable", if (options.allow_manual_update) "1" else "0");
if (options.compression_version) |v| add(buf, &n, "compression_version", v);
// Always sent, even with nothing to say — see `feeder_id_source`. add(buf, &n, "feeder_id", scratch.feederId(options));
if (options.position) |p| { add(buf, &n, "receiverlat", scratch.float(0, p.latitude)); add(buf, &n, "receiverlon", scratch.float(1, p.longitude)); add(buf, &n, "receiveralt", scratch.float(2, p.altitude)); add(buf, &n, "receiveraltref", p.referenceName()); }
return buf[0..n];}
/// Somewhere for `loginFields` to format the values it has to render, since/// a `Field` borrows rather than owns. It must outlive the fields.pub const LoginScratch = struct { numbers: [3][32]u8 = @splat(@splat(0)), version: [64]u8 = @splat(0), /// Room for the source word and any identifier a configuration file is /// likely to hold; FlightAware issues UUIDs, which need thirty-six. feeder: [256]u8 = @splat(0),
fn float(self: *LoginScratch, slot: usize, value: f64) []const u8 { var w: Io.Writer = .fixed(&self.numbers[slot]); w.print("{d}", .{value}) catch return "0"; return w.buffered(); }
/// The identifier and where it came from, as the two-element Tcl list /// the server parses: `cache 0e5b…`, or `cache {}` when there is none /// yet. `{}` is how Tcl writes an empty element, and writing it any /// other way would hand the server an identifier of one space. fn feederId(self: *LoginScratch, options: Options) []const u8 { const tag = @tagName(options.feeder_id_source); const id = options.feeder_id orelse "";
// Whether the identifier fits is decided before anything is written, // because a fixed writer that runs out of room has already written // the part that did fit — so noticing the failure afterwards would // leave a truncated identifier in the buffer and send that. // // What is never given up is the source. Losing it turns `cache` into // `none`, which does not mean "no identifier this time" but "never // give me one": the opposite of what was configured, and not // something anyone would think to look for. const fits = id.len != 0 and tag.len + 1 + id.len <= self.feeder.len;
var w: Io.Writer = .fixed(&self.feeder); w.print("{s} {s}", .{ tag, if (fits) id else "{}" }) catch return "none {}"; return w.buffered(); }
fn versionFull(self: *LoginScratch, options: Options) []const u8 { var w: Io.Writer = .fixed(&self.version); w.print("{s} {s}", .{ options.program, options.version }) catch return options.version; return w.buffered(); }};
/// What a message from the server asks of us.pub const Action = union(enum) { /// Logged in. Carries the identifier the server issued, if it sent one; /// it should be stored and offered at the next login. logged_in: struct { user: ?[]const u8, feeder_id: ?[]const u8, site_url: ?[]const u8 }, /// The server refused the login. Carries its reason. Retrying will not /// help, so this stops rather than reconnecting. login_failed: struct { reason: ?[]const u8 }, /// A keepalive. Reply with `aliveFields` and restart the timeout at /// `interval` seconds; the server's clock is `server_clock` if it sent /// one, which is what the reported offset is measured against. alive: struct { interval: u32, server_clock: ?i64 }, /// The server said something worth passing on to the operator. notice: struct { message: ?[]const u8 }, /// The server asked us to go away. shutdown: struct { reason: ?[]const u8 }, /// The server asked to run software on this machine. Declined — see /// `Options.allow_auto_update`. update_refused, /// Understood and deliberately not acted on. ignored, /// Not understood. PiAware tolerates twenty of these and then reconnects, /// on the grounds that a client which no longer understands the server is /// better off starting again; this port counts them the same way. unrecognized,};
/// How many unrecognized messages in a row to tolerate before reconnecting.////// PiAware counts to the same number and, like this, gives up on the one/// after it rather than on it. Unlike PiAware the count is of a *run*: it/// exists to notice a protocol that has moved out from under the client,/// which is a burst, and a connection held for weeks should not eventually/// drop because it saw one unknown message a day.pub const unrecognized_limit = 20;
/// Decide what a message from the server means.pub fn classify(fields: []const Field) Action { const kind = find(fields, "type") orelse return .unrecognized;
if (std.mem.eql(u8, kind, "login_response")) { const status = find(fields, "status") orelse ""; if (std.mem.eql(u8, status, "ok")) return .{ .logged_in = .{ .user = find(fields, "user"), .feeder_id = find(fields, "feeder_id"), .site_url = find(fields, "site_url"), } }; return .{ .login_failed = .{ .reason = find(fields, "reason") } }; }
if (std.mem.eql(u8, kind, "alive")) { const interval = if (find(fields, "interval")) |text| std.fmt.parseInt(u32, text, 10) catch default_alive_interval_s else default_alive_interval_s; const clock = if (find(fields, "clock")) |text| std.fmt.parseInt(i64, text, 10) catch null else null; return .{ .alive = .{ .interval = interval, .server_clock = clock } }; }
if (std.mem.eql(u8, kind, "notice")) return .{ .notice = .{ .message = find(fields, "message") } };
if (std.mem.eql(u8, kind, "shutdown")) return .{ .shutdown = .{ .reason = find(fields, "reason") } };
if (std.mem.eql(u8, kind, "request_auto_update") or std.mem.eql(u8, kind, "request_manual_update")) return .update_refused;
// Handled by PiAware and deliberately not here. `update_location` would // have this program rewrite its own configured position from the server; // the `faup_*` messages steer a child process there is none of; the // `mlat_*` messages drive a multilateration client that is a separate // program. Naming them costs nothing and keeps them out of the // unrecognized count, which exists to notice a protocol that has moved // rather than one that is being selectively ignored. if (std.mem.eql(u8, kind, "update_location")) return .ignored; if (std.mem.startsWith(u8, kind, "faup_")) return .ignored; if (std.mem.startsWith(u8, kind, "mlat_")) return .ignored;
return .unrecognized;}
/// PiAware's fallback when the server does not name an interval.pub const default_alive_interval_s: u32 = 300;
/// How long to wait for the next keepalive before giving up on the/// connection. PiAware allows the interval and a fifth again.pub fn aliveDeadlineMs(interval_s: u32) u64 { return @as(u64, interval_s) * 1000 * 6 / 5;}
/// The reply to a keepalive: our clock, and how far it is from the server's.////// The offset is what lets FlightAware interpret timestamps from a receiver/// whose clock is wrong, so it is worth sending even when it is large — and/// especially then.pub fn aliveFields(buf: *AliveScratch, now: i64, server_clock: ?i64) []Field { var n: usize = 0; buf.fields[n] = .{ .key = "type", .value = "alive" }; n += 1; buf.fields[n] = .{ .key = "clock", .value = buf.render(0, now) }; n += 1; if (server_clock) |theirs| { // Saturating, because `clock` is whatever the far end sent and // `parseInt` will happily return the bottom of i64. Plain subtraction // overflows there, and an overflow is a panic in every mode this // ships in -- one malformed keepalive would take down the whole // receiver rather than just the uplink. buf.fields[n] = .{ .key = "offset", .value = buf.render(1, now -| theirs) }; n += 1; } return buf.fields[0..n];}
pub const AliveScratch = struct { fields: [4]Field = @splat(.{ .key = "", .value = "" }), numbers: [2][24]u8 = @splat(@splat(0)),
fn render(self: *AliveScratch, slot: usize, value: i64) []const u8 { var w: Io.Writer = .fixed(&self.numbers[slot]); w.print("{d}", .{value}) catch return "0"; return w.buffered(); }};
test "a login message names the feed and refuses to be managed" { var scratch: LoginScratch = .{}; var buf: [max_fields]Field = undefined; const fields = loginFields(&buf, .{ .mac = "001122334455", .version = "0.1.0", .position = .{ .latitude = 41.5868, .longitude = -93.625, .altitude = 900 }, }, &scratch);
try testing.expectEqualStrings("login", find(fields, "type").?); try testing.expectEqualStrings("001122334455", find(fields, "mac").?); try testing.expectEqualStrings("faup1090", find(fields, "transprogram").?); try testing.expectEqualStrings("41.5868", find(fields, "receiverlat").?); try testing.expectEqualStrings("geometric", find(fields, "receiveraltref").?);
// The whole point of the exercise. try testing.expectEqualStrings("0", find(fields, "local_auto_update_enable").?); try testing.expectEqualStrings("0", find(fields, "local_manual_update_enable").?);
// Nothing was declared that would make the server expect the compact // encoding this port does not implement. try testing.expectEqual(@as(?[]const u8, null), find(fields, "compression_version"));}
test "a login message without a position omits it" { var scratch: LoginScratch = .{}; var buf: [max_fields]Field = undefined; const fields = loginFields(&buf, .{ .mac = "001122334455", .version = "0.1.0" }, &scratch);
try testing.expectEqual(@as(?[]const u8, null), find(fields, "receiverlat")); try testing.expectEqual(@as(?[]const u8, null), find(fields, "receiveraltref"));}
test "a successful login yields the identifier to keep" { var fields: [max_fields]Field = undefined; const parsed = try parseLine( "type\tlogin_response\tstatus\tok\tuser\tjeff\tfeeder_id\tabc-123\tsite_url\thttps://example", &fields, ); switch (classify(parsed)) { .logged_in => |ok| { try testing.expectEqualStrings("jeff", ok.user.?); try testing.expectEqualStrings("abc-123", ok.feeder_id.?); try testing.expectEqualStrings("https://example", ok.site_url.?); }, else => return error.WrongAction, }}
test "a refused login is not a reconnect" { var fields: [max_fields]Field = undefined; const parsed = try parseLine( "type\tlogin_response\tstatus\tno\treason\tunknown feeder", &fields, ); switch (classify(parsed)) { .login_failed => |failed| try testing.expectEqualStrings("unknown feeder", failed.reason.?), else => return error.WrongAction, }}
test "a keepalive carries its own interval, and a missing one has a default" { var fields: [max_fields]Field = undefined;
switch (classify(try parseLine("type\talive\tinterval\t60\tclock\t1600000000", &fields))) { .alive => |a| { try testing.expectEqual(@as(u32, 60), a.interval); try testing.expectEqual(@as(i64, 1600000000), a.server_clock.?); }, else => return error.WrongAction, }
var fields2: [max_fields]Field = undefined; switch (classify(try parseLine("type\talive", &fields2))) { .alive => |a| { try testing.expectEqual(default_alive_interval_s, a.interval); try testing.expectEqual(@as(?i64, null), a.server_clock); }, else => return error.WrongAction, }}
test "the keepalive deadline allows the interval and a fifth" { try testing.expectEqual(@as(u64, 360_000), aliveDeadlineMs(300)); try testing.expectEqual(@as(u64, 72_000), aliveDeadlineMs(60));}
test "a keepalive is answered with our clock and its offset" { var scratch: AliveScratch = .{}; const fields = aliveFields(&scratch, 1_600_000_005, 1_600_000_000);
try testing.expectEqualStrings("alive", find(fields, "type").?); try testing.expectEqualStrings("1600000005", find(fields, "clock").?); try testing.expectEqualStrings("5", find(fields, "offset").?);}
test "a keepalive with no server clock is answered without an offset" { var scratch: AliveScratch = .{}; const fields = aliveFields(&scratch, 1_600_000_005, null); try testing.expectEqual(@as(?[]const u8, null), find(fields, "offset"));}
test "requests to run software on this machine are refused" { for ([_][]const u8{ "request_auto_update", "request_manual_update" }) |kind| { var buf: [64]u8 = undefined; const line = try std.fmt.bufPrint(&buf, "type\t{s}", .{kind}); var fields: [max_fields]Field = undefined; try testing.expectEqual(Action.update_refused, classify(try parseLine(line, &fields))); }}
test "messages meant for parts of PiAware that were not ported are ignored, not unrecognized" { // The distinction matters: `unrecognized` is counted towards a reconnect, // so treating a message this port declines to act on as unknown would // drop a working connection every twenty of them. for ([_][]const u8{ "update_location", "faup_start", "mlat_request" }) |kind| { var buf: [64]u8 = undefined; const line = try std.fmt.bufPrint(&buf, "type\t{s}", .{kind}); var fields: [max_fields]Field = undefined; try testing.expectEqual(Action.ignored, classify(try parseLine(line, &fields))); }}
test "a message with no type at all is unrecognized rather than a crash" { var fields: [max_fields]Field = undefined; try testing.expectEqual(Action.unrecognized, classify(try parseLine("clock\t1600000000", &fields)));}
// ---- The connection ----
const builtin = @import("builtin");const tls = @import("tls");const log_mod = @import("log.zig");
/// A TLS session with the adept server, and the reason it is driven by one/// task rather than two.////// The obvious shape for a link that both sends and receives is a task each/// way, which is what every other connection in this program uses. It is not/// used here, because the two directions share one cipher state and a/// rekeying triggered by something arriving would land in the middle of a/// record going out.////// So one task owns the session and interleaves the two directions, which/// needs a read that gives up rather than blocking for ever. That is what/// `read_timeout_ms` is for. Waiting up to a fifth of a second before looking/// at the outbound queue costs nothing: PiAware's own writer batches on a/// 200ms timer, so this is the cadence the far end already expects.////// The TLS is `tls.zig` rather than `std.crypto.tls`, and that is not a/// preference. The standard library's client has `certificate_request` in its/// handshake-type enum and in no switch that handles one, so a server asking/// for a client certificate is answered with `error.TlsUnexpectedMessage`/// before the handshake can finish. FlightAware's server asks. PiAware/// supplies no certificate, so the answer wanted is a refusal rather than a/// credential, and this library gives one.pub const Session = struct { gpa: Allocator, io: Io, stream: Io.net.Stream, state: *State,
pub const read_timeout_ms = 200;
/// Everything the connection points at, in one allocation that does not /// move: the TLS connection holds pointers to the socket's reader and /// writer, and its own reader and writer hold a pointer back to it. pub const State = struct { socket_read: [tls.input_buffer_len]u8 = undefined, socket_write: [tls.output_buffer_len]u8 = undefined, plaintext_read: [max_line * 2]u8 = undefined, plaintext_write: [max_line * 2]u8 = undefined,
reader: Io.net.Stream.Reader = undefined, writer: Io.net.Stream.Writer = undefined, connection: tls.Connection = undefined, plaintext_reader: tls.Connection.Reader = undefined, plaintext_writer: tls.Connection.Writer = undefined, };
/// Dial the server, verify it against the pinned root, and hand back a /// session ready to log in. /// /// The bundle is copied by value into the handshake options but its /// backing memory is borrowed, so it must outlive the session. pub fn connect( gpa: Allocator, io: Io, host: []const u8, port: u16, bundle: *Certificate.Bundle, ) !*Session { const self = try gpa.create(Session); errdefer gpa.destroy(self);
const state = try gpa.create(State); errdefer gpa.destroy(state); state.* = .{};
var stream = try dial(io, host, port); errdefer stream.close(io);
state.reader = stream.reader(io, &state.socket_read); state.writer = stream.writer(io, &state.socket_write);
const rng_source: std.Random.IoSource = .{ .io = io }; state.connection = try tls.client(&state.reader.interface, &state.writer.interface, .{ .rng = rng_source.interface(), .now = Io.Timestamp.now(io, .real), // Real host verification against the name actually dialled, which // the leaf's `DNS:*.flightaware.com` satisfies. PiAware checks // only that the common name is one of four it knows and does no // matching at all, which would take a certificate issued for // `eyes.flightaware.com` as proof of having reached this one. .host = host, .root_ca = bundle.*, });
state.plaintext_reader = state.connection.reader(&state.plaintext_read); state.plaintext_writer = state.connection.writer(&state.plaintext_write);
self.* = .{ .gpa = gpa, .io = io, .stream = stream, .state = state }; return self; }
pub fn deinit(self: *Session) void { self.stream.close(self.io); self.gpa.destroy(self.state); self.gpa.destroy(self); }
/// Send one message, stamping it with the clock if the caller has not. /// /// PiAware adds `clock` to every message it sends. The clock is the /// server's only handle on when a receiver believes something happened, /// so a message without one is worth less. pub fn send(self: *Session, fields: []Field, now: i64) !void { var buf: [24]u8 = undefined; var with_clock: [max_fields]Field = undefined;
const out = if (find(fields, "clock") != null) fields else blk: { if (fields.len + 1 > with_clock.len) return error.TooManyFields; @memcpy(with_clock[0..fields.len], fields); var w: Io.Writer = .fixed(&buf); try w.print("{d}", .{now}); with_clock[fields.len] = .{ .key = "clock", .value = w.buffered() }; break :blk with_clock[0 .. fields.len + 1]; };
try writeLine(&self.state.plaintext_writer.interface, out); try self.state.plaintext_writer.interface.flush(); }
/// Send a line that is already an adept message — which a FATSV track /// line is — without taking it apart and putting it back together. pub fn sendRaw(self: *Session, line: []const u8) !void { const w = &self.state.plaintext_writer.interface; try w.writeAll(line); if (line.len == 0 or line[line.len - 1] != '\n') try w.writeByte('\n'); try w.flush(); }
pub const ReadResult = union(enum) { /// A complete message, valid until the next call. line: []const u8, /// Nothing arrived within the read timeout. Not an error: it is the /// turn-taking this design is built on. idle, };
/// Read one message, or return `idle` when nothing arrived in time. pub fn next(self: *Session) !ReadResult { const r = &self.state.plaintext_reader.interface;
// Only ask the socket when nothing is already in hand. There are // three buffers between the wire and this line, and polling the first // while a message sits in one of the others is how a connection // stalls: two messages arriving in one segment leaves the second // decrypted-but-unread with nothing further due on the wire, and if // that second one is the keepalive this would go on to declare a // perfectly healthy link dead. if (!self.buffered()) { if (!readable(self.stream, read_timeout_ms)) return .idle; }
const line = try r.takeDelimiterInclusive('\n'); return .{ .line = std.mem.trimEnd(u8, line, "\r\n") }; }
/// Whether anything is already held anywhere below `next`. fn buffered(self: *Session) bool { // Decoded, waiting to be taken as a line. if (self.state.plaintext_reader.interface.buffered().len != 0) return true; // Decrypted by the TLS layer but not yet handed up. if (self.state.connection.cleartext_buf.len != 0) return true; // Arrived as ciphertext and not yet decrypted. if (self.state.reader.interface.buffered().len != 0) return true; return false; }};
/// Whether the socket has something to read, waiting up to `timeout_ms`.////// This is how the one task that owns the session takes turns between the two/// directions, and it is `poll` rather than a receive timeout on the socket/// because `SO_RCVTIMEO` cannot be used here at all: a timed-out read returns/// `EAGAIN`, and `Io.Threaded` treats `EAGAIN` on a socket it believes is/// blocking as a programmer error and panics rather than returning/// `error.Timeout`.////// A false negative only costs a fifth of a second, and an error is reported/// as readable so that the read itself surfaces it rather than this quietly/// turning a dead socket into an idle one.fn readable(stream: Io.net.Stream, timeout_ms: i32) bool { // Every POSIX target has `poll`. Anywhere else there is nothing to ask, // and answering "readable" makes the following read a blocking one -- // correct, but it leaves the outbound queue waiting on inbound traffic, // so it is a fallback rather than a supported arrangement. if (builtin.target.os.tag == .windows or builtin.target.os.tag == .wasi) return true; var fds = [_]std.posix.pollfd{.{ .fd = stream.socket.handle, .events = std.posix.POLL.IN, .revents = 0, }}; const ready = std.posix.poll(&fds, timeout_ms) catch return true; return ready > 0;}
/// Connect to a host given either as an address or as a name.////// The same two-step as the feed connectors: `IpAddress.resolve` does not do/// DNS, so a name has to go through `HostName`, which reads `/etc/hosts` and/// `/etc/resolv.conf` and tries every address the name has.fn dial(io: Io, host: []const u8, port: u16) !Io.net.Stream { if (Io.net.IpAddress.parse(host, port)) |address| { return Io.net.IpAddress.connect(&address, io, .{ .mode = .stream }); } else |_| {}
const name = try Io.net.HostName.init(host); return name.connect(io, port, .{ .mode = .stream });}
// ---- The client ----
/// The uplink: one long-lived conversation with FlightAware, restarted/// whenever it drops.////// Tracks are handed in with `submit` from whatever is decoding them and/// queued; the client's own task drains the queue between reads. A queue that/// grows past `max_pending_bytes` is dropped on the floor rather than allowed/// to consume memory without bound, because a receiver that cannot reach/// FlightAware must not stop decoding on that account.pub const Client = struct { gpa: Allocator, options: Options, /// Where to say what is happening. Nothing is written if this is null, /// which makes a client that cannot connect completely silent — so it is /// worth setting. /// /// Shared with the decoding loop and the network services, so it is a /// `Log` rather than a bare writer: several tasks report at once. log: ?*log_mod.Log = null,
/// Where to keep the identifier the server issues, if it should be kept. /// /// Written the moment one arrives rather than at shutdown, because a /// process that is killed rather than asked to stop would otherwise lose /// it — and losing it is not survivable in the way it sounds. A login /// with no identifier is a request for a new one, and FlightAware answers /// it by creating a *second site*, even from the same MAC. Observed: /// two such logins, one identifier each, both different. feeder_id_file: ?[]const u8 = null,
/// Guards `pending` and `identity`. mutex: Io.Mutex = .init, /// Bumped when there is something new to send or the client is stopping. epoch: std.atomic.Value(u32) = .init(0), pending: std.ArrayList(u8) = .empty, running: std.atomic.Value(bool) = .init(true), /// Whether the login has been accepted. Tracks are only queued once it /// has: anything sent earlier would be discarded by the server and only /// makes the reconnect that follows a failed login more expensive. logged_in: std.atomic.Value(bool) = .init(false),
/// What the server last told us about this feed. Owned. identity: Identity = .{},
/// Tracks handed over, and tracks that reached FlightAware. Cumulative /// across reconnects, as PiAware's are. Atomic because they are written /// from the decoding task and read from this one. submitted: std.atomic.Value(u64) = .init(0), sent: std.atomic.Value(u64) = .init(0), dropped: std.atomic.Value(u64) = .init(0),
pub const Identity = struct { feeder_id: ?[]u8 = null, user: ?[]u8 = null, site_url: ?[]u8 = null, };
/// Roughly a second of a busy receiver's tracks. Past this the far end is /// not keeping up and the backlog is stale anyway. pub const max_pending_bytes = 1 << 20;
pub const retry_initial_ms = 5_000; pub const retry_max_ms = 60_000;
pub fn deinit(self: *Client) void { self.pending.deinit(self.gpa); if (self.identity.feeder_id) |v| self.gpa.free(v); if (self.identity.user) |v| self.gpa.free(v); if (self.identity.site_url) |v| self.gpa.free(v); self.identity = .{}; }
/// Copy the identifier the server issued into `buf`, if it has issued one. /// /// A copy rather than a borrow, because the only way to use a borrowed /// one is to hold it past the return -- and by then the lock is gone and /// a reconnect that is issued a different identifier will have freed it. pub fn feederId(self: *Client, io: Io, buf: []u8) ?[]const u8 { self.mutex.lockUncancelable(io); defer self.mutex.unlock(io); const id = self.identity.feeder_id orelse return null; if (id.len > buf.len) return null; @memcpy(buf[0..id.len], id); return buf[0..id.len]; }
/// Queue a track line. Called from the decoding task. /// /// The line is a FATSV line, which is already an adept message, so it /// goes out as it stands rather than being taken apart and rebuilt. pub fn submit(self: *Client, io: Io, line: []const u8) void { if (line.len == 0) return; if (!self.logged_in.load(.acquire)) { // Counted, not merely skipped. An outage is exactly the case the // traffic report exists to make visible, and a report that said // "0 tracks sent" with no losses beside it would be describing a // working feed. _ = self.dropped.fetchAdd(1, .monotonic); return; }
self.mutex.lockUncancelable(io); defer self.mutex.unlock(io);
if (self.pending.items.len + line.len > max_pending_bytes) { _ = self.dropped.fetchAdd(1, .monotonic); return; }
self.pending.appendSlice(self.gpa, line) catch { _ = self.dropped.fetchAdd(1, .monotonic); return; }; if (line[line.len - 1] != '\n') self.pending.append(self.gpa, '\n') catch {}; _ = self.submitted.fetchAdd(1, .monotonic); self.wake(io); }
pub fn stop(self: *Client, io: Io) void { self.running.store(false, .release); self.wake(io); }
fn wake(self: *Client, io: Io) void { _ = self.epoch.fetchAdd(1, .release); io.futexWake(u32, &self.epoch.raw, std.math.maxInt(u32)); }
fn note(self: *Client, comptime format: []const u8, args: anytype) void { const l = self.log orelse return; l.print("flightaware: " ++ format ++ "\n", args); }
/// The client's own task: connect, log in, pump, reconnect. pub fn run(self: *Client, io: Io) void { var bundle = rootBundle(self.gpa, Io.Timestamp.now(io, .real).toSeconds()) catch |err| { self.note("cannot trust the pinned root certificate: {t}", .{err}); return; }; defer bundle.deinit(self.gpa);
var backoff: u64 = retry_initial_ms; var complained = false;
while (self.running.load(.acquire)) { const outcome = self.sessionOnce(io, &bundle, &complained); switch (outcome) { // Nothing will change by trying again with the same // credentials, so this stops rather than reconnecting for // ever against a server that has said no. .rejected => return, .connected => backoff = retry_initial_ms, .failed => backoff = @min(backoff * 2, retry_max_ms), } if (!self.running.load(.acquire)) break; self.waitBackoff(io, backoff); } }
/// Wait out the retry interval, but wake early if asked to stop. /// /// A plain sleep here would be a minute of a shutdown spent waiting for a /// feed nobody wants any more, since `stop` cannot reach a sleeping task /// and cancelling the group does not either. Waiting on the same futex /// `submit` and `stop` poke costs nothing and makes the wait /// interruptible. fn waitBackoff(self: *Client, io: Io, ms: u64) void { const seen = self.epoch.load(.acquire); io.futexWaitTimeout(u32, &self.epoch.raw, seen, .{ .duration = .{ .raw = .fromMilliseconds(@intCast(@min(ms, std.math.maxInt(i64)))), .clock = .awake, } }) catch {}; }
const Outcome = enum { connected, failed, rejected };
fn sessionOnce( self: *Client, io: Io, bundle: *Certificate.Bundle, complained: *bool, ) Outcome { const session = Session.connect( self.gpa, io, self.options.host, self.options.port, bundle, ) catch |err| { if (!complained.*) { self.note("{s}:{d}: {t}", .{ self.options.host, self.options.port, err }); complained.* = true; } return .failed; }; defer session.deinit(); complained.* = false; self.note("{s}:{d}: connected", .{ self.options.host, self.options.port });
var scratch: LoginScratch = .{}; var login_buf: [max_fields]Field = undefined; const login = loginFields(&login_buf, self.options, &scratch); session.send(login, Io.Timestamp.now(io, .real).toSeconds()) catch |err| { self.note("could not send the login: {t}", .{err}); return .failed; };
return self.pump(io, session); }
/// The conversation itself, over anything that can `send`, `sendRaw` and /// `next`. /// /// Generic over the transport rather than taking a `*Session` so that the /// loop can be driven by a scripted stand-in. Everything interesting in /// this client lives here — what a refused login does, when a quiet link /// counts as dead, how many messages it can fail to understand before /// starting again — and none of it should need a socket, let alone /// FlightAware's, to be checked. fn pump(self: *Client, io: Io, session: anytype) Outcome { var unrecognized: u32 = 0; var alive_deadline_ms = monotonicMs(io) + aliveDeadlineMs(default_alive_interval_s); var ever_logged_in = false; // Said once per connection rather than every time: often enough to // show the link is being kept alive and by whose schedule, rarely // enough not to be noise in a log that runs for months. var announced_keepalive = false; var next_report_ms = monotonicMs(io) + traffic_report_interval_ms;
defer self.logged_in.store(false, .release);
while (self.running.load(.acquire)) { if (self.drain(io, session)) |_| {} else |err| { self.note("send failed: {t}", .{err}); return if (ever_logged_in) .connected else .failed; }
const result = session.next() catch |err| { self.note("connection lost: {t}", .{err}); return if (ever_logged_in) .connected else .failed; };
const line = switch (result) { .idle => { const now_ms = monotonicMs(io); if (now_ms >= next_report_ms) { next_report_ms = now_ms + traffic_report_interval_ms; self.reportTraffic(); } // Only a quiet link, unless it has been quiet for longer // than the server promised. if (monotonicMs(io) >= alive_deadline_ms) { self.note("no keepalive from the server; reconnecting", .{}); return if (ever_logged_in) .connected else .failed; } continue; }, .line => |l| l, };
var fields: [max_fields]Field = undefined; const parsed = parseLine(line, &fields) catch { self.note("malformed message from the server; reconnecting", .{}); return if (ever_logged_in) .connected else .failed; };
const action = classify(parsed); // Any message understood ends the run of ones that were not. if (std.meta.activeTag(action) != .unrecognized) unrecognized = 0;
switch (action) { .logged_in => |ok| { ever_logged_in = true; self.remember(io, ok.user, ok.feeder_id, ok.site_url); self.logged_in.store(true, .release); if (ok.user) |u| self.note("logged in as {s}", .{u}); if (ok.feeder_id) |id| self.note("feeder id {s}", .{id}); if (ok.site_url) |url| self.note("statistics at {s}", .{url}); }, .login_failed => |failed| { self.note("login refused: {s}", .{failed.reason orelse "no reason given"}); return .rejected; }, .alive => |a| { alive_deadline_ms = monotonicMs(io) + aliveDeadlineMs(a.interval); if (!announced_keepalive) { announced_keepalive = true; self.note("keepalive every {d}s", .{a.interval}); } var alive: AliveScratch = .{}; const now = Io.Timestamp.now(io, .real).toSeconds(); session.send(aliveFields(&alive, now, a.server_clock), now) catch |err| { self.note("could not answer the keepalive: {t}", .{err}); return if (ever_logged_in) .connected else .failed; }; }, .notice => |n| self.note("server says: {s}", .{n.message orelse ""}), .shutdown => |s| { self.note("server asked us to stop: {s}", .{s.reason orelse "no reason given"}); return if (ever_logged_in) .connected else .failed; }, .update_refused => self.note( "declined a request to update software on this machine", .{}, ), .ignored => {}, .unrecognized => { unrecognized += 1; if (unrecognized > unrecognized_limit) { self.note("too many messages I do not understand; reconnecting", .{}); return if (ever_logged_in) .connected else .failed; } }, } } return .connected; }
/// Write whatever has piled up, in one go. fn drain(self: *Client, io: Io, session: anytype) !void { self.mutex.lockUncancelable(io); if (self.pending.items.len == 0) { self.mutex.unlock(io); return; } // Taken out from under the lock so that the decoding task is never // waiting on a write to FlightAware. var batch = self.pending; self.pending = .empty; self.mutex.unlock(io); defer batch.deinit(self.gpa);
const lines = std.mem.count(u8, batch.items, "\n"); session.sendRaw(batch.items) catch |err| { // The batch is gone either way; say so rather than let it vanish // between "submitted" and "sent". _ = self.dropped.fetchAdd(lines, .monotonic); return err; }; _ = self.sent.fetchAdd(lines, .monotonic); }
/// How often to say what has been sent. /// /// A feed nobody can see the volume of is one nobody can tell is working: /// "connected" and "connected but silent" look identical in a log /// otherwise. PiAware reports the same thing for the same reason. pub const traffic_report_interval_ms = 5 * 60 * 1000;
fn reportTraffic(self: *Client) void { const sent = self.sent.load(.monotonic); const lost = self.dropped.load(.monotonic); if (lost == 0) { self.note("{d} tracks sent", .{sent}); } else { self.note("{d} tracks sent, {d} dropped with nowhere to put them", .{ sent, lost }); } }
fn remember( self: *Client, io: Io, user: ?[]const u8, feeder_id: ?[]const u8, site_url: ?[]const u8, ) void { // Whatever is written to disk is copied out first, because this lock // is the one `submit` takes and `submit` is called from the decoding // loop. Writing a file under it would put a wedged filesystem -- a // hung NFS mount, a full disk retrying -- directly in the path of // demodulation. var copy: [128]u8 = undefined; var to_write: ?[]const u8 = null;
{ self.mutex.lockUncancelable(io); defer self.mutex.unlock(io); _ = replace(self.gpa, &self.identity.user, user); const changed = replace(self.gpa, &self.identity.feeder_id, feeder_id); _ = replace(self.gpa, &self.identity.site_url, site_url);
if (changed and self.feeder_id_file != null) { if (self.identity.feeder_id) |id| { if (id.len <= copy.len) { @memcpy(copy[0..id.len], id); to_write = copy[0..id.len]; } } } }
if (to_write) |id| self.writeFeederId(io, self.feeder_id_file.?, id); }
/// Put the identifier where the next run will find it, atomically, so /// that a crash mid-write cannot leave a half-written one behind. fn writeFeederId(self: *Client, io: Io, path: []const u8, id: []const u8) void { var temporary_buf: [std.fs.max_path_bytes]u8 = undefined; const temporary = std.fmt.bufPrint(&temporary_buf, "{s}.new", .{path}) catch return;
const dir = Io.Dir.cwd(); { const file = dir.createFile(io, temporary, .{}) catch |err| { self.note("cannot write the feeder id to {s}: {t}", .{ path, err }); return; }; defer file.close(io);
var buffer: [128]u8 = undefined; var file_writer = file.writer(io, &buffer); file_writer.interface.print("{s}\n", .{id}) catch |err| { // Silence here would be expensive: the next run logs in with // no identifier, and FlightAware makes a second site. self.note("cannot write the feeder id to {s}: {t}", .{ path, err }); dir.deleteFile(io, temporary) catch {}; return; }; file_writer.interface.flush() catch |err| { self.note("cannot write the feeder id to {s}: {t}", .{ path, err }); dir.deleteFile(io, temporary) catch {}; return; }; } Io.Dir.rename(dir, temporary, dir, path, io) catch |err| { self.note("cannot write the feeder id to {s}: {t}", .{ path, err }); dir.deleteFile(io, temporary) catch {}; }; }
/// Returns whether the stored value actually changed, so that a /// reconnect which is told the same identifier does not rewrite the file /// every time. fn replace(gpa: Allocator, slot: *?[]u8, value: ?[]const u8) bool { const text = value orelse return false; if (slot.*) |old| { if (std.mem.eql(u8, old, text)) return false; } const copy = gpa.dupe(u8, text) catch return false; if (slot.*) |old| gpa.free(old); slot.* = copy; return true; }};
/// Milliseconds on the monotonic clock. A wall clock that steps sideways must/// not turn into a spurious reconnect.fn monotonicMs(io: Io) u64 { const now = Io.Timestamp.now(io, .awake); return @intCast(@divTrunc(now.nanoseconds, std.time.ns_per_ms));}
test "nothing is queued before the login has been accepted" { // Anything sent ahead of the login response is discarded by the server, // and only makes the reconnect after a refused login more expensive. var client: Client = .{ .gpa = testing.allocator, .options = .{ .mac = "001122334455", .version = "0.1.0", } }; defer client.deinit();
client.submit(testing.io, "_v\t9E\tclock\t1\thexid\t4840D6"); try testing.expectEqual(@as(usize, 0), client.pending.items.len);}
test "a queued track keeps its line ending, and gains one if it had none" { var client: Client = .{ .gpa = testing.allocator, .options = .{ .mac = "001122334455", .version = "0.1.0", } }; defer client.deinit(); client.logged_in.store(true, .release);
client.submit(testing.io, "_v\t9E\thexid\t4840D6"); client.submit(testing.io, "_v\t9E\thexid\t484123\n");
try testing.expectEqualStrings( "_v\t9E\thexid\t4840D6\n_v\t9E\thexid\t484123\n", client.pending.items, );}
test "a backlog that cannot be sent is dropped rather than grown without bound" { // A receiver that cannot reach FlightAware must carry on decoding, so the // queue has a ceiling and the oldest thing to give way is the newest // track rather than the process. var client: Client = .{ .gpa = testing.allocator, .options = .{ .mac = "001122334455", .version = "0.1.0", } }; defer client.deinit(); client.logged_in.store(true, .release);
const line = "_v\t9E\thexid\t4840D6\n"; var written: usize = 0; while (written + line.len <= Client.max_pending_bytes) : (written += line.len) { client.submit(testing.io, line); } const at_capacity = client.pending.items.len;
client.submit(testing.io, line); try testing.expectEqual(at_capacity, client.pending.items.len); try testing.expect(at_capacity <= Client.max_pending_bytes);}
/// A stand-in for `Session` that reads from a script and remembers what was/// written, so that the conversation can be tested without a socket.////// `next` hands back the scripted lines in order and then reports the far end/// as gone, which is what ends `pump` in most of the tests below. An `idle`/// entry stands for the read timeout that a quiet link produces several times/// a second.const FakeSession = struct { script: []const Entry, at: usize = 0, sent: std.ArrayList(u8) = .empty, gpa: Allocator,
const Entry = union(enum) { line: []const u8, idle };
fn deinit(self: *FakeSession) void { self.sent.deinit(self.gpa); }
fn send(self: *FakeSession, fields: []Field, now: i64) !void { var buf: [24]u8 = undefined; var with_clock: [max_fields]Field = undefined; const out = if (find(fields, "clock") != null) fields else blk: { @memcpy(with_clock[0..fields.len], fields); var w: Io.Writer = .fixed(&buf); try w.print("{d}", .{now}); with_clock[fields.len] = .{ .key = "clock", .value = w.buffered() }; break :blk with_clock[0 .. fields.len + 1]; }; var writer: Io.Writer.Allocating = .fromArrayList(self.gpa, &self.sent); defer self.sent = writer.toArrayList(); try writeLine(&writer.writer, out); }
fn sendRaw(self: *FakeSession, line: []const u8) !void { try self.sent.appendSlice(self.gpa, line); }
fn next(self: *FakeSession) !Session.ReadResult { if (self.at == self.script.len) return error.EndOfStream; defer self.at += 1; return switch (self.script[self.at]) { .idle => .idle, .line => |l| .{ .line = l }, }; }};
fn testClient(script: []const FakeSession.Entry) struct { Client, FakeSession } { return .{ .{ .gpa = testing.allocator, .options = .{ .mac = "001122334455", .version = "0.1.0", } }, .{ .gpa = testing.allocator, .script = script }, };}
test "an accepted login is remembered and opens the feed" { var client, var session = testClient(&.{ .{ .line = "type\tlogin_response\tstatus\tok\tuser\tjeff\tfeeder_id\tabc-123" }, }); defer client.deinit(); defer session.deinit();
// The script runs out, which reads as the far end going away — and since // the login had been accepted by then, that is a dropped connection to // come back from rather than a failure to get in. try testing.expectEqual(Client.Outcome.connected, client.pump(testing.io, &session)); try testing.expectEqualStrings("abc-123", client.identity.feeder_id.?); try testing.expectEqualStrings("jeff", client.identity.user.?);}
test "a refused login stops instead of reconnecting for ever" { var client, var session = testClient(&.{ .{ .line = "type\tlogin_response\tstatus\tno\treason\tunknown feeder" }, }); defer client.deinit(); defer session.deinit();
// Nothing changes by asking again with the same credentials, so a client // that reconnected here would knock on a closed door every five seconds // for as long as the process lived. try testing.expectEqual(Client.Outcome.rejected, client.pump(testing.io, &session));}
test "a keepalive is answered" { var client, var session = testClient(&.{ .{ .line = "type\tlogin_response\tstatus\tok" }, .{ .line = "type\talive\tinterval\t60\tclock\t1600000000" }, }); defer client.deinit(); defer session.deinit();
_ = client.pump(testing.io, &session);
// The reply carries our clock and how far it is from theirs, which is // what lets FlightAware read timestamps from a receiver whose clock is // wrong. try testing.expect(std.mem.indexOf(u8, session.sent.items, "type\talive") != null); try testing.expect(std.mem.indexOf(u8, session.sent.items, "offset\t") != null);}
test "a link that goes quiet for longer than promised is treated as dead" { // A keepalive interval of zero puts the deadline in the past at once, // which is the same code path as waiting out a real one without the // seventy-two seconds. The line after the idle is the discriminator: it // is only reached if the deadline is *not* noticed, so reading it would // fail the count below rather than passing quietly. var client, var session = testClient(&.{ .{ .line = "type\tlogin_response\tstatus\tok" }, .{ .line = "type\talive\tinterval\t0" }, .idle, .{ .line = "type\tnotice\tmessage\tshould never be read" }, }); defer client.deinit(); defer session.deinit();
try testing.expectEqual(Client.Outcome.connected, client.pump(testing.io, &session)); try testing.expectEqual(@as(usize, 3), session.at);}
test "a run of messages it cannot understand ends the connection" { var script: [unrecognized_limit + 3]FakeSession.Entry = undefined; script[0] = .{ .line = "type\tlogin_response\tstatus\tok" }; for (script[1..]) |*entry| entry.* = .{ .line = "type\tsomething_new" };
var client, var session = testClient(&script); defer client.deinit(); defer session.deinit();
try testing.expectEqual(Client.Outcome.connected, client.pump(testing.io, &session)); // Stopped at the limit rather than reading the whole script. try testing.expectEqual(@as(usize, unrecognized_limit + 2), session.at);}
test "messages that are declined on purpose never trip that limit" { // The counterpart to the test above: twice as many of the messages this // port deliberately does not act on, and the connection survives them. var script: [unrecognized_limit * 2 + 1]FakeSession.Entry = undefined; script[0] = .{ .line = "type\tlogin_response\tstatus\tok" }; for (script[1..], 0..) |*entry, i| { entry.* = .{ .line = switch (i % 3) { 0 => "type\tupdate_location\tlat\t1\tlon\t2", 1 => "type\tfaup_start", else => "type\trequest_auto_update", } }; }
var client, var session = testClient(&script); defer client.deinit(); defer session.deinit();
_ = client.pump(testing.io, &session); try testing.expectEqual(script.len, session.at);}
test "a malformed line is not parsed around" { var client, var session = testClient(&.{ .{ .line = "type\tlogin_response\tstatus\tok" }, .{ .line = "type\talive\tinterval" }, }); defer client.deinit(); defer session.deinit();
try testing.expectEqual(Client.Outcome.connected, client.pump(testing.io, &session)); try testing.expectEqual(@as(usize, 2), session.at);}
test "tracks queued before the login are not sent, and later ones are" { var client, var session = testClient(&.{ .{ .line = "type\tlogin_response\tstatus\tok" }, .idle, }); defer client.deinit(); defer session.deinit();
// Dropped: the server discards anything before the login response. client.submit(testing.io, "_v\t9E\thexid\tBEFORE");
// The login is read on the first pass and the queue drained on the // second, so a track handed over in between goes out. client.logged_in.store(true, .release); client.submit(testing.io, "_v\t9E\thexid\tAFTER");
_ = client.pump(testing.io, &session);
try testing.expect(std.mem.indexOf(u8, session.sent.items, "BEFORE") == null); try testing.expect(std.mem.indexOf(u8, session.sent.items, "AFTER") != null); // Forwarded as it stands rather than taken apart and rebuilt. try testing.expect(std.mem.indexOf(u8, session.sent.items, "_v\t9E\thexid\tAFTER\n") != null);}
test "a shutdown from the server is a reconnect, not a stop" { // The server closing one connection is routine — a deploy, a rebalance — // and is nothing like being told the credentials are wrong. var client, var session = testClient(&.{ .{ .line = "type\tlogin_response\tstatus\tok" }, .{ .line = "type\tshutdown\treason\tserver going down" }, }); defer client.deinit(); defer session.deinit();
try testing.expectEqual(Client.Outcome.connected, client.pump(testing.io, &session));}
test "a connection that dies before the login is a failure to get in" { // Which matters because the two back off differently: a drop after a good // login retries in five seconds, a failure doubles up towards a minute. var client, var session = testClient(&.{.idle}); defer client.deinit(); defer session.deinit();
try testing.expectEqual(Client.Outcome.failed, client.pump(testing.io, &session));}
test "the pinned root verifies FlightAware's live server" { // Off by default: it needs the network, and a test suite that fails // because a laptop is on a train is a test suite people stop believing. // Run it with `zig build test -Dtls-check` when the certificate chain is // in question — after a rotation, or when a handshake starts failing and // it is not obvious whose end the fault is at. // // It connects and completes the handshake and does nothing else. No login // is sent, so no feed is registered and nothing identifies this machine; // it is the same thing `openssl s_client` does, through the code that // will actually be doing it. if (!@import("build_options").tls_check) return error.SkipZigTest;
const io = testing.io; var bundle = try rootBundle(testing.allocator, Io.Timestamp.now(io, .real).toSeconds()); defer bundle.deinit(testing.allocator);
const session = try Session.connect( testing.allocator, io, default_host, default_port, &bundle, ); session.deinit();}
test "a quiet socket reads as idle rather than parking the task" { // The turn-taking the whole single-task design rests on, against a local // socket that nobody writes to: `readable` has to come back false within // its timeout, and true once there is something there. // // Worth its own test because the obvious way to do this — a receive // timeout on the socket — cannot be used at all. A timed-out read returns // EAGAIN, and `Io.Threaded` treats EAGAIN on a socket it believes is // blocking as a programmer error and panics. var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io();
const bind: Io.net.IpAddress = try .parse("127.0.0.1", 0); var listener = try bind.listen(io, .{ .mode = .stream }); defer listener.deinit(io);
const address: Io.net.IpAddress = try .parse("127.0.0.1", listener.socket.address.ip4.port); var client = try Io.net.IpAddress.connect(&address, io, .{ .mode = .stream }); defer client.close(io);
var accepted = try listener.accept(io); defer accepted.close(io);
try testing.expect(!readable(client, 50));
var write_buf: [64]u8 = undefined; var writer = accepted.writer(io, &write_buf); try writer.interface.writeAll("hello\n"); try writer.interface.flush();
try testing.expect(readable(client, 1000));}
test "a first login asks for a feeder id rather than omitting one" { // The difference between being given a site and being told to upgrade. // FlightAware refuses to create one for a client that does not send this // field, since the word before the identifier is how it knows the client // can keep what it is issued. `{}` is Tcl for an empty element. var scratch: LoginScratch = .{}; var buf: [max_fields]Field = undefined; const fields = loginFields(&buf, .{ .mac = "001122334455", .version = "0.1.0", .feeder_id_source = .cache, }, &scratch);
try testing.expectEqualStrings("cache {}", find(fields, "feeder_id").?);}
test "a later login offers the identifier it was given" { var scratch: LoginScratch = .{}; var buf: [max_fields]Field = undefined; const fields = loginFields(&buf, .{ .mac = "001122334455", .version = "0.1.0", .feeder_id = "0e5b1c2d-1111-2222-3333-444455556666", .feeder_id_source = .cache, }, &scratch);
try testing.expectEqualStrings( "cache 0e5b1c2d-1111-2222-3333-444455556666", find(fields, "feeder_id").?, );}
test "a receiver with nowhere to keep an identifier says so" { var scratch: LoginScratch = .{}; var buf: [max_fields]Field = undefined; const fields = loginFields(&buf, .{ .mac = "001122334455", .version = "0.1.0" }, &scratch); try testing.expectEqualStrings("none {}", find(fields, "feeder_id").?);}
test "what was sent is counted, and what was dropped is counted separately" { var client, var session = testClient(&.{ .{ .line = "type\tlogin_response\tstatus\tok" }, .idle, .idle, }); defer client.deinit(); defer session.deinit();
client.logged_in.store(true, .release); client.submit(testing.io, "_v\t9E\thexid\t4840D6"); client.submit(testing.io, "_v\t9E\thexid\t484123");
_ = client.pump(testing.io, &session);
try testing.expectEqual(@as(u64, 2), client.submitted.load(.monotonic)); try testing.expectEqual(@as(u64, 2), client.sent.load(.monotonic)); try testing.expectEqual(@as(u64, 0), client.dropped.load(.monotonic));}
test "a track that cannot be queued is counted as dropped rather than lost quietly" { var client: Client = .{ .gpa = testing.allocator, .options = .{ .mac = "001122334455", .version = "0.1.0", } }; defer client.deinit(); client.logged_in.store(true, .release);
const line = "_v\t9E\thexid\t4840D6\n"; while (client.pending.items.len + line.len <= Client.max_pending_bytes) { client.submit(testing.io, line); } const before = client.dropped.load(.monotonic);
client.submit(testing.io, line); try testing.expectEqual(before + 1, client.dropped.load(.monotonic));}
test "the traffic report says what got through, and mentions losses only when there are some" { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); var log: log_mod.Log = .init(testing.io, &out.writer);
var client: Client = .{ .gpa = testing.allocator, .options = .{ .mac = "001122334455", .version = "0.1.0" }, .log = &log, }; defer client.deinit();
client.sent.store(1234, .monotonic); client.reportTraffic(); try testing.expectEqualStrings("flightaware: 1234 tracks sent\n", out.written());
out.clearRetainingCapacity(); client.dropped.store(7, .monotonic); client.reportTraffic(); try testing.expectEqualStrings( "flightaware: 1234 tracks sent, 7 dropped with nowhere to put them\n", out.written(), );}
test "a connection that dies before the login backs off, however it died" { // All four of these used to report a dropped connection rather than a // failure to get in, which resets the retry interval to five seconds. A // server refusing every connection the same way would then be dialled // every five seconds for as long as the process lived, instead of the // backoff climbing to a minute. const scripts = [_][]const FakeSession.Entry{ &.{.{ .line = "type\tshutdown\treason\ttry later" }}, &.{.{ .line = "type\talive\tinterval" }}, // malformed: odd field count }; for (scripts) |script| { var client, var session = testClient(script); defer client.deinit(); defer session.deinit(); try testing.expectEqual(Client.Outcome.failed, client.pump(testing.io, &session)); }}
test "a run of unknown messages is broken by one that is understood" { // The limit is meant to notice a protocol that has moved, which is a // burst. Counting for the life of the connection instead would drop a // link held for weeks because it saw one unknown message a day. var script: [unrecognized_limit * 2 + 3]FakeSession.Entry = undefined; script[0] = .{ .line = "type\tlogin_response\tstatus\tok" }; for (script[1 .. unrecognized_limit + 1]) |*e| e.* = .{ .line = "type\tsomething_new" }; script[unrecognized_limit + 1] = .{ .line = "type\tnotice\tmessage\tstill here" }; for (script[unrecognized_limit + 2 ..]) |*e| e.* = .{ .line = "type\tsomething_new" };
var client, var session = testClient(&script); defer client.deinit(); defer session.deinit();
_ = client.pump(testing.io, &session); // Read the whole script: forty unknown messages either side of one that // was understood, and no disconnect. try testing.expectEqual(script.len, session.at);}
test "a keepalive with an absurd clock is answered, not fatal" { // `clock` is whatever the far end sent. Subtracting the bottom of i64 // from the current time overflows, and an overflow is a panic in every // mode this ships in — one malformed keepalive would take down the // receiver rather than just the uplink. var scratch: AliveScratch = .{}; const fields = aliveFields(&scratch, 1_600_000_000, std.math.minInt(i64)); try testing.expectEqualStrings("alive", find(fields, "type").?); try testing.expect(find(fields, "offset") != null);
var also: AliveScratch = .{}; _ = aliveFields(&also, std.math.minInt(i64), std.math.maxInt(i64));}
test "an identifier too long to send costs the identifier, never the source" { // Losing the source would turn `cache` into `none`, which does not mean // "no identifier this time" but "never give me one" — so a configuration // asking to be given a site would quietly ask never to have one. var scratch: LoginScratch = .{}; var buf: [max_fields]Field = undefined; const absurd = "x" ** 400; const fields = loginFields(&buf, .{ .mac = "001122334455", .version = "0.1.0", .feeder_id = absurd, .feeder_id_source = .cache, }, &scratch);
try testing.expectEqualStrings("cache {}", find(fields, "feeder_id").?);}
test "tracks handed over during an outage are counted as lost" { // Otherwise the report that exists to distinguish "connected" from // "connected but silent" would describe an outage as a working feed. var client: Client = .{ .gpa = testing.allocator, .options = .{ .mac = "001122334455", .version = "0.1.0", } }; defer client.deinit();
client.submit(testing.io, "_v\t9E\thexid\t4840D6"); client.submit(testing.io, "_v\t9E\thexid\t484123");
try testing.expectEqual(@as(usize, 0), client.pending.items.len); try testing.expectEqual(@as(u64, 2), client.dropped.load(.monotonic)); try testing.expectEqual(@as(u64, 0), client.submitted.load(.monotonic));}