diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 188285d..1f7c98a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,6 +56,11 @@ jobs: fi zig build tempdir-probe python3 tests/test_gettempdir_parity.py + - name: parity with python 3.14 argparse calls + run: | + python3 -c "import sys; assert sys.version_info >= (3, 14), 'argparse parity needs Python 3.14+; found ' + sys.version.split()[0]" + zig build argparse-parity-probe + python3 tests/test_argparse_parity.py - name: no site names in the tree run: | ! git grep -nIiE 'snellius|surf\.nl|/gpfs/|/projects/0|rg\.terra|scratch-shared' -- . ':!.github/workflows/ci.yml' diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 6814f15..94cd73b 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -7,7 +7,7 @@ name: docs on: push: - branches: [main] + branches: [main, develop] pull_request: workflow_dispatch: schedule: diff --git a/CHANGELOG.md b/CHANGELOG.md index eb81c68..c42ade8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,82 @@ +## 0.12.0 (2026-11-19) + +### Features + +- `syslog`: `Identity` names the program and the structured-data identifier of an event; `formatRfc5424For`, `formatJournaldFor` and `emitFor` take one, and `send` delivers an already formatted payload, for a tool with formatting of its own. The functions without an identity keep writing `eb-keep-logs`, as 0.11.0 did, and are removed in 0.13.0. + +### Miscellaneous + +- Prepare `zig-common` `0.12.0` in `COMPAT.md` for callers adopting `syslog.Identity` and `syslog.send`. + + +## 0.11.0 (2026-11-19) + +### Features + +- Add `pytext.osError` and `pytext.osErrorErrno` for Python-formatted `OSError` path messages. +- Add `pytext.reprStr` and `pytext.reprStrAlloc` for Python-compatible surrogateescape string quoting. +- Add `state.lockExclusiveCancel` supporting atomic cancellation while polling `flock`. +- Add `sys.strerror` returning `errnoText(e)` or the enum tag name fallback. +- `json.writeCacheStringTo` writes cache-style JSON strings to a writer without allocation. +- `proc.resolveExecutable` resolves executable names to absolute executable regular-file paths from slash paths or PATH lookup with a null-PATH default of `/bin:/usr/bin`. +- `proc.whichShutil` adds an opt-in executable lookup mode that matches POSIX `shutil.which` behavior. +- `syslog`: the RFC 5424 and systemd-journald event emitter that eb-keep-logs and eessi-arch-guard each carried a copy of: `Target`, `parseTarget`, `parsePen`, `formatRfc5424`, `formatJournald` and `emit`. + +### Fixes + +- Decode UTF-8 keys, UTF-16 surrogate pairs, and surrogateescape cache bytes in `json.Value.get` so escaped non-ASCII keys match like `json.loads`. +- Fix `sys.strerror` to avoid panicking on unnamed `linux.E` values by using `std.enums.tagName` with an `"Unknown error N"` fallback. +- `fsx.appendLine` reports `not a regular file` for an existing non-regular target such as a FIFO. +- `fsx.moveAcross` reports `error.NotRegularFile` when EXDEV fallback copies a tree entry that none of the earlier copy branches handle. +- `fsx.moveAcross` reports `not a regular file` for a FIFO source that takes the EXDEV copy fallback. +- `fsx.openRegular` now reports `error.NotRegularFile` for FIFOs, sockets, and device nodes, and `sys.describe` renders that as `not a regular file` instead of `[Errno 22] Invalid argument`. +- `fsx.openRegular` now returns `error.IsDir` for directory paths, so `sys.describe` reports `[Errno 21] Is a directory` instead of `[Errno 22] Invalid argument` for that case. + +### Documentation + +- List every public function and error set including PR #24 shared helpers in `docs/orgmode/reference/api.org`. + +### Miscellaneous + +- Add `atomic.Ops` fault hooks and unit tests covering `atomicWrite` failures on `ENOSPC`, `EROFS`, and `EXDEV`, as well as `makedirs` and `fsyncDir` error paths. +- Add unit tests covering `gzipInPlace` error paths (missing file, directory, symlink, hard link, and existing `.gz` archive) in `src/logs.zig`. +- Add unit tests covering `sys.errnoText` for unknown errno values and error paths for `sys` syscall wrappers. +- Add unit tests covering error and boundary paths for `which`, `groupAlive`, `killGroup`, `stopGroup`, and `run` in `src/proc.zig`. +- Add unit tests covering error paths for public file and directory helpers in `src/fsx.zig`. +- Add unit tests verifying `cli.put` and `cli.print` ignore descriptor write errors and checking `cli.versionLine` formatting. +- Prepare `zig-common` `0.11.0` in `COMPAT.md` for callers adopting `syslog`. A release is now `cog bump` on a release branch: `cog.toml` sets the version in `build.zig.zon` and refuses a version without a `COMPAT.md` row. +- Proc resolver tests share one executable fixture helper for scratch script and plain file setup. +- Route `lockExclusiveCancel` through `state.lock_ops.flock` and add unit tests covering `lockExclusive` with timeout 0, bounded timeout, unsupported `flock`, and private state file error paths. +- The private `proc.isExecutableFile` helper holds the executable regular-file probe that `proc.which` runs for each PATH candidate. +- `json.writeWireString` writes each string through one writer and the shared escape code. +- `proc.resolveExecutable` tests cover relative slash paths for executable and non-executable files. +- `proc.which` tests cover executable resolution and null returns for non-executable candidates. +- `proc.which` uses one internal options-driven search loop for executable path matching. +- `proc` test fixtures clean up scratch directories when setup fails after partial creation. + + +## 0.10.0 (2026-11-18) + +### Features + +- Add `fsx.mkdtemp` to create a private `0700` directory with a random suffix under a given parent directory and retry on name collisions. +- Add `fsx.normPath` and `fsx.absPath` to normalize and absolutize POSIX paths without following symbolic links. +- `fsx.moveAcross` adds a durable cross-filesystem move primitive: it tries `rename` first, falls back on EXDEV to a destination-side temporary copy, publishes with an atomic rename, and removes the source only after publish. The new `fsx.MoveAcrossOptions` policy is opt-in, with `strict` for ACL-preserving copies and `portable` for ACL downgrade when destination filesystems do not represent the source ACL form. + +### Documentation + +- Every `pub` declaration has a doc comment, whose first sentence is the summary the API pages list. +- The documentation site is built from Org pages in `docs/orgmode/` with Sphinx, in four parts: the tutorial "Write a small tool on zig-common", how-to guides, explanation and reference. Each module's API page is generated from its doc comments, and the site publishes an `objects.inv` of every `pub` declaration for the tools' sites to link into. `pixi run -e docs docbld` builds it as CI does and fails on a warning, an unresolved name or a dead internal link; `pixi run -e docs linkcheck` checks the external links. The `docs` workflow publishes the site to GitHub Pages; `docs/requirements.txt` and `pages.yml` are gone. +- The site has how-to guides for replacing a file and keeping its access control lists, keeping private state in `/tmp`, compressing logs that `.licensed-logs` marks, matching a Python tool's output and upgrading zig-common; explanations of process groups and deadlines, system calls without a C library, and Python compatibility; and a reference of the messages, exit statuses and version line that `cli` gives the tools. + +### Miscellaneous + +- Prepare `zig-common` `0.10.0` in `build.zig.zon` and `COMPAT.md` for callers adopting `fsx.mkdtemp` plus `fsx.normPath` and `fsx.absPath`. + + ## 0.9.0 (2026-11-16) ### Features diff --git a/changelog.d/+append-line-fifo-text.bugfix.md b/changelog.d/+append-line-fifo-text.bugfix.md deleted file mode 100644 index 7196917..0000000 --- a/changelog.d/+append-line-fifo-text.bugfix.md +++ /dev/null @@ -1 +0,0 @@ -`fsx.appendLine` reports `not a regular file` for an existing non-regular target such as a FIFO. 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-error-tests.misc.md b/changelog.d/+atomic-write-error-tests.misc.md deleted file mode 100644 index a163b29..0000000 --- a/changelog.d/+atomic-write-error-tests.misc.md +++ /dev/null @@ -1 +0,0 @@ -Add `atomic.Ops` fault hooks and unit tests covering `atomicWrite` failures on `ENOSPC`, `EROFS`, and `EXDEV`, as well as `makedirs` and `fsyncDir` error paths. 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/+ci-argparse-parity.misc.md b/changelog.d/+ci-argparse-parity.misc.md new file mode 100644 index 0000000..8064d04 --- /dev/null +++ b/changelog.d/+ci-argparse-parity.misc.md @@ -0,0 +1 @@ +The CI runs the argparse parity suite under Python 3.14 next to the JSON, filesystem and `tempfile.gettempdir` suites, guarded by a Python 3.14+ version check. diff --git a/changelog.d/+cli-checked-stdout.feature.md b/changelog.d/+cli-checked-stdout.feature.md new file mode 100644 index 0000000..4dd9784 --- /dev/null +++ b/changelog.d/+cli-checked-stdout.feature.md @@ -0,0 +1 @@ +Add `cli.Stdout` and `cli.writeOut` for checked standard-output writes that report the first write error on standard error and turn a zero exit status into `1`. diff --git a/changelog.d/+cli-write-errors-test.misc.md b/changelog.d/+cli-write-errors-test.misc.md deleted file mode 100644 index 7759594..0000000 --- a/changelog.d/+cli-write-errors-test.misc.md +++ /dev/null @@ -1 +0,0 @@ -Add unit tests verifying `cli.put` and `cli.print` ignore descriptor write errors and checking `cli.versionLine` formatting. diff --git a/changelog.d/+doc-comments.doc.md b/changelog.d/+doc-comments.doc.md deleted file mode 100644 index 4636ddf..0000000 --- a/changelog.d/+doc-comments.doc.md +++ /dev/null @@ -1 +0,0 @@ -Every `pub` declaration has a doc comment, whose first sentence is the summary the API pages list. diff --git a/changelog.d/+docs-pages.doc.md b/changelog.d/+docs-pages.doc.md deleted file mode 100644 index 987695c..0000000 --- a/changelog.d/+docs-pages.doc.md +++ /dev/null @@ -1 +0,0 @@ -The site has how-to guides for replacing a file and keeping its access control lists, keeping private state in `/tmp`, compressing logs that `.licensed-logs` marks, matching a Python tool's output and upgrading zig-common; explanations of process groups and deadlines, system calls without a C library, and Python compatibility; and a reference of the messages, exit statuses and version line that `cli` gives the tools. diff --git a/changelog.d/+docs-site.doc.md b/changelog.d/+docs-site.doc.md deleted file mode 100644 index 9c048c0..0000000 --- a/changelog.d/+docs-site.doc.md +++ /dev/null @@ -1 +0,0 @@ -The documentation site is built from Org pages in `docs/orgmode/` with Sphinx, in four parts: the tutorial "Write a small tool on zig-common", how-to guides, explanation and reference. Each module's API page is generated from its doc comments, and the site publishes an `objects.inv` of every `pub` declaration for the tools' sites to link into. `pixi run -e docs docbld` builds it as CI does and fails on a warning, an unresolved name or a dead internal link; `pixi run -e docs linkcheck` checks the external links. The `docs` workflow publishes the site to GitHub Pages; `docs/requirements.txt` and `pages.yml` are gone. diff --git a/changelog.d/+fsx-error-paths-test.misc.md b/changelog.d/+fsx-error-paths-test.misc.md deleted file mode 100644 index 2a927cf..0000000 --- a/changelog.d/+fsx-error-paths-test.misc.md +++ /dev/null @@ -1 +0,0 @@ -Add unit tests covering error paths for public file and directory helpers in `src/fsx.zig`. diff --git a/changelog.d/+fsx-mkdtemp.feature.md b/changelog.d/+fsx-mkdtemp.feature.md deleted file mode 100644 index bd11c7e..0000000 --- a/changelog.d/+fsx-mkdtemp.feature.md +++ /dev/null @@ -1 +0,0 @@ -Add `fsx.mkdtemp` to create a private `0700` directory with a random suffix under a given parent directory and retry on name collisions. diff --git a/changelog.d/+fsx-normpath.feature.md b/changelog.d/+fsx-normpath.feature.md deleted file mode 100644 index 76e0848..0000000 --- a/changelog.d/+fsx-normpath.feature.md +++ /dev/null @@ -1 +0,0 @@ -Add `fsx.normPath` and `fsx.absPath` to normalize and absolutize POSIX paths without following symbolic links. diff --git a/changelog.d/+gzip-long-name-tmp-overflow.bugfix.md b/changelog.d/+gzip-long-name-tmp-overflow.bugfix.md new file mode 100644 index 0000000..b1e1427 --- /dev/null +++ b/changelog.d/+gzip-long-name-tmp-overflow.bugfix.md @@ -0,0 +1,7 @@ +`gzipInPlace` refused to compress a log whose name, well within the +reference compressor's own limit, no longer fit a filesystem's 255-byte +limit on one path component once its temporary file's pid and random +suffix were added on. That suffix alone already makes the temporary +name unique, so the original name is left off a temporary name that +would otherwise overflow, and a name that reference tool would have +compressed compresses here too. diff --git a/changelog.d/+json-value-get-utf8.bugfix.md b/changelog.d/+json-value-get-utf8.bugfix.md deleted file mode 100644 index 4b41829..0000000 --- a/changelog.d/+json-value-get-utf8.bugfix.md +++ /dev/null @@ -1 +0,0 @@ -Decode UTF-8 keys, UTF-16 surrogate pairs, and surrogateescape cache bytes in `json.Value.get` so escaped non-ASCII keys match like `json.loads`. diff --git a/changelog.d/+json-write-cache-string-to.feature.md b/changelog.d/+json-write-cache-string-to.feature.md deleted file mode 100644 index 3d3f8be..0000000 --- a/changelog.d/+json-write-cache-string-to.feature.md +++ /dev/null @@ -1 +0,0 @@ -`json.writeCacheStringTo` writes cache-style JSON strings to a writer without allocation. diff --git a/changelog.d/+json-write-wire-shared-writer.misc.md b/changelog.d/+json-write-wire-shared-writer.misc.md deleted file mode 100644 index a9e9250..0000000 --- a/changelog.d/+json-write-wire-shared-writer.misc.md +++ /dev/null @@ -1 +0,0 @@ -`json.writeWireString` writes each string through one writer and the shared escape code. 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/+logs-error-tests.misc.md b/changelog.d/+logs-error-tests.misc.md deleted file mode 100644 index eb25516..0000000 --- a/changelog.d/+logs-error-tests.misc.md +++ /dev/null @@ -1 +0,0 @@ -Add unit tests covering `gzipInPlace` error paths (missing file, directory, symlink, hard link, and existing `.gz` archive) in `src/logs.zig`. 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/+move-across-fifo-source-text.bugfix.md b/changelog.d/+move-across-fifo-source-text.bugfix.md deleted file mode 100644 index 0d29ba3..0000000 --- a/changelog.d/+move-across-fifo-source-text.bugfix.md +++ /dev/null @@ -1 +0,0 @@ -`fsx.moveAcross` reports `not a regular file` for a FIFO source that takes the EXDEV copy fallback. diff --git a/changelog.d/+move-across.feature.md b/changelog.d/+move-across.feature.md deleted file mode 100644 index c49aff8..0000000 --- a/changelog.d/+move-across.feature.md +++ /dev/null @@ -1 +0,0 @@ -`fsx.moveAcross` adds a durable cross-filesystem move primitive: it tries `rename` first, falls back on EXDEV to a destination-side temporary copy, publishes with an atomic rename, and removes the source only after publish. The new `fsx.MoveAcrossOptions` policy is opt-in, with `strict` for ACL-preserving copies and `portable` for ACL downgrade when destination filesystems do not represent the source ACL form. diff --git a/changelog.d/+move-tree-special-entry-diagnostic.bugfix.md b/changelog.d/+move-tree-special-entry-diagnostic.bugfix.md deleted file mode 100644 index fd34662..0000000 --- a/changelog.d/+move-tree-special-entry-diagnostic.bugfix.md +++ /dev/null @@ -1 +0,0 @@ -`fsx.moveAcross` reports `error.NotRegularFile` when EXDEV fallback copies a tree entry that none of the earlier copy branches handle. diff --git a/changelog.d/+moveacross-call-trace.misc.md b/changelog.d/+moveacross-call-trace.misc.md new file mode 100644 index 0000000..07c4714 --- /dev/null +++ b/changelog.d/+moveacross-call-trace.misc.md @@ -0,0 +1 @@ +`fsx` unit tests trace the renames and directory syncs that `moveAcross` makes. diff --git a/changelog.d/+moveacross-nested-target-parent.bugfix.md b/changelog.d/+moveacross-nested-target-parent.bugfix.md new file mode 100644 index 0000000..5706237 --- /dev/null +++ b/changelog.d/+moveacross-nested-target-parent.bugfix.md @@ -0,0 +1 @@ +`fsx.moveAcross` syncs the destination parent directory for nested targets. diff --git a/changelog.d/+moveacross-source-parent.bugfix.md b/changelog.d/+moveacross-source-parent.bugfix.md new file mode 100644 index 0000000..fc21013 --- /dev/null +++ b/changelog.d/+moveacross-source-parent.bugfix.md @@ -0,0 +1 @@ +`fsx.moveAcross` syncs the parent directory of the source name, also when one descriptor holds both names and the destination is nested. diff --git a/changelog.d/+open-regular-dir-errno.bugfix.md b/changelog.d/+open-regular-dir-errno.bugfix.md deleted file mode 100644 index 2e9ab40..0000000 --- a/changelog.d/+open-regular-dir-errno.bugfix.md +++ /dev/null @@ -1 +0,0 @@ -`fsx.openRegular` now returns `error.IsDir` for directory paths, so `sys.describe` reports `[Errno 21] Is a directory` instead of `[Errno 22] Invalid argument` for that case. diff --git a/changelog.d/+open-regular-special-files-text.bugfix.md b/changelog.d/+open-regular-special-files-text.bugfix.md deleted file mode 100644 index 4f66d34..0000000 --- a/changelog.d/+open-regular-special-files-text.bugfix.md +++ /dev/null @@ -1 +0,0 @@ -`fsx.openRegular` now reports `error.NotRegularFile` for FIFOs, sockets, and device nodes, and `sys.describe` renders that as `not a regular file` instead of `[Errno 22] Invalid argument`. 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/+proc-error-tests.misc.md b/changelog.d/+proc-error-tests.misc.md deleted file mode 100644 index 67ad9a9..0000000 --- a/changelog.d/+proc-error-tests.misc.md +++ /dev/null @@ -1 +0,0 @@ -Add unit tests covering error and boundary paths for `which`, `groupAlive`, `killGroup`, `stopGroup`, and `run` in `src/proc.zig`. diff --git a/changelog.d/+proc-executable-file-check.misc.md b/changelog.d/+proc-executable-file-check.misc.md deleted file mode 100644 index 277303b..0000000 --- a/changelog.d/+proc-executable-file-check.misc.md +++ /dev/null @@ -1 +0,0 @@ -The private `proc.isExecutableFile` helper holds the executable regular-file probe that `proc.which` runs for each PATH candidate. diff --git a/changelog.d/+proc-executable-fixture-tests.misc.md b/changelog.d/+proc-executable-fixture-tests.misc.md deleted file mode 100644 index ae66a4d..0000000 --- a/changelog.d/+proc-executable-fixture-tests.misc.md +++ /dev/null @@ -1 +0,0 @@ -Proc resolver tests share one executable fixture helper for scratch script and plain file setup. diff --git a/changelog.d/+proc-fixture-failure-cleanup.misc.md b/changelog.d/+proc-fixture-failure-cleanup.misc.md deleted file mode 100644 index 527d5b6..0000000 --- a/changelog.d/+proc-fixture-failure-cleanup.misc.md +++ /dev/null @@ -1 +0,0 @@ -`proc` test fixtures clean up scratch directories when setup fails after partial creation. diff --git a/changelog.d/+proc-resolve-executable-relative-slash.misc.md b/changelog.d/+proc-resolve-executable-relative-slash.misc.md deleted file mode 100644 index c028154..0000000 --- a/changelog.d/+proc-resolve-executable-relative-slash.misc.md +++ /dev/null @@ -1 +0,0 @@ -`proc.resolveExecutable` tests cover relative slash paths for executable and non-executable files. diff --git a/changelog.d/+proc-resolve-executable.feature.md b/changelog.d/+proc-resolve-executable.feature.md deleted file mode 100644 index 7ce97a4..0000000 --- a/changelog.d/+proc-resolve-executable.feature.md +++ /dev/null @@ -1 +0,0 @@ -`proc.resolveExecutable` resolves executable names to absolute executable regular-file paths from slash paths or PATH lookup with a null-PATH default of `/bin:/usr/bin`. diff --git a/changelog.d/+proc-which-direct.misc.md b/changelog.d/+proc-which-direct.misc.md deleted file mode 100644 index 104037c..0000000 --- a/changelog.d/+proc-which-direct.misc.md +++ /dev/null @@ -1 +0,0 @@ -`proc.which` tests cover executable resolution and null returns for non-executable candidates. diff --git a/changelog.d/+proc-which-search-options.misc.md b/changelog.d/+proc-which-search-options.misc.md deleted file mode 100644 index 87540fc..0000000 --- a/changelog.d/+proc-which-search-options.misc.md +++ /dev/null @@ -1 +0,0 @@ -`proc.which` uses one internal options-driven search loop for executable path matching. diff --git a/changelog.d/+proc-which-shutil.feature.md b/changelog.d/+proc-which-shutil.feature.md deleted file mode 100644 index f4f6977..0000000 --- a/changelog.d/+proc-which-shutil.feature.md +++ /dev/null @@ -1 +0,0 @@ -`proc.whichShutil` adds an opt-in executable lookup mode that matches POSIX `shutil.which` behavior. diff --git a/changelog.d/+pytext-os-error.feature.md b/changelog.d/+pytext-os-error.feature.md deleted file mode 100644 index e55b842..0000000 --- a/changelog.d/+pytext-os-error.feature.md +++ /dev/null @@ -1 +0,0 @@ -Add `pytext.osError` and `pytext.osErrorErrno` for Python-formatted `OSError` path messages. diff --git a/changelog.d/+pytext-repr.feature.md b/changelog.d/+pytext-repr.feature.md deleted file mode 100644 index 25c625b..0000000 --- a/changelog.d/+pytext-repr.feature.md +++ /dev/null @@ -1 +0,0 @@ -Add `pytext.reprStr` and `pytext.reprStrAlloc` for Python-compatible surrogateescape string quoting. diff --git a/changelog.d/+reference-api-pr24.doc.md b/changelog.d/+reference-api-pr24.doc.md deleted file mode 100644 index a0b6038..0000000 --- a/changelog.d/+reference-api-pr24.doc.md +++ /dev/null @@ -1 +0,0 @@ -List every public function and error set including PR #24 shared helpers in `docs/orgmode/reference/api.org`. diff --git a/changelog.d/+release-0.10.0.misc.md b/changelog.d/+release-0.10.0.misc.md deleted file mode 100644 index d676173..0000000 --- a/changelog.d/+release-0.10.0.misc.md +++ /dev/null @@ -1 +0,0 @@ -Prepare `zig-common` `0.10.0` in `build.zig.zon` and `COMPAT.md` for callers adopting `fsx.mkdtemp` plus `fsx.normPath` and `fsx.absPath`. diff --git a/changelog.d/+release-0.11.0.misc.md b/changelog.d/+release-0.11.0.misc.md deleted file mode 100644 index 2f5905b..0000000 --- a/changelog.d/+release-0.11.0.misc.md +++ /dev/null @@ -1 +0,0 @@ -Prepare `zig-common` `0.11.0` in `COMPAT.md` for callers adopting `syslog`. A release is now `cog bump` on a release branch: `cog.toml` sets the version in `build.zig.zon` and refuses a version without a `COMPAT.md` row. diff --git a/changelog.d/+release-0.12.0.misc.md b/changelog.d/+release-0.12.0.misc.md deleted file mode 100644 index 529f264..0000000 --- a/changelog.d/+release-0.12.0.misc.md +++ /dev/null @@ -1 +0,0 @@ -Prepare `zig-common` `0.12.0` in `COMPAT.md` for callers adopting `syslog.Identity` and `syslog.send`. 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/changelog.d/+state-lock-cancel.feature.md b/changelog.d/+state-lock-cancel.feature.md deleted file mode 100644 index c408c01..0000000 --- a/changelog.d/+state-lock-cancel.feature.md +++ /dev/null @@ -1 +0,0 @@ -Add `state.lockExclusiveCancel` supporting atomic cancellation while polling `flock`. diff --git a/changelog.d/+state-lock-exclusive-errors-test.misc.md b/changelog.d/+state-lock-exclusive-errors-test.misc.md deleted file mode 100644 index 1ab3440..0000000 --- a/changelog.d/+state-lock-exclusive-errors-test.misc.md +++ /dev/null @@ -1 +0,0 @@ -Route `lockExclusiveCancel` through `state.lock_ops.flock` and add unit tests covering `lockExclusive` with timeout 0, bounded timeout, unsupported `flock`, and private state file error paths. diff --git a/changelog.d/+sys-errnotext-unknown-test.misc.md b/changelog.d/+sys-errnotext-unknown-test.misc.md deleted file mode 100644 index 59f38a4..0000000 --- a/changelog.d/+sys-errnotext-unknown-test.misc.md +++ /dev/null @@ -1 +0,0 @@ -Add unit tests covering `sys.errnoText` for unknown errno values and error paths for `sys` syscall wrappers. diff --git a/changelog.d/+sys-strerror-unknown-panic.bugfix.md b/changelog.d/+sys-strerror-unknown-panic.bugfix.md deleted file mode 100644 index e0c47c7..0000000 --- a/changelog.d/+sys-strerror-unknown-panic.bugfix.md +++ /dev/null @@ -1 +0,0 @@ -Fix `sys.strerror` to avoid panicking on unnamed `linux.E` values by using `std.enums.tagName` with an `"Unknown error N"` fallback. diff --git a/changelog.d/+sys-strerror.feature.md b/changelog.d/+sys-strerror.feature.md deleted file mode 100644 index 0e628e9..0000000 --- a/changelog.d/+sys-strerror.feature.md +++ /dev/null @@ -1 +0,0 @@ -Add `sys.strerror` returning `errnoText(e)` or the enum tag name fallback. diff --git a/changelog.d/+syslog-identity-and-send.feature.md b/changelog.d/+syslog-identity-and-send.feature.md deleted file mode 100644 index b362f19..0000000 --- a/changelog.d/+syslog-identity-and-send.feature.md +++ /dev/null @@ -1 +0,0 @@ -`syslog`: `Identity` names the program and the structured-data identifier of an event; `formatRfc5424For`, `formatJournaldFor` and `emitFor` take one, and `send` delivers an already formatted payload, for a tool with formatting of its own. The functions without an identity keep writing `eb-keep-logs`, as 0.11.0 did, and are removed in 0.13.0. diff --git a/changelog.d/+syslog.feature.md b/changelog.d/+syslog.feature.md deleted file mode 100644 index 6c4c620..0000000 --- a/changelog.d/+syslog.feature.md +++ /dev/null @@ -1 +0,0 @@ -`syslog`: the RFC 5424 and systemd-journald event emitter that eb-keep-logs and eessi-arch-guard each carried a copy of: `Target`, `parseTarget`, `parsePen`, `formatRfc5424`, `formatJournald` and `emit`. 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/docs/orgmode/reference/api.org b/docs/orgmode/reference/api.org index 5e4725e..836ee1e 100644 --- a/docs/orgmode/reference/api.org +++ b/docs/orgmode/reference/api.org @@ -94,9 +94,13 @@ Error set: [[zig:zig_common.logs.GzipError]]. | Function | Error set | |----------------------------------------+-----------| +| [[zig:zig_common.cli.Stdout.write]] | none | +| [[zig:zig_common.cli.Stdout.print]] | none | +| [[zig:zig_common.cli.Stdout.finish]] | none | | [[zig:zig_common.cli.put]] | none | | [[zig:zig_common.cli.print]] | none | | [[zig:zig_common.cli.out]] | none | +| [[zig:zig_common.cli.writeOut]] | none | | [[zig:zig_common.cli.err]] | none | | [[zig:zig_common.cli.die]] | none | | [[zig:zig_common.cli.versionLine]] | none | diff --git a/docs/orgmode/reference/cli-conventions.org b/docs/orgmode/reference/cli-conventions.org index 43ca4d5..d1e2814 100644 --- a/docs/orgmode/reference/cli-conventions.org +++ b/docs/orgmode/reference/cli-conventions.org @@ -8,17 +8,20 @@ The messages, exit statuses and version line that the stackhands Zig tools share ** Messages -| Call | Writes | To | -|------------------------------+---------------------------------------------+----------------------| -| [[zig:zig_common.cli.put]] | the bytes as given | the descriptor given | -| [[zig:zig_common.cli.print]] | the arguments, formatted | the descriptor given | -| [[zig:zig_common.cli.out]] | the arguments, formatted | stdout, descriptor 1 | -| [[zig:zig_common.cli.err]] | the arguments, formatted | stderr, descriptor 2 | -| [[zig:zig_common.cli.die]] | =TOOL: message= and a newline, then exits 2 | stderr, descriptor 2 | +| Call | Writes | To | +|--------------------------------------+------------------------------------------------------+----------------------| +| [[zig:zig_common.cli.put]] | the bytes as given | the descriptor given | +| [[zig:zig_common.cli.print]] | the arguments, formatted | the descriptor given | +| [[zig:zig_common.cli.out]] | the arguments, formatted | stdout, descriptor 1 | +| [[zig:zig_common.cli.writeOut]] | the bytes as given, reporting a write failure | stdout, descriptor 1 | +| [[zig:zig_common.cli.Stdout.write]] | the bytes as given, latching the first write failure | stdout, descriptor 1 | +| [[zig:zig_common.cli.Stdout.print]] | the arguments, formatted, latching write failures | stdout, descriptor 1 | +| [[zig:zig_common.cli.err]] | the arguments, formatted | stderr, descriptor 2 | +| [[zig:zig_common.cli.die]] | =TOOL: message= and a newline, then exits 2 | stderr, descriptor 2 | - Only =die= adds a newline. -- A write that fails, as one to a closed stdout or to =/dev/full= does, is ignored: it changes neither what the tool did nor its exit status. -- A message longer than 8 KiB is formatted on the heap; when that allocation fails, nothing is written. +- =put=, =print=, =out= and =err= ignore write errors. When stdout carries what a caller captures or evaluates, [[zig:zig_common.cli.writeOut]] and [[zig:zig_common.cli.Stdout]] check the write, print =TOOL: cannot write output (ERRNO)= on stderr once, and [[zig:zig_common.cli.Stdout.finish]] turns exit status 0 into 1. +- A message longer than 8 KiB is formatted on the heap; when that allocation fails, =print= writes nothing and =Stdout.print= marks output failed. ** Exit status diff --git a/src/atomic.zig b/src/atomic.zig index c99dc6f..cb13892 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,25 @@ 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. + // 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 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 +630,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 +644,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 @@ -595,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 @@ -609,10 +694,32 @@ 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 {}; } +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 +734,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 +766,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 +799,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,9 +810,40 @@ 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" { const gpa = std.testing.allocator; var cwd_buf: [sys.path_max]u8 = undefined; @@ -700,6 +860,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..b11d88f 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,164 @@ 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; +} + +/// 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 = ""; + +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 "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(); + 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 +1914,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 +1922,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 +1930,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/cli.zig b/src/cli.zig index 43a517b..99ee866 100644 --- a/src/cli.zig +++ b/src/cli.zig @@ -33,6 +33,63 @@ pub fn out(comptime fmt: []const u8, args: anytype) void { print(1, fmt, args); } +const printFd = print; + +/// Checked writer for standard output (`fd` 1 by default) that reports the +/// first write failure on `err_fd` as `"TOOL: cannot write output (ERRNO)"` +/// and remembers the error so later writes stop and exit status `0` becomes +/// `1`. +pub const Stdout = struct { + tool: []const u8, + fd: sys.fd_t = 1, + err_fd: sys.fd_t = 2, + failed: bool = false, + + /// Write `bytes` to `fd`. On the first failure, sets `failed`, writes + /// `"TOOL: cannot write output (ERRNO)\n"` to `err_fd`, and returns + /// `false`; later calls return `false` without repeating the message. + pub fn write(self: *Stdout, bytes: []const u8) bool { + if (self.failed) return false; + sys.writeAll(self.fd, bytes) catch |e| { + self.failed = true; + printFd(self.err_fd, "{s}: cannot write output ({s})\n", .{ self.tool, sys.describe(e) }); + return false; + }; + return true; + } + + /// Format `args` with `fmt` and `write` the text. A message longer than + /// 8 KiB is formatted on the heap; when that allocation fails, sets + /// `failed` and reports out of memory on `err_fd`. + pub fn print(self: *Stdout, comptime fmt: []const u8, args: anytype) bool { + if (self.failed) return false; + var buf: [8192]u8 = undefined; + if (std.mem.print(&buf, fmt, args)) |s| { + return self.write(s); + } else |_| {} + var w: std.Io.Writer.Allocating = .init(std.heap.page_allocator); + defer w.deinit(); + w.writer.print(fmt, args) catch { + self.failed = true; + printFd(self.err_fd, "{s}: cannot write output (out of memory)\n", .{self.tool}); + return false; + }; + return self.write(w.written()); + } + + /// Return `1` when `rc` is `0` and an earlier write failed; otherwise `rc`. + pub fn finish(self: *const Stdout, rc: u8) u8 { + return if (rc == 0 and self.failed) 1 else rc; + } +}; + +/// Write `bytes` to stdout, reporting `"TOOL: cannot write output (ERRNO)"` +/// on stderr and returning `false` when the write fails. +pub fn writeOut(tool: []const u8, bytes: []const u8) bool { + var s: Stdout = .{ .tool = tool }; + return s.write(bytes); +} + /// `print` to stderr. No newline is added. pub fn err(comptime fmt: []const u8, args: anytype) void { print(2, fmt, args); @@ -63,3 +120,102 @@ test "put and print ignore write errors and versionLine formats tool and version try std.testing.expect(std.mem.startsWith(u8, line, "demo 1.2.3 (")); try std.testing.expect(std.mem.endsWith(u8, line, ", abc1234)\n")); } + +test "Stdout and writeOut deliver output and report first write failure once" { + const linux = std.os.linux; + const fsx = @import("fsx.zig"); + const a = std.testing.allocator; + + { + var out_fds: [2]i32 = undefined; + try std.testing.expectEqual(linux.E.SUCCESS, linux.errno(linux.pipe2(&out_fds, .{ .CLOEXEC = true }))); + defer sys.close(out_fds[0]); + var err_fds: [2]i32 = undefined; + try std.testing.expectEqual(linux.E.SUCCESS, linux.errno(linux.pipe2(&err_fds, .{ .CLOEXEC = true }))); + defer sys.close(err_fds[0]); + + var s: Stdout = .{ .tool = "demo", .fd = out_fds[1], .err_fd = err_fds[1] }; + try std.testing.expect(s.write("hello ")); + try std.testing.expect(s.print("world {d}\n", .{7})); + var big: [9000]u8 = undefined; + @memset(&big, 'a'); + try std.testing.expect(s.print("{s}\n", .{big[0..]})); + sys.close(out_fds[1]); + sys.close(err_fds[1]); + + const got_out = try fsx.readAll(a, out_fds[0], 32 * 1024); + defer a.free(got_out); + const got_err = try fsx.readAll(a, err_fds[0], 4096); + defer a.free(got_err); + try std.testing.expectEqual(@as(usize, 14 + 9001), got_out.len); + try std.testing.expect(std.mem.startsWith(u8, got_out, "hello world 7\naaa")); + try std.testing.expectEqualStrings("", got_err); + try std.testing.expect(!s.failed); + try std.testing.expectEqual(@as(u8, 0), s.finish(0)); + try std.testing.expectEqual(@as(u8, 2), s.finish(2)); + } + + { + var err_fds: [2]i32 = undefined; + try std.testing.expectEqual(linux.E.SUCCESS, linux.errno(linux.pipe2(&err_fds, .{ .CLOEXEC = true }))); + defer sys.close(err_fds[0]); + + var s: Stdout = .{ .tool = "eb-local", .fd = -1, .err_fd = err_fds[1] }; + const runNested = struct { + fn call(out_writer: *Stdout) u8 { + _ = out_writer.print("first {d}\n", .{1}); + return 0; + } + }.call; + try std.testing.expectEqual(@as(u8, 1), s.finish(runNested(&s))); + try std.testing.expect(s.failed); + try std.testing.expect(!s.write("second\n")); + try std.testing.expect(!s.print("third {d}\n", .{3})); + sys.close(err_fds[1]); + + const got_err = try fsx.readAll(a, err_fds[0], 4096); + defer a.free(got_err); + try std.testing.expectEqualStrings("eb-local: cannot write output ([Errno 9] Bad file descriptor)\n", got_err); + try std.testing.expectEqual(@as(u8, 1), s.finish(0)); + try std.testing.expectEqual(@as(u8, 2), s.finish(2)); + } + + if (sys.openat(linux.AT.FDCWD, "/dev/full", .{ .ACCMODE = .WRONLY }, 0)) |full_fd| { + defer sys.close(full_fd); + var err_fds: [2]i32 = undefined; + try std.testing.expectEqual(linux.E.SUCCESS, linux.errno(linux.pipe2(&err_fds, .{ .CLOEXEC = true }))); + defer sys.close(err_fds[0]); + + var big: [9000]u8 = undefined; + @memset(&big, 'z'); + var s: Stdout = .{ .tool = "eb-local", .fd = full_fd, .err_fd = err_fds[1] }; + try std.testing.expect(!s.print("{s}\n", .{big[0..]})); + try std.testing.expect(!s.write("after\n")); + sys.close(err_fds[1]); + + const got_err = try fsx.readAll(a, err_fds[0], 4096); + defer a.free(got_err); + try std.testing.expectEqualStrings("eb-local: cannot write output ([Errno 28] No space left on device)\n", got_err); + + var child_err: [2]i32 = undefined; + try std.testing.expectEqual(linux.E.SUCCESS, linux.errno(linux.pipe2(&child_err, .{ .CLOEXEC = true }))); + defer sys.close(child_err[0]); + const pid: isize = @bitCast(linux.fork()); + if (pid < 0) return error.TestUnexpectedResult; + if (pid == 0) { + _ = linux.dup2(full_fd, 1); + _ = linux.dup2(child_err[1], 2); + const ok = writeOut("demo", "payload\n"); + linux.exit_group(if (ok) 0 else 1); + } + sys.close(child_err[1]); + var raw: i32 = 0; + while (linux.errno(linux.wait4(@intCast(pid), &raw, 0, null)) == .INTR) {} + const st: u32 = @bitCast(raw); + try std.testing.expect(linux.W.IFEXITED(st)); + try std.testing.expectEqual(@as(u8, 1), linux.W.EXITSTATUS(st)); + const child_msg = try fsx.readAll(a, child_err[0], 4096); + defer a.free(child_msg); + try std.testing.expectEqualStrings("demo: cannot write output ([Errno 28] No space left on device)\n", child_msg); + } else |_| {} +} diff --git a/src/fsx.zig b/src/fsx.zig index 3a98713..ba38607 100644 --- a/src/fsx.zig +++ b/src/fsx.zig @@ -412,14 +412,47 @@ const MoveFaults = struct { force_cross_device_rename: bool = false, reach_fn: ?*const fn (?*anyopaque, []const u8) void = null, fail_fn: ?*const fn (?*anyopaque, []const u8) ?Error = null, + trace_fn: ?*const fn (?*anyopaque, MoveCall) void = null, ctx: ?*anyopaque = null, }; +/// A rename or directory sync that moveAcross completed; the descriptor of +/// a sync is open only while the trace runs. +const MoveCall = union(enum) { + rename, + fsync: fd_t, +}; + fn moveFaultsStep(faults: MoveFaults, step: []const u8) Error!void { if (faults.reach_fn) |f| f(faults.ctx, step); if (faults.fail_fn) |f| if (f(faults.ctx, step)) |err| return err; } +fn moveRename(faults: MoveFaults, old_dir: fd_t, old_name: []const u8, new_dir: fd_t, new_name: []const u8) Error!void { + try sys.renameat(old_dir, old_name, new_dir, new_name); + if (faults.trace_fn) |f| f(faults.ctx, .rename); +} + +fn moveFsync(faults: MoveFaults, dir: fd_t) Error!void { + try sys.fsync(dir); + if (faults.trace_fn) |f| f(faults.ctx, .{ .fsync = dir }); +} + +/// `fsyncNameParent` for moveAcross, reported to its trace. +fn moveFsyncNameParent(faults: MoveFaults, dir: fd_t, name: []const u8) Error!void { + const parent_dir = try openDir(dir, std.fs.path.dirname(name) orelse ".", true); + defer sys.close(parent_dir); + try moveFsync(faults, parent_dir); +} + +/// Whether `a_dir/a_name` and `b_dir/b_name` name entries of the same +/// directory by the same path. False does not mean the directories differ. +fn sameNameParent(a_dir: fd_t, a_name: []const u8, b_dir: fd_t, b_name: []const u8) bool { + const a = std.fs.path.dirname(a_name) orelse "."; + const b = std.fs.path.dirname(b_name) orelse "."; + return a_dir == b_dir and std.mem.eql(u8, a, b); +} + fn tmpName(base: []const u8, out: *[sys.path_max]u8) Error![]const u8 { var rnd: [4]u8 = undefined; _ = try sys.call(linux.getrandom, .{ &rnd, rnd.len, 0 }); @@ -543,24 +576,24 @@ fn moveAcrossCopy(gpa: Allocator, src_dir: fd_t, src_name: []const u8, dst_dir: } try moveFaultsStep(faults, "move.publish"); - try sys.renameat(dst_dir, tmp, dst_dir, dst_name); + try moveRename(faults, dst_dir, tmp, dst_dir, dst_name); published = true; - try sys.fsync(dst_dir); + try moveFsyncNameParent(faults, dst_dir, dst_name); try moveFaultsStep(faults, "move.remove-source"); if (src.isDir()) { try deleteTree(gpa, src_dir, src_name); } else { try sys.unlinkat(src_dir, src_name, 0); } - try sys.fsync(src_dir); + try moveFsyncNameParent(faults, src_dir, src_name); } fn moveAcrossInternal(gpa: Allocator, src_dir: fd_t, src_name: []const u8, dst_dir: fd_t, dst_name: []const u8, opts: MoveAcrossOptions, faults: MoveFaults) (Error || Allocator.Error)!void { try moveFaultsStep(faults, "move.rename"); if (!faults.force_cross_device_rename) { - if (sys.renameat(src_dir, src_name, dst_dir, dst_name)) |_| { - try sys.fsync(dst_dir); - if (src_dir != dst_dir) try sys.fsync(src_dir); + if (moveRename(faults, src_dir, src_name, dst_dir, dst_name)) |_| { + try moveFsyncNameParent(faults, dst_dir, dst_name); + if (!sameNameParent(src_dir, src_name, dst_dir, dst_name)) try moveFsyncNameParent(faults, src_dir, src_name); return; } else |err| switch (err) { error.CrossDevice => {}, @@ -1631,6 +1664,169 @@ const MoveProbe = struct { } }; +/// The renames and directory syncs one moveAcross call makes, in order. A +/// sync is kept as the device and inode of the directory it flushed. +const MoveTrace = struct { + calls: [16]Call = undefined, + len: usize = 0, + + const Call = union(enum) { + rename, + fsync: struct { dev: u64, ino: u64 }, + }; + + fn record(ctx: ?*anyopaque, call: MoveCall) void { + const self: *MoveTrace = @ptrCast(@alignCast(ctx.?)); + if (self.len == self.calls.len) return; + self.calls[self.len] = switch (call) { + .rename => .rename, + .fsync => |fd| if (fstat(fd)) |st| .{ .fsync = .{ .dev = st.dev, .ino = st.ino } } else |_| .{ .fsync = .{ .dev = 0, .ino = 0 } }, + }; + self.len += 1; + } + + fn faults(self: *MoveTrace, cross_device: bool) MoveFaults { + return .{ .force_cross_device_rename = cross_device, .trace_fn = record, .ctx = self }; + } + + fn sync(dir: Stat) Call { + return .{ .fsync = .{ .dev = dir.dev, .ino = dir.ino } }; + } + + fn expectCalls(self: *const MoveTrace, want: []const Call) !void { + try std.testing.expectEqualSlices(Call, want, self.calls[0..self.len]); + } + + /// Whether `dir` is synced after the last rename. + fn syncedAfterPublish(self: *const MoveTrace, dir: Stat) bool { + var i = self.len; + while (i > 0) { + i -= 1; + switch (self.calls[i]) { + .rename => return false, + .fsync => |s| if (s.dev == dir.dev and s.ino == dir.ino) return true, + } + } + return false; + } +}; + +/// Scratch directory under `.zig-cache` for the moveAcross trace tests. +const MoveScratch = struct { + gpa: Allocator, + base: []u8, + d: fd_t, + + fn init(gpa: Allocator, tag: []const u8) !MoveScratch { + var cwd_buf: [sys.path_max]u8 = undefined; + const here = try realpath(cwd, ".", &cwd_buf); + const base = try std.fmt.allocPrint(gpa, "{s}/.zig-cache/zig-common-{s}-{d}", .{ here, tag, linux.getpid() }); + errdefer gpa.free(base); + var zb: [sys.path_max:0]u8 = undefined; + _ = linux.mkdirat(cwd, (try sys.z(&zb, base)).ptr, 0o700); + return .{ .gpa = gpa, .base = base, .d = try openDir(cwd, base, false) }; + } + + fn deinit(self: MoveScratch) void { + deleteTree(self.gpa, cwd, self.base) catch {}; + sys.close(self.d); + self.gpa.free(self.base); + } + + fn mkdir(self: MoveScratch, name: []const u8) !Stat { + var zb: [sys.path_max:0]u8 = undefined; + _ = try sys.call(linux.mkdirat, .{ self.d, (try sys.z(&zb, name)).ptr, @as(linux.mode_t, 0o700) }); + return statAt(self.d, name, false); + } + + fn put(self: MoveScratch, name: []const u8) !void { + const fd = try sys.openat(self.d, name, .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true }, 0o644); + defer sys.close(fd); + try sys.writeAll(fd, "moved\n"); + } + + fn expectMoved(self: MoveScratch, src: []const u8, dst: []const u8) !void { + try std.testing.expectError(error.NotFound, statAt(self.d, src, false)); + const got = try openRegular(self.d, dst, false); + defer sys.close(got.fd); + const text = try readAll(self.gpa, got.fd, 64); + defer self.gpa.free(text); + try std.testing.expectEqualStrings("moved\n", text); + } +}; + +test "moveAcross traces the rename and the directory syncs that publish it" { + const gpa = std.testing.allocator; + const s = try MoveScratch.init(gpa, "move-trace"); + defer s.deinit(); + const root = try fstat(s.d); + + try s.put("src"); + var renamed = MoveTrace{}; + try moveAcrossInternal(gpa, s.d, "src", s.d, "dst", .{}, renamed.faults(false)); + try s.expectMoved("src", "dst"); + try renamed.expectCalls(&.{ .rename, MoveTrace.sync(root) }); + + var copied = MoveTrace{}; + try moveAcrossInternal(gpa, s.d, "dst", s.d, "src", .{}, copied.faults(true)); + try s.expectMoved("dst", "src"); + try copied.expectCalls(&.{ .rename, MoveTrace.sync(root), MoveTrace.sync(root) }); +} + +test "moveAcross syncs the parent that receives a nested destination" { + const gpa = std.testing.allocator; + const s = try MoveScratch.init(gpa, "move-nested-dst"); + defer s.deinit(); + const sub = try s.mkdir("sub"); + + try s.put("src"); + var renamed = MoveTrace{}; + try moveAcrossInternal(gpa, s.d, "src", s.d, "sub/renamed", .{}, renamed.faults(false)); + try s.expectMoved("src", "sub/renamed"); + try std.testing.expect(renamed.syncedAfterPublish(sub)); + + try s.put("src"); + var copied = MoveTrace{}; + try moveAcrossInternal(gpa, s.d, "src", s.d, "sub/copied", .{}, copied.faults(true)); + try s.expectMoved("src", "sub/copied"); + try std.testing.expect(copied.syncedAfterPublish(sub)); +} + +test "moveAcross syncs the source parent beside a nested destination" { + const gpa = std.testing.allocator; + const s = try MoveScratch.init(gpa, "move-nested-src"); + defer s.deinit(); + const root = try fstat(s.d); + const sub = try s.mkdir("sub"); + const a = try s.mkdir("a"); + + try s.put("src"); + var flat = MoveTrace{}; + try moveAcrossInternal(gpa, s.d, "src", s.d, "sub/flat", .{}, flat.faults(false)); + try s.expectMoved("src", "sub/flat"); + try std.testing.expect(flat.syncedAfterPublish(sub)); + try std.testing.expect(flat.syncedAfterPublish(root)); + + try s.put("a/src"); + var renamed = MoveTrace{}; + try moveAcrossInternal(gpa, s.d, "a/src", s.d, "sub/renamed", .{}, renamed.faults(false)); + try s.expectMoved("a/src", "sub/renamed"); + try std.testing.expect(renamed.syncedAfterPublish(sub)); + try std.testing.expect(renamed.syncedAfterPublish(a)); + + try s.put("a/src"); + var copied = MoveTrace{}; + try moveAcrossInternal(gpa, s.d, "a/src", s.d, "sub/copied", .{}, copied.faults(true)); + try s.expectMoved("a/src", "sub/copied"); + try std.testing.expect(copied.syncedAfterPublish(sub)); + try std.testing.expect(copied.syncedAfterPublish(a)); + + var beside = MoveTrace{}; + try moveAcrossInternal(gpa, s.d, "sub/copied", s.d, "sub/beside", .{}, beside.faults(false)); + try s.expectMoved("sub/copied", "sub/beside"); + try beside.expectCalls(&.{ .rename, MoveTrace.sync(sub) }); +} + test "moveAcross falls back on EXDEV and removes the source after publish" { const gpa = std.testing.allocator; var cwd_buf: [sys.path_max]u8 = undefined; diff --git a/src/logs.zig b/src/logs.zig index cd00ea4..4183275 100644 --- a/src/logs.zig +++ b/src/logs.zig @@ -13,6 +13,10 @@ const flate = std.compress.flate; /// path per line. `renameInList` gives its text after files are renamed. pub const licensed_list = ".licensed-logs"; +/// The longest a single path component may be on a Linux filesystem +/// holding log files: ext4, xfs, btrfs and tmpfs all share this limit. +const name_component_max = 255; + /// The errors of `gzipInPlace`: the `sys.Error` of a failed call, /// `error.OutOfMemory`, or `error.WriteFailed` from writing the /// compressed stream. @@ -42,7 +46,21 @@ pub fn gzipInPlace(gpa: Allocator, io: Io, dir: fsx.fd_t, name: []const u8) Gzip _ = try sys.call(linux.getrandom, .{ &rnd, rnd.len, 0 }); const gz_parent = std.fs.path.dirname(gz_name) orelse "."; const gz_base = std.fs.path.basename(gz_name); - const tmp_name = try gpa.print("{s}/.{s}.{d}.{x:0>8}.tmp", .{ gz_parent, gz_base, linux.getpid(), std.mem.readInt(u32, &rnd, .little) }); + const pid = linux.getpid(); + const suffix = std.mem.readInt(u32, &rnd, .little); + // A name this program's own `name.gz` already fits in one path + // component can still leave the temporary file holding both that name + // and the pid and random suffix guarding it from a concurrent or a + // retried run over that component's own limit. The suffix alone is + // already enough to keep two temporary files from colliding in `dir`, + // so a name that would overflow is left out of the temporary one + // rather than failing a compression this program's own final name + // would otherwise have gone on to complete. + const tagged_len = std.fmt.count(".{s}.{d}.{x:0>8}.tmp", .{ gz_base, pid, suffix }); + const tmp_name = if (tagged_len <= name_component_max) + try gpa.print("{s}/.{s}.{d}.{x:0>8}.tmp", .{ gz_parent, gz_base, pid, suffix }) + else + try gpa.print("{s}/.{d}.{x:0>8}.tmp", .{ gz_parent, pid, suffix }); defer gpa.free(tmp_name); const dst = try sys.openat(dir, tmp_name, .{ .ACCMODE = .WRONLY, @@ -386,3 +404,37 @@ test "gzipInPlace handles nested paths like gzip -9 sub/file" { try std.testing.expectError(error.NotFound, fsx.statAt(dir, "sub/nested.log", false)); try std.testing.expect((fsx.statAt(dir, "sub/nested.log.gz", false) catch null) != null); } + +test "gzipInPlace compresses a name its own temporary file alone would overflow" { + const gpa = std.testing.allocator; + var cwd_buf: [sys.path_max]u8 = undefined; + const here = try fsx.realpath(fsx.cwd, ".", &cwd_buf); + var pb: [sys.path_max]u8 = undefined; + const base = try std.mem.print(&pb, "{s}/.zig-cache/zig-common-logs-long-{d}", .{ here, linux.getpid() }); + var zb: [sys.path_max:0]u8 = undefined; + _ = linux.mkdirat(fsx.cwd, (try sys.z(&zb, base)).ptr, 0o700); + const dir = try fsx.openDir(fsx.cwd, base, false); + defer { + fsx.deleteTree(gpa, fsx.cwd, base) catch {}; + sys.close(dir); + } + + // 240 bytes: short enough that `gzip -9` on the real reference + // compressor takes it (its own overhead is the 3 bytes of `.gz`), long + // enough that adding a pid and a random suffix on top overflows one + // path component's 255-byte limit no matter how many digits the + // running process's own pid happens to have. + var name_buf: [240]u8 = undefined; + @memset(&name_buf, 'a'); + const name = &name_buf; + const src = try sys.openat(dir, name, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, 0o644); + try sys.writeAll(src, "a log with a long name\n"); + sys.close(src); + + const io = std.Io.Threaded.global_single_threaded.io(); + try gzipInPlace(gpa, io, dir, name); + try std.testing.expectError(error.NotFound, fsx.statAt(dir, name, false)); + var gz_buf: [244]u8 = undefined; + const gz_name = try std.fmt.bufPrint(&gz_buf, "{s}.gz", .{name}); + try std.testing.expect((fsx.statAt(dir, gz_name, false) catch null) != null); +} diff --git a/src/state.zig b/src/state.zig index 5a1e5ec..edc6159 100644 --- a/src/state.zig +++ b/src/state.zig @@ -12,6 +12,69 @@ 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; + +/// 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] }; +} + +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; +} + /// 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 +454,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 +463,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 +481,13 @@ 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 { + // 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), } } } @@ -448,27 +516,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 +548,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 +572,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 +699,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 +725,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 +767,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 +850,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..4b2f51a 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,91 @@ 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 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); + 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 +305,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 +407,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..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,14 @@ 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 }{ .{ .name = "rc-keep", .data = "replaced\n" }, @@ -198,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 { @@ -880,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)