stratum_node_cli/
private_file.rs1use std::fs::{self, File, OpenOptions};
4use std::io::{self, Read as _, Write as _};
5use std::os::unix::fs::{MetadataExt as _, OpenOptionsExt as _};
6use std::path::Path;
7
8use rustix::fs::{Mode, OFlags};
9use rustix::io::Errno;
10use rustix::process::geteuid;
11use zeroize::Zeroizing;
12
13const PRIVATE_MODE: u32 = 0o600;
15
16const GROUP_OTHER_BITS: u32 = 0o077;
19
20#[derive(Debug, thiserror::Error)]
24#[non_exhaustive]
25pub enum PrivateFileError {
26 #[error("file already exists and will not be overwritten")]
28 AlreadyExists,
29 #[error("file is a symbolic link")]
31 Symlink,
32 #[error("file is not a regular file")]
34 NotRegularFile,
35 #[error("file mode {mode:04o} is wider than 0600")]
37 TooPermissive {
38 mode: u32,
40 },
41 #[error("file is larger than {limit} bytes")]
43 TooLarge {
44 limit: usize,
46 },
47 #[error("file is owned by uid {uid}, not by the user running stratum")]
51 WrongOwner {
52 uid: u32,
54 },
55 #[error("{0}")]
57 Io(#[source] io::Error),
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub(crate) enum ModePolicy {
63 OwnerOnly,
65 Any,
67}
68
69pub(crate) fn read(
82 path: &Path,
83 limit: usize,
84 policy: ModePolicy,
85) -> Result<Zeroizing<Vec<u8>>, PrivateFileError> {
86 let flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC;
87 let fd = rustix::fs::open(path, flags, Mode::empty()).map_err(|errno| {
88 if errno == Errno::LOOP {
89 PrivateFileError::Symlink
90 } else {
91 PrivateFileError::Io(io::Error::from(errno))
92 }
93 })?;
94 let file = File::from(fd);
95 let opened = file.metadata().map_err(PrivateFileError::Io)?;
96 if !opened.is_file() {
97 return Err(PrivateFileError::NotRegularFile);
98 }
99 if policy == ModePolicy::OwnerOnly {
100 let mode = opened.mode() & 0o7777;
101 if mode & GROUP_OTHER_BITS != 0 {
102 return Err(PrivateFileError::TooPermissive { mode });
103 }
104 let euid = geteuid();
105 if !euid.is_root() && opened.uid() != euid.as_raw() {
106 return Err(PrivateFileError::WrongOwner { uid: opened.uid() });
107 }
108 }
109 let cap = u64::try_from(limit).map_or(u64::MAX, |n| n.saturating_add(1));
110 let mut contents = Zeroizing::new(Vec::with_capacity(limit.saturating_add(1)));
111 file.take(cap)
112 .read_to_end(&mut contents)
113 .map_err(PrivateFileError::Io)?;
114 if contents.len() > limit {
115 return Err(PrivateFileError::TooLarge { limit });
116 }
117 Ok(contents)
118}
119
120pub(crate) fn create(path: &Path, contents: &[u8]) -> Result<(), PrivateFileError> {
127 let mut file = OpenOptions::new()
128 .write(true)
129 .create_new(true)
130 .mode(PRIVATE_MODE)
131 .open(path)
132 .map_err(|err| {
133 if err.kind() == io::ErrorKind::AlreadyExists {
134 PrivateFileError::AlreadyExists
135 } else {
136 PrivateFileError::Io(err)
137 }
138 })?;
139 let written = file
140 .write_all(contents)
141 .and_then(|()| file.sync_all())
142 .map_err(PrivateFileError::Io);
143 if let Err(err) = written {
144 drop(file);
145 let _removed = fs::remove_file(path);
147 return Err(err);
148 }
149 sync_parent(path);
150 Ok(())
151}
152
153pub(crate) fn remove(path: &Path) -> Result<(), PrivateFileError> {
155 fs::remove_file(path).map_err(PrivateFileError::Io)?;
156 sync_parent(path);
157 Ok(())
158}
159
160fn sync_parent(path: &Path) {
165 let parent = match path.parent() {
166 Some(dir) if !dir.as_os_str().is_empty() => dir,
167 _ => Path::new("."),
168 };
169 if let Ok(dir) = File::open(parent) {
170 let _synced = dir.sync_all();
171 }
172}