From deb32fb554e2f0cde2a822f362ef5701f97c9200 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Wed, 25 Nov 2026 22:58:40 +0000 Subject: [PATCH] fix: check the close of atomically written files atomicWrite and atomicWriteAt close the temporary file once, before the rename. A failed close removes the temporary file, leaves the destination unchanged, and returns the errno the other steps return. A close that a signal interrupts is not retried and is not an error, which is how sys.result treats it. The close goes through atomic.ops so a test can inject a failure. --- README.md | 2 +- changelog.d/+atomic-write-close.bugfix.md | 1 + .../howto/replace-a-file-keeping-its-acls.org | 6 +- src/atomic.zig | 98 ++++++++---- src/atomic_test.zig | 144 ++++++++++++++++++ tests/test_fs_lock_parity.py | 13 +- 6 files changed, 231 insertions(+), 33 deletions(-) create mode 100644 changelog.d/+atomic-write-close.bugfix.md diff --git a/README.md b/README.md index cc5aedf..585d624 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ the entry and its hash. | `state` | private files in a shared directory: trusted only when the open file is a regular file of this user with one link and no group or other bits, a lock trusted the same way, atomic 0600 writes; `RootLock`, a flock gate plus a POSIX record lock on a sidecar, with a deadline read from the clock. The gate and the sidecar must each be a regular file of this user with one link | | `json` | a JSON reader with Python's two string encodings (surrogateescape text, one byte per code point), Python values, and `json.dumps(indent=N, sort_keys=True)` byte for byte, float repr included | | `pytext` | byte strings as Python text: the surrogateescape character, the 'replace' decoder, str.isspace, strip and split, shlex.quote | -| `atomic` | `atomic_write`: replace a file only after its bytes, owner, mode and every ACL form (GPFS NFSv4, NFSv4, POSIX access) are durable and read back; fault points before write, fsync and rename | +| `atomic` | `atomic_write`: replace a file only after its bytes, owner, mode and every ACL form (GPFS NFSv4, NFSv4, POSIX access) are durable and read back, and the temporary file has been closed; fault points before write, fsync and rename | | `syslog` | events to a collector: a `unix:`, `journal:`, `udp:` or `tcp:` target, RFC 5424 and native journald framing for the `Identity` the caller names, and `send`, the transport alone, with a timeout; nothing here fails the caller | | `cli` | messages to stdout and stderr that ignore a closed stream, exit code 2 for a refused invocation, the version line | diff --git a/changelog.d/+atomic-write-close.bugfix.md b/changelog.d/+atomic-write-close.bugfix.md new file mode 100644 index 0000000..bc38fb9 --- /dev/null +++ b/changelog.d/+atomic-write-close.bugfix.md @@ -0,0 +1 @@ +`atomic.atomicWrite` and `atomic.atomicWriteAt` sync and close the temporary file before renaming it over the destination. A failed close is returned as `sys.Error`, the destination is left as it was, and the temporary file is removed. `atomicWrite` puts that errno in `why` with no path, as it does for a failed write or fsync. Before this change, `atomicWrite` ignored the close, and `atomicWriteAt` closed only after the rename and ignored the result. A write that the Network File System (NFS) reported lost at the close then replaced the destination and was returned as success. A close that `EINTR` interrupts is not retried and is not an error, as `sys.result` treats `EINTR`. The call is replaceable through `atomic.ops.close` in the same builds as the other `atomic.ops` calls. 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 d5ba304..0b1cc42 100644 --- a/docs/orgmode/howto/replace-a-file-keeping-its-acls.org +++ b/docs/orgmode/howto/replace-a-file-keeping-its-acls.org @@ -5,7 +5,9 @@ * Replace a file and keep its access control lists Use this when a tool rewrites a file whose owner, group, mode or access control lists (ACLs) decide who may read it, such as a module file under =/project/climate= that the project's members read through an ACL. -[[zig:zig_common.atomic.atomicWrite]] writes the new bytes to a temporary file beside the old one, gives it the old file's owner, group, mode and ACLs, reads them back, and only then renames it over the old file. +[[zig:zig_common.atomic.atomicWrite]] writes the new bytes to a temporary file beside the old one, gives it the old file's owner, group, mode and ACLs, reads them back, syncs and closes the temporary file, and renames it over the old file only when that close succeeds. +A close that =EINTR= interrupts is not an error and is not retried: Linux has already freed the descriptor, and the sync before the close has flushed the bytes. +[[zig:zig_common.atomic.atomicWriteAt]] closes the same way before its rename. A reader sees the old file or the new one, never a part of either, and never the new bytes with other permissions. [[file:../explanation/descriptor-checks.org][Checks on the descriptor, not the path]] says why each check is made on an open file. @@ -38,7 +40,7 @@ A reader sees the old file or the new one, never a part of either, and never the }; #+end_src - =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=. + =why.msg= carries the text of an operating-system error. When the failing call names a path, the text includes that filename, or both filenames of a rename. A failed write, sync or close of the open temporary file names no path. If a failure happened before the text 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 cb13892..7c714ed 100644 --- a/src/atomic.zig +++ b/src/atomic.zig @@ -1,9 +1,9 @@ //! Same-directory replacement of a file whose access metadata must survive: //! the bytes, owner, mode and every listed ACL form are written to a -//! temporary file, read back, made durable, and only then renamed over the -//! destination. The ACL forms are the GPFS native NFSv4 ACL, the generic -//! NFSv4 ACL and the POSIX access ACL, most native first; a filesystem may -//! expose one ACL through several of them. +//! temporary file, read back, made durable, closed, and only then renamed +//! over the destination. The ACL forms are the GPFS native NFSv4 ACL, the +//! generic NFSv4 ACL and the POSIX access ACL, most native first; a +//! filesystem may expose one ACL through several of them. const std = @import("std"); const builtin = @import("builtin"); const linux = std.os.linux; @@ -22,7 +22,8 @@ const posix_access = "system.posix_acl_access"; /// filesystem's ACL model or a failing call, in a `replaceable` build only /// (this library's tests, a tool's -Dtest-ops artifact). `created` runs on /// the temporary file right after its O_EXCL creation, where a filesystem -/// applies an inherited ACL. +/// applies an inherited ACL. `close` is that temporary file's close, before +/// the rename; the caller does not retry it. pub const Ops = struct { flistxattr: *const fn (fd: sys.fd_t, buf: []u8) usize = realList, fgetxattr: *const fn (fd: sys.fd_t, name: [:0]const u8, buf: []u8) usize = realGet, @@ -31,6 +32,7 @@ pub const Ops = struct { fchmod: *const fn (fd: sys.fd_t, mode: u32) usize = realChmod, fchown: *const fn (fd: sys.fd_t, uid: linux.uid_t, gid: linux.gid_t) usize = realChown, fsync: *const fn (fd: sys.fd_t) usize = realFsync, + close: *const fn (fd: sys.fd_t) usize = realClose, openat: *const fn (dir: sys.fd_t, path: [*:0]const u8, flags: sys.O, mode: linux.mode_t) usize = realOpenat, write: *const fn (fd: sys.fd_t, bytes: []const u8) usize = realWrite, renameat: *const fn (old_dir: sys.fd_t, old_path: [*:0]const u8, new_dir: sys.fd_t, new_path: [*:0]const u8) usize = realRenameat, @@ -70,6 +72,9 @@ fn realChown(fd: sys.fd_t, uid: linux.uid_t, gid: linux.gid_t) usize { fn realFsync(fd: sys.fd_t) usize { return linux.fsync(fd); } +fn realClose(fd: sys.fd_t) usize { + return linux.close(fd); +} fn realOpenat(dir: sys.fd_t, path: [*:0]const u8, flags: sys.O, mode: linux.mode_t) usize { return linux.openat(dir, path, flags, mode); } @@ -108,6 +113,22 @@ fn writeTemp(fd: sys.fd_t, bytes: []const u8) sys.Error!void { } } +/// Close the temporary file once. EINTR is not retried, as Linux has +/// freed the descriptor, and is not an error, as `sys.result` treats +/// EINTR. Any other errno is returned with `sys.last_errno` set. +fn closeTemp(fd: sys.fd_t) sys.Error!void { + _ = try sys.result(ops.close(fd)); +} + +/// Close a temporary file whose result is not the one being returned. +/// Linux frees the descriptor whatever close reports, so the result is +/// ignored, and `sys.last_errno` stays the errno of the failure in hand. +fn closeDiscarded(fd: sys.fd_t) void { + const saved = sys.last_errno; + defer sys.last_errno = saved; + _ = ops.close(fd); +} + fn renameTemp(old_path: []const u8, new_path: []const u8) sys.Error!void { var za: [sys.path_max:0]u8 = undefined; var zb: [sys.path_max:0]u8 = undefined; @@ -562,13 +583,21 @@ pub const WriteOptions = struct { }; /// atomic_write: replace `path` only after its bytes and access metadata -/// are durable. An existing file keeps its owner, mode and ACL forms, -/// including the absence of one; `metadata_from` names another file whose -/// 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 failure message -/// in `why`. Call `why.deinit(a)` after any error. +/// are durable. The temporary file is synced and closed before the rename. +/// A failed close is reported the way a failed write or fsync is, with +/// no path in the message; the temporary file is removed and the +/// destination is left as it was. 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. An existing file keeps +/// its owner, mode and ACL forms, including the absence of one; +/// `metadata_from` names another file whose 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. The close goes through +/// `ops.close`. Everything it 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 "."; @@ -608,30 +637,34 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write 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. A failed // cleanup must not replace the errno the message was built from. + closeDiscarded(fd); const saved = sys.last_errno; defer sys.last_errno = saved; sys.unlinkat(fsx.cwd, tmp, 0) catch {}; return failed; }; ops.created(fd); + var open = true; var renamed = false; errdefer if (!renamed) discard(tmp, created); + defer if (open) closeDiscarded(fd); + writeTemp(fd, data) catch |err| return failOs(a, why, err, null, null); { - defer sys.close(fd); - 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) }); - { - const step = try a.print("{s}.fsync", .{opts.step}); - defer a.free(step); - if (opts.faults.fails(step)) return injected(a, why, step); - } - _ = op(ops.fsync, .{fd}) catch |err| return failOs(a, why, err, null, null); } + { + const step = try a.print("{s}.fsync", .{opts.step}); + defer a.free(step); + if (opts.faults.fails(step)) return injected(a, why, step); + } + _ = op(ops.fsync, .{fd}) catch |err| return failOs(a, why, err, null, null); + // Once, before the rename. A later failure must not close again. + open = false; + closeTemp(fd) catch |err| return failOs(a, why, err, null, null); if (metadata) |m| { var inner: Why = .{}; defer inner.deinit(a); @@ -655,12 +688,17 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write /// atomic_write pinned to an open directory: replace `dir/name` with /// `bytes` at exactly `mode`, whatever the process umask leaves, as /// the tools' metrics writer does with the descriptor it holds. The -/// bytes go to a temporary file in the same directory, made durable, -/// and only then renamed over the destination; a failure leaves the -/// destination as it was and removes the temporary file. Shares -/// atomicWrite's write, sync and rename steps, through the same ops a -/// replaceable build may fail. Everything it allocates from `a` is -/// freed before it returns. +/// bytes go to a temporary file in the same directory, synced and +/// closed, and only then renamed over the destination. A failed write, +/// fchmod, fsync or close is returned with `sys.last_errno` set to its +/// errno; the destination 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. Shares atomicWrite's write, sync, close +/// and rename steps, through the same ops a replaceable build may fail. +/// Everything it allocates from `a` is freed before it returns. pub fn atomicWriteAt(a: Allocator, dir: sys.fd_t, name: []const u8, data: []const u8, mode: u32) (Allocator.Error || sys.Error)!void { sys.last_errno = .SUCCESS; var rnd: [4]u8 = undefined; @@ -671,9 +709,10 @@ pub fn atomicWriteAt(a: Allocator, dir: sys.fd_t, name: []const u8, data: []cons const ztmp = try sys.z(&zb, tmp); const flags: sys.O = .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true, .NOFOLLOW = true, .CLOEXEC = true }; const fd: sys.fd_t = @intCast(try op(ops.openat, .{ dir, ztmp.ptr, flags, @as(linux.mode_t, 0o600) })); + var open = true; var done = false; defer { - sys.close(fd); + if (open) closeDiscarded(fd); if (!done) { // The temporary name may already be gone. That failure is not // the call the caller is reporting. @@ -687,6 +726,9 @@ pub fn atomicWriteAt(a: Allocator, dir: sys.fd_t, name: []const u8, data: []cons _ = try op(ops.fchmod, .{ fd, mode }); try writeTemp(fd, data); _ = try op(ops.fsync, .{fd}); + // Once, before the rename. A later failure must not close again. + open = false; + try closeTemp(fd); var zn: [sys.path_max:0]u8 = undefined; _ = try op(ops.renameat, .{ dir, ztmp.ptr, dir, (try sys.z(&zn, name)).ptr }); done = true; diff --git a/src/atomic_test.zig b/src/atomic_test.zig index b11d88f..4e914ec 100644 --- a/src/atomic_test.zig +++ b/src/atomic_test.zig @@ -12,6 +12,7 @@ const linux = std.os.linux; const atomic = @import("atomic.zig"); const sys = @import("sys.zig"); const fsx = @import("fsx.zig"); +const test_support = @import("test_support.zig"); const testing = std.testing; const Allocator = std.mem.Allocator; @@ -1937,3 +1938,146 @@ test "atomicWrite returns NoSpace, ReadOnly, and CrossDevice without touching th try testing.expectError(error.NotDir, atomic.makedirs(join(pt[0], "child"))); try testing.expectError(error.NotFound, atomic.fsyncDir(join(dir, "absent"))); } + +// ---- close of the temporary file, before the rename ------------------------- + +const CloseHook = struct { + var closes: usize = 0; + var close_errno: linux.E = .SUCCESS; + + fn set(e: linux.E) void { + closes = 0; + close_errno = e; + atomic.ops.close = close; + } + + /// 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: sys.fd_t) usize { + closes += 1; + const rc = linux.close(fd); + if (close_errno == .SUCCESS or closes > 1) return rc; + return err(close_errno); + } +}; + +fn closeError(e: linux.E) sys.Error { + return switch (e) { + .IO => error.Unexpected, + .NOSPC, .DQUOT => error.NoSpace, + else => unreachable, + }; +} + +fn expectNoPublishTemp(gpa: Allocator, dir: fsx.fd_t) !void { + var it = try fsx.DirIter.init(gpa, dir); + defer it.deinit(gpa); + while (try it.next()) |entry| { + try testing.expect(std.mem.indexOf(u8, entry.name, ".tmp") == null); + try testing.expect(!std.mem.endsWith(u8, entry.name, ".new")); + } +} + +fn seed(path: []const u8, present: bool) void { + if (present) { + writeFile(path, "old\n"); + } else { + sys.unlinkat(fsx.cwd, path, 0) catch {}; + } +} + +fn armPublish(close_errno: linux.E, fsync_fails: bool) void { + atomic.ops.* = .{}; + CloseHook.set(close_errno); + if (fsync_fails) atomic.ops.fsync = eioFsync; +} + +/// One publish through `atomicWrite` and one through `atomicWriteAt`, each +/// for an existing name and a name that is absent. `fails` means `failure` +/// is returned, `sys.last_errno` is `errno_out`, the previous bytes stay, +/// and an absent name stays absent. Otherwise the new bytes are published. +/// Either way the temporary file is gone, the descriptor was closed once, +/// and the process's descriptor count is unchanged. The hook is installed +/// again before every publish: each publish resets `atomic.ops`. +fn expectPublishClose(dir_path: []const u8, dfd: fsx.fd_t, close_errno: linux.E, fsync_fails: bool, errno_out: linux.E, failure: sys.Error, fails: bool) !void { + const gpa = testing.allocator; + const cases = [_]struct { name: []const u8, present: bool, at: bool }{ + .{ .name = "kept", .present = true, .at = false }, + .{ .name = "fresh", .present = false, .at = false }, + .{ .name = "metrics", .present = true, .at = true }, + .{ .name = "fresh-at", .present = false, .at = true }, + }; + for (cases) |c| { + const path = join(dir_path, c.name); + seed(path, c.present); + armPublish(close_errno, fsync_fails); + const before = try test_support.fdCount(gpa); + const ncloses = if (c.at) blk: { + const wrote = atomic.atomicWriteAt(gpa, dfd, c.name, "new\n", 0o644); + const n = CloseHook.closes; + if (fails) { + try testing.expectError(failure, wrote); + try testing.expectEqual(errno_out, sys.last_errno); + try testing.expectEqualStrings(sys.describeErrno(errno_out), sys.describe(failure)); + } else try wrote; + break :blk n; + } else blk: { + var why: atomic.Why = .{}; + defer why.deinit(gpa); + const wrote = atomic.atomicWrite(gpa, path, "new\n", .{}, &why); + const n = CloseHook.closes; + if (fails) { + try testing.expectError(failure, wrote); + try testing.expectEqual(errno_out, sys.last_errno); + const text = sys.describeErrno(errno_out); + try testing.expectEqualStrings(text, why.msg); + try testing.expectEqualStrings(text, sys.describe(failure)); + } else { + try wrote; + try testing.expectEqualStrings("", why.msg); + } + break :blk n; + }; + if (fails) { + if (c.present) { + try testing.expectEqualStrings("old\n", readFile(path)); + } else try testing.expect(!exists(path)); + } else try testing.expectEqualStrings("new\n", readFile(path)); + try testing.expectEqual(@as(usize, 1), ncloses); + try testing.expectEqual(before, try test_support.fdCount(gpa)); + try expectNoPublishTemp(gpa, dfd); + } +} + +test "a failed close of an atomic write is returned and the destination is unchanged" { + begin(); + defer end(); + const dir_path = tmpdir(); + defer cleanup(dir_path); + const dfd = try fsx.openDir(fsx.cwd, dir_path, false); + defer sys.close(dfd); + for ([_]linux.E{ .IO, .NOSPC, .DQUOT }) |e| { + try expectPublishClose(dir_path, dfd, e, false, e, closeError(e), true); + } +} + +test "a close that EINTR interrupts is not retried and the file is published" { + begin(); + defer end(); + const dir_path = tmpdir(); + defer cleanup(dir_path); + const dfd = try fsx.openDir(fsx.cwd, dir_path, false); + defer sys.close(dfd); + try expectPublishClose(dir_path, dfd, .INTR, false, .SUCCESS, error.Unexpected, false); +} + +test "a failed fsync of an atomic write closes the temporary file once" { + begin(); + defer end(); + const dir_path = tmpdir(); + defer cleanup(dir_path); + const dfd = try fsx.openDir(fsx.cwd, dir_path, false); + defer sys.close(dfd); + try expectPublishClose(dir_path, dfd, .SUCCESS, true, .IO, error.Unexpected, true); +} diff --git a/tests/test_fs_lock_parity.py b/tests/test_fs_lock_parity.py index fd5950d..de824cb 100644 --- a/tests/test_fs_lock_parity.py +++ b/tests/test_fs_lock_parity.py @@ -220,7 +220,13 @@ def make_atomic_fixture(root): def py_atomic_write(root, name, data, mode=None): """The documented atomicWrite behavior: a temp file beside the target, the existing mode kept, 0644 less the umask for a new one, a symlink - refused, then os.replace and a parent fsync.""" + refused, the temp file closed before os.replace, then a parent fsync. + + A close error other than InterruptedError leaves the destination + unchanged and removes the temp file. InterruptedError is not an + error and is not retried: Linux has already closed the descriptor, + which is how atomicWrite treats EINTR from close (sys.result). + """ path = os.path.join(root, name) if os.path.islink(path): return "ERR:Refused" @@ -239,7 +245,10 @@ def py_atomic_write(root, name, data, mode=None): os.fsync(fd) os.fchmod(fd, want) finally: - os.close(fd) + try: + os.close(fd) + except InterruptedError: + pass os.replace(tmp, path) fsync_dir(parent) return "OK"