Skip to content
zit Artifact [c3169eddb5]
Login

Artifact [c3169eddb5]

Artifact c3169eddb5c2290a42766fa26188ad37e605b08154c4fbef0ec6e29fee4fa22f:


//! `zit config`: export, import and pull configuration areas.

const std = @import("std");
const cli = @import("zit").cli;
const diagnostics = @import("../cli/diagnostics.zig");
const help_pages = @import("../cli/help.zig");
const logstore = @import("zit").logstore;
const max_password_len = @import("sync_dialogue.zig").max_password_len;
const max_stalled_sync_rounds = zit.sync_session.max_stalled_sync_rounds;
const noRemoteError = @import("sync_dialogue.zig").noRemoteError;
const notePlaintext = @import("sync_dialogue.zig").notePlaintext;
const plural = @import("sync_dialogue.zig").plural;
const repoReadFail = diagnostics.repoReadFail;
const repoSyncIdentity = zit.sync_session.repoSyncIdentity;
const reportTruncatedPayloads = @import("sync_dialogue.zig").reportTruncatedPayloads;
const repostate = zit.repostate;
const resolvePushCredential = @import("sync_dialogue.zig").resolvePushCredential;
const resolveRemoteUrl = zit.sync_session.resolveRemoteUrl;
const stateOom = diagnostics.stateOom;
const storage = @import("zit").storage;
const storeAppendFail = diagnostics.storeAppendFail;
const storeReadFail = diagnostics.storeReadFail;
const syncOpenFail = @import("sync_dialogue.zig").syncOpenFail;
const syncRunFail = @import("sync_dialogue.zig").syncRunFail;
const sync_client_version_info = zit.sync_session.sync_client_version_info;
const sync_driver = @import("../net/sync_driver.zig");
const transport = @import("../net/transport.zig");
const zit = @import("zit");

// ---------------------------------------------------------------------------
// `zit config pull AREA`: the explicit configuration request side
// ---------------------------------------------------------------------------

/// `zit config pull shun [URL]` — fossil's `configuration pull AREA ?URL?`.
///
/// Configuration carriage is otherwise CLONE-TIME ONLY, and deliberately so: a
/// shun table that refreshed on every sync would let any peer suppress content
/// in this repository on its own say-so. This verb is how an operator asks for
/// it anyway — explicitly, naming the area, against a peer they chose.
///
/// zit models `interwiki`, `shun` and `user`. The rest of fossil's areas
/// describe a web interface zit has no equivalent for; naming one of those is
/// a clean refusal rather than a silent no-op, so an operator learns which
/// areas exist rather than watching nothing happen.
/// Apply the peer's user rows to this repository's table. Shares
/// `runConfigFromFile`'s two modes and its one-marker rule: `overwrite`
/// replaces, and the marker lands before the first row and only when there
/// is a row to land, so a pull that returned nothing never wipes the table it
/// could not replace.
///
/// An EMPTY result is reported rather than treated as success-with-nothing:
/// against fossil, "no rows" is what an under-privileged client sees, so an
/// operator who forgot `--user` must not read it as "the peer has no users".
fn applyPeerUsers(
    gpa: std.mem.Allocator,
    io: std.Io,
    root_dir: std.Io.Dir,
    rows: []const zit.sync.OwnedUserRow,
    overwrite: bool,
    streams: cli.Streams,
) cli.Exit {
    if (rows.len == 0) {
        streams.err.writeAll(
            "zit config: the peer offered no user rows\n" ++
                "zit config: fossil serves the user area to an administrator only -- " ++
                "pass --user=NAME (and --password=, or $ZIT_PASSWORD)\n",
        ) catch {};
        return .failure;
    }

    var store_append = cli.openStoreAppend(io, root_dir) catch |e| return storeAppendFail(streams, "config", e);
    defer store_append.close(io);
    const file = store_append.file;
    const st = file.stat(io) catch return repoReadFail(streams, "config");
    var fs = storage.FileStorage.init(io, file, st.size);
    var log = logstore.LogStore.open(gpa, fs.storageFile(), 0) catch
        return repoReadFail(streams, "config");
    defer log.deinit(gpa);

    if (overwrite) log.putUserReset(0) catch return repoReadFail(streams, "config");
    var skipped: usize = 0;
    for (rows) |row| {
        log.putUser(.{
            .login = row.login,
            .pw = row.pw,
            .cap = row.cap,
            .info = row.info,
            .mtime = row.mtime,
        }) catch |e| switch (e) {
            error.OutOfMemory => return stateOom(streams, "config"),
            error.Storage => return repoReadFail(streams, "config"),
            error.LoginTooLong, error.FieldTooLong => {
                skipped += 1;
                continue;
            },
        };
    }
    log.commit() catch return repoReadFail(streams, "config");

    const table = log.userTable(gpa) catch return stateOom(streams, "config");
    defer gpa.free(table);
    streams.out.print("user: {d} row{s} {s} from the peer; {d} in the table", .{
        rows.len,
        plural(rows.len),
        if (overwrite) "adopted" else "merged",
        table.len,
    }) catch {};
    if (skipped != 0) streams.out.print("; {d} unusable and skipped", .{skipped}) catch {};
    streams.out.writeAll("\n") catch {};
    if (skipped != 0) return .failure;
    return .ok;
}

/// Apply the peer's interwiki rows (`applyInterwikiRows` for the two modes).
/// No rows is not a failure: fossil serves this area to anyone with Read, so
/// an empty answer means the peer has no map.
fn applyPeerInterwiki(
    gpa: std.mem.Allocator,
    io: std.Io,
    root_dir: std.Io.Dir,
    rows: []const zit.sync.ConfigRow,
    overwrite: bool,
    streams: cli.Streams,
) cli.Exit {
    if (rows.len == 0) {
        streams.out.writeAll("no interwiki rows offered by the peer\n") catch {};
        return .ok;
    }
    var store_append = cli.openStoreAppend(io, root_dir) catch |e| return storeAppendFail(streams, "config", e);
    defer store_append.close(io);
    const file = store_append.file;
    const st = file.stat(io) catch return repoReadFail(streams, "config");
    var fs = storage.FileStorage.init(io, file, st.size);
    var log = logstore.LogStore.open(gpa, fs.storageFile(), 0) catch
        return repoReadFail(streams, "config");
    defer log.deinit(gpa);

    var skipped: usize = 0;
    const written = applyInterwikiRows(&log, rows, overwrite, &skipped) catch |e| switch (e) {
        error.OutOfMemory => return stateOom(streams, "config"),
        error.Storage => return repoReadFail(streams, "config"),
    };
    log.commit() catch return repoReadFail(streams, "config");
    const held = interwikiCount(gpa, &log) catch return stateOom(streams, "config");
    streams.out.print("interwiki: {d} row{s} {s} from the peer; {d} in the table", .{
        written,
        plural(written),
        if (overwrite) "adopted" else "merged",
        held,
    }) catch {};
    if (skipped != 0) streams.out.print("; {d} unusable and skipped", .{skipped}) catch {};
    streams.out.writeAll("\n") catch {};
    if (skipped != 0) return .failure;
    return .ok;
}

/// `zit config`'s three shapes, spelled as fossil spells them
/// (`configuration pull|import|merge`).
const ConfigSub = enum { pull, import, merge, @"export" };

const config_usage_line: []const u8 =
    "zit config: usage: zit config pull interwiki|shun|user [URL] | zit config import|merge FILE | zit config export interwiki|shun|user [FILE]\n";

/// The largest configuration export this verb will read whole. A user table
/// is a handful of rows per operator; a file past this bound is not a
/// configuration export and is refused rather than allocated for.
const max_config_file_bytes: usize = 8 * 1024 * 1024;

/// The `reqconfig` GROUPNAME an area name selects, or null. Fossil matches by
/// PREFIX (`configure_name_to_mask`) and orders `shun` before `user` in
/// `aGroupName`, so an ambiguous prefix resolves the way fossil resolves it.
fn configGroupOf(want: []const u8) ?[]const u8 {
    if (want.len == 0) return null;
    if (std.mem.startsWith(u8, "shun", want)) return zit.sync.config_shun_group;
    if (std.mem.startsWith(u8, "user", want)) return zit.sync.config_user_group;
    if (std.mem.startsWith(u8, "interwiki", want)) return zit.sync.config_interwiki_group;
    return null;
}

const unknown_area_message = "zit config: unknown configuration area '{s}' (known: interwiki, shun, user)\n";

/// Apply interwiki rows to the open store, fossil's two modes: `overwrite`
/// (`configuration import`, `pull --overwrite`) replaces a row whatever its
/// mtime; otherwise a row lands only when strictly newer than the one held,
/// `configure_receive`'s `mtime<` test. Rows the source does not name are
/// left alone either way. Returns how many rows were written.
fn applyInterwikiRows(
    log: *logstore.LogStore,
    rows: []const zit.sync.ConfigRow,
    overwrite: bool,
    skipped: *usize,
) error{ OutOfMemory, Storage }!usize {
    var written: usize = 0;
    for (rows) |row| {
        if (!overwrite) {
            if (log.settingRow(row.name)) |held| if (held.mtime >= row.mtime) continue;
        }
        log.putSetting(.{ .name = row.name, .value = row.value, .mtime = row.mtime }) catch |e| switch (e) {
            error.OutOfMemory => return error.OutOfMemory,
            error.Storage => return error.Storage,
            error.NameTooLong, error.ValueTooLong, error.TooManySettings => {
                skipped.* += 1;
                continue;
            },
        };
        written += 1;
    }
    return written;
}

/// How many interwiki rows the store holds, one per tag.
fn interwikiCount(gpa: std.mem.Allocator, log: *const logstore.LogStore) error{OutOfMemory}!usize {
    const table = try log.settingTable(gpa);
    defer gpa.free(table);
    var n: usize = 0;
    for (table) |row| {
        if (std.mem.startsWith(u8, row.name, zit.sync.interwiki_row_prefix)) n += 1;
    }
    return n;
}

/// `zit config export AREA [FILE]` — fossil's `configuration export AREA
/// FILE`, the inverse of `import`/`merge`: a `#` banner, then one `config
/// /AREA SIZE` card per row, byte-identical to what the wire carries for the
/// area. So a table can be backed up before `import` replaces it. FILE
/// absent or `-` is stdout. Read-only: the store is opened without a lock,
/// as every reader opens it.
fn runConfigExport(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    group: []const u8,
    file_arg: []const u8,
    repo_override: ?[]const u8,
    streams: cli.Streams,
) cli.Exit {
    const root = (cli.resolveRoot(arena, io, repo_override) catch return stateOom(streams, "config")) orelse {
        diagnostics.reportNoRoot(streams, io, "config", repo_override);
        return .failure;
    };
    var root_dir = root.dir;
    defer root_dir.close(io);

    var file = cli.openStoreRead(io, root_dir) catch |e| return storeReadFail(streams, "config", e);
    defer file.close(io);
    const st = file.stat(io) catch return repoReadFail(streams, "config");
    var fs = storage.FileStorage.init(io, file, st.size);
    var log = logstore.LogStore.openReadOnly(gpa, fs.storageFile()) catch
        return repoReadFail(streams, "config");
    defer log.deinit(gpa);

    var out: std.ArrayList(u8) = .empty;
    defer out.deinit(gpa);
    const area_name = group[1..];
    // fossil's banner shape. No timestamp: two exports of an unchanged table
    // are the same bytes, so a backup can be compared with `cmp`.
    out.print(gpa, "# The \"{s}\" configuration exported from\n# repository \"{s}\"\n", .{ area_name, std.fs.path.basename(root.abs) }) catch
        return stateOom(streams, "config");

    var line_buf: [64]u8 = undefined;
    var rows: usize = 0;
    if (std.mem.eql(u8, group, zit.sync.config_interwiki_group)) {
        const table = log.settingTable(gpa) catch return stateOom(streams, "config");
        defer gpa.free(table);
        var payload_buf: [zit.sync.interwiki_config_payload_max]u8 = undefined;
        for (table) |r| {
            if (r.mtime < 0 or !zit.sync.isInterwikiRow(r.name, r.value)) continue;
            const payload = zit.sync.writeScalarConfig(@intCast(r.mtime), r.name, r.value, &payload_buf) catch continue;
            // fossil writes a `config`-table row under the scalar marker,
            // whatever area selected it.
            appendExportCard(gpa, &out, zit.sync.config_scalar_marker, payload, &line_buf) catch return stateOom(streams, "config");
            rows += 1;
        }
    } else if (std.mem.eql(u8, group, zit.sync.config_user_group)) {
        const table = log.userTable(gpa) catch return stateOom(streams, "config");
        defer gpa.free(table);
        var payload_buf: [zit.sync.user_config_payload_max]u8 = undefined;
        for (table) |u| {
            const payload = zit.sync.writeUserConfigPayload(.{
                .login = u.login,
                .pw = u.pw,
                .cap = u.cap,
                .info = u.info,
                .mtime = u.mtime,
            }, &payload_buf) catch continue;
            appendExportCard(gpa, &out, group, payload, &line_buf) catch return stateOom(streams, "config");
            rows += 1;
        }
    } else {
        var payload_buf: [zit.sync.shun_config_payload_max]u8 = undefined;
        var hex_buf: [64]u8 = undefined;
        for (log.shunList()) |r| {
            if (r.hash.len > 32) continue;
            const hex = std.fmt.bufPrint(&hex_buf, "{x}", .{r.hash}) catch unreachable;
            const payload = zit.sync.writeShunConfigPayload(.{
                .hash = hex,
                .epoch = r.epoch,
                .reason = r.reason,
            }, &payload_buf) catch continue;
            appendExportCard(gpa, &out, group, payload, &line_buf) catch return stateOom(streams, "config");
            rows += 1;
        }
    }

    if (file_arg.len == 0 or std.mem.eql(u8, file_arg, "-")) {
        streams.out.writeAll(out.items) catch return .failure;
        return .ok;
    }
    std.Io.Dir.cwd().writeFile(io, .{ .sub_path = file_arg, .data = out.items }) catch {
        streams.err.print("zit config: cannot write '{s}'\n", .{file_arg}) catch {};
        return .failure;
    };
    streams.out.print("{s}: {d} row{s} exported to {s}\n", .{ area_name, rows, plural(rows), file_arg }) catch {};
    return .ok;
}

