//! What the sync verbs say and ask: credential prompts and saved logins,
//! progress, the peer's notes and refusals, failure wording, and the forks
//! an exchange leaves behind.
const std = @import("std");
const ConfigPatch = zit.repo_config.ConfigPatch;
const File = Io.File;
const Io = std.Io;
const PersistLockedError = zit.repo_config.PersistLockedError;
const Repository = @import("zit").Repository;
const cli = @import("zit").cli;
const diagnostics = @import("../diagnostics.zig");
const logstore = @import("zit").logstore;
const openLogAdoptingIndex = zit.log_index_store.openLogAdoptingIndex;
const savedRemoteIn = zit.sync_session.savedRemoteIn;
const stateOom = diagnostics.stateOom;
const storage = @import("zit").storage;
const sync_driver = @import("../sync_driver.zig");
const transport = @import("../transport.zig");
const updateConfigOpen = zit.repo_config.updateConfigOpen;
const zit = @import("zit");
/// The stderr live-progress sink a TTY clone runs with. Each completed
/// round overwrites one line in place (\r, no newline); `finishLine` closes it
/// with a newline exactly once, so whatever stderr carries next starts clean.
/// Flushed per round — a progress line that sits in a buffer until the clone
/// ends reports nothing.
pub const CloneProgress = struct {
err: *std.Io.Writer,
emitted: bool = false,
pub fn emit(ctx: *anyopaque, info: sync_driver.RoundInfo) void {
const self: *CloneProgress = @ptrCast(@alignCast(ctx));
self.emitted = true;
self.err.print(
"\rround {d}: {d} bytes received",
.{ info.round, info.total_received },
) catch return;
self.err.flush() catch {};
}
pub fn finishLine(self: *CloneProgress) void {
if (!self.emitted) return;
self.emitted = false;
self.err.writeAll("\n") catch return;
self.err.flush() catch {};
}
};
/// Quote a peer's refusal in its own words. Fossil's `wrong project` names
/// neither side, so it is glossed with what it means for this run and the
/// way out. A push that is refused met a peer that does not adopt, so the
/// only way in is a clone. A pull or sync may be the first contact with a
/// new empty repository that would adopt a push, which a pull card never
/// reaches; that is also what an autosync before the first push prints.
pub fn reportPeerRefusal(streams: cli.Streams, verb: []const u8, text: []const u8) void {
if (!std.mem.eql(u8, text, zit.sync.wrong_project_text)) {
streams.err.print("zit {s}: the peer refused: {s}\n", .{ verb, text }) catch {};
return;
}
const way_out = if (std.mem.eql(u8, verb, "push"))
"clone the peer to work on it"
else
"if the peer is a new empty repository run 'zit push' first, otherwise clone it";
streams.err.print("zit {s}: the peer refused: wrong project (this repository and the peer's are different projects; {s})\n", .{ verb, way_out }) catch {};
}
/// What the server said beside the exchange, copied out of the client before
/// it is deinit'd: its `message` cards, and whether it kept a pushed check-in
/// on an attempt branch (`pragma zit-diverted`).
pub const ServerNotes = struct {
messages: std.ArrayListUnmanaged([]u8) = .empty,
diverted: bool = false,
/// Signed erasures past the per-session cap, left for the next session.
erasures_deferred: usize = 0,
pub fn adopt(self: *ServerNotes, client: *zit.sync.Client) void {
self.messages = client.server_messages;
client.server_messages = .empty;
self.diverted = client.diverted;
self.erasures_deferred += client.erasures_deferred;
}
pub fn deinit(self: *ServerNotes, gpa: std.mem.Allocator) void {
for (self.messages.items) |m| gpa.free(m);
self.messages.deinit(gpa);
}
/// Each message on its own line, the way fossil prints them, so a person
/// reads what the server had to say.
pub fn show(self: *const ServerNotes, streams: cli.Streams) void {
for (self.messages.items) |m| streams.err.print("server: {s}\n", .{m}) catch {};
if (self.erasures_deferred != 0) streams.err.print(
"zit: {d} signed erasure row{s} wait for the next session; one session carries at most {d}\n",
.{ self.erasures_deferred, if (self.erasures_deferred == 1) "" else "s", zit.sync.max_pushed_erasures },
) catch {};
}
};
/// English plural suffix for `n`. Used only in these reports.
pub fn plural(n: usize) []const u8 {
return if (n == 1) "" else "s";
}
/// The `-es` plural suffix, for the one noun these reports pluralize that does
/// not take a bare `-s`: "hash" / "hashes". A separate function rather than a
/// caller-supplied string so no call site can spell it "hashs".
pub fn pluralEs(n: usize) []const u8 {
return if (n == 1) "" else "es";
}
/// Maps a transport-open failure (bad URL) to the `verb` diagnostic + exit 1.
/// Shared by clone and pull — the only difference is the verb label.
pub fn syncOpenFail(s: cli.Streams, verb: []const u8, url: []const u8, err: transport.TransportError) cli.Exit {
switch (err) {
error.InvalidUrl => s.err.print("zit {s}: '{s}' is not a valid URL\n", .{ verb, url }) catch {},
error.UnsupportedScheme => s.err.print("zit {s}: unsupported URL scheme in '{s}' (use http or https)\n", .{ verb, url }) catch {},
error.OutOfMemory => s.err.print("zit {s}: out of memory\n", .{verb}) catch {},
else => s.err.print("zit {s}: cannot open '{s}'\n", .{ verb, url }) catch {},
}
return .failure;
}
/// Maps a sync run (transport + driver) failure to the `verb` diagnostic + exit
/// 1. Exhaustive over the driver's own causes and the transport's, so the whole
/// closed error set is accounted for (no `else`). Shared by clone and pull.
/// `status` is the transport's `last_status` -- the HTTP status that produced an
/// `error.ProtocolError`, or null for every other cause. Named in the message
/// because "an unexpected HTTP status" sends an investigation nowhere: 500, 413,
/// 400 and 417 are four different bugs and the operator could not tell which one
/// they had hit.
/// Tolerate-and-report — one stderr line naming what the session
/// declined: unversioned files a fossil peer offered that zit has no store
/// for. Zero is silent; the count makes the data non-transfer VISIBLE, which
/// is the entire posture (the alternative was an abort nobody chose).
pub fn reportUvSkipped(s: cli.Streams, verb: []const u8, count: u64) void {
if (count == 0) return;
s.err.print(
"zit {s}: {d} unversioned file(s) not transferred (unsupported)\n",
.{ verb, count },
) catch {};
}
/// sync §5.1/§10.1 — a reply that ended inside a file, cfile or uvfile
/// payload: the cards before it were kept and the exchange went on, so a
/// later round can ask again for what was cut off. A warning for pull, push,
/// sync, config and uv; clone also fails, as Fossil's does.
pub fn reportTruncatedPayloads(s: cli.Streams, verb: []const u8, count: u64) void {
if (count == 0) return;
s.err.print(
"zit {s}: warning: {d} reply payload(s) cut short by the end of the reply; the cards before each were kept\n",
.{ verb, count },
) catch {};
}
/// What the transport did about an HTTP Basic challenge, for the 401 sentence.
const BasicState = enum { none, challenged, sent };
fn basicStateOf(tr: *const transport.Transport) BasicState {
if (tr.basic_armed) return .sent;
if (tr.basic_challenged) return .challenged;
return .none;
}
pub fn syncRunFail(s: cli.Streams, verb: []const u8, url: []const u8, err: sync_driver.RunError(*transport.Transport), tr: *const transport.Transport) cli.Exit {
const status = tr.last_status;
const basic = basicStateOf(tr);
const reason: []const u8 = switch (err) {
error.OutOfMemory => "out of memory",
// Not "did not converge": the guard counts rounds that moved no bytes,
// so this fires only when the peer kept the exchange open while
// delivering nothing. A slow or very large transfer never reaches it.
error.RoundLimitExceeded => "the peer kept the exchange open without transferring anything",
error.FatalProtocolError => "the peer sent a fatal protocol error",
error.RequestTooLarge => "the sync request exceeded the transport limit",
error.ReplyTruncated, error.ReplyMalformed => "the peer sent a malformed reply",
// The streaming drain's own faults, surfaced through the
// driver: writing the destination log failed, or a received artifact
// did not verify against its name.
error.Storage => "cannot write the cloned repository",
error.Corrupt => "a received artifact failed verification",
error.ReplyTooLarge => "the peer's reply exceeded the size limit",
error.RedirectLimit => "too many HTTP redirects",
error.InsecureRedirect => "the peer redirected HTTPS to plaintext HTTP",
error.RedirectNotAllowed => "the peer redirected on a transport that forbids it",
error.CrossOriginRedirect => return refusedRedirect(s, verb, tr),
error.NoResolveEntry => {
s.err.print("zit {s}: no --resolve entry for {s}; not connecting\n", .{ verb, tr.refused_target orelse "the peer" }) catch {};
return .failure;
},
error.MissingLocation => "the peer sent a redirect with no location",
error.InvalidUrl => "a redirect target was not a valid URL",
error.UnsupportedScheme => "a redirect named an unsupported URL scheme",
error.ProtocolError => blk: {
if (status) |st| {
if (st == .unauthorized) {
// The one status that means "ask again, properly". Which
// half is missing decides the sentence.
if (basic == .sent) {
s.err.print("zit {s}: the peer refused the login (HTTP 401)\n", .{verb}) catch {};
} else if (basic == .challenged) {
s.err.print("zit {s}: the peer wants a login (HTTP 401): give --user and --password, or set ZIT_PASSWORD\n", .{verb}) catch {};
} else {
s.err.print("zit {s}: the peer answered HTTP 401 (Unauthorized) without saying how to log in\n", .{verb}) catch {};
}
return .failure;
}
s.err.print("zit {s}: the peer answered HTTP {d} ({s})\n", .{ verb, @backingInt(st), st.phrase() orelse "unrecognized" }) catch {};
return .failure;
}
break :blk "the peer answered with an unexpected HTTP status";
},
error.PeerBusy => {
// A zit server's 503 for a held repository lock, recognised by its
// body. Nothing was lost, so say to retry. Any other 503 is an
// outage of some other kind and takes the status line above.
s.err.print("zit {s}: the peer's repository is busy with another writer (HTTP 503); try again\n", .{verb}) catch {};
return .failure;
},
error.ConnectionFailed => {
s.err.print("zit {s}: cannot connect to {s}\n", .{ verb, url }) catch {};
return .failure;
},
error.InsecureCredential => {
// Name the fix, not just the refusal: the same URL over https.
const rest = if (std.ascii.startsWithIgnoreCase(url, "http://")) url["http://".len..] else url;
s.err.print(
"zit {s}: refusing to send credentials over unencrypted http://{s}; use https://{s}\n",
.{ verb, rest, rest },
) catch {};
return .failure;
},
};
s.err.print("zit {s}: {s}\n", .{ verb, reason }) catch {};
return .failure;
}
/// A redirect to another host or port was refused before anything reached it.
/// The target is named, userinfo removed, so the operator can decide to use it.
pub fn refusedRedirect(s: cli.Streams, verb: []const u8, tr: *const transport.Transport) cli.Exit {
s.err.print(
"zit {s}: the peer redirected to {s}, another host or port; not followed (if you trust it, run the command against that URL directly)\n",
.{ verb, tr.refused_target orelse "another host" },
) catch {};
return .failure;
}
/// One stderr note when a sync crosses plaintext http to a host that is not
/// this machine. Credentials are refused there outright (the transport's
/// `InsecureCredential`), but the exchange itself still crosses readable: a
/// private repository's content included. Loopback is silent, which is how a
/// forge reaches its own zit child.
pub fn notePlaintext(s: cli.Streams, verb: []const u8, url: []const u8) void {
if (!transport.plaintextToRemote(url)) return;
s.err.print("zit {s}: note: {s} is unencrypted http; what this exchange carries is readable in transit\n", .{ verb, url }) catch {};
}
/// sync §4/§6 — the usage error (exit 2) when a sync-family `verb` is given no
/// URL and the repository has no saved remote to fall back to. Names the fix.
/// Shared by pull, push, and sync so the wording lives in one place.
pub fn noRemoteError(s: cli.Streams, verb: []const u8) cli.Exit {
s.err.print("zit {s}: no repository URL given and no saved remote\n", .{verb}) catch {};
s.err.writeAll("set one with 'zit remote URL', or pass the URL explicitly\n") catch {};
return .usage;
}
/// Horizon draft sections 6.2.5 and 6.3 -- a store at the structural depth
/// whose origin did not reply `horizon-served structural` (`served`) MUST
/// fall back to the content horizon at the same C and rule: the store cone
/// is rewritten at the content depth, the seed is dropped (a content horizon
/// derives from the manifests it holds), and the fallback is reported. The
/// caller then fetches what the content depth holds. True when it fell back;
/// `cone` is then the content cone.
pub fn fallBackToContent(
gpa: std.mem.Allocator,
io: std.Io,
root_dir: std.Io.Dir,
streams: cli.Streams,
verb: []const u8,
cone: *zit.cone.Cone,
served: ?zit.sync.HorizonLevel,
) error{OutOfMemory}!bool {
const h = cone.horizon orelse return false;
if (h.depth != .structural or served == .structural) return false;
// The cone was read back from the store, so it re-validates.
var content = zit.cone.Cone.initFrom(gpa, cone, .{ .hash = h.hash, .rule = h.rule, .depth = .content }) catch |e| switch (e) {
error.OutOfMemory => return error.OutOfMemory,
else => unreachable,
};
cone.deinit(gpa);
cone.* = content;
content = undefined;
zit.repocache.writeStoreCone(gpa, io, root_dir, cone);
zit.repocache.writeHorizonSeed(io, root_dir, null);
streams.err.print("zit {s}: the origin did not serve the structural horizon; keeping the content horizon instead, with every manifest below it\n", .{verb}) catch {};
return true;
}
/// Whether a peer's refusal is the one a pushed `config /shun` card draws, on
/// a session that pushed signed erasures. Says so, and why, on stderr; the
/// caller runs the exchange again without them and still exits 1, because
/// the erasures did not reach the peer.
pub fn erasureRefused(streams: cli.Streams, verb: []const u8, text: []const u8, pushed: usize) bool {
if (pushed == 0 or !std.mem.startsWith(u8, text, zit.sync.config_push_unauthorized_text)) return false;
streams.err.print(
"zit {s}: the peer refused this repository's signed erasures: {s}\n" ++
"zit {s}: a stock Fossil server takes /shun rows only from an Admin login, and a zit server only rows its own pinned erasure-key signed; the exchange runs again without them\n",
.{ verb, text, verb },
) catch {};
return true;
}
/// The upper bound on an interactively-typed or `$ZIT_PASSWORD` password. A
/// login password far shorter than this in practice; the fixed bound keeps the
/// no-echo read on the stack with no unbounded allocation (TigerStyle).
pub const max_password_len: usize = 1024;
/// sync §6.3 — a resolved push credential and whether its secret was freshly
/// derived (so it should be persisted after a successful push).
const ResolvedCredential = struct {
credential: zit.sync.Credential,
persist: bool,
/// The plaintext password when this run had one (--password, the
/// environment, or the prompt): what an HTTP Basic challenge is answered
/// with. A stored login has none, and a Basic challenge then fails with
/// a message naming the flag. Borrows argv, the environment, or pw_buf.
plaintext: ?[]const u8 = null,
};
/// The causes `resolvePushCredential` can surface: store read failure, OOM, or
/// a `--user` with no obtainable password (`NoPassword`). Closed set so the
/// caller switches exhaustively.
const ResolveError = error{ OutOfMemory, Storage, NoPassword };
/// sync §6.3/DECISION-3 — turn `push`'s `--user`/`--password` into a signing
/// credential. An empty `--user` is an anonymous push (null result). An
/// ABSENT `--user` falls back to the login a previous authenticated push
/// stored: that credential is reused as-is and this branch never
/// prompts — there is no operator at a keyboard by definition, since it is
/// how autosync pushes — so with nothing stored the push is anonymous. That is
/// fossil's shape: a remembered login authenticates every later sync.
/// Otherwise the 40-hex secret is resolved, in order, from: a stored credential
/// for this exact login (reused verbatim, already durable), `--password`,
/// `$ZIT_PASSWORD`, or a no-echo terminal prompt. A freshly derived secret is
/// flagged `persist`; the plaintext lives only in `pw_buf`/argv/env and is
/// never returned or stored. `user_buf` holds a stored login's name for the
/// returned credential to borrow; it must outlive the credential.
/// Give the transport the plaintext this run holds, so a peer that gates the
/// READ with an HTTP Basic challenge (a forge in front of a private
/// repository) can be answered; nothing is sent unless the peer asks.
pub fn armBasicAuth(tr: *transport.Transport, user: []const u8, plaintext: ?[]const u8) error{OutOfMemory}!void {
const pw = plaintext orelse return;
try tr.setBasicAuth(user, pw);
}
/// The user named in a remote URL's `user@host` component, or null. A
/// `user:password@host` form yields the user only; the password part of a URL
/// is never read from here (the saved remote strips it by construction).
pub fn urlUser(url: []const u8) ?[]const u8 {
const scheme_end = std.mem.indexOf(u8, url, "://") orelse return null;
const rest = url[scheme_end + 3 ..];
const authority_end = std.mem.indexOfScalar(u8, rest, '/') orelse rest.len;
const authority = rest[0..authority_end];
const at = std.mem.lastIndexOfScalar(u8, authority, '@') orelse return null;
const userinfo = authority[0..at];
const colon = std.mem.indexOfScalar(u8, userinfo, ':') orelse userinfo.len;
const user = userinfo[0..colon];
return if (user.len == 0) null else user;
}
/// `url` split around any `user[:password]@`: the scheme and `://`, and the
/// rest after the userinfo. Without `://` the whole URL is `rest`.
fn splitUserinfo(url: []const u8) struct { scheme: []const u8, rest: []const u8 } {
const scheme_end = std.mem.indexOf(u8, url, "://") orelse return .{ .scheme = "", .rest = url };
const rest = url[scheme_end + 3 ..];
const authority_end = std.mem.indexOfScalar(u8, rest, '/') orelse rest.len;
const at = std.mem.lastIndexOfScalar(u8, rest[0..authority_end], '@') orelse
return .{ .scheme = url[0 .. scheme_end + 3], .rest = rest };
return .{ .scheme = url[0 .. scheme_end + 3], .rest = rest[at + 1 ..] };
}
/// Whether `a` and `b` name the same remote. A saved login belongs to the
/// saved remote, which may carry a user name (clone keeps it) while the
/// URL contacted names another or none, so userinfo is ignored on both sides.
/// A host with no path and the same host with the path "/" are one remote:
/// clone saves the second for a URL given as the first.
pub fn sameRemote(a: []const u8, b: []const u8) bool {
if (a.len == 0 or b.len == 0) return false;
const x = splitUserinfo(a);
const y = splitUserinfo(b);
return std.mem.eql(u8, x.scheme, y.scheme) and std.mem.eql(u8, withoutRootPath(x.rest), withoutRootPath(y.rest));
}
/// `rest` without its final "/" when that "/" is the whole path.
fn withoutRootPath(rest: []const u8) []const u8 {
const slash = std.mem.indexOfScalar(u8, rest, '/') orelse return rest;
return if (slash == rest.len - 1) rest[0..slash] else rest;
}
pub fn resolvePushCredential(
gpa: std.mem.Allocator,
io: std.Io,
dir: std.Io.Dir,
streams: cli.Streams,
project_code: []const u8,
parsed: cli.PushArgs,
amb: cli.Ambient,
pw_buf: *[max_password_len]u8,
user_buf: *[logstore.max_config_str]u8,
) ResolveError!?ResolvedCredential {
const stored = try storedLogin(gpa, io, dir);
return resolveCredential(stored, streams, project_code, parsed, amb, pw_buf, user_buf);
}
/// `resolvePushCredential` given the login this repository stored, read by
/// the caller from a log it already holds open.
pub fn resolveCredential(
stored_login: ?StoredLogin,
streams: cli.Streams,
project_code: []const u8,
parsed: cli.PushArgs,
amb: cli.Ambient,
pw_buf: *[max_password_len]u8,
user_buf: *[logstore.max_config_str]u8,
) ResolveError!?ResolvedCredential {
// The stored login was made for the saved remote and goes nowhere else:
// to any other URL this resolves as if nothing were stored.
const stored_for_url: ?StoredLogin = if (stored_login) |s|
(if (sameRemote(s.remote(), parsed.url)) s else null)
else
null;
// --user, then the remote URL's user@, then the login a previous
// authenticated round stored; none of the three means anonymous.
const explicit = parsed.user != null;
const user = parsed.user orelse urlUser(parsed.url) orelse {
const stored = stored_for_url orelse return null;
@memcpy(user_buf[0..stored.user_len], stored.user());
return .{
.credential = .{ .user = user_buf[0..stored.user_len], .secret_hex = stored.secret_hex },
.persist = false,
};
};
if (user.len == 0) return null; // an empty --user is an anonymous push
std.debug.assert(!zit.sync.containsFossilWhitespace(user)); // pre-validated in runPush
// A stored secret for this exact login is reused as-is: no re-derive, no
// prompt, no re-persist. Only consulted when no explicit password is given.
if (parsed.password == null and amb.push_password == null) {
if (stored_for_url) |stored| {
if (std.mem.eql(u8, stored.user(), user)) {
return .{ .credential = .{ .user = user, .secret_hex = stored.secret_hex }, .persist = false };
}
}
}
// Otherwise derive from a plaintext password. Precedence: --password, then
// $ZIT_PASSWORD, then an interactive no-echo prompt. A user named only by
// the URL is a hint, not a demand: with no password to be had, the round
// goes anonymous and says so, so a private repository's 404 at least
// points at the credential it wanted. --user with no password is an error.
const password: []const u8 = parsed.password orelse amb.push_password orelse
(readPasswordNoEcho(streams, user, pw_buf) orelse {
if (explicit) return error.NoPassword;
streams.err.print("zit: no password for '{s}' from the remote URL (set ZIT_PASSWORD or pass --user/--password); continuing anonymously\n", .{user}) catch {};
return null;
});
const secret = zit.sync.deriveSharedSecret(project_code, user, password);
return .{ .credential = .{ .user = user, .secret_hex = secret }, .persist = true, .plaintext = password };
}
/// The login a successful authenticated push left in this repo's config
/// (DECISION-3): the name and its 40-hex secret, with the saved remote it
/// belongs to, all copied out — the config frame is freed here — so the value
/// outlives the read.
const StoredLogin = struct {
user_buf: [logstore.max_config_str]u8,
user_len: usize,
secret_hex: [40]u8,
remote_buf: [logstore.max_config_str]u8,
remote_len: usize,
fn user(self: *const StoredLogin) []const u8 {
return self.user_buf[0..self.user_len];
}
fn remote(self: *const StoredLogin) []const u8 {
return self.remote_buf[0..self.remote_len];
}
};
/// The stored login, or null when none is stored. Read-only.
fn storedLogin(
gpa: std.mem.Allocator,
io: std.Io,
dir: std.Io.Dir,
) error{ OutOfMemory, Storage }!?StoredLogin {
var file = cli.openStoreRead(io, dir) catch return error.Storage;
defer file.close(io);
const st = file.stat(io) catch return error.Storage;
var fs = storage.FileStorage.init(io, file, st.size);
var log = openLogAdoptingIndex(gpa, io, dir, fs.storageFile(), .refresh_on_scan) catch |e| switch (e) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.Storage,
};
defer log.deinit(gpa);
return storedLoginIn(gpa, &log);
}
/// `storedLogin` over a log the caller holds open.
pub fn storedLoginIn(gpa: std.mem.Allocator, log: *logstore.LogStore) error{ OutOfMemory, Storage }!?StoredLogin {
var oc = (log.readConfig(gpa) catch |e| switch (e) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.Storage,
}) orelse return null;
defer oc.deinit(gpa);
if (oc.config.login_secret_hex.len != 40) return null;
const name = oc.config.login_user;
if (name.len == 0 or name.len > logstore.max_config_str) return null;
const saved = oc.config.remote_url;
if (saved.len > logstore.max_config_str) return null;
var out: StoredLogin = .{ .user_buf = undefined, .user_len = name.len, .secret_hex = undefined, .remote_buf = undefined, .remote_len = saved.len };
@memcpy(out.user_buf[0..name.len], name);
@memcpy(&out.secret_hex, oc.config.login_secret_hex[0..40]);
@memcpy(out.remote_buf[0..saved.len], saved);
return out;
}
/// DECISION-3 — persist the derived login credential into the repo config,
/// preserving every other field, then tighten the repository file to 0600 so
/// the stored secret is owner-only at rest. The permission tightening is
/// best-effort: the secret is already durable, so a filesystem that refuses
/// chmod does not fail the push (perms + FDE are the boundary, not the sole
/// guarantee — per DECISION-3). NEVER writes the plaintext password.
///
/// The login belongs to the saved remote, as fossil pairs last-sync-pw with
/// last-sync-url: it is saved only when `url` is that remote, and a store
/// with no saved remote adopts `url`, without its userinfo, in the same
/// config frame. False, with nothing written, when another remote is saved.
pub fn storePushCredential(
gpa: std.mem.Allocator,
io: std.Io,
dir: std.Io.Dir,
credential: zit.sync.Credential,
url: []const u8,
) PersistLockedError!bool {
std.debug.assert(credential.secret_hex.len == 40);
{
var store_append = cli.openStoreAppend(io, dir) catch |e| switch (e) {
error.StoreBusy => return error.StoreBusy,
else => return error.Storage,
};
defer store_append.close(io);
const st = store_append.file.stat(io) catch return error.Storage;
var fs = storage.FileStorage.init(io, store_append.file, st.size);
var log = logstore.LogStore.open(gpa, fs.storageFile(), 0) catch |e| switch (e) {
error.OutOfMemory => return error.OutOfMemory,
error.Storage => return error.Storage,
error.Corrupt => return error.Corrupt,
};
defer log.deinit(gpa);
var remote_buf: [logstore.max_config_str]u8 = undefined;
const saved = savedRemoteIn(gpa, &log, &remote_buf) catch |e| switch (e) {
error.OutOfMemory => return error.OutOfMemory,
error.Storage => return error.Storage,
error.NoRemote => "",
};
var url_buf: [logstore.max_config_str]u8 = undefined;
var patch: ConfigPatch = .{ .login = credential };
if (saved.len == 0) {
// A login the URL cannot be saved beside would never be sent.
const parts = splitUserinfo(url);
if (parts.scheme.len + parts.rest.len > url_buf.len) return false;
@memcpy(url_buf[0..parts.scheme.len], parts.scheme);
@memcpy(url_buf[parts.scheme.len..][0..parts.rest.len], parts.rest);
patch.remote_url = url_buf[0 .. parts.scheme.len + parts.rest.len];
} else if (!sameRemote(saved, url)) return false;
try updateConfigOpen(gpa, &log, patch);
log.commit() catch return error.Storage;
}
// Owner-only now that the file carries a credential (best-effort; see above).
var store_append = cli.openStoreAppend(io, dir) catch return true;
defer store_append.close(io);
const file = store_append.file;
file.setPermissions(io, File.Permissions.fromMode(0o600)) catch {};
return true;
}
/// The one line a verb prints when the login it just used was not saved
/// because `url` is not the saved remote. Names the fix. The URL is shown
/// without its userinfo, which may hold a password.
pub fn noteLoginNotSaved(streams: cli.Streams, verb: []const u8, url: []const u8) void {
const p = splitUserinfo(url);
streams.err.print("zit {s}: login not saved: {s}{s} is not the saved remote ('zit remote {s}{s}' makes it so)\n", .{ verb, p.scheme, p.rest, p.scheme, p.rest }) catch {};
}
/// CLI/IO seam — prompt on stderr and read one password line from the terminal
/// with echo disabled, returning the trimmed line in `buf` (never its newline),
/// or null on a read failure or an empty line. Echo is restored on every exit
/// path; when stdin is not a terminal (`tcgetattr` fails) the line is read with
/// no termios toggle. Not exercised by the automated gates (they pass
/// `--password`/`$ZIT_PASSWORD`) — this is the interactive path.
pub fn readPasswordNoEcho(
streams: cli.Streams,
user: []const u8,
buf: *[max_password_len]u8,
) ?[]const u8 {
// No terminal, no prompt: a script, an autosync, or a test would otherwise
// see a prompt it cannot answer and a read error underneath it.
_ = std.posix.tcgetattr(std.posix.STDIN_FILENO) catch return null;
streams.err.print("Password for {s}: ", .{user}) catch {};
streams.err.flush() catch {};
const fd = std.posix.STDIN_FILENO;
const restore: ?std.posix.termios = blk: {
var t = std.posix.tcgetattr(fd) catch break :blk null;
const saved = t;
t.lflag.ECHO = false;
std.posix.tcsetattr(fd, .FLUSH, t) catch break :blk null;
break :blk saved;
};
defer if (restore) |saved| {
std.posix.tcsetattr(fd, .FLUSH, saved) catch {};
streams.err.writeAll("\n") catch {};
streams.err.flush() catch {};
};
const n = std.posix.read(fd, buf) catch return null;
if (n == 0) return null;
var line = buf[0..n];
// Trim a single trailing CRLF/LF; interior bytes (including spaces) are kept.
if (line.len > 0 and line[line.len - 1] == '\n') line = line[0 .. line.len - 1];
if (line.len > 0 and line[line.len - 1] == '\r') line = line[0 .. line.len - 1];
if (line.len == 0) return null;
return line;
}
/// A branch with more than one open leaf after an exchange. `paths` are the
/// files whose content differs between any two of the leaves, or null when
/// a leaf's tree is not all here (a cone or horizon elides part of it).
const ForkReport = struct {
branch: []const u8,
/// Newest first, full hashes.
leaves: []const []const u8,
paths: ?[]const []const u8,
/// The exchange brought or made it: a leaf it lists was not an open leaf
/// of the branch before.
new: bool,
};
/// Every branch's open leaves before an exchange, and which store file they
/// were read from. After the exchange the forks are read again only when the
/// store moved: a sync that stored nothing has the leaves it started with.
/// Read off the zero-parse image (`.fast_read`), as `zit leaves` reads them;
/// a full view is opened only to name the paths a fork's leaves disagree on.
pub const LeafWatch = struct {
before: []const zit.feed.Branch,
seen: StoreStamp,
/// False when the store cannot be read; the diagnostic is printed.
pub fn open(self: *LeafWatch, gpa: std.mem.Allocator, io: std.Io, arena: std.mem.Allocator, root_dir: std.Io.Dir, streams: cli.Streams, verb: []const u8) bool {
const read = readBranches(gpa, io, arena, root_dir, streams, verb) orelse return false;
self.* = .{ .before = read.branches, .seen = read.stamp };
return true;
}
};
/// The store file's identity and length: an append grows it, a rewrite
/// replaces it.
pub const StoreStamp = struct {
inode: std.Io.File.INode,
size: u64,
pub fn of(io: std.Io, root_dir: std.Io.Dir) ?StoreStamp {
var file = cli.openStoreRead(io, root_dir) catch return null;
defer file.close(io);
const st = file.stat(io) catch return null;
return .{ .inode = st.inode, .size = st.size };
}
};
const ReadBranches = struct { branches: []const zit.feed.Branch, stamp: StoreStamp };
fn readBranches(gpa: std.mem.Allocator, io: std.Io, arena: std.mem.Allocator, root_dir: std.Io.Dir, streams: cli.Streams, verb: []const u8) ?ReadBranches {
var repo: Repository = undefined;
repo.open(gpa, io, root_dir, .{ .mode = .fast_read }) catch |e| {
if (e == error.OutOfMemory) {
_ = stateOom(streams, verb);
return null;
}
streams.err.print("zit {s}: cannot read this repository's leaves: {s}\n", .{ verb, @errorName(e) }) catch {};
return null;
};
defer repo.deinit(gpa);
const st = repo.snapshot_file.stat(io) catch {
streams.err.print("zit {s}: cannot read this repository's leaves: input/output error\n", .{verb}) catch {};
return null;
};
const branches = zit.feed.branchesIn(arena, repo.state()) catch {
_ = stateOom(streams, verb);
return null;
};
return .{ .branches = branches, .stamp = .{ .inode = st.inode, .size = repo.snapshot_size } };
}
fn leavesFail(streams: cli.Streams, verb: []const u8, e: zit.feed.Error, diag: *const zit.feed.Diag) ?[]const zit.feed.Branch {
if (e == error.OutOfMemory) {
_ = stateOom(streams, verb);
return null;
}
streams.err.print("zit {s}: cannot read this repository's leaves: {s}\n", .{ verb, if (diag.text().len > 0) diag.text() else @errorName(e) }) catch {};
return null;
}
/// The forks the store holds after an exchange, each marked new when one of
/// its leaves was not an open leaf of its branch in `before`. `now` is the
/// store's branches when the caller already has them. Null when the store
/// cannot be read; the diagnostic is printed.
pub fn forksAfter(
gpa: std.mem.Allocator,
io: std.Io,
arena: std.mem.Allocator,
root_dir: std.Io.Dir,
streams: cli.Streams,
verb: []const u8,
before: []const zit.feed.Branch,
now: ?[]const zit.feed.Branch,
) ?[]const ForkReport {
const branches = now orelse (readBranches(gpa, io, arena, root_dir, streams, verb) orelse return null).branches;
var reader: ?zit.feed.Reader = null;
defer if (reader) |*r| r.deinit();
var forks: std.ArrayList(ForkReport) = .empty;
for (branches) |b| {
if (b.leaves.len < 2) continue;
if (reader == null) {
var diag: zit.feed.Diag = .{};
reader = @as(zit.feed.Reader, undefined);
reader.?.open(gpa, io, root_dir, null, &diag) catch |e| {
reader = null;
_ = leavesFail(streams, verb, e, &diag);
return null;
};
}
const paths = forkPaths(&reader.?, arena, b.leaves) catch {
_ = stateOom(streams, verb);
return null;
};
forks.append(arena, .{
.branch = b.name,
.leaves = b.leaves,
.paths = paths,
.new = !leavesHeldBefore(before, b),
}) catch {
_ = stateOom(streams, verb);
return null;
};
}
return forks.items;
}
fn leavesHeldBefore(before: []const zit.feed.Branch, after: zit.feed.Branch) bool {
const prior = for (before) |b| {
if (std.mem.eql(u8, b.name, after.name)) break b.leaves;
} else return false;
for (after.leaves) |leaf| {
for (prior) |p| {
if (std.mem.eql(u8, p, leaf)) break;
} else return false;
}
return true;
}
/// The paths that differ between any two of `leaves`, in name order. Each
/// leaf is compared with the first only: a path two later leaves disagree on
/// cannot match the first leaf in both, so N-1 tree walks find every pair's
/// differences without a merge-base search.
fn forkPaths(reader: *zit.feed.Reader, arena: std.mem.Allocator, leaves: []const []const u8) error{OutOfMemory}!?[]const []const u8 {
var seen: std.StringArrayHashMapUnmanaged(void) = .empty;
var diag: zit.feed.Diag = .{};
for (leaves[1..]) |leaf| {
const d = reader.diff(arena, leaves[0], leaf, .{}, &diag) catch |e| switch (e) {
error.OutOfMemory => return error.OutOfMemory,
else => return null,
};
for (d.files) |row| try seen.put(arena, row.name, {});
}
const names = seen.keys();
std.mem.sort([]const u8, names, {}, struct {
fn lessThan(_: void, a: []const u8, b: []const u8) bool {
return std.mem.order(u8, a, b) == .lt;
}
}.lessThan);
return names;
}
/// One stderr line per fork: `fork on BRANCH: N leaves (HASH12, ...)`.
pub fn printForks(err: *std.Io.Writer, forks: []const ForkReport) void {
for (forks) |f| {
err.print("fork on {s}: {d} leaves (", .{ f.branch, f.leaves.len }) catch {};
for (f.leaves, 0..) |leaf, i| {
if (i > 0) err.writeAll(", ") catch {};
err.writeAll(leaf[0..@min(leaf.len, 12)]) catch {};
}
err.writeAll(")\n") catch {};
}
}
/// The counts an exchange reports; `sent` is null for a pull.
const ExchangeCounts = struct {
sent: ?u64,
received: u64,
rounds: u64,
/// Signed erasure rows this session carried but did not fully apply.
erasures_deferred: u64,
};
/// `sync`/`pull -F json`: one object on stdout.
fn writeExchangeJson(out: *std.Io.Writer, counts: ExchangeCounts, forks: []const ForkReport) std.Io.Writer.Error!void {
var jw: std.json.Stringify = .{ .writer = out };
try jw.beginObject();
try jw.objectField("schema_version");
try jw.write(1);
if (counts.sent) |n| {
try jw.objectField("sent");
try jw.write(n);
}
try jw.objectField("received");
try jw.write(counts.received);
try jw.objectField("rounds");
try jw.write(counts.rounds);
try jw.objectField("erasures_deferred");
try jw.write(counts.erasures_deferred);
try jw.objectField("forks");
try jw.write(forks);
try jw.endObject();
try out.writeByte('\n');
}
/// How `sync` and `pull` end once the exchange succeeded: a line per fork
/// on stderr, the JSON object when asked, and `forked` when the exchange
/// brought or made one. A fork already here before is reported at `ok`.
pub fn finishExchange(
gpa: std.mem.Allocator,
io: std.Io,
arena: std.mem.Allocator,
root_dir: std.Io.Dir,
streams: cli.Streams,
verb: []const u8,
watch: *const LeafWatch,
json: bool,
counts: ExchangeCounts,
) cli.Exit {
const unmoved = if (StoreStamp.of(io, root_dir)) |now| std.meta.eql(now, watch.seen) else false;
const forks = forksAfter(gpa, io, arena, root_dir, streams, verb, watch.before, if (unmoved) watch.before else null) orelse return .failure;
printForks(streams.err, forks);
if (json) writeExchangeJson(streams.out, counts, forks) catch {};
for (forks) |f| if (f.new) return .forked;
return .ok;
}