Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/+write-private-close-test.misc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add tests that `state.writePrivate` returns a failed `fsync` or `close` injected through `state.write_ops`, closes the descriptor once, leaves the name and no temporary file, retries an `fsync` that `EINTR` interrupts, and treats a `close` that `EINTR` interrupts as success without a retry.
1 change: 1 addition & 0 deletions changelog.d/+write-private-close.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`state.writePrivate` syncs and closes the temporary file before it renames it over the name. A failed fsync or close is returned as `sys.Error`, the name is left as it was, and the temporary file is removed. Before this change the file was closed after the rename and the close error was dropped, so a write that a network file system (NFS) reported lost at the close replaced the name and was returned as success. A close that `EINTR` interrupts is not retried and is not an error, as `sys.result` treats `EINTR`. The calls are replaceable through `state.write_ops` in the same builds as `state.lock_ops`.
2 changes: 1 addition & 1 deletion docs/orgmode/howto/keep-private-state-in-tmp.org
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ Use this when a tool keeps a small file between runs in a directory every user m
#+end_src

[[zig:zig_common.state.readPrivate]] returns null for a file that is absent, larger than the limit or not private, so the tool starts over instead of trusting it.
[[zig:zig_common.state.writePrivate]] writes =.NAME.PID.RANDOM.tmp= with mode 0600 and renames it over the name.
[[zig:zig_common.state.writePrivate]] writes =.NAME.PID.RANDOM.tmp= with mode 0600, syncs and closes it, and renames it over the name only when the sync and the close both succeed.

** Check that it worked

Expand Down
45 changes: 41 additions & 4 deletions src/state.zig
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,14 @@ pub fn createPrivateAt(dir: fsx.fd_t, name: []const u8, bytes: []const u8, mode:
}

/// Replace `dir/name` with `bytes`: written to `.NAME.PID.RANDOM.tmp` with
/// mode 0600, then renamed over the name.
/// mode 0600, flushed with fsync and closed, then renamed over the name.
/// A failed write, fchmod, fsync or close is returned with `sys.last_errno`
/// set to its errno; the name is left as it was and the temporary file is
/// removed. A write lost on NFS may be reported only by the close. The
/// descriptor is closed once on every path. A close that EINTR
/// interrupts is not retried, as Linux has freed the descriptor, and is
/// not an error, as `sys.result` treats EINTR; the fsync before it has
/// already flushed the bytes.
pub fn writePrivate(gpa: Allocator, dir: fsx.fd_t, name: []const u8, bytes: []const u8) (Error || Allocator.Error)!void {
var rnd: [6]u8 = undefined;
_ = try sys.call(linux.getrandom, .{ &rnd, rnd.len, 0 });
Expand All @@ -208,17 +215,47 @@ pub fn writePrivate(gpa: Allocator, dir: fsx.fd_t, name: []const u8, bytes: []co
const tmp = try gpa.print("{s}/.{s}.{d}.{x}.tmp", .{ parent, base, linux.getpid(), rnd });
defer gpa.free(tmp);
const fd = try sys.openat(dir, tmp, .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true, .NOFOLLOW = true }, 0o600);
var open = true;
var done = false;
defer {
sys.close(fd);
if (!done) sys.unlinkat(dir, tmp, 0) catch {};
if (open) _ = write_ops.close(fd);
if (!done) {
// The error being returned keeps its errno.
const saved = sys.last_errno;
defer sys.last_errno = saved;
sys.unlinkat(dir, tmp, 0) catch {};
}
}
try sys.writeAll(fd, bytes);
try sys.fchmod(fd, 0o600);
_ = try lockCall(write_ops.fsync, .{fd});
open = false;
_ = try sys.result(write_ops.close(fd));
try sys.renameat(dir, tmp, dir, name);
done = true;
}

