Skip to main content

write_atomic_restricted

Function write_atomic_restricted 

Source
pub fn write_atomic_restricted(
    path: &Path,
    contents: &[u8],
    file_mode: u32,
    dir_mode: u32,
) -> Result<()>
Expand description

Write contents to path atomically with file_mode, ensuring the parent directory exists and is set to dir_mode.

On Unix the target file is created with OpenOptions::mode(file_mode) before any bytes are written, closing the TOCTOU window that fs::write(…) + set_permissions(…) opens. The parent directory is created with DirBuilder::mode(dir_mode); if the directory already exists with a looser mode, it is tightened.

On non-Unix platforms the mode arguments are ignored and the function falls back to std::fs::create_dir_all + tempfile + rename.

Atomicity: contents are written to a sibling tempfile and then renamed over path, so readers always observe either the full old contents or the full new contents — never a truncated file.

§Errors

Returns an error if path has no parent or no file-name component, the parent directory cannot be created or chmod’d to dir_mode, the tempfile cannot be opened with file_mode or written, or the final rename over path fails. The tempfile is cleaned up on rename failure so secret material doesn’t linger.