diff --git a/changelog.d/+atomic-oserror-oom.bugfix.md b/changelog.d/+atomic-oserror-oom.bugfix.md new file mode 100644 index 0000000..dfc0fe0 --- /dev/null +++ b/changelog.d/+atomic-oserror-oom.bugfix.md @@ -0,0 +1 @@ +Keep the original operating-system error when allocation fails while formatting its atomic-write diagnostic. diff --git a/changelog.d/+atomic-write-oserror-text.bugfix.md b/changelog.d/+atomic-write-oserror-text.bugfix.md new file mode 100644 index 0000000..7760f67 --- /dev/null +++ b/changelog.d/+atomic-write-oserror-text.bugfix.md @@ -0,0 +1 @@ +A failed replacement names the temporary file when the open fails, names both files when the rename fails, and names no file when the write or the flush fails. diff --git a/changelog.d/+lock-acquire-filename.bugfix.md b/changelog.d/+lock-acquire-filename.bugfix.md new file mode 100644 index 0000000..7c79b66 --- /dev/null +++ b/changelog.d/+lock-acquire-filename.bugfix.md @@ -0,0 +1 @@ +A failed lock acquisition records the OSError text and whether Python names .lock, .lock.posix, the state directory, or no file. diff --git a/changelog.d/+makedirs-failed-ancestor.bugfix.md b/changelog.d/+makedirs-failed-ancestor.bugfix.md new file mode 100644 index 0000000..7247385 --- /dev/null +++ b/changelog.d/+makedirs-failed-ancestor.bugfix.md @@ -0,0 +1 @@ +Report the ancestor that actually failed when recursive state-root or atomic-write directory creation stops. diff --git a/changelog.d/+oserror-errno-lifetime.bugfix.md b/changelog.d/+oserror-errno-lifetime.bugfix.md new file mode 100644 index 0000000..77325ad --- /dev/null +++ b/changelog.d/+oserror-errno-lifetime.bugfix.md @@ -0,0 +1 @@ +Reset stale lock errno state and preserve the parent-directory errno after an atomic replacement has been renamed. diff --git a/changelog.d/+rootlock-preflight-osfailure.bugfix.md b/changelog.d/+rootlock-preflight-osfailure.bugfix.md new file mode 100644 index 0000000..2b22899 --- /dev/null +++ b/changelog.d/+rootlock-preflight-osfailure.bugfix.md @@ -0,0 +1 @@ +Record the state-root path and error text when lock acquisition rejects a non-directory or broken symbolic link. diff --git a/docs/orgmode/howto/replace-a-file-keeping-its-acls.org b/docs/orgmode/howto/replace-a-file-keeping-its-acls.org index 4bc9677..d5ba304 100644 --- a/docs/orgmode/howto/replace-a-file-keeping-its-acls.org +++ b/docs/orgmode/howto/replace-a-file-keeping-its-acls.org @@ -26,24 +26,19 @@ A reader sees the old file or the new one, never a part of either, and never the The steps that follow use =atomicWrite=. -2. Call it with a [[zig:zig_common.atomic.Why]], which receives the reason for a refusal, and free that with =deinit=: +2. Call it with a [[zig:zig_common.atomic.Why]], which receives the reason for any failure, and free that with =deinit=: #+begin_src zig var why: common.atomic.Why = .{}; defer why.deinit(gpa); - common.atomic.atomicWrite(gpa, path, bytes, .{}, &why) catch |err| switch (err) { - error.Refused => { - common.cli.err("tool: {s}\n", .{why.msg}); - return 1; - }, - else => |e| { - common.cli.err("tool: {s}: {s}\n", .{ path, common.atomic.describe(e) }); - return 1; - }, + common.atomic.atomicWrite(gpa, path, bytes, .{}, &why) catch |err| { + const message = if (why.msg.len > 0) why.msg else common.atomic.describe(err); + common.cli.err("tool: {s}\n", .{message}); + return 1; }; #+end_src - [[zig:zig_common.atomic.describe]] words any other error as Python's =OSError= does, such as =[Errno 28] No space left on device=. + =why.msg= includes the filename or filenames of an operating-system error. If a failure happened before it could be filled, [[zig:zig_common.atomic.describe]] supplies text such as =[Errno 12] Cannot allocate memory=. 3. To give the new file the access of another file, such as a file prepared beside the live one it is to replace, name that file in [[zig:zig_common.atomic.WriteOptions]]: diff --git a/src/atomic.zig b/src/atomic.zig index c99dc6f..6b44504 100644 --- a/src/atomic.zig +++ b/src/atomic.zig @@ -9,6 +9,7 @@ const builtin = @import("builtin"); const linux = std.os.linux; const sys = @import("sys.zig"); const fsx = @import("fsx.zig"); +const pytext = @import("pytext.zig"); const Allocator = std.mem.Allocator; @@ -124,11 +125,40 @@ pub fn describe(err: Error) []const u8 { }; } -/// Why a replacement was refused; filled in when an error is returned. The -/// message is allocated from the allocator given with `why` and belongs to -/// the caller: `deinit` frees it. +/// Python's text for an OSError from a step of `atomicWrite`. `path` is the +/// filename and `path2` the second filename of a rename. A null path is a +/// call that carries none, such as write or fsync of an open descriptor. +/// The error itself is unchanged; `why.msg` holds the text. +fn failOs(a: Allocator, why: *Why, err: sys.Error, path: ?[]const u8, path2: ?[]const u8) Error { + const text = sys.describe(err); + if (path2) |second| { + const q1 = pytext.reprStrAlloc(a, path orelse "") catch { + why.msg = unallocated_refusal; + return err; + }; + defer a.free(q1); + const q2 = pytext.reprStrAlloc(a, second) catch { + why.msg = unallocated_refusal; + return err; + }; + defer a.free(q2); + why.msg = a.print("{s}: {s} -> {s}", .{ text, q1, q2 }) catch unallocated_refusal; + } else if (path) |one| { + const q1 = pytext.reprStrAlloc(a, one) catch { + why.msg = unallocated_refusal; + return err; + }; + defer a.free(q1); + why.msg = a.print("{s}: {s}", .{ text, q1 }) catch unallocated_refusal; + } else why.msg = a.print("{s}", .{text}) catch unallocated_refusal; + return err; +} + +/// Why a replacement failed; filled in when an error is returned. The +/// message may be allocated from the allocator given with `why` and belongs +/// to the caller: call `deinit` after any error. pub const Why = struct { - /// The reason for the refusal; empty until there is one. + /// The reason for the failure; empty until there is one. msg: []const u8 = "", /// Free the message when it was allocated from `a`, and empty it. An @@ -139,9 +169,9 @@ pub const Why = struct { } }; -/// The errors of this module: `error.Refused`, with the reason in the -/// caller's `Why`; `error.OutOfMemory`; or the `sys.Error` of a failed -/// call, which `describe` words as Python does. +/// The errors of this module: `error.Refused`, `error.OutOfMemory`, or the +/// `sys.Error` of a failed call, which `describe` words as Python does. +/// `atomicWrite` callers deinitialize `Why` after any error. pub const Error = error{ Refused, OutOfMemory } || sys.Error; /// The message of a refusal that could not allocate its own. @@ -417,27 +447,49 @@ pub fn fsyncDir(path: []const u8) sys.Error!void { /// when that name is absent, as Python checks `exists(head)` first and /// swallows the recursion's FileExistsError. pub fn makedirs(path: []const u8) sys.Error!void { + var failed_path: ?[]const u8 = null; + return makedirsTracked(path, &failed_path); +} + +/// `makedirs`, also returning the path passed to the system call that +/// failed. The slice points into `path` and remains null on success. +pub fn makedirsTracked(path: []const u8, failed_path: *?[]const u8) sys.Error!void { + failed_path.* = null; if (fsx.statAt(fsx.cwd, path, true)) |st| { if (st.isDir()) return; + failed_path.* = path; return error.Exists; } else |_| {} if (std.fs.path.dirname(path)) |parent| if (parent.len > 0) { if (fsx.statAt(fsx.cwd, parent, true)) |_| {} else |_| { - makedirs(parent) catch |err| switch (err) { - error.Exists => {}, + makedirsTracked(parent, failed_path) catch |err| switch (err) { + error.Exists => failed_path.* = null, else => return err, }; } }; var zb: [sys.path_max:0]u8 = undefined; - _ = sys.call(linux.mkdirat, .{ fsx.cwd, (try sys.z(&zb, path)).ptr, @as(linux.mode_t, 0o777) }) catch |err| switch (err) { + const zpath = sys.z(&zb, path) catch |err| { + failed_path.* = path; + return err; + }; + _ = sys.call(linux.mkdirat, .{ fsx.cwd, zpath.ptr, @as(linux.mode_t, 0o777) }) catch |err| switch (err) { error.Exists => { // A name another process created meanwhile passes only when // it is a directory; anything else keeps Python's EEXIST. - const st = fsx.statAt(fsx.cwd, path, true) catch return error.Exists; - if (!st.isDir()) return error.Exists; + const st = fsx.statAt(fsx.cwd, path, true) catch { + failed_path.* = path; + return error.Exists; + }; + if (!st.isDir()) { + failed_path.* = path; + return error.Exists; + } + }, + else => { + failed_path.* = path; + return err; }, - else => return err, }; } @@ -477,6 +529,21 @@ test "makedirs surfaces the errnos of os.makedirs with exist_ok" { defer gpa.free(below_dangling); try std.testing.expectError(error.NotFound, makedirs(below_dangling)); try std.testing.expectEqualStrings("[Errno 2] No such file or directory", sys.describe(error.NotFound)); + + // A caller receives the ancestor passed to the mkdir that failed, not + // the deeper leaf whose recursive creation was requested. + const nested_target = try std.fmt.allocPrint(gpa, "{s}/dangling/child/grandchild/file", .{base}); + defer gpa.free(nested_target); + const failed_ancestor = try std.fmt.allocPrint(gpa, "{s}/dangling/child", .{base}); + defer gpa.free(failed_ancestor); + var why: Why = .{}; + defer why.deinit(gpa); + try std.testing.expectError(error.NotFound, atomicWrite(gpa, nested_target, "x", .{}, &why)); + const quoted = try pytext.reprStrAlloc(gpa, failed_ancestor); + defer gpa.free(quoted); + const want = try std.fmt.allocPrint(gpa, "[Errno 2] No such file or directory: {s}", .{quoted}); + defer gpa.free(want); + try std.testing.expectEqualStrings(want, why.msg); } /// What `atomicWrite` gives the new file besides its bytes, and the names @@ -500,12 +567,13 @@ pub const WriteOptions = struct { /// metadata to apply. Fault points STEP.write, STEP.fsync and STEP.rename /// precede those operations, and in a replaceable build can fail them /// (Faults.fails); the destination is never unlinked first. Everything it -/// allocates from `a` is freed before it returns, except the message of a -/// refusal (see `Why`). +/// allocates from `a` is freed before it returns, except the failure message +/// in `why`. Call `why.deinit(a)` after any error. pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: WriteOptions, why: *Why) Error!void { sys.last_errno = .SUCCESS; const parent = if (std.fs.path.dirname(path)) |d| (if (d.len > 0) d else ".") else "."; - try makedirs(parent); + var failed_path: ?[]const u8 = null; + makedirsTracked(parent, &failed_path) catch |err| return failOs(a, why, err, failed_path orelse parent, null); if (fsx.statAt(fsx.cwd, path, false)) |st| { if (st.isLink()) return refuse(a, why, "refusing to replace a symlink: {s}", .{path}); } else |_| {} @@ -527,7 +595,7 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write const owner_ok = stale.uid == euid or (metadata != null and stale.uid == metadata.?.info.uid); if (!stale.isReg() or !owner_ok or stale.nlink != 1) return refuse(a, why, "temporary file must be an owned regular file with one link: {s}", .{tmp}); - try sys.unlinkat(fsx.cwd, tmp, 0); + sys.unlinkat(fsx.cwd, tmp, 0) catch |err| return failOs(a, why, err, tmp, null); } else |_| {} { @@ -535,18 +603,22 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write defer a.free(step); if (opts.faults.fails(step)) return injected(a, why, step); } - const fd = try openTemp(tmp, .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true, .NOFOLLOW = true }, 0o600); + const fd = openTemp(tmp, .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true, .NOFOLLOW = true }, 0o600) catch |err| + return failOs(a, why, err, tmp, null); const created = fsx.fstat(fd) catch |err| { + // os.fstat names no path. Record that before the cleanup calls. + const failed = failOs(a, why, err, null, null); sys.close(fd); // Created above with O_EXCL, so it is this call's file. sys.unlinkat(fsx.cwd, tmp, 0) catch {}; - return err; + return failed; }; ops.created(fd); - errdefer discard(tmp, created); + var renamed = false; + errdefer if (!renamed) discard(tmp, created); { defer sys.close(fd); - try writeTemp(fd, data); + writeTemp(fd, data) catch |err| return failOs(a, why, err, null, null); var inner: Why = .{}; defer inner.deinit(a); restoreMetadata(a, fd, metadata, mode, &inner) catch |err| return refuse(a, why, "cannot preserve access metadata for {s}: {s}", .{ path, if (err == error.Refused) inner.msg else describe(err) }); @@ -555,7 +627,7 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write defer a.free(step); if (opts.faults.fails(step)) return injected(a, why, step); } - _ = try op(ops.fsync, .{fd}); + _ = op(ops.fsync, .{fd}) catch |err| return failOs(a, why, err, null, null); } if (metadata) |m| { var inner: Why = .{}; @@ -569,8 +641,12 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write defer a.free(step); if (opts.faults.fails(step)) return injected(a, why, step); } - try renameTemp(tmp, path); - try fsyncDir(parent); + renameTemp(tmp, path) catch |err| return failOs(a, why, err, tmp, path); + renamed = true; + // Opening the directory names it. Flushing the descriptor names no file. + const directory = sys.openat(fsx.cwd, parent, .{}, 0) catch |err| return failOs(a, why, err, parent, null); + defer sys.close(directory); + sys.fsync(directory) catch |err| return failOs(a, why, err, null, null); } /// atomic_write pinned to an open directory: replace `dir/name` with @@ -613,6 +689,24 @@ fn discard(tmp: []const u8, created: fsx.Stat) void { if (cur.dev == created.dev and cur.ino == created.ino) sys.unlinkat(fsx.cwd, tmp, 0) catch {}; } +var saved_nofile: linux.rlimit = undefined; +var nofile_lowered = false; + +fn renameThenExhaustFiles(old_dir: sys.fd_t, old_path: [*:0]const u8, new_dir: sys.fd_t, new_path: [*:0]const u8) usize { + const rc = linux.renameat(old_dir, old_path, new_dir, new_path); + if (linux.errno(rc) != .SUCCESS) return rc; + if (linux.errno(linux.prlimit(0, .NOFILE, null, &saved_nofile)) != .SUCCESS) return @bitCast(-@as(isize, @backingInt(linux.E.IO))); + const none: linux.rlimit = .{ .cur = 0, .max = saved_nofile.max }; + if (linux.errno(linux.prlimit(0, .NOFILE, &none, null)) != .SUCCESS) return @bitCast(-@as(isize, @backingInt(linux.E.IO))); + nofile_lowered = true; + return rc; +} + +fn restoreFileLimit() void { + if (nofile_lowered) _ = linux.prlimit(0, .NOFILE, &saved_nofile, null); + nofile_lowered = false; +} + test "Why.deinit frees a refusal's message only when it was allocated" { const gpa = std.testing.allocator; var why: Why = .{}; @@ -627,6 +721,26 @@ test "Why.deinit frees a refusal's message only when it was allocated" { try std.testing.expectEqualStrings("", why.msg); } +test "an OOM while formatting any OSError path keeps the system error" { + const gpa = std.testing.allocator; + var why: Why = .{}; + try std.testing.expectEqual(error.NoSpace, failOs(std.testing.failing_allocator, &why, error.NoSpace, "path", null)); + try std.testing.expectEqualStrings("refused", why.msg); + why.deinit(gpa); + + var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 1 }); + try std.testing.expectEqual(error.NoSpace, failOs(failing.allocator(), &why, error.NoSpace, "path", null)); + try std.testing.expectEqualStrings("refused", why.msg); + why.deinit(gpa); + + for (0..3) |fail_index| { + var two_path_failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = fail_index }); + try std.testing.expectEqual(error.NoSpace, failOs(two_path_failing.allocator(), &why, error.NoSpace, "old", "new")); + try std.testing.expectEqualStrings("refused", why.msg); + why.deinit(gpa); + } +} + test "atomicWrite keeps the mode and refuses a symlink" { var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); @@ -639,6 +753,7 @@ test "atomicWrite keeps the mode and refuses a symlink" { defer fsx.deleteTree(a, fsx.cwd, base) catch {}; const p = try a.print("{s}/j.json", .{base}); var why: Why = .{}; + defer why.deinit(a); try atomicWrite(a, p, "one\n", .{ .mode = 0o640 }, &why); try std.testing.expectEqual(@as(u32, 0o640), (try fsx.statAt(fsx.cwd, p, false)).perm()); try atomicWrite(a, p, "two\n", .{}, &why); @@ -671,6 +786,7 @@ test "a step a test makes fail leaves the destination and no temporary file" { defer fsx.deleteTree(a, fsx.cwd, dir) catch {}; const path = try a.print("{s}/f", .{dir}); var why: Why = .{}; + defer why.deinit(a); try atomicWrite(a, path, "old\n", .{}, &why); for ([_][]const u8{ "j.write", "j.fsync", "j.rename" }) |step| { var want: []const u8 = step; @@ -681,7 +797,38 @@ test "a step a test makes fail leaves the destination and no temporary file" { defer sys.close(f.fd); try std.testing.expectEqualStrings("old\n", try fsx.readAll(a, f.fd, 16)); try std.testing.expectError(error.NotFound, fsx.statAt(fsx.cwd, try a.print("{s}/.f.new", .{dir}), false)); + why.deinit(a); + } +} + +test "opening a file in an unwritable directory names the temporary file" { + if (linux.geteuid() == 0) return; + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + var cwd_buf: [sys.path_max]u8 = undefined; + const cwd = try fsx.realpath(fsx.cwd, ".", &cwd_buf); + const dir = try a.print("{s}/.zig-cache/atomic-ro-{d}", .{ cwd, linux.getpid() }); + try makedirs(dir); + const directory = try sys.openat(fsx.cwd, dir, .{ .DIRECTORY = true }, 0); + _ = linux.fchmod(directory, 0o555); + sys.close(directory); + defer { + const again = sys.openat(fsx.cwd, dir, .{ .DIRECTORY = true }, 0) catch unreachable; + _ = linux.fchmod(again, 0o755); + sys.close(again); + fsx.deleteTree(a, fsx.cwd, dir) catch {}; } + const path = try a.print("{s}/metrics.prom", .{dir}); + var why: Why = .{}; + defer why.deinit(a); + try std.testing.expectError(error.AccessDenied, atomicWrite(a, path, "x\n", .{}, &why)); + const tmp = try a.print("{s}/.metrics.prom.new", .{dir}); + const quoted = try pytext.reprStrAlloc(a, tmp); + defer a.free(quoted); + const want = try a.print("[Errno 13] Permission denied: {s}", .{quoted}); + try std.testing.expectEqualStrings(want, why.msg); + try std.testing.expectError(error.NotFound, fsx.statAt(fsx.cwd, tmp, false)); } test "atomicWrite frees what it allocates" { @@ -700,6 +847,38 @@ test "atomicWrite frees what it allocates" { try std.testing.expectEqual(@as(usize, 0), why.msg.len); } +test "a post-rename parent-open failure keeps its errno" { + const gpa = std.testing.allocator; + var cwd_buf: [sys.path_max]u8 = undefined; + const cwd = try fsx.realpath(fsx.cwd, ".", &cwd_buf); + const dir = try std.fmt.allocPrint(gpa, "{s}/.zig-cache/atomic-parent-open-{d}", .{ cwd, linux.getpid() }); + defer gpa.free(dir); + try makedirs(dir); + defer fsx.deleteTree(gpa, fsx.cwd, dir) catch {}; + const path = try std.fmt.allocPrint(gpa, "{s}/f", .{dir}); + defer gpa.free(path); + var why: Why = .{}; + defer why.deinit(gpa); + const old_ops = ops.*; + defer ops.* = old_ops; + ops.renameat = renameThenExhaustFiles; + defer restoreFileLimit(); + + try std.testing.expectError(error.Unexpected, atomicWrite(gpa, path, "new\n", .{}, &why)); + try std.testing.expectEqual(linux.E.MFILE, sys.last_errno); + const quoted = try pytext.reprStrAlloc(gpa, dir); + defer gpa.free(quoted); + const want = try std.fmt.allocPrint(gpa, "[Errno 24] Too many open files: {s}", .{quoted}); + defer gpa.free(want); + try std.testing.expectEqualStrings(want, why.msg); + restoreFileLimit(); + const live = try fsx.openRegular(fsx.cwd, path, false); + defer sys.close(live.fd); + const bytes = try fsx.readAll(gpa, live.fd, 16); + defer gpa.free(bytes); + try std.testing.expectEqualStrings("new\n", bytes); +} + test "an interrupted ACL read is retried" { const gpa = std.testing.allocator; var cwd_buf: [sys.path_max]u8 = undefined; diff --git a/src/atomic_test.zig b/src/atomic_test.zig index ab233f7..d0e13c0 100644 --- a/src/atomic_test.zig +++ b/src/atomic_test.zig @@ -133,8 +133,9 @@ fn touch(fd: sys.fd_t) void { fn write(path: []const u8, data: []const u8, opts: atomic.WriteOptions) atomic.Error!void { var why: atomic.Why = .{}; + defer why.deinit(A); atomic.atomicWrite(A, path, data, opts, &why) catch |e| { - last_why = why.msg; + last_why = A.dupe(u8, why.msg) catch "out of memory"; return e; }; } @@ -1716,16 +1717,17 @@ test "atomicWrite frees what it allocates but a refusal's message" { const s = scenario(&m); defer cleanup(s.dir); var why: atomic.Why = .{}; + defer why.deinit(gpa); try atomic.atomicWrite(gpa, s.path, "new", replace, &why); try atomic.atomicWrite(gpa, join(s.dir, "copy.lua"), "copy", .{ .metadata_from = s.path }, &why); try testing.expectEqualStrings("", why.msg); try testing.expectError(error.Refused, atomic.atomicWrite(gpa, s.path, "x", .{ .step = "replace", .faults = .{ .fail_fn = failFsync } }, &why)); - gpa.free(why.msg); + why.deinit(gpa); target = s.path; hook_errno = .STALE; m.hooks.get = hFail; try testing.expectError(error.Refused, atomic.atomicWrite(gpa, s.path, "x", replace, &why)); - gpa.free(why.msg); + why.deinit(gpa); reset(&m); try testing.expectEqualStrings("new", readFile(s.path)); try expectAttrs(s.expected, m.getPath(s.path)); @@ -1744,6 +1746,104 @@ fn exdevRenameat(_: sys.fd_t, _: [*:0]const u8, _: sys.fd_t, _: [*:0]const u8) u return err(.XDEV); } +fn eioFsync(_: sys.fd_t) usize { + return err(.IO); +} + +fn closedOpenat(dir: sys.fd_t, path: [*:0]const u8, flags: sys.O, mode: linux.mode_t) usize { + const rc = linux.openat(dir, path, flags, mode); + if (linux.errno(rc) == .SUCCESS) sys.close(@intCast(rc)); + return rc; +} + +var stale_path: []const u8 = ""; +var parent_path: []const u8 = ""; +var moved_parent_path: []const u8 = ""; + +fn replaceStaleWithDirectory() linux.uid_t { + sys.unlinkat(fsx.cwd, stale_path, 0) catch unreachable; + var zb: [sys.path_max:0]u8 = undefined; + _ = linux.mkdirat(fsx.cwd, (sys.z(&zb, stale_path) catch unreachable).ptr, 0o700); + return linux.geteuid(); +} + +fn renameThenUseProcParent(old_dir: sys.fd_t, old_path: [*:0]const u8, new_dir: sys.fd_t, new_path: [*:0]const u8) usize { + const rc = linux.renameat(old_dir, old_path, new_dir, new_path); + if (linux.errno(rc) != .SUCCESS) return rc; + _ = linux.renameat(fsx.cwd, z(parent_path).ptr, fsx.cwd, z(moved_parent_path).ptr); + _ = linux.symlinkat("/proc", fsx.cwd, z(parent_path).ptr); + return rc; +} + +fn restoreProcParent() void { + _ = linux.unlinkat(fsx.cwd, z(parent_path).ptr, 0); + _ = linux.renameat(fsx.cwd, z(moved_parent_path).ptr, fsx.cwd, z(parent_path).ptr); +} + +test "OSError messages cover write, fsync, fstat, and stale unlink failures" { + begin(); + defer end(); + const dir = tmpdir(); + defer cleanup(dir); + const path = join(dir, "fresh"); + const tmp = join(dir, ".fresh.new"); + + atomic.ops.write = enospcWrite; + try testing.expectError(error.NoSpace, write(path, "new", replace)); + try testing.expectEqualStrings("[Errno 28] No space left on device", last_why); + + atomic.ops.* = .{}; + atomic.ops.fsync = eioFsync; + try testing.expectError(error.Unexpected, write(path, "new", replace)); + try testing.expectEqualStrings("[Errno 5] Input/output error", last_why); + + atomic.ops.* = .{}; + atomic.ops.openat = closedOpenat; + try testing.expectError(error.InvalidArgument, write(path, "new", replace)); + try testing.expectEqualStrings("[Errno 9] Bad file descriptor", last_why); + + atomic.ops.* = .{}; + writeFile(tmp, "stale"); + stale_path = tmp; + atomic.ops.geteuid = replaceStaleWithDirectory; + try testing.expectError(error.IsDir, write(path, "new", replace)); + try testing.expectEqualStrings(try A.print("[Errno 21] Is a directory: '{s}'", .{tmp}), last_why); +} + +test "a parent fsync failure carries no filename and keeps its errno" { + begin(); + defer end(); + const dir = tmpdir(); + defer cleanup(dir); + parent_path = dir; + moved_parent_path = A.print("{s}.moved", .{dir}) catch unreachable; + const path = join(dir, "fresh"); + atomic.ops.renameat = renameThenUseProcParent; + const result = write(path, "new", replace); + const kept_errno = sys.last_errno; + restoreProcParent(); + try testing.expectError(error.InvalidArgument, result); + try testing.expectEqual(linux.E.INVAL, kept_errno); + try testing.expectEqualStrings("[Errno 22] Invalid argument", last_why); + try testing.expectEqualStrings("new", readFile(path)); +} + +test "a sys-error message can be released with a general-purpose allocator" { + begin(); + defer end(); + const gpa = testing.allocator; + const dir = tmpdir(); + defer cleanup(dir); + const path = join(dir, "fresh"); + atomic.ops.write = enospcWrite; + var why: atomic.Why = .{}; + defer why.deinit(gpa); + try testing.expectError(error.NoSpace, atomic.atomicWrite(gpa, path, "new", replace, &why)); + try testing.expectEqualStrings("[Errno 28] No space left on device", why.msg); + why.deinit(gpa); + try testing.expectEqualStrings("", why.msg); +} + test "atomicWrite returns NoSpace, ReadOnly, and CrossDevice without touching the live file" { begin(); defer end(); @@ -1754,6 +1854,7 @@ test "atomicWrite returns NoSpace, ReadOnly, and CrossDevice without touching th atomic.ops.write = enospcWrite; try testing.expectError(error.NoSpace, write(pt[0], "new", replace)); try testing.expectEqualStrings("[Errno 28] No space left on device", atomic.describe(error.NoSpace)); + try testing.expectEqualStrings("[Errno 28] No space left on device", last_why); try testing.expect(!exists(pt[1])); try testing.expectEqualStrings("old", readFile(pt[0])); @@ -1761,6 +1862,7 @@ test "atomicWrite returns NoSpace, ReadOnly, and CrossDevice without touching th atomic.ops.openat = erofsOpenat; try testing.expectError(error.ReadOnly, write(pt[0], "new", replace)); try testing.expectEqualStrings("[Errno 30] Read-only file system", atomic.describe(error.ReadOnly)); + try testing.expectEqualStrings(try A.print("[Errno 30] Read-only file system: '{s}'", .{pt[1]}), last_why); try testing.expect(!exists(pt[1])); try testing.expectEqualStrings("old", readFile(pt[0])); @@ -1768,6 +1870,7 @@ test "atomicWrite returns NoSpace, ReadOnly, and CrossDevice without touching th atomic.ops.renameat = exdevRenameat; try testing.expectError(error.CrossDevice, write(pt[0], "new", replace)); try testing.expectEqualStrings("[Errno 18] Invalid cross-device link", atomic.describe(error.CrossDevice)); + try testing.expectEqualStrings(try A.print("[Errno 18] Invalid cross-device link: '{s}' -> '{s}'", .{ pt[1], pt[0] }), last_why); try testing.expect(!exists(pt[1])); try testing.expectEqualStrings("old", readFile(pt[0])); diff --git a/src/state.zig b/src/state.zig index 5a1e5ec..c8b518d 100644 --- a/src/state.zig +++ b/src/state.zig @@ -12,6 +12,64 @@ const Allocator = std.mem.Allocator; /// The errors of this module's calls: `sys.Error`. pub const Error = sys.Error; +/// Python's text for the OSError that made the latest `RootLock.acquire` +/// fail, snapshotted before a later close. `path` is empty when Python +/// names no file (a write, flush, or lock on an open descriptor). Absent +/// when the failure was not an operating-system error. +pub const OsFailure = struct { text: []const u8, path: []const u8 }; + +threadlocal var os_noted: bool = false; +threadlocal var os_text: [128]u8 = undefined; +threadlocal var os_text_len: usize = 0; +threadlocal var os_path: [sys.path_max]u8 = undefined; +threadlocal var os_path_len: usize = 0; + +pub fn osFailure() ?OsFailure { + if (!os_noted) return null; + return .{ .text = os_text[0..os_text_len], .path = os_path[0..os_path_len] }; +} + +fn clearOsFailure() void { + os_noted = false; + os_text_len = 0; + os_path_len = 0; +} + +fn noteText(text: []const u8, path: ?[]const u8) void { + const n = @min(text.len, os_text.len); + @memcpy(os_text[0..n], text[0..n]); + os_text_len = n; + if (path) |p| { + const m = @min(p.len, os_path.len); + @memcpy(os_path[0..m], p[0..m]); + os_path_len = m; + } else os_path_len = 0; + os_noted = true; +} + +fn noted(err: Error, path: ?[]const u8) Error { + noteText(sys.describe(err), path); + return err; +} + +fn notedUnder(err: Error, root: []const u8, name: []const u8) Error { + noteText(sys.describe(err), null); + var n: usize = 0; + const root_part = if (std.mem.eql(u8, root, "/")) "" else root; + const parts = [_][]const u8{ root_part, "/", name }; + for (parts) |part| { + const take = @min(part.len, os_path.len - n); + @memcpy(os_path[n..][0..take], part[0..take]); + n += take; + } + os_path_len = n; + return err; +} + +fn noteErrno(e: linux.E, path: ?[]const u8) void { + noteText(sys.describeErrno(e), path); +} + /// Regular, owned by `uid`, one link, mode & 0o077 == 0. pub fn privateOk(st: fsx.Stat, uid: linux.uid_t) bool { return st.isReg() and st.uid == uid and st.nlink == 1 and st.mode & 0o077 == 0; @@ -391,7 +449,7 @@ pub const RootLock = struct { fn takeFlock(fd: fsx.fd_t, deadline_ms: ?i64) AcquireError!void { const d = deadline_ms orelse { - _ = try lockCall(lock_ops.flock, .{ fd, @as(i32, std.posix.LOCK.EX) }); + _ = lockCall(lock_ops.flock, .{ fd, @as(i32, std.posix.LOCK.EX) }) catch |err| return noted(err, null); return; }; while (true) { @@ -400,7 +458,7 @@ pub const RootLock = struct { .SUCCESS => return, .INTR => continue, .AGAIN, .ACCES => {}, - else => return mapped(rc), + else => return noted(mapped(rc), null), } if (try pause(d)) return error.Busy; } @@ -418,8 +476,11 @@ pub const RootLock = struct { .INTR => continue, .AGAIN, .ACCES => if (deadline_ms) |d| { if (try pause(d)) return error.Busy; - } else return error.Unexpected, - else => return mapped(rc), + } else { + noteErrno(linux.errno(rc), null); + return error.Unexpected; + }, + else => return noted(mapped(rc), null), } } } @@ -448,27 +509,31 @@ pub const RootLock = struct { _ = gpa; const atomic = @import("atomic.zig"); const root = withoutTrailingSlashes(state_root); + sys.last_errno = .SUCCESS; // The Python tool pre-checks the root before makedirs; a // non-directory root is ENOTDIR here whatever makedirs alone // would say. A root that is a directory once links are followed // passes this and is refused below only when the root itself is // a link, as the root is opened without following it. - try preflightRoot(root); - try atomic.makedirs(root); + clearOsFailure(); + preflightRoot(root) catch |err| return noted(err, root); + var failed_path: ?[]const u8 = null; + atomic.makedirsTracked(root, &failed_path) catch |err| return noted(err, failed_path orelse root); const deadline: ?i64 = if (timeout_ms) |t| nowMs() + t else null; - const dir = try fsx.openDir(fsx.cwd, root, false); + const dir = fsx.openDir(fsx.cwd, root, false) catch |err| return noted(err, root); defer sys.close(dir); - const gate = (try openLockFile(dir, gate_name, realOpenLock)) orelse return error.GateNotPrivate; + const gate = (try openLockFile(dir, root, gate_name, realOpenLock)) orelse return error.GateNotPrivate; errdefer sys.close(gate); try takeFlock(gate, deadline); - const posix = (try openLockFile(dir, sidecar_name, lock_ops.open_sidecar)) orelse return error.NotPrivate; + const posix = (try openLockFile(dir, root, sidecar_name, lock_ops.open_sidecar)) orelse return error.NotPrivate; errdefer sys.close(posix); try takeRecord(posix, deadline); - if (!try isSoleLink(dir, gate_name, gate)) return error.GateNotPrivate; - _ = try lockCall(lock_ops.ftruncate, .{ gate, @as(i64, 0) }); + if (!try isSoleLink(dir, root, gate_name, gate)) return error.GateNotPrivate; + _ = lockCall(lock_ops.ftruncate, .{ gate, @as(i64, 0) }) catch |err| return noted(err, null); var buf: [24]u8 = undefined; const line = std.mem.print(&buf, "{d}\n", .{linux.getpid()}) catch unreachable; - if ((try lockCall(lock_ops.write, .{ gate, line })) != line.len) return error.NoSpace; + const n = lockCall(lock_ops.write, .{ gate, line }) catch |err| return noted(err, null); + if (n != line.len) return noted(error.NoSpace, null); return .{ .gate = gate, .posix = posix, .owner = linux.getpid() }; } @@ -476,20 +541,20 @@ pub const RootLock = struct { /// absent or a regular file of this user with one link before the open, /// so a FIFO, device or symbolic link there is never opened, and the /// descriptor is that file after it. - fn openLockFile(dir: fsx.fd_t, name: [:0]const u8, open: *const fn (dir: fsx.fd_t, name: [*:0]const u8) usize) Error!?fsx.fd_t { + fn openLockFile(dir: fsx.fd_t, root: []const u8, name: [:0]const u8, open: *const fn (dir: fsx.fd_t, name: [*:0]const u8) usize) Error!?fsx.fd_t { if (fsx.statAt(dir, name, false)) |st| { if (!st.isReg() or st.nlink != 1 or st.uid != linux.geteuid()) return null; } else |err| switch (err) { error.NotFound => {}, - else => |e| return e, + else => |e| return notedUnder(e, root, name), } const fd: fsx.fd_t = @intCast(lockCall(open, .{ dir, name.ptr }) catch |err| switch (err) { error.SymLink, error.IsDir => return null, - else => |e| return e, + else => |e| return notedUnder(e, root, name), }); errdefer sys.close(fd); - if (try isSoleLink(dir, name, fd)) { - try sys.fchmod(fd, 0o600); + if (try isSoleLink(dir, root, name, fd)) { + sys.fchmod(fd, 0o600) catch |err| return noted(err, null); return fd; } sys.close(fd); @@ -500,12 +565,12 @@ pub const RootLock = struct { /// `dir/name`. The name is looked up as well as the descriptor: a /// planted hard link unlinked while the lock is awaited leaves the /// descriptor on the other name's file, with one link. - fn isSoleLink(dir: fsx.fd_t, name: []const u8, fd: fsx.fd_t) Error!bool { - const st = try fsx.fstat(fd); + fn isSoleLink(dir: fsx.fd_t, root: []const u8, name: []const u8, fd: fsx.fd_t) Error!bool { + const st = fsx.fstat(fd) catch |err| return noted(err, null); if (!st.isReg() or st.nlink != 1 or st.uid != linux.geteuid()) return false; const at = fsx.statAt(dir, name, false) catch |err| switch (err) { error.NotFound => return false, - else => |e| return e, + else => |e| return notedUnder(e, root, name), }; return at.dev == st.dev and at.ino == st.ino and at.nlink == 1; } @@ -627,6 +692,16 @@ test "the state root preflight matches lexists and isdir" { try std.testing.expectError(error.NotDir, preflightRoot(at.at(base, "link-loop", &nb))); } +test "lock filenames are joined to every state-root spelling without allocation" { + try std.testing.expectEqual(error.Unexpected, notedUnder(error.Unexpected, "/", ".lock.posix")); + var failure = osFailure() orelse unreachable; + try std.testing.expectEqualStrings("/.lock.posix", failure.path); + + try std.testing.expectEqual(error.Unexpected, notedUnder(error.Unexpected, ".lock", ".lock")); + failure = osFailure() orelse unreachable; + try std.testing.expectEqualStrings(".lock/.lock", failure.path); +} + test "RootLock refuses a non-directory state root with NotDir" { const gpa = std.testing.allocator; var pb: [sys.path_max]u8 = undefined; @@ -643,13 +718,37 @@ test "RootLock refuses a non-directory state root with NotDir" { const fd = try sys.openat(fsx.cwd, file_root, .{ .ACCMODE = .WRONLY, .CREAT = true }, 0o644); sys.close(fd); try std.testing.expectError(error.NotDir, RootLock.acquire(gpa, file_root, 0)); - try std.testing.expectEqualStrings("[Errno 20] Not a directory", sys.describe(error.NotDir)); + var failure = osFailure() orelse unreachable; + try std.testing.expectEqualStrings(file_root, failure.path); + try std.testing.expectEqualStrings("[Errno 20] Not a directory", failure.text); // a dangling symbolic link as the root const dangling_root = try std.fmt.allocPrint(gpa, "{s}/dangling-root", .{base}); defer gpa.free(dangling_root); _ = linux.symlinkat("nowhere", fsx.cwd, (try sys.z(&zb, dangling_root)).ptr); try std.testing.expectError(error.NotDir, RootLock.acquire(gpa, dangling_root, 0)); + failure = osFailure() orelse unreachable; + try std.testing.expectEqualStrings(dangling_root, failure.path); + try std.testing.expectEqualStrings("[Errno 20] Not a directory", failure.text); + + // Recursive creation names the ancestor at which mkdir failed. + const nested_root = try std.fmt.allocPrint(gpa, "{s}/child/grandchild", .{dangling_root}); + defer gpa.free(nested_root); + const failed_ancestor = try std.fmt.allocPrint(gpa, "{s}/child", .{dangling_root}); + defer gpa.free(failed_ancestor); + try std.testing.expectError(error.NotFound, RootLock.acquire(gpa, nested_root, 0)); + failure = osFailure() orelse unreachable; + try std.testing.expectEqualStrings(failed_ancestor, failure.path); + try std.testing.expectEqualStrings("[Errno 2] No such file or directory", failure.text); + + // a symbolic-link loop as the root + const loop_root = try std.fmt.allocPrint(gpa, "{s}/loop-root", .{base}); + defer gpa.free(loop_root); + _ = linux.symlinkat("loop-root", fsx.cwd, (try sys.z(&zb, loop_root)).ptr); + try std.testing.expectError(error.NotDir, RootLock.acquire(gpa, loop_root, 0)); + failure = osFailure() orelse unreachable; + try std.testing.expectEqualStrings(loop_root, failure.path); + try std.testing.expectEqualStrings("[Errno 20] Not a directory", failure.text); // a symlink to a directory as the root: the Python tool refuses it // as unsafe through its component check, RootLock with the NotDir @@ -661,6 +760,9 @@ test "RootLock refuses a non-directory state root with NotDir" { defer gpa.free(link_root); _ = linux.symlinkat("real-root", fsx.cwd, (try sys.z(&zb, link_root)).ptr); try std.testing.expectError(error.NotDir, RootLock.acquire(gpa, link_root, 0)); + failure = osFailure() orelse unreachable; + try std.testing.expectEqualStrings(link_root, failure.path); + try std.testing.expectEqualStrings("[Errno 20] Not a directory", failure.text); } test "RootLock refuses a second holder and is free after release" { @@ -741,3 +843,29 @@ test "lockExclusive covers timeout 0, bounded timeout, and unsupported flock" { } } } + +test "creating the gate in a read-only directory names .lock" { + if (linux.geteuid() == 0) return; + const gpa = std.testing.allocator; + var pb: [sys.path_max]u8 = undefined; + var cwd_buf: [sys.path_max]u8 = undefined; + const cwd = try fsx.realpath(fsx.cwd, ".", &cwd_buf); + const base = try std.mem.print(&pb, "{s}/.zig-cache/zig-common-ro-{d}", .{ cwd, linux.getpid() }); + const held = try RootLock.acquire(gpa, base, 0); + held.release(); + var zb: [sys.path_max:0]u8 = undefined; + const gate = try std.mem.print(zb[0..zb.len], "{s}/.lock", .{base}); + try sys.unlinkat(fsx.cwd, gate, 0); + const sidecar = try std.mem.print(zb[0..zb.len], "{s}/.lock.posix", .{base}); + sys.unlinkat(fsx.cwd, sidecar, 0) catch {}; + const zbase = try sys.z(&zb, base); + try std.testing.expect(linux.errno(linux.fchmodat(fsx.cwd, zbase.ptr, 0o555)) == .SUCCESS); + defer _ = linux.fchmodat(fsx.cwd, zbase.ptr, 0o755); + defer fsx.deleteTree(gpa, fsx.cwd, base) catch {}; + try std.testing.expectError(error.AccessDenied, RootLock.acquire(gpa, base, 0)); + const note = osFailure() orelse unreachable; + const want_gate = try std.fmt.allocPrint(gpa, "{s}/.lock", .{base}); + defer gpa.free(want_gate); + try std.testing.expectEqualStrings(want_gate, note.path); + try std.testing.expectEqualStrings("[Errno 13] Permission denied", note.text); +} diff --git a/src/state_test.zig b/src/state_test.zig index ff719df..bc26724 100644 --- a/src/state_test.zig +++ b/src/state_test.zig @@ -102,7 +102,10 @@ test "failed local contenders keep the record lock" { defer end(root); const holder = try RootLock.acquire(A, root, 0); defer holder.release(); - for (0..4) |_| try testing.expectError(error.Busy, RootLock.acquire(A, root, 0)); + for (0..4) |_| { + try testing.expectError(error.Busy, RootLock.acquire(A, root, 0)); + try testing.expect(state.osFailure() == null); + } try assertRemoteExcluded(root); } @@ -159,6 +162,9 @@ fn eioFtruncate(_: fsx.fd_t, _: i64) usize { fn eioWrite(_: fsx.fd_t, _: []const u8) usize { return err(.IO); } +fn shortWrite(_: fsx.fd_t, bytes: []const u8) usize { + return bytes.len - 1; +} fn eioOpen(_: fsx.fd_t, _: [*:0]const u8) usize { return err(.IO); } @@ -176,21 +182,57 @@ test "acquisition errors release the descriptors and the gate" { l.release(); return error.TestUnexpectedResult; } else |_| {} + const failure = state.osFailure() orelse unreachable; + try testing.expectEqualStrings("", failure.path); + try testing.expectEqualStrings("[Errno 5] Input/output error", failure.text); state.lock_ops.* = .{}; try testing.expectEqual(before, fdCount(A)); try acquireAndRelease(root); } } +test "a short pid write does not reuse a stale errno" { + const root = begin(); + defer end(root); + const initialized = try RootLock.acquire(A, root, 0); + initialized.release(); + sys.last_errno = .DQUOT; + state.lock_ops.write = shortWrite; + try testing.expectError(error.NoSpace, RootLock.acquire(A, root, 0)); + const failure = state.osFailure() orelse unreachable; + try testing.expectEqualStrings("", failure.path); + try testing.expectEqualStrings("[Errno 28] No space left on device", failure.text); +} + test "a sidecar open failure releases the local gate" { const root = begin(); defer end(root); state.lock_ops.open_sidecar = eioOpen; try testing.expectError(error.Unexpected, RootLock.acquire(A, root, 0)); + const failure = state.osFailure() orelse unreachable; + try testing.expectEqualStrings(try A.print("{s}/.lock.posix", .{root}), failure.path); + try testing.expectEqualStrings("[Errno 5] Input/output error", failure.text); state.lock_ops.* = .{}; try acquireAndRelease(root); } +fn oPathOpen(dir: fsx.fd_t, name: [*:0]const u8) usize { + return linux.openat(dir, name, .{ .PATH = true, .NOFOLLOW = true, .CLOEXEC = true }, 0); +} + +test "an fchmod failure carries no filename" { + const root = begin(); + defer end(root); + const dir = try fsx.openDir(fsx.cwd, root, false); + defer sys.close(dir); + try createFile(dir, ".lock.posix", ""); + state.lock_ops.open_sidecar = oPathOpen; + try testing.expectError(error.InvalidArgument, RootLock.acquire(A, root, 0)); + const failure = state.osFailure() orelse unreachable; + try testing.expectEqualStrings("", failure.path); + try testing.expectEqualStrings("[Errno 9] Bad file descriptor", failure.text); +} + test "a forked child's release does not unlock the parent" { const root = begin(); defer end(root); @@ -229,6 +271,7 @@ test "a hard-linked sidecar is refused" { var zb: [sys.path_max:0]u8 = undefined; _ = linux.linkat(linux.AT.FDCWD, (try sys.z(&za, sidecar)).ptr, linux.AT.FDCWD, (try sys.z(&zb, try A.print("{s}/sidecar-alias", .{root}))).ptr, 0); try testing.expectError(error.NotPrivate, RootLock.acquire(A, root, 0)); + try testing.expect(state.osFailure() == null); } test "a timed acquire does not wait forever" { @@ -330,6 +373,7 @@ test "a gate hard-linked to another file is refused and the file keeps its bytes try createFile(dir, "victim", "secret"); _ = try sys.call(linux.linkat, .{ dir, "victim", dir, ".lock", @as(u32, 0) }); try testing.expectError(error.GateNotPrivate, RootLock.acquire(gpa, root, 0)); + try testing.expect(state.osFailure() == null); try expectContents(gpa, dir, "victim", "secret"); } diff --git a/tests/fs_lock_parity_probe.zig b/tests/fs_lock_parity_probe.zig index 54387ff..c4e1f9e 100644 --- a/tests/fs_lock_parity_probe.zig +++ b/tests/fs_lock_parity_probe.zig @@ -176,6 +176,7 @@ fn atomicMode() void { for (aw_cases) |c| { var why: common.atomic.Why = .{}; opLine("atomicwrite", c.name, common.atomic.atomicWrite(A, c.name, c.data, c.opts, &why)); + why.deinit(A); } const rc_cases = [_]struct { name: []const u8, data: []const u8 }{ .{ .name = "rc-keep", .data = "replaced\n" },