/// The calls `writePrivate` makes on the temporary file, as raw
/// system-call results. Replaceable in the same builds as `lock_ops`;
/// constant real calls in any other build.
pub const WriteOps = struct {
fsync: *const fn (fd: fsx.fd_t) usize = realFsync,
close: *const fn (fd: fsx.fd_t) usize = realClose,
};

var test_write_ops: WriteOps = .{};
const real_write_ops: WriteOps = .{};
/// The calls in use. A replaceable build may assign through it
/// (`write_ops.* = ...`); any other build points it at constant real calls.
pub const write_ops = if (@import("atomic.zig").replaceable) &test_write_ops else &real_write_ops;

fn realFsync(fd: fsx.fd_t) usize {
return linux.fsync(fd);
}
fn realClose(fd: fsx.fd_t) usize {
return linux.close(fd);
}

test "createPrivateAt creates without clobbering" {
const gpa = std.testing.allocator;
var pb: [sys.path_max]u8 = undefined;
Expand Down Expand Up @@ -655,7 +692,7 @@ fn realOpenLock(dir: fsx.fd_t, name: [*:0]const u8) usize {
return linux.openat(dir, name, .{ .ACCMODE = .RDWR, .CREAT = true, .NOFOLLOW = true, .NONBLOCK = true, .CLOEXEC = true }, 0o600);
}

/// One of `lock_ops`, retrying on EINTR.
/// One of `lock_ops` or `write_ops`, retrying on EINTR.
fn lockCall(f: anytype, args: anytype) Error!usize {
while (true) {
if (try sys.result(@call(.auto, f, args))) |rc| return rc;
Expand Down
141 changes: 141 additions & 0 deletions src/state_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -548,3 +548,144 @@ test "acquire tightens existing owned lock files to mode 0600" {
try testing.expectEqual(@as(u32, 0o600), (try fsx.fstat(l.gate)).perm());
try testing.expectEqual(@as(u32, 0o600), (try fsx.fstat(l.posix)).perm());
}

// ---- writePrivate: the sync and the close come before the rename ----------

const WriteHooks = struct {
var closes: usize = 0;
var close_errno: linux.E = .SUCCESS;
var fsync_errno: linux.E = .SUCCESS;

fn set(fsync_e: linux.E, close_e: linux.E) void {
closes = 0;
fsync_errno = fsync_e;
close_errno = close_e;
state.write_ops.* = .{ .fsync = fsync, .close = close };
}
fn fsync(fd: fsx.fd_t) usize {
if (fsync_errno != .SUCCESS) return err(fsync_errno);
return linux.fsync(fd);
}
/// Linux frees the descriptor whatever close returns, so the hook
/// closes it for real and then reports the errno it was given, on the
/// first call only: a second close of the descriptor is EBADF.
fn close(fd: fsx.fd_t) usize {
closes += 1;
const rc = linux.close(fd);
if (close_errno == .SUCCESS or closes > 1) return rc;
return err(close_errno);
}
};

fn expectNoTemporary(gpa: std.mem.Allocator, dir: fsx.fd_t) !void {
var it = try fsx.DirIter.init(gpa, dir);
defer it.deinit(gpa);
while (try it.next()) |e| try testing.expect(!std.mem.endsWith(u8, e.name, ".tmp"));
}

const WriteCase = struct { fsync: linux.E = .SUCCESS, close: linux.E = .SUCCESS, want: sys.Error };

fn expectWriteRefused(gpa: std.mem.Allocator, cases: []const WriteCase) !void {
const root = try scratchRoot(gpa);
defer removeRoot(gpa, root);
defer state.write_ops.* = .{};
const dir = try fsx.openDir(fsx.cwd, root, false);
defer sys.close(dir);
try state.writePrivate(gpa, dir, "c.json", "old\n");
for (cases) |c| {
const code = if (c.close != .SUCCESS) c.close else c.fsync;
for ([_][]const u8{ "c.json", "fresh.json" }) |name| {
const before = try test_support.fdCount(gpa);
WriteHooks.set(c.fsync, c.close);
sys.last_errno = .SUCCESS;
const wrote = state.writePrivate(gpa, dir, name, "new\n");
state.write_ops.* = .{};
try testing.expectError(c.want, wrote);
try testing.expectEqual(code, sys.last_errno);
try testing.expectEqualStrings(sys.describeErrno(code), sys.describe(c.want));
try testing.expectEqual(@as(usize, 1), WriteHooks.closes);
try testing.expectEqual(before, try test_support.fdCount(gpa));
try expectNoTemporary(gpa, dir);
}
try expectContents(gpa, dir, "c.json", "old\n");
try testing.expectError(error.NotFound, fsx.statAt(dir, "fresh.json", false));
}
}

test "a failed close of the written file is returned and the name is not replaced" {
try expectWriteRefused(testing.allocator, &.{
.{ .close = .IO, .want = error.Unexpected },
.{ .close = .NOSPC, .want = error.NoSpace },
.{ .close = .DQUOT, .want = error.NoSpace },
});
}

test "a failed fsync of the written file is returned and the file is closed once" {
try expectWriteRefused(testing.allocator, &.{
.{ .fsync = .IO, .want = error.Unexpected },
.{ .fsync = .NOSPC, .want = error.NoSpace },
});
}

test "a close that EINTR interrupts is not retried and is not an error" {
const gpa = testing.allocator;
const root = try scratchRoot(gpa);
defer removeRoot(gpa, root);
defer state.write_ops.* = .{};
const dir = try fsx.openDir(fsx.cwd, root, false);
defer sys.close(dir);
try state.writePrivate(gpa, dir, "c.json", "old\n");
const before = try test_support.fdCount(gpa);
WriteHooks.set(.SUCCESS, .INTR);
try state.writePrivate(gpa, dir, "c.json", "new\n");
state.write_ops.* = .{};
try testing.expectEqual(@as(usize, 1), WriteHooks.closes);
try testing.expectEqual(before, try test_support.fdCount(gpa));
try expectContents(gpa, dir, "c.json", "new\n");
try expectNoTemporary(gpa, dir);
}

test "a sync that EINTR interrupts is retried" {
const gpa = testing.allocator;
const root = try scratchRoot(gpa);
defer removeRoot(gpa, root);
defer state.write_ops.* = .{};
const dir = try fsx.openDir(fsx.cwd, root, false);
defer sys.close(dir);
const Intr = struct {
var syncs: usize = 0;
fn fsync(fd: fsx.fd_t) usize {
syncs += 1;
if (syncs == 1) return err(.INTR);
return linux.fsync(fd);
}
};
const before = try test_support.fdCount(gpa);
WriteHooks.set(.SUCCESS, .SUCCESS);
Intr.syncs = 0;
state.write_ops.fsync = Intr.fsync;
try state.writePrivate(gpa, dir, "c.json", "new\n");
state.write_ops.* = .{};
try testing.expectEqual(@as(usize, 2), Intr.syncs);
try testing.expectEqual(@as(usize, 1), WriteHooks.closes);
try testing.expectEqual(before, try test_support.fdCount(gpa));
try expectContents(gpa, dir, "c.json", "new\n");
try expectNoTemporary(gpa, dir);
}

test "writePrivate closes the written file once when it succeeds" {
const gpa = testing.allocator;
const root = try scratchRoot(gpa);
defer removeRoot(gpa, root);
defer state.write_ops.* = .{};
const dir = try fsx.openDir(fsx.cwd, root, false);
defer sys.close(dir);
const before = try test_support.fdCount(gpa);
WriteHooks.set(.SUCCESS, .SUCCESS);
try state.writePrivate(gpa, dir, "c.json", "new\n");
state.write_ops.* = .{};
try testing.expectEqual(@as(usize, 1), WriteHooks.closes);
try testing.expectEqual(before, try test_support.fdCount(gpa));
try expectContents(gpa, dir, "c.json", "new\n");
try expectNoTemporary(gpa, dir);
}
Loading