fileutil

package
v1.0.509 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 9 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package fileutil provides durable filesystem helpers shared by package main and internal/* packages (ADR-0003). It has no dependency on the rest of Culvert: the standard library, plus golang.org/x/sys/unix on Linux for the read-only ReplacementBlocked check (replacement_linux.go).

Index

Constants

This section is empty.

Variables

View Source
var ErrReplacedNotSynced = errors.New("atomic write: target replaced but parent directory not synced")

ErrReplacedNotSynced marks an AtomicWrite failure that occurred AFTER the rename: the target file already carries the new content (visible to every reader, and on the overwhelming majority of filesystems durable), but the parent-directory sync failed, so the rename's durability across an immediate crash is not guaranteed. Callers running compensating rollbacks must NOT restore prior in-memory state on this error — memory would then contradict the visible file, and a restart would load the "rolled back" content anyway. Test with errors.Is.

View Source
var ErrReplacementBlocked = errors.New("the target cannot be replaced by any save")

ErrReplacementBlocked means rename(2) would refuse to replace the target itself — it is immutable or append-only, a mount point, or in an immutable or append-only directory — so no save can land there. Returned by ReplacementBlocked, which detects it only on Linux.

Functions

func AtomicWrite

func AtomicWrite(path string, data []byte, perm os.FileMode) error

AtomicWrite writes data to path atomically: it writes to a unique temp file in the same directory, chmods, fsyncs the file, renames over the target, and best-effort fsyncs the parent directory. A crash mid-write never leaves a partial or corrupt target file. Moved verbatim from package main's atomicWriteFile (ADR-0003); behaviour is unchanged.

Every failure branch additionally notifies the write-failure observer (CHAOS-45) so error-discarding callers cannot fail silently.

func DirSyncUnsupported added in v1.0.507

func DirSyncUnsupported(err error) bool

DirSyncUnsupported reports whether err, the result of fsyncing a directory, is one of the codes a filesystem returns when it does not support directory fsync (EINVAL, ENOTSUP, EOPNOTSUPP). Such a filesystem has already given every durability guarantee it has, so callers treat the sync as done.

func ReplacementBlocked added in v1.0.269

func ReplacementBlocked(path string) error

ReplacementBlocked reports, without writing anything, whether rename(2) would refuse to replace the file at path itself: it returns an error wrapping ErrReplacementBlocked (and EPERM or EBUSY) for an immutable or append-only file (inode flags or statx), a mount point, or an immutable or append-only directory; nil when none applies; any other error when the target could not be inspected. The inode flags are read only from a regular file (an ioctl on a device node would reach its driver).

func SetWriteFailureObserver added in v1.0.175

func SetWriteFailureObserver(fn func(path string, err error))

SetWriteFailureObserver publishes the durable-write failure observer. Published once at startup by package main. A nil fn clears the observer, which is what tests use to restore the default no-op state.

func SetWriteSuccessObserver added in v1.0.175

func SetWriteSuccessObserver(fn func(path string))

SetWriteSuccessObserver publishes the durable-write success observer. Nil clears it. See writeOKObserver for why successes are observed at all.

func SyncDir added in v1.0.507

func SyncDir(dir string) error

SyncDir opens dir and fsyncs it so that entries created, renamed or removed inside it are durable. It is the strict form: a directory that cannot be opened is an error, returned unwrapped. A filesystem without directory fsync support (DirSyncUnsupported) is success. The handle is always closed; its close error is returned only when the fsync itself succeeded.

func WriteFileExclusive added in v1.0.253

func WriteFileExclusive(path string, data []byte, perm os.FileMode) error

WriteFileExclusive is the safe counterpart to AtomicWrite for the few callers that CANNOT use a random temp name because the path itself is a rendezvous another code path looks for by name (the CDR renewal's "<bundle>.tmp" files, which reconcileCredentialLineage finds at the next boot to finish an interrupted swap).

It exists because os.WriteFile is unsafe for secret material on a predictable path, in two ways that are easy to miss and were each reproduced against this tree:

  • IT FOLLOWS SYMLINKS. O_CREATE without O_EXCL opens the link's TARGET, so an entry planted at the path before the first write sends the bytes somewhere the writer never chose — outside the data directory entirely. For a key file the read side makes this worse rather than better: os.ReadFile on a DANGLING link reports fs.ErrNotExist, which is exactly the condition every mint path treats as "no key yet, create one".
  • ITS perm ARGUMENT APPLIES ONLY ON CREATION. Writing over a file that already exists keeps that file's mode, so a 0666 file planted at the path receives the secret and stays world-readable however carefully 0600 was passed.

WriteFileExclusive removes any pre-existing entry — link or file, which is what makes the create exclusive rather than merely racy — then creates the path with O_EXCL at perm, writes, fsyncs and closes. Removing first keeps the drop-in semantics of os.WriteFile (a stale rendezvous file from an interrupted predecessor is superseded, exactly as a truncating write superseded it before); O_EXCL then guarantees the descriptor refers to a file THIS call created, at THIS mode, at THIS path.

Anything the remove cannot clear — a non-empty directory, a parent that denies unlink — fails the call CLOSED, with nothing written and the existing entry untouched. An EMPTY directory is cleared like a stale file; that is a deliberate widening over os.WriteFile's EISDIR, since nothing security-relevant distinguishes an empty directory at a rendezvous path from no entry at all.

Callers that do NOT need a predictable path must use AtomicWrite instead: it is the durable-write chokepoint, it is atomic against readers, and its rename-over-the-target replaces a planted symlink rather than writing through it.

Deliberately NOT wired to the AtomicWrite observers (CHAOS-45): this is not that chokepoint, and every call site checks the returned error itself. Notifying only the failure seam would degrade the storage row with no success seam able to clear it by evidence.

Types

type RotatingFile added in v1.0.16

type RotatingFile struct {
	// contains filtered or unexported fields
}

RotatingFile wraps a log file and rotates it when it exceeds maxBytes.

func NewRotatingFile added in v1.0.16

func NewRotatingFile(path string, maxMB int) (*RotatingFile, error)

NewRotatingFile opens path for append and returns a writer that rotates the file to path+".1" when it exceeds maxMB (<=0 falls back to 50 MB). It refuses a symlink at path and anything that is not a regular file, and does not block on a FIFO there (see openLogAppend).

func (*RotatingFile) Close added in v1.0.16

func (r *RotatingFile) Close() error

Close closes the underlying file.

func (*RotatingFile) Write added in v1.0.16

func (r *RotatingFile) Write(p []byte) (int, error)

Write appends p, rotating first when the size cap would be exceeded.

type WriteResult added in v1.0.269

type WriteResult struct {
	// Landed is the FileInfo of the file the write put at path: fstat on a
	// descriptor of the temp file itself, taken just AFTER it is renamed over
	// path (a duplicate kept open across the rename on Unix; elsewhere the
	// file's last fstat before it). So it describes exactly the inode the
	// write put there, including the ctime the rename itself set, even if an
	// external writer replaces path again before the caller could look at
	// it — which a stat of the path after the write cannot promise. Nil when
	// nothing landed.
	Landed os.FileInfo
	// DirSynced reports whether the parent directory was fsynced after the
	// rename (or the platform reports a directory fsync as unsupported, the
	// best it offers). It is false when the directory could not even be
	// opened for its fsync — a write+search-only 0300 directory gives EACCES
	// — which AtomicWrite reports as success, as it always has: its callers
	// roll back on any error, and the file did land. A caller that must know
	// reads it here.
	DirSynced bool
}

WriteResult describes what AtomicWriteInfo landed.

func AtomicWriteInfo added in v1.0.269

func AtomicWriteInfo(path string, data []byte, perm os.FileMode) (WriteResult, error)

AtomicWriteInfo is AtomicWrite that also reports what it landed. Its error and its observer notifications are exactly AtomicWrite's.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL