1use std::borrow::Cow;
5use std::fs::File;
6use std::io::{self, Write};
7use std::path::{Path, PathBuf};
8use std::sync::Arc;
9
10use crate::access::WriteProbe;
11use crate::paths::extended;
12
13pub trait Fs: Send + Sync {
14 fn root(&self) -> Option<&Path>;
17
18 fn exists(&self, path: &Path) -> bool;
19
20 fn is_dir(&self, path: &Path) -> bool;
21
22 fn read_to_string(&self, path: &Path) -> io::Result<String>;
23
24 fn read(&self, path: &Path) -> io::Result<Vec<u8>>;
26
27 fn file_size(&self, path: &Path) -> io::Result<u64> {
30 self.read(path).map(|bytes| bytes.len() as u64)
31 }
32
33 fn write(&self, path: &Path, contents: &[u8]) -> io::Result<()>;
34
35 fn write_new(&self, path: &Path, contents: &[u8], like: Option<&Path>) -> io::Result<()>;
40
41 fn replace(&self, from: &Path, to: &Path) -> io::Result<()>;
44
45 fn write_private(&self, path: &Path, contents: &[u8]) -> io::Result<()>;
49
50 fn create_dir_all(&self, path: &Path) -> io::Result<()>;
51
52 fn create_private_dir_all(&self, path: &Path) -> io::Result<()>;
56
57 fn remove_file(&self, path: &Path) -> io::Result<()>;
58
59 fn is_regular_file(&self, path: &Path) -> bool;
62
63 fn overwrite_with_zeros(&self, path: &Path) -> io::Result<()>;
69
70 fn remove_dir_all(&self, path: &Path) -> io::Result<()>;
71
72 fn read_dir(&self, path: &Path) -> io::Result<Vec<PathBuf>>;
74
75 fn open_lock_file(&self, path: &Path) -> io::Result<File>;
78
79 fn canonicalize(&self, path: &Path) -> io::Result<PathBuf> {
83 Ok(path.to_path_buf())
84 }
85
86 fn note_dependency(&self, _path: &Path) {}
91
92 fn write_probe(&self) -> Option<WriteProbe> {
97 None
98 }
99}
100
101#[derive(Debug, Clone, Copy, Default)]
103pub struct RealFs;
104
105pub(crate) fn long(path: &Path) -> Cow<'_, Path> {
111 const LIMIT: usize = 248;
113 if cfg!(windows) && path.as_os_str().len() >= LIMIT {
114 extended(path)
115 } else {
116 Cow::Borrowed(path)
117 }
118}
119
120impl Fs for RealFs {
121 fn root(&self) -> Option<&Path> {
122 None
123 }
124
125 fn exists(&self, path: &Path) -> bool {
126 long(path).exists()
127 }
128
129 fn is_dir(&self, path: &Path) -> bool {
130 long(path).is_dir()
131 }
132
133 fn read_to_string(&self, path: &Path) -> io::Result<String> {
134 std::fs::read_to_string(long(path))
135 }
136
137 fn read(&self, path: &Path) -> io::Result<Vec<u8>> {
138 std::fs::read(long(path))
139 }
140
141 fn file_size(&self, path: &Path) -> io::Result<u64> {
142 std::fs::metadata(long(path)).map(|meta| meta.len())
143 }
144
145 fn write(&self, path: &Path, contents: &[u8]) -> io::Result<()> {
146 std::fs::write(long(path), contents)
147 }
148
149 fn write_new(&self, path: &Path, contents: &[u8], like: Option<&Path>) -> io::Result<()> {
150 let path = long(path);
151 let like = like.map(long);
152 let mut options = File::options();
153 options.write(true).create_new(true);
154 if let Some(like) = &like {
155 platform::copy_open_options(&mut options, like)?;
156 }
157 let mut file = options.open(&path)?;
158 let written = (|| {
159 if let Some(like) = &like {
160 platform::copy_permissions(like, &path, &file)?;
161 }
162 file.write_all(contents)?;
163 file.sync_all()
164 })();
165 if written.is_err() {
166 drop(file);
167 let _ = std::fs::remove_file(&path);
168 }
169 written
170 }
171
172 fn replace(&self, from: &Path, to: &Path) -> io::Result<()> {
173 let to = long(to);
174 std::fs::rename(long(from), &to)?;
175 platform::sync_parent(&to)
176 }
177
178 fn write_private(&self, path: &Path, contents: &[u8]) -> io::Result<()> {
179 let path = long(path);
180 let mut options = File::options();
181 options.write(true).create(true).truncate(true);
182 platform::private_open_options(&mut options);
183 let mut file = options.open(&path)?;
184 platform::make_private(&path, &file)?;
186 file.write_all(contents)?;
187 file.sync_all()
188 }
189
190 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
191 std::fs::create_dir_all(long(path))
192 }
193
194 fn create_private_dir_all(&self, path: &Path) -> io::Result<()> {
195 let path = long(path);
196 std::fs::create_dir_all(&path)?;
197 platform::make_private_dir(&path)
198 }
199
200 fn remove_file(&self, path: &Path) -> io::Result<()> {
201 std::fs::remove_file(long(path))
202 }
203
204 fn is_regular_file(&self, path: &Path) -> bool {
205 std::fs::symlink_metadata(long(path)).is_ok_and(|meta| meta.file_type().is_file())
206 }
207
208 fn overwrite_with_zeros(&self, path: &Path) -> io::Result<()> {
209 let path = long(path);
210 if !std::fs::symlink_metadata(&path)?.file_type().is_file() {
211 return Err(io::Error::new(
212 io::ErrorKind::InvalidInput,
213 "not a regular file",
214 ));
215 }
216 let mut file = File::options().write(true).open(&path)?;
219 let mut left = file.metadata()?.len();
220 let zeros = [0u8; 64 * 1024];
221 while left > 0 {
222 let chunk = usize::try_from(left).map_or(zeros.len(), |left| left.min(zeros.len()));
223 file.write_all(&zeros[..chunk])?;
224 left -= chunk as u64;
225 }
226 file.sync_all()
227 }
228
229 fn remove_dir_all(&self, path: &Path) -> io::Result<()> {
230 std::fs::remove_dir_all(long(path))
231 }
232
233 fn read_dir(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
234 let mut entries = std::fs::read_dir(long(path))?
236 .map(|entry| entry.map(|entry| path.join(entry.file_name())))
237 .collect::<io::Result<Vec<_>>>()?;
238 entries.sort();
239 Ok(entries)
240 }
241
242 fn open_lock_file(&self, path: &Path) -> io::Result<File> {
243 File::options()
244 .read(true)
245 .write(true)
246 .create(true)
247 .truncate(false)
248 .open(long(path))
249 }
250
251 fn canonicalize(&self, path: &Path) -> io::Result<PathBuf> {
252 std::fs::canonicalize(long(path))
253 }
254
255 fn write_probe(&self) -> Option<WriteProbe> {
256 Some(Arc::new(crate::access::probe))
257 }
258}
259
260#[cfg(unix)]
261mod platform {
262 use std::fs::{File, OpenOptions, Permissions};
263 use std::io;
264 use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
265 use std::path::Path;
266
267 pub fn copy_open_options(options: &mut OpenOptions, like: &Path) -> io::Result<()> {
268 let mode = std::fs::metadata(like)?.permissions().mode();
269 options.mode(mode & 0o7777);
270 Ok(())
271 }
272
273 pub fn copy_permissions(like: &Path, _path: &Path, file: &File) -> io::Result<()> {
275 let mode = std::fs::metadata(like)?.permissions().mode();
276 file.set_permissions(Permissions::from_mode(mode & 0o7777))
277 }
278
279 pub fn private_open_options(options: &mut OpenOptions) {
280 options.mode(0o600);
281 }
282
283 pub fn make_private(_path: &Path, file: &File) -> io::Result<()> {
284 file.set_permissions(Permissions::from_mode(0o600))
285 }
286
287 pub fn make_private_dir(path: &Path) -> io::Result<()> {
288 std::fs::set_permissions(path, Permissions::from_mode(0o700))
289 }
290
291 pub fn sync_parent(path: &Path) -> io::Result<()> {
293 match path.parent().filter(|dir| !dir.as_os_str().is_empty()) {
294 Some(dir) => File::open(dir)?.sync_all(),
295 None => Ok(()),
296 }
297 }
298}
299
300#[cfg(windows)]
301mod platform {
302 use std::fs::{File, OpenOptions};
303 use std::io;
304 use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
305 use std::path::Path;
306
307 use windows_permissions::constants::{AceFlags, SeObjectType, SecurityInformation};
308 use windows_permissions::{LocalBox, SecurityDescriptor, wrappers};
309
310 const KEPT_ATTRIBUTES: u32 = 0x2 | 0x4 | 0x20 | 0x2000; pub fn copy_open_options(options: &mut OpenOptions, like: &Path) -> io::Result<()> {
318 let attributes = std::fs::metadata(like)?.file_attributes() & KEPT_ATTRIBUTES;
319 options.attributes(attributes);
320 Ok(())
321 }
322
323 pub fn copy_permissions(like: &Path, path: &Path, _file: &File) -> io::Result<()> {
326 let sd = wrappers::GetNamedSecurityInfo(
327 like.as_os_str(),
328 SeObjectType::SE_FILE_OBJECT,
329 SecurityInformation::Dacl,
330 )?;
331 let sddl = sd.as_sddl()?.to_string_lossy().into_owned();
332 let protected = dacl_flags(&sddl).contains('P');
333 let Some(dacl) = sd.dacl() else {
334 return Ok(());
335 };
336 let explicit = (0..dacl.len())
337 .filter_map(|index| dacl.get_ace(index))
338 .any(|ace| !ace.flags().contains(AceFlags::Inherited));
339 if !protected && !explicit {
340 return Ok(());
341 }
342 let protection = if protected {
343 SecurityInformation::ProtectedDacl
344 } else {
345 SecurityInformation::UnprotectedDacl
346 };
347 wrappers::SetNamedSecurityInfo(
348 path.as_os_str(),
349 SeObjectType::SE_FILE_OBJECT,
350 SecurityInformation::Dacl | protection,
351 None,
352 None,
353 Some(dacl),
354 None,
355 )
356 }
357
358 fn dacl_flags(sddl: &str) -> String {
361 let Some(start) = sddl.find("D:") else {
362 return String::new();
363 };
364 let rest = &sddl[start + 2..];
365 let end = rest.find('(').unwrap_or(rest.len());
366 rest[..end].replace("AI", "").replace("AR", "")
367 }
368
369 pub fn private_open_options(_options: &mut OpenOptions) {}
370
371 pub fn make_private(path: &Path, _file: &File) -> io::Result<()> {
372 owner_only(path, false)
373 }
374
375 pub fn make_private_dir(path: &Path) -> io::Result<()> {
376 owner_only(path, true)
377 }
378
379 fn owner_only(path: &Path, dir: bool) -> io::Result<()> {
382 let sd = wrappers::GetNamedSecurityInfo(
383 path.as_os_str(),
384 SeObjectType::SE_FILE_OBJECT,
385 SecurityInformation::Owner,
386 )?;
387 let owner = sd
388 .owner()
389 .ok_or_else(|| io::Error::other("the file has no owner"))?;
390 let inherit = if dir { "OICI" } else { "" };
391 let sddl = format!("D:P(A;{inherit};FA;;;{owner})");
392 let private: LocalBox<SecurityDescriptor> = sddl.parse()?;
393 let dacl = private
394 .dacl()
395 .ok_or_else(|| io::Error::other("the private DACL did not parse"))?;
396 wrappers::SetNamedSecurityInfo(
397 path.as_os_str(),
398 SeObjectType::SE_FILE_OBJECT,
399 SecurityInformation::Dacl | SecurityInformation::ProtectedDacl,
400 None,
401 None,
402 Some(dacl),
403 None,
404 )
405 }
406
407 pub fn sync_parent(_path: &Path) -> io::Result<()> {
409 Ok(())
410 }
411}