diff --git a/src/atomic.zig b/src/atomic.zig index 6b44504..cb13892 100644 --- a/src/atomic.zig +++ b/src/atomic.zig @@ -609,7 +609,10 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write // 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. + // 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. + const saved = sys.last_errno; + defer sys.last_errno = saved; sys.unlinkat(fsx.cwd, tmp, 0) catch {}; return failed; }; @@ -671,7 +674,13 @@ pub fn atomicWriteAt(a: Allocator, dir: sys.fd_t, name: []const u8, data: []cons var done = false; defer { sys.close(fd); - if (!done) sys.unlinkat(dir, tmp, 0) catch {}; + if (!done) { + // The temporary name may already be gone. That failure is not + // the call the caller is reporting. + const saved = sys.last_errno; + defer sys.last_errno = saved; + sys.unlinkat(dir, tmp, 0) catch {}; + } } // openat applies the umask to the create, so the exact mode the // caller names is set on the descriptor before anything is written @@ -685,6 +694,10 @@ pub fn atomicWriteAt(a: Allocator, dir: sys.fd_t, name: []const u8, data: []cons } fn discard(tmp: []const u8, created: fsx.Stat) void { + // stat or unlink can fail when the temporary name was removed + // already. That failure is not the call the caller is reporting. + const saved = sys.last_errno; + defer sys.last_errno = saved; const cur = fsx.statAt(fsx.cwd, tmp, false) catch return; if (cur.dev == created.dev and cur.ino == created.ino) sys.unlinkat(fsx.cwd, tmp, 0) catch {}; } diff --git a/src/atomic_test.zig b/src/atomic_test.zig index d0e13c0..b11d88f 100644 --- a/src/atomic_test.zig +++ b/src/atomic_test.zig @@ -1756,6 +1756,27 @@ fn closedOpenat(dir: sys.fd_t, path: [*:0]const u8, flags: sys.O, mode: linux.mo return rc; } +/// Remove the open file, then fail the write with EIO. Cleanup's later +/// stat or unlink fails with ENOENT, a different errno. +fn ioAfterUnlink(fd: sys.fd_t, _: []const u8) usize { + var buf: [sys.path_max]u8 = undefined; + const path = fsx.realpathFd(fd, &buf) catch unreachable; + sys.unlinkat(fsx.cwd, path, 0) catch unreachable; + return err(.IO); +} + +/// Open the temporary file, remove it, and close the descriptor. The +/// following fstat fails with EBADF and the cleanup unlink with ENOENT. +fn closeAndUnlink(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) return rc; + const fd: sys.fd_t = @intCast(rc); + const un = linux.unlinkat(dir, path, 0); + sys.close(fd); + if (linux.errno(un) != .SUCCESS) return un; + return rc; +} + var stale_path: []const u8 = ""; var parent_path: []const u8 = ""; var moved_parent_path: []const u8 = ""; @@ -1810,6 +1831,45 @@ test "OSError messages cover write, fsync, fstat, and stale unlink failures" { try testing.expectEqualStrings(try A.print("[Errno 21] Is a directory: '{s}'", .{tmp}), last_why); } +test "discard keeps the errno when its stat fails" { + begin(); + defer end(); + const dir = tmpdir(); + defer cleanup(dir); + const path = join(dir, "fresh"); + // The write hook removes the temporary file, so discard's stat is ENOENT. + atomic.ops.write = ioAfterUnlink; + try testing.expectError(error.Unexpected, write(path, "new", replace)); + try testing.expectEqual(linux.E.IO, sys.last_errno); + try testing.expectEqualStrings("[Errno 5] Input/output error", last_why); +} + +test "fstat cleanup keeps the errno when its unlink fails" { + begin(); + defer end(); + const dir = tmpdir(); + defer cleanup(dir); + const path = join(dir, "fresh"); + // The open hook closes the descriptor and removes the file, so fstat is + // EBADF and the cleanup unlink is ENOENT. + atomic.ops.openat = closeAndUnlink; + try testing.expectError(error.InvalidArgument, write(path, "new", replace)); + try testing.expectEqual(linux.E.BADF, sys.last_errno); + try testing.expectEqualStrings("[Errno 9] Bad file descriptor", last_why); +} + +test "atomicWriteAt cleanup keeps the errno when its unlink fails" { + begin(); + defer end(); + const dir = tmpdir(); + defer cleanup(dir); + atomic.ops.write = ioAfterUnlink; + const dfd = try fsx.openDir(fsx.cwd, dir, false); + defer sys.close(dfd); + try testing.expectError(error.Unexpected, atomic.atomicWriteAt(A, dfd, "at", "new", 0o644)); + try testing.expectEqual(linux.E.IO, sys.last_errno); +} + test "a parent fsync failure carries no filename and keeps its errno" { begin(); defer end(); diff --git a/src/state.zig b/src/state.zig index c8b518d..edc6159 100644 --- a/src/state.zig +++ b/src/state.zig @@ -24,6 +24,15 @@ threadlocal var os_text_len: usize = 0; threadlocal var os_path: [sys.path_max]u8 = undefined; threadlocal var os_path_len: usize = 0; +/// The OSError recorded for the latest `RootLock.acquire` on this thread. +/// Null when that acquire has not failed, or failed for a reason that is +/// not an operating-system error. `text` is Python's "[Errno N] ..." line +/// without a filename. `path` is the file that call would name, or empty +/// when it names none, such as a write or a lock on an open descriptor. +/// +/// Both slices refer to thread-local storage. The next `RootLock.acquire` +/// on this thread reuses that storage, so copy them before calling it +/// again. pub fn osFailure() ?OsFailure { if (!os_noted) return null; return .{ .text = os_text[0..os_text_len], .path = os_path[0..os_path_len] }; @@ -66,10 +75,6 @@ fn notedUnder(err: Error, root: []const u8, name: []const u8) Error { 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; @@ -477,8 +482,10 @@ pub const RootLock = struct { .AGAIN, .ACCES => if (deadline_ms) |d| { if (try pause(d)) return error.Busy; } else { - noteErrno(linux.errno(rc), null); - return error.Unexpected; + // F_SETLKW does not treat these as contention. Return the + // mapped error so describe agrees with the snapshot: + // EAGAIN is Unexpected, EACCES is AccessDenied. + return noted(mapped(rc), null); }, else => return noted(mapped(rc), null), } diff --git a/src/state_test.zig b/src/state_test.zig index bc26724..4b2f51a 100644 --- a/src/state_test.zig +++ b/src/state_test.zig @@ -191,6 +191,40 @@ test "acquisition errors release the descriptors and the gate" { } } +test "a blocking record lock records EAGAIN and EACCES" { + const root = begin(); + defer end(root); + const Hooks = struct { + var code: linux.E = .AGAIN; + fn fail(_: fsx.fd_t, _: i32, _: usize) usize { + return err(code); + } + }; + defer state.lock_ops.* = .{}; + state.lock_ops.fcntl = Hooks.fail; + for ([_]linux.E{ .AGAIN, .ACCES }) |code| { + Hooks.code = code; + sys.last_errno = .SUCCESS; + if (RootLock.acquire(A, root, null)) |_| { + return error.TestUnexpectedResult; + } else |failed| { + const failure = state.osFailure() orelse return error.TestUnexpectedResult; + try testing.expectEqualStrings("", failure.path); + try testing.expectEqualStrings(sys.describeErrno(code), failure.text); + try testing.expectEqual(code, sys.last_errno); + // describe of the returned error must name this errno. Returning + // Unexpected for EACCES makes it print an I/O error instead. + const sys_err = sys.asError(failed) orelse return error.TestUnexpectedResult; + try testing.expectEqualStrings(failure.text, sys.describe(sys_err)); + switch (code) { + .AGAIN => try testing.expectEqual(error.Unexpected, sys_err), + .ACCES => try testing.expectEqual(error.AccessDenied, sys_err), + else => unreachable, + } + } + } +} + test "a short pid write does not reuse a stale errno" { const root = begin(); defer end(root); diff --git a/tests/fs_lock_parity_probe.zig b/tests/fs_lock_parity_probe.zig index c4e1f9e..0890e26 100644 --- a/tests/fs_lock_parity_probe.zig +++ b/tests/fs_lock_parity_probe.zig @@ -17,6 +17,12 @@ //! short timeout, printing the outcome. The test holds the lock. //! - `hold-lock PATH MS`: takes the lock with no timeout, prints //! `held`, sleeps MS and exits, releasing the lock as it goes. +//! - `osfail`: atomicWrite failures. The last field is the full +//! `why.msg`, compared with str() of the OSError Python raises for +//! the same call. +//! - `rootlock`: RootLock.acquire failures. The last two fields are +//! osFailure text and path, or NONE when the failure was not an +//! operating-system error. const std = @import("std"); const linux = std.os.linux; const common = @import("zig_common"); @@ -175,7 +181,13 @@ 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)); + const result = common.atomic.atomicWrite(A, c.name, c.data, c.opts, &why); + if (result) |_| { + emit(&.{ "atomicwrite", hexOf(c.name), "OK", hexOf(why.msg) }); + } else |e| { + const status = std.fmt.allocPrint(A, "ERR:{s}", .{errName(e)}) catch unreachable; + emit(&.{ "atomicwrite", hexOf(c.name), status, hexOf(why.msg) }); + } why.deinit(A); } const rc_cases = [_]struct { name: []const u8, data: []const u8 }{ @@ -199,6 +211,142 @@ fn atomicMode() void { } } +/// One atomicWrite, including the full failure text. `why.msg` is copied +/// into the output before it is freed. +fn writeFail(name: []const u8, path: []const u8, data: []const u8, opts: common.atomic.WriteOptions) void { + var why: common.atomic.Why = .{}; + const result = common.atomic.atomicWrite(A, path, data, opts, &why); + const status = if (result) |_| + "OK" + else |e| + std.fmt.allocPrint(A, "ERR:{s}", .{@errorName(e)}) catch unreachable; + emit(&.{ "osfail", name, status, hexOf(why.msg) }); + why.deinit(A); +} + +/// A write that the file-size limit stops. Python's os.write names no +/// file for that OSError, and neither does atomicWrite. A flush of a +/// regular file cannot be made to fail from this process, so the write +/// is the no-filename failure the probe can raise. +fn writeTooBig() void { + var old: linux.rlimit = undefined; + if (linux.errno(linux.prlimit(0, .FSIZE, null, &old)) != .SUCCESS) { + emit(&.{ "osfail", "write-fsize", "SKIP", "" }); + return; + } + const unlimited = std.math.maxInt(u64); + const room: u64 = if (old.max == unlimited) 8 else old.max; + if (room < 8) { + emit(&.{ "osfail", "write-fsize", "SKIP", "" }); + return; + } + const ign: linux.Sigaction = .{ .handler = .{ .handler = linux.SIG.IGN }, .mask = linux.sigemptyset(), .flags = 0 }; + var prev: linux.Sigaction = undefined; + _ = linux.sigaction(.XFSZ, &ign, &prev); + defer _ = linux.sigaction(.XFSZ, &prev, null); + const lim: linux.rlimit = .{ .cur = 8, .max = old.max }; + if (linux.errno(linux.prlimit(0, .FSIZE, &lim, null)) != .SUCCESS) { + emit(&.{ "osfail", "write-fsize", "SKIP", "" }); + return; + } + defer _ = linux.prlimit(0, .FSIZE, &old, null); + var payload: [64]u8 = @splat('x'); + writeFail("write-fsize", "fsize-out", &payload, .{}); +} + +fn chmodAt(path: []const u8, mode: linux.mode_t) void { + var zb: [sys.path_max:0]u8 = undefined; + const z = sys.z(&zb, path) catch unreachable; + if (linux.errno(linux.fchmodat(fsx.cwd, z.ptr, mode)) != .SUCCESS) unreachable; +} + +/// `osfail` mode: real atomicWrite failures whose text is Python's +/// OSError for the same operation. The fixture is created here, in the +/// working directory, and any directory made unwritable is restored +/// before returning so the caller can remove the tree. +fn osFailMode() void { + var zb: [sys.path_max:0]u8 = undefined; + _ = linux.mkdirat(fsx.cwd, (sys.z(&zb, "ro") catch unreachable).ptr, 0o755); + if (linux.geteuid() == 0) { + emit(&.{ "osfail", "open-ro", "SKIP", "" }); + emit(&.{ "osfail", "mkdir-ro", "SKIP", "" }); + } else { + chmodAt("ro", 0o555); + defer chmodAt("ro", 0o755); + // open of the temporary file, which Python names rather than the + // destination + writeFail("open-ro", "ro/new", "x\n", .{}); + // mkdir of the first missing ancestor, not the leaf that was asked for + writeFail("mkdir-ro", "ro/a/b/file", "x\n", .{}); + } + + _ = linux.mkdirat(fsx.cwd, (sys.z(&zb, "adir") catch unreachable).ptr, 0o755); + const meta = sys.openat(fsx.cwd, "meta", .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true }, 0o644) catch unreachable; + sys.writeAll(meta, "m\n") catch unreachable; + sys.close(meta); + // metadata comes from a regular file, so the directory at the + // destination is reached by rename rather than refused as a source + writeFail("rename-dir", "adir", "data\n", .{ .metadata_from = "meta" }); + + _ = linux.symlinkat("nowhere", fsx.cwd, (sys.z(&zb, "gone") catch unreachable).ptr); + writeFail("missing-ancestor", "gone/a/b/file", "x\n", .{}); + writeTooBig(); +} + +fn lockCase(name: []const u8, root: []const u8) void { + if (state.RootLock.acquire(A, root, 0)) |held| { + held.release(); + emit(&.{ "rootlock", name, "OK", "", "" }); + } else |e| { + const status = std.fmt.allocPrint(A, "ERR:{s}", .{@errorName(e)}) catch unreachable; + if (state.osFailure()) |failure| { + emit(&.{ "rootlock", name, status, hexOf(failure.text), hexOf(failure.path) }); + } else { + emit(&.{ "rootlock", name, status, "NONE", "NONE" }); + } + } +} + +/// `rootlock` mode: RootLock.acquire failures. Text and path are the +/// osFailure snapshot; NONE means the failure was not an OS error and +/// the snapshot was cleared. +fn rootLockMode() void { + var zb: [sys.path_max:0]u8 = undefined; + const file = sys.openat(fsx.cwd, "fileroot", .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true }, 0o644) catch unreachable; + sys.close(file); + lockCase("file-root", "fileroot"); + + _ = linux.symlinkat("nowhere", fsx.cwd, (sys.z(&zb, "dangling") catch unreachable).ptr); + lockCase("dangling-root", "dangling"); + + _ = linux.symlinkat("nowhere", fsx.cwd, (sys.z(&zb, "gone") catch unreachable).ptr); + lockCase("ancestor", "gone/a/b"); + + if (linux.geteuid() == 0) { + emit(&.{ "rootlock", "gate-ro", "SKIP", "", "" }); + emit(&.{ "rootlock", "sidecar-ro", "SKIP", "", "" }); + } else { + _ = linux.mkdirat(fsx.cwd, (sys.z(&zb, "gate") catch unreachable).ptr, 0o755); + chmodAt("gate", 0o555); + defer chmodAt("gate", 0o755); + lockCase("gate-ro", "gate"); + + _ = linux.mkdirat(fsx.cwd, (sys.z(&zb, "side") catch unreachable).ptr, 0o755); + const side = sys.openat(fsx.cwd, "side/.lock", .{ .ACCMODE = .RDWR, .CREAT = true, .EXCL = true }, 0o600) catch unreachable; + sys.close(side); + chmodAt("side", 0o555); + defer chmodAt("side", 0o755); + lockCase("sidecar-ro", "side"); + } + + // a directory planted at the gate is refused without an OSError, and + // only after the cases above have recorded one, so a stale snapshot + // would show up here + _ = linux.mkdirat(fsx.cwd, (sys.z(&zb, "gatedir") catch unreachable).ptr, 0o755); + _ = linux.mkdirat(fsx.cwd, (sys.z(&zb, "gatedir/.lock") catch unreachable).ptr, 0o755); + lockCase("gate-dir", "gatedir"); +} + /// `which` mode: whichShutil over a PATH fixture the test built around /// the probe's working directory, plus the unset-PATH cases. fn whichMode() void { @@ -881,6 +1029,10 @@ pub fn main(init: std.process.Init.Minimal) !void { effectsMode(); } else if (std.mem.eql(u8, mode, "atomic")) { atomicMode(); + } else if (std.mem.eql(u8, mode, "osfail")) { + osFailMode(); + } else if (std.mem.eql(u8, mode, "rootlock")) { + rootLockMode(); } else if (std.mem.eql(u8, mode, "which")) { whichMode(); } else if (std.mem.eql(u8, mode, "diag")) { diff --git a/tests/test_fs_lock_parity.py b/tests/test_fs_lock_parity.py index a30571b..fd5950d 100644 --- a/tests/test_fs_lock_parity.py +++ b/tests/test_fs_lock_parity.py @@ -8,7 +8,9 @@ once through the Python reference calls on an identical one, and the two trees plus the surfaced errnos are compared; realpath is compared with os.path.realpath(strict=True); flock exclusive and try semantics -are exercised in both directions with fcntl.flock. +are exercised in both directions with fcntl.flock. Atomic-write and +state-lock failures are compared with str() of the OSError the same +operation raises. Run with `python3 tests/test_fs_lock_parity.py` from a checkout that has the probe built; the test builds it when zig is on PATH and the binary @@ -19,7 +21,9 @@ import gzip import json import os +import resource import shutil +import signal import stat import subprocess import sys @@ -278,6 +282,81 @@ def py_replace_contents(root, name, data): return "ERR:" + BY_ERRNO.get(exc.errno, "Errno%d" % exc.errno) +def zig_temp_for(path): + """The temporary name atomicWrite uses beside `path`.""" + parent = os.path.dirname(path) + if parent == "": + parent = "." + return parent + "/." + os.path.basename(path) + ".new" + + +def _in_dir(root, fn): + old = os.getcwd() + os.chdir(root) + try: + return fn() + finally: + os.chdir(old) + + +def _relax(root): + """Let a temporary tree be removed after a mode-0555 case.""" + for dirpath, dirnames, _ in os.walk(root): + for name in dirnames: + path = os.path.join(dirpath, name) + try: + os.chmod(path, 0o755) + except OSError: + pass + + +def track(test, root): + """Remove `root` after restoring directory modes. + + Cleanup runs last in, first out. rmtree is registered first so the + mode restore runs before it. The other order deletes a mode-0555 + directory first and leaves the tree behind. + """ + test.addCleanup(shutil.rmtree, root, ignore_errors=True) + test.addCleanup(_relax, root) + + +def fresh_dir(): + root = tempfile.mkdtemp() + return root + + +def run_oserror(fn): + """str() of the OSError `fn` raises, and the exception itself.""" + try: + fn() + except OSError as exc: + return str(exc), exc + raise AssertionError("the reference operation succeeded") + + +# zig's sys.Error name for the errno of a real OSError. EFBIG is not one +# of the named errors and surfaces as Unexpected, as the copy tests do. +ZIG_ERR = { + errno.EACCES: "AccessDenied", + errno.EPERM: "AccessDenied", + errno.ENOENT: "NotFound", + errno.ENOTDIR: "NotDir", + errno.EISDIR: "IsDir", + errno.EEXIST: "Exists", + errno.EFBIG: "Unexpected", + errno.ENOSPC: "NoSpace", + errno.EROFS: "ReadOnly", +} + + +def rendered_oserror(text, path): + """str(OSError) from the text and path osFailure keeps apart.""" + if path == "": + return text + return text + ": " + repr(path) + + def py_append_line(root, name, line): """The documented appendLine behavior: one appended line, a symlink or non-regular target refused, a new file 0666 less the umask.""" @@ -495,8 +574,9 @@ def test_effects(self): def test_atomic_replace_append(self): probe_root = tempfile.mkdtemp() python_root = tempfile.mkdtemp() - self.addCleanup(shutil.rmtree, probe_root, ignore_errors=True) - self.addCleanup(shutil.rmtree, python_root, ignore_errors=True) + # The fixture leaves ro/ at mode 0555. Restore that before rmtree. + track(self, probe_root) + track(self, python_root) make_atomic_fixture(python_root) make_atomic_fixture(probe_root) @@ -520,14 +600,282 @@ def test_atomic_replace_append(self): want.append(("appendline", "ro/ap-new", py_append_line(python_root, "ro/ap-new", "x"))) want.append(("appendline", "ap-fifo", py_append_line(python_root, "ap-fifo", "x"))) - for (g_op, g_arg, g_res), (w_op, w_name, w_res) in zip(got, want): + for parts, (w_op, w_name, w_res) in zip(got, want): + g_op, g_arg, g_res = parts[0], parts[1], parts[2] self.assertEqual(g_op, w_op) self.assertEqual(bytes.fromhex(g_arg), enc(w_name)) self.assertEqual(g_res, w_res, "%s %s" % (w_op, w_name)) + if w_op == "atomicwrite" and w_name == "ro/aw-new" and g_res != "OK": + got_msg = bytes.fromhex(parts[3]).decode("utf-8", "surrogateescape") + ref = fresh_dir() + track(self, ref) + + def open_temp(): + os.mkdir("ro", 0o755) + os.chmod("ro", 0o555) + os.open( + zig_temp_for("ro/aw-new"), + os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, + 0o600, + ) + + want_msg, _ = _in_dir(ref, lambda: run_oserror(open_temp)) + self.assertEqual(got_msg, want_msg, "atomic write names the temporary file") # the two trees must agree, mode bits under the umask included self.assert_trees_equal(probe_root, python_root) + def _osfail(self): + root = fresh_dir() + track(self, root) + out = run_probe("osfail", cwd=root) + cases = {} + for line in out.splitlines(): + parts = line.split("\t") + self.assertEqual(parts[0], "osfail") + cases[parts[1]] = parts + return cases + + def _rootlock(self): + root = fresh_dir() + track(self, root) + out = run_probe("rootlock", cwd=root) + cases = {} + for line in out.splitlines(): + parts = line.split("\t") + self.assertEqual(parts[0], "rootlock") + cases[parts[1]] = parts + return cases + + def _assert_osfail(self, name, reference): + parts = self._osfail()[name] + if parts[2] == "SKIP": + # open-ro and mkdir-ro skip only when this process is root. + # write-fsize skips when RLIMIT_FSIZE cannot be lowered. + if name in ("open-ro", "mkdir-ro"): + self.assertEqual(os.geteuid(), 0) + return + want, exc = reference() + self.assertEqual(parts[2], "ERR:" + ZIG_ERR[exc.errno], name) + got = bytes.fromhex(parts[3]).decode("utf-8", "surrogateescape") + self.assertEqual(got, want, name) + + def _assert_rootlock(self, name, reference): + parts = self._rootlock()[name] + if parts[2] == "SKIP": + self.assertEqual(os.geteuid(), 0) + return + want, exc = reference() + self.assertEqual(parts[2], "ERR:" + ZIG_ERR[exc.errno], name) + self.assertNotEqual(parts[3], "NONE", name) + text = bytes.fromhex(parts[3]).decode("utf-8", "surrogateescape") + path = bytes.fromhex(parts[4]).decode("utf-8", "surrogateescape") + self.assertEqual(rendered_oserror(text, path), want, name) + filename = "" if exc.filename is None else os.fsdecode(exc.filename) + self.assertEqual(path, filename, name) + + def test_open_names_the_temporary_file(self): + """A failed open names the temporary file, as os.open does.""" + + def reference(): + root = fresh_dir() + track(self, root) + + def op(): + os.mkdir("ro", 0o755) + os.chmod("ro", 0o555) + os.open( + zig_temp_for("ro/new"), + os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, + 0o600, + ) + + return _in_dir(root, lambda: run_oserror(op)) + + self._assert_osfail("open-ro", reference) + + def test_write_names_no_file(self): + """A failed write names no file, as os.write on the descriptor does.""" + + def reference(): + root = fresh_dir() + self.addCleanup(shutil.rmtree, root, ignore_errors=True) + + def op(): + previous = signal.signal(signal.SIGXFSZ, signal.SIG_IGN) + soft, hard = resource.getrlimit(resource.RLIMIT_FSIZE) + fd = None + try: + resource.setrlimit(resource.RLIMIT_FSIZE, (8, hard)) + fd = os.open( + "fsize-out", + os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, + 0o600, + ) + data = b"x" * 64 + off = 0 + while off < len(data): + n = os.write(fd, data[off:]) + if n == 0: + raise OSError(errno.ENOSPC, os.strerror(errno.ENOSPC)) + off += n + finally: + if fd is not None: + os.close(fd) + resource.setrlimit(resource.RLIMIT_FSIZE, (soft, hard)) + signal.signal(signal.SIGXFSZ, previous) + + return _in_dir(root, lambda: run_oserror(op)) + + self._assert_osfail("write-fsize", reference) + + def test_rename_names_both_files(self): + """A failed rename names the temporary file and the destination.""" + + def reference(): + root = fresh_dir() + self.addCleanup(shutil.rmtree, root, ignore_errors=True) + + def op(): + os.mkdir("adir", 0o755) + fd = os.open("./.adir.new", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644) + os.close(fd) + os.replace("./.adir.new", "adir") + + return _in_dir(root, lambda: run_oserror(op)) + + self._assert_osfail("rename-dir", reference) + + def test_makedirs_names_the_failing_ancestor(self): + """A missing parent names the mkdir that failed, not the leaf.""" + + def reference(): + root = fresh_dir() + self.addCleanup(shutil.rmtree, root, ignore_errors=True) + + def op(): + os.symlink("nowhere", "gone") + os.makedirs("gone/a/b", exist_ok=True) + + return _in_dir(root, lambda: run_oserror(op)) + + self._assert_osfail("missing-ancestor", reference) + + def test_mkdir_permission_names_the_failing_ancestor(self): + """A refused mkdir names that ancestor, not the requested leaf.""" + + def reference(): + root = fresh_dir() + track(self, root) + + def op(): + os.mkdir("ro", 0o755) + os.chmod("ro", 0o555) + os.makedirs("ro/a/b", exist_ok=True) + + return _in_dir(root, lambda: run_oserror(op)) + + self._assert_osfail("mkdir-ro", reference) + + def test_rootlock_preflight_matches_oserror(self): + """A non-directory state root matches open(O_DIRECTORY).""" + + def reference(): + root = fresh_dir() + self.addCleanup(shutil.rmtree, root, ignore_errors=True) + + def op(): + fd = os.open("fileroot", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644) + os.close(fd) + os.open("fileroot", os.O_RDONLY | os.O_DIRECTORY) + + return _in_dir(root, lambda: run_oserror(op)) + + self._assert_rootlock("file-root", reference) + + def test_rootlock_dangling_root_matches_oserror(self): + """A dangling state root matches open of that link as a directory.""" + + def reference(): + root = fresh_dir() + self.addCleanup(shutil.rmtree, root, ignore_errors=True) + + def op(): + os.symlink("nowhere", "dangling") + os.open("dangling", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + + return _in_dir(root, lambda: run_oserror(op)) + + self._assert_rootlock("dangling-root", reference) + + def test_rootlock_names_the_failing_ancestor(self): + """Creating a state root names the mkdir that failed.""" + + def reference(): + root = fresh_dir() + self.addCleanup(shutil.rmtree, root, ignore_errors=True) + + def op(): + os.symlink("nowhere", "gone") + os.makedirs("gone/a/b", exist_ok=True) + + return _in_dir(root, lambda: run_oserror(op)) + + self._assert_rootlock("ancestor", reference) + + def test_rootlock_gate_names_the_lock_file(self): + """A refused gate open names STATE_ROOT/.lock, not the root alone.""" + + def reference(): + root = fresh_dir() + track(self, root) + + def op(): + os.mkdir("gate", 0o755) + os.chmod("gate", 0o555) + os.open( + "gate/.lock", + os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, + 0o600, + ) + + return _in_dir(root, lambda: run_oserror(op)) + + self._assert_rootlock("gate-ro", reference) + + def test_rootlock_sidecar_names_the_lock_file(self): + """A refused sidecar open names STATE_ROOT/.lock.posix.""" + + def reference(): + root = fresh_dir() + track(self, root) + + def op(): + os.mkdir("side", 0o755) + fd = os.open( + "side/.lock", + os.O_RDWR | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, + 0o600, + ) + os.close(fd) + os.chmod("side", 0o555) + os.open( + "side/.lock.posix", + os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, + 0o600, + ) + + return _in_dir(root, lambda: run_oserror(op)) + + self._assert_rootlock("sidecar-ro", reference) + + def test_rootlock_non_os_refusal_has_no_oserror(self): + """A directory planted at the gate is not reported as an OSError.""" + parts = self._rootlock()["gate-dir"] + self.assertEqual(parts[2], "ERR:GateNotPrivate") + self.assertEqual(parts[3], "NONE") + self.assertEqual(parts[4], "NONE") + def test_which_shutil(self): with tempfile.TemporaryDirectory() as probe_root, tempfile.TemporaryDirectory() as python_root: make_which_fixture(probe_root)