pub fn create_dir_all_safe(path: &Path, mode: u32) -> Result<DirFd>Expand description
Safely create all parent directories for a path using directory file descriptors. This prevents symlink race conditions by anchoring all operations to directory fds.
§Security
This function prevents TOCTOU race conditions by:
- Finding the deepest existing ancestor directory (path-based, but safe since it exists)
- Opening that ancestor with a file descriptor
- Creating all new directories using fd-based operations (mkdirat, openat with O_NOFOLLOW)
Once we have a fd for an existing ancestor, all subsequent operations use that fd as the anchor. If an attacker replaces a newly-created directory with a symlink, our openat with O_NOFOLLOW will fail, preventing the attack.
Existing symlinks in the path (like /var -> /private/var on macOS) are followed when finding the ancestor, which is safe since they already exist.
§Arguments
path- The path to create directories formode- The mode to use when creating new directories (e.g., 0o755). The actual mode will be modified by the process umask.
§Returns
A DirFd for the final created directory, or the first existing parent if all directories already exist.