Skip to content
zit Artifact [31b84eec48]
Login

Artifact [31b84eec48]

Artifact 31b84eec4851bb13bd57d25ed3bc250bfa73b881278b8ab041e3f642d1c3c511:


//! `zit uv`: list, fetch, send and remove unversioned files on the peer.

const std = @import("std");
const armBasicAuth = @import("sync_dialogue.zig").armBasicAuth;
const artifact = zit.artifact;
const cli = @import("zit").cli;
const diagnostics = @import("../diagnostics.zig");
const help_pages = @import("../help.zig");
const logstore = @import("zit").logstore;
const max_password_len = @import("sync_dialogue.zig").max_password_len;
const not_a_repo_msg = diagnostics.not_a_repo_msg;
const notePlaintext = @import("sync_dialogue.zig").notePlaintext;
const refusedRedirect = @import("sync_dialogue.zig").refusedRedirect;
const repoReadFail = diagnostics.repoReadFail;
const repoSyncIdentity = zit.sync_session.repoSyncIdentity;
const reportTruncatedPayloads = @import("sync_dialogue.zig").reportTruncatedPayloads;
const resolvePushCredential = @import("sync_dialogue.zig").resolvePushCredential;
const stateOom = diagnostics.stateOom;
const syncOpenFail = @import("sync_dialogue.zig").syncOpenFail;
const sync_client_version_info = zit.sync_session.sync_client_version_info;
const transport = @import("../transport.zig");
const zit = @import("zit");

// ---------------------------------------------------------------------------
// `zit push URL` — the mirror of pull: UPLOAD this repository's artifacts into an
// EXISTING served repo. It opens the cwd's `.zit`, announces what it holds so the
// peer requests only what it lacks (sync §3.2/§3.3 igot/gimme), and uploads the
// missing artifacts as `file` cards, driving to §3.7 termination. The peer's
// `zit serve` persists what it receives; nothing changes on this side (§3.3 r24).
// Anonymous only.
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// `zit uv` -- unversioned files, moved between a server and plain files.
//
// quarry keeps a repository's unversioned files in its own storage and answers
// the uv cards itself, so a zit repository holds no copy of them: this client
// lists, fetches, sends and deletes them on the server and writes nothing to
// `.zit`. The wire is fossil's (sync.wiki §3.11): `pragma uv-hash`, answered
// by `uv-push-ok` or `uv-pull-only` and a `uvigot` catalog, then `uvgimme` and
// `uvfile`. A uv exchange carries no `pull` or `push` card; that is what a
// stock fossil client sends for `fossil uv sync`, captured on the wire.
// ---------------------------------------------------------------------------

/// The catalog hash this client announces. A fossil server answers only when
/// the client's hash differs from its own, so a client announcing an empty
/// catalog would hear nothing from a server holding no files, which reads the
/// same as a server that does not share. No catalog hashes to this.
const uv_hash_never = "0000000000000000000000000000000000000000";

/// Rounds a pull may take: a server may answer a batch of `uvgimme` with only
/// some files when a reply would be too large, so the rest are asked again.
const uv_max_rounds: usize = 64;

/// Fossil's limit on an unversioned file's name.
const uv_max_name: usize = 500;

const UvAccess = enum { none, pull_only, push_ok };

const UvEntry = struct {
    name: []const u8,
    mtime: i64,
    /// `-` for a tombstone.
    hash: []const u8,
    size: u32,

    fn deleted(self: UvEntry) bool {
        return std.mem.eql(u8, self.hash, "-");
    }
};

const UvFile = struct { name: []const u8, content: []const u8 };

/// What one reply said, arena-owned.
const UvReply = struct {
    access: UvAccess = .none,
    catalog: std.ArrayList(UvEntry) = .empty,
    files: std.ArrayList(UvFile) = .empty,
    /// The server's own words from an `error` card, decoded.
    refusal: ?[]const u8 = null,
    /// sync §5.1/§10.1 — the body ended inside a uvfile payload; the cards
    /// before it stand and the rest of the reply was not read.
    truncated: bool = false,

    fn find(self: *const UvReply, name: []const u8) ?UvEntry {
        for (self.catalog.items) |e| if (std.mem.eql(u8, e.name, name)) return e;
        return null;
    }
};

/// Fossil's rules for an unversioned name: no whitespace or control
/// characters, at most 500 bytes, a relative path with no `.` or `..`
/// component. `releases/1.2.3/x.tar.gz` is just a name.
fn uvNameOk(name: []const u8) bool {
    if (name.len == 0 or name.len > uv_max_name) return false;
    if (name[0] == '/' or name[name.len - 1] == '/') return false;
    for (name) |c| if (c <= ' ' or c == 0x7f or c == '\\') return false;
    var it = std.mem.splitScalar(u8, name, '/');
    while (it.next()) |part| {
        if (part.len == 0 or std.mem.eql(u8, part, ".") or std.mem.eql(u8, part, "..")) return false;
    }
    return true;
}

/// One uv round: the client-version pragma and `cards`, signed with a login
/// card when there is a credential, sent, and the reply parsed. A reply card
/// this client has no use for (`pragma server-version`, a `#` comment) is
/// passed over; a malformed uv card or content that does not match its hash
/// is a protocol error.
fn uvRound(
    gpa: std.mem.Allocator,
    arena: std.mem.Allocator,
    tr: *transport.Transport,
    credential: ?zit.sync.Credential,
    cards: []const u8,
) !UvReply {
    var tail: std.ArrayList(u8) = .empty;
    defer tail.deinit(gpa);
    var line_buf: [zit.sync.max_line_len]u8 = undefined;
    try tail.appendSlice(gpa, try zit.sync.writeClientVersion(sync_client_version_info, &line_buf));
    try tail.append(gpa, '\n');
    try tail.appendSlice(gpa, cards);

    var request: std.ArrayList(u8) = .empty;
    defer request.deinit(gpa);
    if (credential) |cred| {
        const nonce = zit.sync.computeNonce(tail.items);
        const signature = zit.sync.computeSignature(&nonce, &cred.secret_hex);
        try request.appendSlice(gpa, try zit.sync.writeLogin(.{ .user = cred.user, .nonce = &nonce, .signature = &signature }, &line_buf));
        try request.append(gpa, '\n');
    }
    try request.appendSlice(gpa, tail.items);

    const body = try tr.exchange(gpa, request.items);
    defer gpa.free(body);
    return parseUvReply(arena, try arena.dupe(u8, body));
}

/// Read one uv reply body. `owned` lives in `arena`, as do the names and file
/// contents the reply points into.
fn parseUvReply(arena: std.mem.Allocator, owned: []const u8) !UvReply {
    var reply: UvReply = .{};
    var pos: usize = 0;
    while (pos < owned.len) {
        const eol = std.mem.indexOfScalarPos(u8, owned, pos, '\n') orelse owned.len;
        const line = owned[pos..eol];
        pos = @min(eol + 1, owned.len);
        if (line.len == 0 or line[0] == '#') continue;
        const tokens = zit.sync.tokenizeCard(line);
        if (tokens.len == 0) continue;
        const op = tokens.items[0];
        if (std.mem.eql(u8, op, "pragma") and tokens.len >= 2) {
            if (std.mem.eql(u8, tokens.items[1], "uv-push-ok")) reply.access = .push_ok;
            if (std.mem.eql(u8, tokens.items[1], "uv-pull-only") and reply.access != .push_ok) reply.access = .pull_only;
        } else if (std.mem.eql(u8, op, "uvigot")) {
            const card = zit.sync.parseUvigotCard(tokens) catch return error.ProtocolError;
            try reply.catalog.append(arena, .{ .name = try uvDecodeName(arena, card.name), .mtime = card.mtime, .hash = card.hash, .size = card.size });
        } else if (std.mem.eql(u8, op, "uvfile")) {
            const card = zit.sync.parseUvfileCard(tokens) catch return error.ProtocolError;
            const payload = zit.sync.consumeUvfilePayload(owned, pos, card) catch {
                reply.truncated = true;
                break;
            };
            pos = payload.next;
            if (card.isDeletion() or card.contentOmitted()) continue;
            if (!zit.sync.verifyUvContent(card.hash, payload.bytes)) return error.ProtocolError;
            try reply.files.append(arena, .{ .name = try uvDecodeName(arena, card.name), .content = payload.bytes });
        } else if (std.mem.eql(u8, op, "error") and tokens.len >= 2) {
            reply.refusal = try uvDecodeName(arena, tokens.items[1]);
        }
    }
    return reply;
}

fn uvDecodeName(arena: std.mem.Allocator, wire: []const u8) ![]const u8 {
    const out = try arena.alloc(u8, wire.len);
    return artifact.decodeEscapes(wire, out);
}

/// The catalog round every subcommand starts with.
fn uvCatalog(gpa: std.mem.Allocator, arena: std.mem.Allocator, tr: *transport.Transport, credential: ?zit.sync.Credential) !UvReply {
    return uvRound(gpa, arena, tr, credential, "pragma uv-hash " ++ uv_hash_never ++ "\n");
}

pub fn runUv(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
) cli.Exit {
    const parsed = switch (cli.parseUvArgs(gpa, verb_args) catch return stateOom(streams, "uv")) {
        .ok => |p| p,
        .unknown_option => |tok| return cli.usageError(streams, "uv", .unknown_option, tok),
        .bad_subcommand => |tok| return cli.usageError(streams, "uv", .bad_subcommand, tok),
    };
    defer gpa.free(parsed.positionals);
    if (parsed.help) {
        streams.out.writeAll(help_pages.uv_help) catch {};
        return .ok;
    }
    const sub = parsed.sub orelse return cli.usageError(streams, "uv", .bad_subcommand, "");
    const url = parsed.url orelse return cli.usageError(streams, "uv", .no_url, "");
    switch (uvCheckArgs(streams, sub, parsed)) {
        .ok => {},
        else => |rc| return rc,
    }
    if (parsed.user) |u| if (u.len > 0 and zit.sync.containsFossilWhitespace(u)) {
        streams.err.writeAll("zit uv: --user must not contain whitespace\n") catch {};
        return .failure;
    };

    // The login is the repository's, as for push: the shared secret is
    // derived from the project code the server serves.
    const root = (cli.resolveRoot(arena, io, amb.repo_override) catch return stateOom(streams, "uv")) orelse {
        streams.err.writeAll(not_a_repo_msg) catch {};
        return .failure;
    };
    var root_dir = root.dir;
    defer root_dir.close(io);
    var pc_buf: [zit.sync.max_projectcode_len]u8 = undefined;
    const identity = repoSyncIdentity(gpa, io, root_dir, root.abs, &pc_buf) catch |e| switch (e) {
        error.OutOfMemory => return stateOom(streams, "uv"),
        error.Storage => return repoReadFail(streams, "uv"),
    };
    var pw_buf: [max_password_len]u8 = undefined;
    defer std.crypto.secureZero(u8, &pw_buf);
    var user_buf: [logstore.max_config_str]u8 = undefined;
    const resolved = resolvePushCredential(gpa, io, root_dir, streams, identity.project_code, .{ .url = url, .user = parsed.user, .password = parsed.password }, amb, &pw_buf, &user_buf) catch |e| switch (e) {
        error.OutOfMemory => return stateOom(streams, "uv"),
        error.Storage => return repoReadFail(streams, "uv"),
        error.NoPassword => {
            streams.err.writeAll("zit uv: no password supplied for --user\n") catch {};
            return .failure;
        },
    };

    var tr = transport.Transport.open(io, gpa, url) catch |e| return syncOpenFail(streams, "uv", url, e);
    defer tr.close();
    notePlaintext(streams, "uv", url);
    if (resolved) |r| armBasicAuth(&tr, r.credential.user, r.plaintext) catch return stateOom(streams, "uv");
    const credential: ?zit.sync.Credential = if (resolved) |r| r.credential else null;

    const catalog = uvCatalog(gpa, arena, &tr, credential) catch |e| return uvFail(streams, url, e, &tr);
    reportTruncatedPayloads(streams, "uv", @intFromBool(catalog.truncated));
    if (catalog.refusal) |why| {
        streams.err.print("zit uv: the server refused: {s}\n", .{why}) catch {};
        return .failure;
    }
    if (catalog.access == .none) {
        streams.err.print("zit uv: {s} does not share unversioned files with {s}\n", .{ url, if (credential) |c| c.user else "an anonymous user" }) catch {};
        return .failure;
    }
    return switch (sub) {
        .list => uvList(streams, &catalog, parsed.long),
        .pull => uvPull(gpa, io, arena, streams, &tr, credential, &catalog, parsed, url),
        .push => uvPush(gpa, io, arena, streams, &tr, credential, &catalog, parsed, amb, url),
        .rm => uvRm(gpa, arena, streams, &tr, credential, &catalog, parsed, amb, url),
    };
}

/// The flags each subcommand takes and the operands it needs, before any
/// network or store work.
fn uvCheckArgs(streams: cli.Streams, sub: cli.UvSub, p: cli.UvArgs) cli.Exit {
    const misuse = struct {
        fn say(s: cli.Streams, comptime msg: []const u8) cli.Exit {
            s.err.writeAll("zit uv: " ++ msg ++ "\ntry 'zit uv --help'\n") catch {};
            return .usage;
        }
    };
    if (p.long and sub != .list) return misuse.say(streams, "-l belongs to 'uv list'");
    if ((p.all or p.out_dir != null) and sub != .pull) return misuse.say(streams, "--all and -o belong to 'uv pull'");
    if ((p.as != null) and sub != .push) return misuse.say(streams, "--as belongs to 'uv push'");
    if ((p.mtime != null) and sub != .push and sub != .rm) return misuse.say(streams, "--mtime belongs to 'uv push' and 'uv rm'");
    switch (sub) {
        .list => if (p.items.len != 0) return misuse.say(streams, "'uv list' takes only the URL"),
        .pull => {
            if (p.all and p.items.len != 0) return misuse.say(streams, "'uv pull' takes NAMEs or --all, not both");
            if (!p.all and p.items.len == 0) return misuse.say(streams, "'uv pull' needs a NAME or --all");
        },
        .push => {
            if (p.items.len == 0) return misuse.say(streams, "'uv push' needs a FILE");
            if (p.as != null and p.items.len != 1) return misuse.say(streams, "--as names one FILE");
        },
        .rm => if (p.items.len == 0) return misuse.say(streams, "'uv rm' needs a NAME"),
    }
    if (p.mtime) |m| _ = std.fmt.parseInt(i64, m, 10) catch return misuse.say(streams, "--mtime takes seconds since 1970 (date +%s)");
    for (if (sub == .push) (if (p.as) |a| &[_][]const u8{a} else p.items) else p.items) |name| {
        if (!uvNameOk(name)) {
            streams.err.print("zit uv: '{s}' is not an unversioned file name: no spaces, no '.' or '..' parts, no leading '/', at most {d} bytes\n", .{ name, uv_max_name }) catch {};
            return .usage;
        }
    }
    return .ok;
}

fn uvList(streams: cli.Streams, catalog: *const UvReply, long: bool) cli.Exit {
    const entries = catalog.catalog.items;
    std.mem.sort(UvEntry, entries, {}, struct {
        fn lt(_: void, a: UvEntry, b: UvEntry) bool {
            return std.mem.order(u8, a.name, b.name) == .lt;
        }
    }.lt);
    for (entries) |e| {
        if (long) {
            if (e.deleted())
                streams.out.print("{s} {d} deleted 0\n", .{ e.name, e.mtime }) catch {}
            else
                streams.out.print("{s} {d} {s} {d}\n", .{ e.name, e.mtime, e.hash, e.size }) catch {};
        } else if (!e.deleted()) {
            streams.out.print("{s}\n", .{e.name}) catch {};
        }
    }
    return .ok;
}

fn uvPull(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    streams: cli.Streams,
    tr: *transport.Transport,
    credential: ?zit.sync.Credential,
    catalog: *const UvReply,
    p: cli.UvArgs,
    url: []const u8,
) cli.Exit {
    var rc: cli.Exit = .ok;
    var wanted: std.ArrayList([]const u8) = .empty;
    if (p.all) {
        for (catalog.catalog.items) |e| if (!e.deleted()) wanted.append(arena, e.name) catch return stateOom(streams, "uv");
    } else for (p.items) |name| {
        const e = catalog.find(name) orelse {
            streams.err.print("zit uv: the server holds no '{s}'\n", .{name}) catch {};
            rc = .failure;
            continue;
        };
        if (e.deleted()) {
            streams.err.print("zit uv: '{s}' is deleted on the server\n", .{name}) catch {};
            rc = .failure;
            continue;
        }
        wanted.append(arena, name) catch return stateOom(streams, "uv");
    }

    var out = std.Io.Dir.cwd().createDirPathOpen(io, p.out_dir orelse ".", .{}) catch {
        streams.err.print("zit uv: cannot open '{s}'\n", .{p.out_dir orelse "."}) catch {};
        return .failure;
    };
    defer out.close(io);

    var round: usize = 0;
    while (wanted.items.len != 0 and round < uv_max_rounds) : (round += 1) {
        var cards: std.ArrayList(u8) = .empty;
        for (wanted.items) |name| {
            var name_buf: [2 * uv_max_name]u8 = undefined;
            cards.print(arena, "uvgimme {s}\n", .{artifact.encodeEscapes(name, &name_buf)}) catch return stateOom(streams, "uv");
        }
        const reply = uvRound(gpa, arena, tr, credential, cards.items) catch |e| return uvFail(streams, url, e, tr);
        reportTruncatedPayloads(streams, "uv", @intFromBool(reply.truncated));
        if (reply.files.items.len == 0) break; // the server sent nothing more
        for (reply.files.items) |f| {
            const i = for (wanted.items, 0..) |w, j| {
                if (std.mem.eql(u8, w, f.name)) break j;
            } else continue; // not asked for
            if (!uvNameOk(f.name)) continue;
            zit.update.restoreFile(io, out, f.name, f.content, .regular) catch {
                streams.err.print("zit uv: cannot write '{s}'\n", .{f.name}) catch {};
                return .failure;
            };
            _ = wanted.swapRemove(i);
        }
    }
    for (wanted.items) |name| {
        streams.err.print("zit uv: the server did not send '{s}'\n", .{name}) catch {};
        rc = .failure;
    }
    return rc;
}

/// The hash a pushed file is named by: the catalog's own algorithm, so a
/// server on SHA1 names compares equal names, else SHA3-256.
fn uvHashAlgo(catalog: *const UvReply) artifact.HashAlgo {
    for (catalog.catalog.items) |e| if (!e.deleted()) return artifact.nameAlgo(e.hash.len) orelse .sha3_256;
    return .sha3_256;
}

fn uvPush(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    streams: cli.Streams,
    tr: *transport.Transport,
    credential: ?zit.sync.Credential,
    catalog: *const UvReply,
    p: cli.UvArgs,
    amb: cli.Ambient,
    url: []const u8,
) cli.Exit {
    if (catalog.access != .push_ok) return uvNoPush(streams, url, credential);
    const mtime: i64 = if (p.mtime) |m| std.fmt.parseInt(i64, m, 10) catch unreachable else amb.now_epoch;
    const algo = uvHashAlgo(catalog);
    var rc: cli.Exit = .ok;
    var cards: std.ArrayList(u8) = .empty;
    const Sent = struct { name: []const u8, hash: []const u8 };
    var sent: std.ArrayList(Sent) = .empty;
    for (p.items) |path| {
        const name = p.as orelse path;
        const content = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(zit.sync.reply_body_cap)) catch {
            streams.err.print("zit uv: cannot read '{s}'\n", .{path}) catch {};
            rc = .failure;
            continue;
        };
        var hash_buf: [64]u8 = undefined;
        const hash = arena.dupe(u8, artifact.artifactName(algo, content, &hash_buf)) catch return stateOom(streams, "uv");
        if (catalog.find(name)) |held| {
            if (std.mem.eql(u8, held.hash, hash)) continue; // already there
            if (held.mtime >= mtime) {
                streams.err.print("zit uv: the server's '{s}' is as new or newer; pass a later --mtime to replace it\n", .{name}) catch {};
                rc = .failure;
                continue;
            }
        }
        var name_buf: [2 * uv_max_name]u8 = undefined;
        cards.print(arena, "uvfile {s} {d} {s} {d} 0\n", .{ artifact.encodeEscapes(name, &name_buf), mtime, hash, content.len }) catch return stateOom(streams, "uv");
        cards.appendSlice(arena, content) catch return stateOom(streams, "uv");
        sent.append(arena, .{ .name = name, .hash = hash }) catch return stateOom(streams, "uv");
    }
    if (sent.items.len == 0) return rc;
    return uvSendAndConfirm(gpa, arena, streams, tr, credential, cards.items, sent.items, url, rc);
}

fn uvRm(
    gpa: std.mem.Allocator,
    arena: std.mem.Allocator,
    streams: cli.Streams,
    tr: *transport.Transport,
    credential: ?zit.sync.Credential,
    catalog: *const UvReply,
    p: cli.UvArgs,
    amb: cli.Ambient,
    url: []const u8,
) cli.Exit {
    if (catalog.access != .push_ok) return uvNoPush(streams, url, credential);
    const mtime: i64 = if (p.mtime) |m| std.fmt.parseInt(i64, m, 10) catch unreachable else amb.now_epoch;
    var rc: cli.Exit = .ok;
    var cards: std.ArrayList(u8) = .empty;
    const Sent = struct { name: []const u8, hash: []const u8 };
    var sent: std.ArrayList(Sent) = .empty;
    for (p.items) |name| {
        const held = catalog.find(name) orelse {
            streams.err.print("zit uv: the server holds no '{s}'\n", .{name}) catch {};
            rc = .failure;
            continue;
        };
        if (held.deleted()) continue; // already deleted
        if (held.mtime >= mtime) {
            streams.err.print("zit uv: the server's '{s}' is as new or newer; pass a later --mtime to delete it\n", .{name}) catch {};
            rc = .failure;
            continue;
        }
        var name_buf: [2 * uv_max_name]u8 = undefined;
        cards.print(arena, "uvfile {s} {d} - 0 0\n", .{ artifact.encodeEscapes(name, &name_buf), mtime }) catch return stateOom(streams, "uv");
        sent.append(arena, .{ .name = name, .hash = "-" }) catch return stateOom(streams, "uv");
    }
    if (sent.items.len == 0) return rc;
    return uvSendAndConfirm(gpa, arena, streams, tr, credential, cards.items, sent.items, url, rc);
}

/// Send the `uvfile` cards, then read the catalog again: a fossil server
/// keeps whichever copy is newer and says nothing when it keeps its own, so
/// only the catalog shows whether each file was taken.
fn uvSendAndConfirm(
    gpa: std.mem.Allocator,
    arena: std.mem.Allocator,
    streams: cli.Streams,
    tr: *transport.Transport,
    credential: ?zit.sync.Credential,
    cards: []const u8,
    sent: anytype,
    url: []const u8,
    rc_in: cli.Exit,
) cli.Exit {
    var rc = rc_in;
    const reply = uvRound(gpa, arena, tr, credential, cards) catch |e| return uvFail(streams, url, e, tr);
    reportTruncatedPayloads(streams, "uv", @intFromBool(reply.truncated));
    if (reply.refusal) |why| {
        streams.err.print("zit uv: the server refused: {s}\n", .{why}) catch {};
        return .failure;
    }
    const after = uvCatalog(gpa, arena, tr, credential) catch |e| return uvFail(streams, url, e, tr);
    reportTruncatedPayloads(streams, "uv", @intFromBool(after.truncated));
    for (sent) |s| {
        const now = after.find(s.name);
        if (now == null or !std.mem.eql(u8, now.?.hash, s.hash)) {
            streams.err.print("zit uv: the server did not take '{s}'\n", .{s.name}) catch {};
            rc = .failure;
        }
    }
    return rc;
}

fn uvNoPush(streams: cli.Streams, url: []const u8, credential: ?zit.sync.Credential) cli.Exit {
    streams.err.print("zit uv: {s} lets {s} read unversioned files but not change them (that takes the 'y' capability)\n", .{ url, if (credential) |c| c.user else "an anonymous user" }) catch {};
    return .failure;
}

fn uvFail(streams: cli.Streams, url: []const u8, err: anyerror, tr: *const transport.Transport) cli.Exit {
    switch (err) {
        error.OutOfMemory => return stateOom(streams, "uv"),
        error.PeerBusy => streams.err.print("zit uv: {s} is busy with another writer (HTTP 503); try again\n", .{url}) catch {},
        error.CrossOriginRedirect => return refusedRedirect(streams, "uv", tr),
        error.ProtocolError => {
            if (tr.last_status) |st| if (st != .ok) {
                streams.err.print("zit uv: {s} answered HTTP {d} ({s})\n", .{ url, @backingInt(st), st.phrase() orelse "unrecognized" }) catch {};
                return .failure;
            };
            streams.err.print("zit uv: {s} sent a reply this client cannot read\n", .{url}) catch {};
        },
        else => streams.err.print("zit uv: cannot talk to {s}: {s}\n", .{ url, @errorName(err) }) catch {},
    }
    return .failure;
}

test "sync §5.1/§10.1: a uv reply cut short inside a uvfile payload keeps the files before it" {
    var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena_state.deinit();
    const abc_hash = "a9993e364706816aba3e25717850c26c9cd0d89d";
    const body = "uvfile a 1 " ++ abc_hash ++ " 3 0\nabc" ++
        "uvfile b 1 " ++ abc_hash ++ " 3 0\nab";
    const reply = try parseUvReply(arena_state.allocator(), body);
    try std.testing.expect(reply.truncated);
    try std.testing.expectEqual(@as(usize, 1), reply.files.items.len);
    try std.testing.expectEqualStrings("a", reply.files.items[0].name);
    try std.testing.expectEqualStrings("abc", reply.files.items[0].content);
}