fn appendExportCard(
    gpa: std.mem.Allocator,
    out: *std.ArrayList(u8),
    group: []const u8,
    payload: []const u8,
    line_buf: []u8,
) error{OutOfMemory}!void {
    const card = zit.sync.writeConfigCard(group, @intCast(payload.len), line_buf) catch unreachable;
    try out.appendSlice(gpa, card);
    try out.append(gpa, '\n');
    try out.appendSlice(gpa, payload);
    try out.append(gpa, '\n');
}

/// Apply a fossil configuration export file: the output of
/// `fossil configuration export AREA FILE`, which is byte-identical to what
/// the sync protocol carries for the same area (`config /AREA SIZE\n` then
/// SIZE payload bytes then a newline), plus `#` comment lines at the top.
///
/// That identity is the whole reason this path exists: a repository's users
/// reach zit with no SQLite reader, no network, and no fossil server — one
/// `fossil configuration export` on the migration host, and the SAME parser
/// the wire path will use.
///
/// `replace` is fossil's `CONFIGSET_OVERWRITE`. Applied ONCE, before the
/// first row lands, exactly as `configure_receive`'s `configHasBeenReset`
/// guard does — a per-row reset would leave only the last row of the file.
fn runConfigFromFile(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    path: []const u8,
    replace: bool,
    repo_override: ?[]const u8,
    streams: cli.Streams,
) cli.Exit {
    // The user/shun areas are store tables; `-R` redirects which
    // store they land in. The FILE is still read from the cwd (fossil's
    // `configuration import FILENAME`), so only the store is redirected.
    const root = (cli.resolveRoot(arena, io, repo_override) catch return stateOom(streams, "config")) orelse {
        diagnostics.reportNoRoot(streams, io, "config", repo_override);
        return .failure;
    };
    var root_dir = root.dir;
    defer root_dir.close(io);

    const text = std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(max_config_file_bytes)) catch {
        streams.err.print("zit config: cannot read '{s}'\n", .{path}) catch {};
        return .failure;
    };
    defer gpa.free(text);

    var users: std.ArrayList(zit.sync.UserRow) = .empty;
    defer users.deinit(gpa);
    var value_arena = std.heap.ArenaAllocator.init(gpa);
    defer value_arena.deinit();
    const va = value_arena.allocator();
    // Shun rows are held as hex off the file text's own unquote scratch, so
    // they are copied onto the value arena before the next card reuses it.
    var shuns: std.ArrayList(zit.sync.ShunRow) = .empty;
    defer shuns.deinit(gpa);
    var interwiki: std.ArrayList(zit.sync.ConfigRow) = .empty;
    defer interwiki.deinit(gpa);
    // Interwiki cards seen, readable or not: a file of them is not a user file.
    var interwiki_cards: usize = 0;
    var skipped: usize = 0;
    var other_areas: usize = 0;

    var pos: usize = 0;
    while (pos < text.len) {
        const line_end = std.mem.indexOfScalarPos(u8, text, pos, '\n') orelse text.len;
        const line = text[pos..line_end];
        // `configuration export` writes a `#` banner naming the repository and
        // the export time; blank lines separate nothing but are harmless.
        if (line.len == 0 or line[0] == '#') {
            pos = line_end + 1;
            continue;
        }
        const card = parseConfigCardLine(line) orelse {
            streams.err.print("zit config: '{s}' is not a configuration export\n", .{path}) catch {};
            return .failure;
        };
        const payload = zit.sync.consumeConfigPayload(text, line_end + 1, card.size) catch {
            streams.err.print("zit config: '{s}' is truncated\n", .{path}) catch {};
            return .failure;
        };
        pos = payload.next;
        if (std.mem.eql(u8, card.area, zit.sync.config_shun_group)) {
            var bufs: zit.sync.ShunPayloadBufs = undefined;
            const row = zit.sync.parseShunConfigPayload(payload.bytes, &bufs) orelse {
                skipped += 1;
                continue;
            };
            const hash = va.dupe(u8, row.hash) catch return stateOom(streams, "config");
            const reason = va.dupe(u8, row.reason) catch return stateOom(streams, "config");
            shuns.append(gpa, .{ .hash = hash, .epoch = row.epoch, .reason = reason }) catch
                return stateOom(streams, "config");
            continue;
        }
        if (std.mem.eql(u8, card.area, zit.sync.config_scalar_marker)) {
            // A `config`-table row. Only interwiki rows are kept; any other
            // name belongs to an area zit does not model.
            const sc = zit.sync.parseScalarConfig(payload.bytes) catch {
                skipped += 1;
                continue;
            };
            if (!std.mem.startsWith(u8, sc.quoted_name[1..], zit.sync.interwiki_row_prefix)) {
                other_areas += 1;
                continue;
            }
            interwiki_cards += 1;
            var bufs: zit.sync.InterwikiPayloadBufs = undefined;
            const row = zit.sync.parseInterwikiConfigRow(payload.bytes, &bufs) orelse {
                skipped += 1;
                continue;
            };
            const name = va.dupe(u8, row.name) catch return stateOom(streams, "config");
            const value = va.dupe(u8, row.value) catch return stateOom(streams, "config");
            interwiki.append(gpa, .{ .name = name, .value = value, .mtime = row.mtime }) catch
                return stateOom(streams, "config");
            continue;
        }
        if (!std.mem.eql(u8, card.area, zit.sync.config_user_group)) {
            other_areas += 1;
            continue;
        }
        const row = zit.sync.parseUserConfigPayload(payload.bytes) catch {
            skipped += 1;
            continue;
        };
        const parsed = unquoteUserRow(va, row) catch |e| switch (e) {
            error.OutOfMemory => return stateOom(streams, "config"),
            error.Malformed => {
                skipped += 1;
                continue;
            },
        };
        users.append(gpa, parsed) catch return stateOom(streams, "config");
    }

    if (other_areas != 0 and users.items.len == 0 and shuns.items.len == 0 and interwiki_cards == 0) {
        streams.err.print(
            "zit config: '{s}' carries no interwiki, /user or /shun cards ({d} card{s} in areas zit does not model)\n",
            .{ path, other_areas, plural(other_areas) },
        ) catch {};
        return .failure;
    }

    var store_append = cli.openStoreAppend(io, root_dir) catch |e| return storeAppendFail(streams, "config", e);
    defer store_append.close(io);
    const file = store_append.file;
    const st = file.stat(io) catch return repoReadFail(streams, "config");
    var fs = storage.FileStorage.init(io, file, st.size);
    var log = logstore.LogStore.open(gpa, fs.storageFile(), 0) catch
        return repoReadFail(streams, "config");
    defer log.deinit(gpa);

    // The marker lands before the first row and only when there is a row to
    // land: an import whose file held nothing applicable must not wipe the
    // table it could not replace.
    if (replace and users.items.len != 0) {
        log.putUserReset(0) catch return repoReadFail(streams, "config");
    }
    for (users.items) |row| {
        log.putUser(.{
            .login = row.login,
            .pw = row.pw,
            .cap = row.cap,
            .info = row.info,
            .mtime = row.mtime,
        }) catch |e| switch (e) {
            error.OutOfMemory => return stateOom(streams, "config"),
            error.Storage => return repoReadFail(streams, "config"),
            // A row this store cannot key or hold is reported, never silently
            // dropped: an operator migrating an access-control table needs to
            // know a login did not come across.
            error.LoginTooLong, error.FieldTooLong => {
                skipped += 1;
                continue;
            },
        };
    }
    // Shun rows are ADDED in both modes, never replaced. Replacing the table
    // would un-shun whatever the file happens not to name, and a shun is
    // never undone here — not by `zit shun`, and so not as a side effect of
    // restoring a backup. The same line `config pull` holds.
    var shun_added: usize = 0;
    for (shuns.items) |row| {
        var digest_buf: [32]u8 = undefined;
        const digest = digest_buf[0 .. row.hash.len / 2];
        _ = std.fmt.hexToBytes(digest, row.hash) catch {
            skipped += 1;
            continue;
        };
        log.putShun(digest, row.reason, row.epoch) catch |e| switch (e) {
            error.OutOfMemory => return stateOom(streams, "config"),
            else => {
                skipped += 1;
                continue;
            },
        };
        shun_added += 1;
    }
    const interwiki_written = applyInterwikiRows(&log, interwiki.items, replace, &skipped) catch |e| switch (e) {
        error.OutOfMemory => return stateOom(streams, "config"),
        error.Storage => return repoReadFail(streams, "config"),
    };
    log.commit() catch return repoReadFail(streams, "config");

    if (interwiki_cards != 0) {
        const held = interwikiCount(gpa, &log) catch return stateOom(streams, "config");
        streams.out.print("interwiki: {d} row{s} {s}; {d} in the table\n", .{
            interwiki_written,
            plural(interwiki_written),
            if (replace) "imported" else "merged",
            held,
        }) catch {};
    }
    if (users.items.len != 0 or (shuns.items.len == 0 and interwiki_cards == 0)) {
        const table = log.userTable(gpa) catch return stateOom(streams, "config");
        defer gpa.free(table);
        streams.out.print("user: {d} row{s} {s}; {d} in the table\n", .{
            users.items.len,
            plural(users.items.len),
            if (replace) "imported" else "merged",
            table.len,
        }) catch {};
    }
    if (shuns.items.len != 0) {
        streams.out.print("shun: {d} row{s} added; {d} in the table\n", .{
            shun_added,
            plural(shun_added),
            log.shunList().len,
        }) catch {};
    }
    if (skipped != 0) streams.out.print("{d} unreadable and skipped\n", .{skipped}) catch {};
    if (other_areas != 0) streams.out.print("{d} card{s} in other areas ignored\n", .{ other_areas, plural(other_areas) }) catch {};
    if (skipped != 0) return .failure;
    return .ok;
}

/// One `config /AREA SIZE` card header line.
const ConfigCardLine = struct { area: []const u8, size: u32 };

fn parseConfigCardLine(line: []const u8) ?ConfigCardLine {
    const prefix = "config ";
    if (!std.mem.startsWith(u8, line, prefix)) return null;
    const rest = line[prefix.len..];
    const sp = std.mem.indexOfScalar(u8, rest, ' ') orelse return null;
    const area = rest[0..sp];
    if (area.len == 0 or area[0] != '/') return null;
    const size = std.fmt.parseInt(u32, rest[sp + 1 ..], 10) catch return null;
    return .{ .area = area, .size = size };
}

/// Unquote a wire user row's fields onto `arena`. A field fossil omitted is
/// the empty string here — zit models "no password" as empty rather than as
/// a distinct NULL, which is also what it emits back on the wire.
fn unquoteUserRow(arena: std.mem.Allocator, row: zit.sync.QuotedUserRow) error{ OutOfMemory, Malformed }!zit.sync.UserRow {
    const mtime = std.fmt.parseInt(i64, row.mtime_text, 10) catch return error.Malformed;
    return .{
        .login = try unquoteField(arena, row.quoted_login),
        .pw = try unquoteField(arena, row.quoted_pw),
        .cap = try unquoteField(arena, row.quoted_cap),
        .info = try unquoteField(arena, row.quoted_info),
        .mtime = mtime,
    };
}

fn unquoteField(arena: std.mem.Allocator, quoted: ?[]const u8) error{ OutOfMemory, Malformed }![]const u8 {
    const q = quoted orelse return "";
    const buf = try arena.alloc(u8, q.len);
    const out = zit.sync.fossilUnquote(q, buf) catch return error.Malformed;
    return out;
}

pub fn runConfig(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
) cli.Exit {
    var area: ?[]const u8 = null;
    var url_arg: []const u8 = "";
    var sub: ?ConfigSub = null;
    var overwrite = false;
    var login_user: ?[]const u8 = null;
    var login_password: ?[]const u8 = null;
    for (verb_args) |tok| {
        if (std.mem.eql(u8, tok, "-h") or std.mem.eql(u8, tok, "--help")) {
            streams.out.writeAll(help_pages.config_help) catch {};
            return .ok;
        } else if (std.mem.eql(u8, tok, "--overwrite")) {
            overwrite = true;
        } else if (std.mem.startsWith(u8, tok, "--user=")) {
            login_user = tok["--user=".len..];
        } else if (std.mem.startsWith(u8, tok, "--password=")) {
            login_password = tok["--password=".len..];
        } else if (tok.len > 1 and tok[0] == '-') {
            return cli.usageError(streams, "config", .unknown_option, tok);
        } else if (sub == null) {
            sub = std.meta.stringToEnum(ConfigSub, tok) orelse
                return cli.usageError(streams, "config", .unknown_option, tok);
        } else if (area == null) {
            area = tok;
        } else if (url_arg.len == 0) {
            url_arg = tok;
        } else {
            return cli.usageError(streams, "config", .extra_argument, tok);
        }
    }
    if (sub == null or area == null) {
        streams.err.writeAll(config_usage_line) catch {};
        return .usage;
    }
    // `import`/`merge` take a FILE, not an area and a URL: fossil's own
    // `configuration import|merge FILENAME`. The two differ in exactly one
    // thing, which is why they share a body: `import` REPLACES the local table
    // (fossil's `CONFIGSET_OVERWRITE` — `DELETE FROM user` then `REPLACE
    // INTO`), `merge` folds rows in newest-mtime-wins.
    switch (sub.?) {
        .import, .merge => {
            if (url_arg.len != 0) return cli.usageError(streams, "config", .extra_argument, url_arg);
            // The file forms take their mode from the SUBCOMMAND, as fossil's
            // do; accepting a contradicting --overwrite would give one
            // invocation two ways to say the same thing and one way to lie.
            if (overwrite) return cli.usageError(streams, "config", .unknown_option, "--overwrite");
            if (login_user != null or login_password != null) {
                streams.err.writeAll("zit config: --user/--password apply to 'config pull', not to a file\n") catch {};
                return .usage;
            }
            return runConfigFromFile(gpa, io, arena, area.?, sub.? == .import, amb.repo_override, streams);
        },
        .@"export" => {
            if (overwrite) return cli.usageError(streams, "config", .unknown_option, "--overwrite");
            if (login_user != null or login_password != null) {
                streams.err.writeAll("zit config: --user/--password apply to 'config pull', not to an export\n") catch {};
                return .usage;
            }
            const group = configGroupOf(area.?) orelse {
                streams.err.print(unknown_area_message, .{area.?}) catch {};
                return .failure;
            };
            return runConfigExport(gpa, io, arena, group, url_arg, amb.repo_override, streams);
        },
        .pull => {},
    }
    // Fossil matches area names by PREFIX (`configure_name_to_mask`), and so
    // does the server side of this exchange, so the CLI accepts the same.
    const want = area.?;
    const group = configGroupOf(want) orelse {
        streams.err.print(unknown_area_message, .{want}) catch {};
        return .failure;
    };

    const root = (cli.resolveRoot(arena, io, amb.repo_override) catch return stateOom(streams, "config")) orelse {
        diagnostics.reportNoRoot(streams, io, "config", amb.repo_override);
        return .failure;
    };
    var root_dir = root.dir;
    defer root_dir.close(io);

    var url_buf: [logstore.max_config_str]u8 = undefined;
    const url = resolveRemoteUrl(gpa, io, root_dir, url_arg, &url_buf) catch |e| switch (e) {
        error.OutOfMemory => return stateOom(streams, "config"),
        error.Storage => return repoReadFail(streams, "config"),
        error.NoRemote => return noRemoteError(streams, "config"),
    };

    var tr = transport.Transport.open(io, gpa, url) catch |e|
        return syncOpenFail(streams, "config", url, e);
    defer tr.close();
    notePlaintext(streams, "config", url);

    var ms = repostate.MemStore.init(gpa);
    defer ms.deinit();

    // §9.1 — the pull card carries this repository's adopted project code, and a
    // real peer refuses a mismatch, so the identity is loaded even though this
    // exchange moves no artifacts. The buffer outlives the run (the client
    // borrows it).
    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, "config"),
        error.Storage => return repoReadFail(streams, "config"),
    };

    // A pull-shaped session that asks for one group. The in-memory store stays
    // EMPTY on purpose: this verb moves CONFIGURATION, never artifacts, so an
    // operator asking for a shun table cannot be handed a repository's worth of
    // content as a side effect.
    // fossil serves the user area to an ADMINISTRATOR only
    // (`configure.c`: `m &= ~(CONFIGSET_USER|CONFIGSET_SCRIBER)` for a client
    // without Admin), so a `/user` pull is credentialed or it comes back
    // empty. The §6.3 derivation is `resolvePushCredential`'s, reused rather
    // than restated: one place turns a password into a signing secret.
    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 = login_user, .password = login_password },
        amb,
        &pw_buf,
        &user_buf,
    ) catch |e| switch (e) {
        error.OutOfMemory => return stateOom(streams, "config"),
        error.Storage => return repoReadFail(streams, "config"),
        error.NoPassword => {
            streams.err.writeAll("zit config: no password supplied for --user\n") catch {};
            return .failure;
        },
    };

    var client = zit.sync.Client{
        .state = zit.sync.initialState(.pull),
        .operation = .pull,
        .self_servercode = &identity.server_code,
        .project_code = identity.project_code,
        .version = sync_client_version_info,
        .request_config = true,
        .config_group = group,
        .credential = if (resolved) |r| r.credential else null,
    };
    defer client.deinit(gpa);
    defer reportTruncatedPayloads(streams, "config", client.payloads_truncated);
    _ = sync_driver.runSync(gpa, &client, ms.store(), &tr, max_stalled_sync_rounds) catch |e|
        return syncRunFail(streams, "config", url, e, &tr);

    if (std.mem.eql(u8, group, zit.sync.config_user_group)) {
        return applyPeerUsers(gpa, io, root_dir, client.peerUserRows(), overwrite, streams);
    }
    if (std.mem.eql(u8, group, zit.sync.config_interwiki_group)) {
        return applyPeerInterwiki(gpa, io, root_dir, client.peerConfigRows(), overwrite, streams);
    }

    const rows = client.peerShunRows();
    if (rows.len == 0) {
        streams.out.writeAll("no shun rows offered by the peer\n") catch {};
        return .ok;
    }

    var store_append = cli.openStoreAppend(io, root_dir) catch |e| return storeAppendFail(streams, "config", e);
    defer store_append.close(io);
    const file = store_append.file;
    const st = file.stat(io) catch return repoReadFail(streams, "config");
    var fs = storage.FileStorage.init(io, file, st.size);
    var log = logstore.LogStore.open(gpa, fs.storageFile(), 0) catch
        return repoReadFail(streams, "config");
    defer log.deinit(gpa);

    // Count by the TABLE's own size, not by successful calls: `putShun` is
    // idempotent on a name already present, so counting calls would report rows
    // the operator already had as newly adopted.
    const before = log.shunList().len;
    var skipped: usize = 0;
    for (rows) |row| {
        var digest_buf: [32]u8 = undefined;
        if (row.hash.len != 40 and row.hash.len != 64) {
            skipped += 1;
            continue;
        }
        const digest = digest_buf[0 .. row.hash.len / 2];
        _ = std.fmt.hexToBytes(digest, row.hash) catch {
            skipped += 1;
            continue;
        };
        // `putShun` is idempotent on a name already present, so re-running this
        // verb converges rather than accumulating.
        log.putShun(digest, row.reason, row.epoch) catch |e| switch (e) {
            error.OutOfMemory => return stateOom(streams, "config"),
            else => {
                skipped += 1;
                continue;
            },
        };
    }
    const added = log.shunList().len - before;
    log.commit() catch return repoReadFail(streams, "config");
    streams.out.print("shun: {d} new row{s} adopted", .{ added, plural(added) }) catch {};
    if (skipped != 0) streams.out.print("; {d} unreadable and skipped", .{skipped}) catch {};
    streams.out.writeAll("\n") catch {};
    return .ok;
}