1#[cfg(unix)]
4use super::flush_batch::BatchFolder;
5use super::{FileName, FlushBatch, StoreReadLock};
6use std::fs;
7use std::io::{self, Read, Write};
8use std::path::{Path, PathBuf};
9use std::sync::Arc;
10
11#[derive(Debug, thiserror::Error)]
13pub enum FileError {
14 #[error("{operation} {}: {source}", path.display())]
16 Io {
17 operation: &'static str,
19 path: PathBuf,
21 #[source]
23 source: Box<dyn std::error::Error + Send + Sync>,
24 },
25 #[error("{operation} {}: {source}; open files: {}", path.display(), held_paths(held))]
29 HeldOpen {
30 operation: &'static str,
32 path: PathBuf,
34 held: Vec<PathBuf>,
36 #[source]
38 source: Box<dyn std::error::Error + Send + Sync>,
39 },
40 #[error("sync directory after replacing {}: {source}", path.display())]
42 AfterReplace {
43 path: PathBuf,
45 #[source]
47 source: Box<dyn std::error::Error + Send + Sync>,
48 },
49 #[error("sync directory after removing {}: {source}", path.display())]
51 AfterRemove {
52 path: PathBuf,
54 #[source]
56 source: Box<dyn std::error::Error + Send + Sync>,
57 },
58 #[error("{operation}; removing temporary file failed: {cleanup}")]
60 Cleanup {
61 #[source]
63 operation: Box<FileError>,
64 cleanup: Box<dyn std::error::Error + Send + Sync>,
66 },
67 #[error("{}: the device is locked, and the file is protected until it unlocks", path.display())]
71 DeviceLocked {
72 path: PathBuf,
75 },
76 #[error(transparent)]
79 Shutdown(#[from] crate::task::Shutdown),
80 #[error(transparent)]
83 Bug(#[from] crate::task::Bug),
84}
85
86impl crate::task::CarriesBug for FileError {
87 fn bug(&self) -> Option<&crate::task::Bug> {
88 match self {
89 Self::Bug(bug) => Some(bug),
90 Self::Cleanup { operation, .. } => operation.bug(),
91 _ => None,
92 }
93 }
94}
95
96impl From<crate::task::TaskFailed> for FileError {
97 fn from(failed: crate::task::TaskFailed) -> Self {
98 failed.into_error()
99 }
100}
101
102fn held_paths(paths: &[PathBuf]) -> String {
103 paths.iter().map(|path| path.display().to_string()).collect::<Vec<_>>().join(", ")
104}
105
106impl FileError {
107 pub fn installed_new_bytes(&self) -> bool {
109 matches!(self, Self::AfterReplace { .. })
110 }
111
112 pub(crate) fn at(operation: &'static str, path: &Path, source: io::Error) -> Self {
113 Self::Io { operation, path: path.to_owned(), source: Box::new(source) }
114 }
115}
116
117#[derive(Clone, Debug)]
120pub struct AtomicFile {
121 path: PathBuf,
122}
123
124impl AtomicFile {
125 pub(crate) fn new(path: PathBuf) -> Self {
126 Self { path }
127 }
128
129 pub fn read_optional(&self) -> Result<Option<Vec<u8>>, FileError> {
132 read_optional(&self.path)
133 }
134
135 pub fn open_reader(&self) -> Result<super::FileReader, super::ObservationError> {
137 super::FileReader::open(&self.path)
138 }
139
140 pub fn replace(&self, bytes: &[u8]) -> Result<(), FileError> {
150 install(prepare(&self.path, bytes, &own_temporaries(&self.path))?, &self.path)
151 }
152
153 pub fn write_recorded(&self, bytes: &[u8]) -> Result<(), FileError> {
159 let path = self.resolved()?;
160 #[cfg(any(test, feature = "test-utils"))]
161 super::reached::reached(&path);
162 let mut file = owned_options()
163 .create(true)
164 .truncate(true)
165 .open(&path)
166 .map_err(|source| FileError::at("create owned file", &path, source))?;
167 let regular = file
168 .metadata()
169 .map_err(|source| FileError::at("inspect owned file", &path, source))?
170 .is_file();
171 if !regular {
172 return Err(FileError::at(
173 "create owned file",
174 &path,
175 io::Error::new(io::ErrorKind::InvalidInput, "a regular file is required"),
176 ));
177 }
178 file.write_all(bytes)
179 .and_then(|()| sync_file(&file))
180 .map_err(|source| FileError::at("write owned file", &path, source))?;
181 #[cfg(unix)]
182 sync_directory(parent(&path))
183 .map_err(|source| FileError::at("sync owned file directory", &path, source))?;
184 Ok(())
185 }
186
187 pub fn overwrite_at(&self, offset: u64, bytes: &[u8]) -> Result<(), super::ObservationError> {
193 let path = self.resolved()?;
194 #[cfg(any(test, feature = "test-utils"))]
195 super::reached::reached(&path);
196 let file = owned_options()
197 .open(&path)
198 .map_err(|error| super::ObservationError::at("open owned file", &path, error))?;
199 let metadata =
200 file.metadata().map_err(|source| FileError::at("inspect owned file", &path, source))?;
201 if !metadata.is_file()
202 || offset.checked_add(bytes.len() as u64).is_none_or(|end| end > metadata.len())
203 {
204 return Err(FileError::at(
205 "overwrite owned file",
206 &path,
207 io::Error::new(io::ErrorKind::InvalidInput, "a range within a regular file"),
208 )
209 .into());
210 }
211 write_all_at(&file, offset, bytes)
214 .and_then(|()| file.sync_all())
215 .map_err(|source| FileError::at("overwrite owned file", &path, source))?;
216 Ok(())
217 }
218
219 pub fn set_len(&self, length: u64) -> Result<(), super::ObservationError> {
222 let path = self.resolved()?;
223 #[cfg(any(test, feature = "test-utils"))]
224 super::reached::reached(&path);
225 let file = owned_options()
226 .open(&path)
227 .map_err(|error| super::ObservationError::at("open owned file", &path, error))?;
228 let regular =
229 file.metadata().map_err(|source| FileError::at("inspect owned file", &path, source))?;
230 if !regular.is_file() {
231 return Err(FileError::at(
232 "resize owned file",
233 &path,
234 io::Error::new(io::ErrorKind::InvalidInput, "a regular file is required"),
235 )
236 .into());
237 }
238 file.set_len(length)
241 .and_then(|()| file.sync_all())
242 .map_err(|source| FileError::at("resize owned file", &path, source))?;
243 Ok(())
244 }
245
246 fn resolved(&self) -> Result<PathBuf, FileError> {
249 let directory = fs::canonicalize(parent(&self.path))
250 .map_err(|source| FileError::at("resolve parent directory", &self.path, source))?;
251 let name = self.path.file_name().ok_or_else(|| {
252 FileError::at(
253 "create owned file",
254 &self.path,
255 io::Error::new(io::ErrorKind::InvalidInput, "file name required"),
256 )
257 })?;
258 Ok(directory.join(name))
259 }
260
261 pub fn remove(&self) -> Result<(), FileError> {
265 remove(&self.path)
266 }
267
268 pub fn remove_with_temporaries(&self) -> Result<(), FileError> {
273 let prefix = own_temporaries(&self.path);
274 remove_named(parent(&self.path), |name| {
275 let random = name.strip_prefix(prefix.as_bytes());
276 random.is_some_and(|random| random.len() == TEMPORARY_RANDOM)
277 })?;
278 remove(&self.path)
279 }
280
281 #[cfg(any(test, feature = "test-utils"))]
284 pub fn leave_temporary(&self, bytes: &[u8]) -> PathBuf {
285 let temp = prepare(&self.path, bytes, &own_temporaries(&self.path)).unwrap();
286 temp.keep().expect("a temporary file can be kept").1
287 }
288}
289
290pub struct FileWriter {
295 file: Arc<tokio::sync::Mutex<LockedWriter>>,
296 path: PathBuf,
297 bugs: crate::task::BugSinkRef,
299}
300struct LockedWriter {
301 file: fs::File,
302 lock: Option<Arc<StoreReadLock>>,
305}
306
307#[derive(Clone)]
312pub struct WriterFolder {
313 path: PathBuf,
314 lock: Arc<StoreReadLock>,
315 bugs: crate::task::BugSinkRef,
317}
318
319impl WriterFolder {
320 pub(super) fn open(
324 path: &Path,
325 lock: Arc<StoreReadLock>,
326 bugs: crate::task::BugSinkRef,
327 ) -> Result<Self, FileError> {
328 let path = fs::canonicalize(path)
329 .map_err(|source| FileError::at("resolve parent directory", path, source))?;
330 Ok(Self { path, lock, bugs })
331 }
332
333 pub fn create(&self, name: &FileName) -> Result<FileWriter, FileError> {
336 let path = self.path.join(name.as_str());
337 let file = create_new(&path)
338 .map_err(|source| FileError::at("create owned file", &path, source))?;
339 Ok(FileWriter::new(file, path, Some(self.lock.clone()), self.bugs.clone()))
340 }
341
342 pub fn write_whole(
347 &self,
348 name: &FileName,
349 bytes: &[u8],
350 batch: &mut FlushBatch,
351 ) -> Result<(), FileError> {
352 let path = self.path.join(name.as_str());
353 let mut file = create_new(&path)
354 .map_err(|source| FileError::at("create owned file", &path, source))?;
355 file.write_all(bytes)
356 .map_err(|source| FileError::at("append owned file", &path, source))?;
357 sync_file(&file).map_err(|source| FileError::at("sync owned file", &path, source))?;
358 #[cfg(unix)]
359 batch.add(
360 BatchFolder::open(self.path.clone(), Some(self.lock.clone()))
361 .map_err(|source| FileError::at("sync owned file", &path, source))?,
362 );
363 #[cfg(windows)]
364 batch.add();
365 Ok(())
366 }
367}
368
369impl FileWriter {
370 fn new(
371 file: fs::File,
372 path: PathBuf,
373 lock: Option<Arc<StoreReadLock>>,
374 bugs: crate::task::BugSinkRef,
375 ) -> Self {
376 Self { file: Arc::new(tokio::sync::Mutex::new(LockedWriter { file, lock })), path, bugs }
377 }
378
379 pub(super) fn resume(
384 file: &AtomicFile,
385 lock: StoreReadLock,
386 bugs: crate::task::BugSinkRef,
387 length: u64,
388 ) -> Result<Self, FileError> {
389 use std::io::Seek;
390 let path = file.resolved()?;
391 let mut file = owned_options()
392 .open(&path)
393 .map_err(|source| FileError::at("reopen owned file", &path, source))?;
394 let metadata =
395 file.metadata().map_err(|source| FileError::at("inspect owned file", &path, source))?;
396 if !metadata.is_file() || metadata.len() < length {
397 return Err(FileError::at(
398 "reopen owned file",
399 &path,
400 io::Error::new(io::ErrorKind::InvalidInput, "a regular file holding its bytes"),
401 ));
402 }
403 file.set_len(length)
404 .and_then(|()| file.seek(io::SeekFrom::Start(length)).map(|_| ()))
405 .map_err(|source| FileError::at("reopen owned file", &path, source))?;
406 Ok(Self::new(file, path, Some(Arc::new(lock)), bugs))
407 }
408
409 pub async fn write_from<R: tokio::io::AsyncRead + Unpin>(
412 mut self,
413 reader: &mut R,
414 mut written: impl FnMut(&[u8]),
415 batch: &mut FlushBatch,
416 ) -> Result<(), FileError> {
417 use tokio::io::AsyncReadExt;
418 let mut buffer = vec![0; 64 * 1024];
419 loop {
420 let count = reader
421 .read(&mut buffer)
422 .await
423 .map_err(|source| FileError::at("read file source", &self.path, source))?;
424 if count == 0 {
425 break;
426 }
427 self.append(&buffer[..count]).await?;
428 written(&buffer[..count]);
429 }
430 self.finish_into(batch).await
431 }
432
433 pub async fn append(&mut self, bytes: &[u8]) -> Result<(), FileError> {
435 let bytes = bytes.to_vec();
436 self.run("append owned file", move |writer, _| writer.file.write_all(&bytes)).await
437 }
438
439 pub async fn finish(self) -> Result<(), FileError> {
442 self.run("sync owned file", |writer, path| {
443 sync_file(&writer.file)?;
444 #[cfg(unix)]
445 sync_directory(parent(path))?;
446 #[cfg(not(unix))]
447 let _ = path;
448 Ok(())
449 })
450 .await
451 }
452
453 pub async fn sync(&mut self) -> Result<(), FileError> {
457 self.run("sync owned file", |writer, path| {
458 sync_file(&writer.file)?;
459 #[cfg(unix)]
460 sync_directory(parent(path))?;
461 #[cfg(not(unix))]
462 let _ = path;
463 Ok(())
464 })
465 .await
466 }
467
468 pub async fn finish_into(self, batch: &mut FlushBatch) -> Result<(), FileError> {
471 #[cfg(unix)]
472 {
473 let folder = self
474 .run("sync owned file", |writer, path| {
475 sync_file(&writer.file)?;
476 BatchFolder::open(parent(path).to_owned(), writer.lock.take())
477 })
478 .await?;
479 batch.add(folder);
480 }
481 #[cfg(windows)]
483 {
484 self.run("sync owned file", |writer, _| {
485 sync_file(&writer.file)?;
486 drop(writer.lock.take());
487 Ok(())
488 })
489 .await?;
490 batch.add();
491 }
492 Ok(())
493 }
494
495 async fn run<T: Send + 'static>(
496 &self,
497 operation: &'static str,
498 run: impl FnOnce(&mut LockedWriter, &Path) -> io::Result<T> + Send + 'static,
499 ) -> Result<T, FileError> {
500 let mut file = self.file.clone().lock_owned().await;
503 let path = self.path.clone();
504 crate::task::blocking_completing(operation, self.bugs.clone(), move || {
505 run(&mut file, &path).map_err(|source| FileError::at(operation, &path, source))
506 })
507 .await?
508 }
509}
510
511fn write_all_at(file: &fs::File, offset: u64, bytes: &[u8]) -> io::Result<()> {
513 #[cfg(unix)]
514 {
515 use std::os::unix::fs::FileExt;
516 file.write_all_at(bytes, offset)
517 }
518 #[cfg(windows)]
519 {
520 use std::os::windows::fs::FileExt;
521 let (mut offset, mut bytes) = (offset, bytes);
522 while !bytes.is_empty() {
523 match file.seek_write(bytes, offset) {
524 Ok(0) => return Err(io::ErrorKind::WriteZero.into()),
525 Ok(count) => {
526 bytes = &bytes[count..];
527 offset += count as u64;
528 }
529 Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
530 Err(error) => return Err(error),
531 }
532 }
533 Ok(())
534 }
535}
536
537pub(super) fn sync_file(file: &fs::File) -> io::Result<()> {
541 #[cfg(unix)]
542 {
543 rustix::fs::fsync(file).map_err(Into::into)
544 }
545 #[cfg(windows)]
546 {
547 file.sync_all()
548 }
549}
550
551pub(super) fn exists(operation: &'static str, path: &Path) -> Result<bool, FileError> {
554 match fs::symlink_metadata(path) {
555 Ok(_) => Ok(true),
556 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
557 Err(source) => Err(FileError::at(operation, path, source)),
558 }
559}
560
561pub(crate) fn remove(path: &Path) -> Result<(), FileError> {
562 match fs::remove_file(path) {
563 Ok(()) => {}
564 Err(error) if error.kind() == io::ErrorKind::NotFound => {
565 tracing::debug!(path = %path.display(), "file is already absent");
566 }
567 Err(source) => return Err(FileError::at("remove file", path, source)),
568 }
569 #[cfg(unix)]
570 match sync_directory(parent(path)) {
571 Ok(()) => {}
572 Err(error) if error.kind() == io::ErrorKind::NotFound => {
573 tracing::debug!(path = %path.display(), "file's parent is absent");
574 }
575 Err(source) => {
576 return Err(FileError::AfterRemove { path: path.to_owned(), source: Box::new(source) })
577 }
578 }
579 Ok(())
580}
581
582pub(crate) fn remove_empty_folder(path: &Path) -> Result<(), FileError> {
587 match fs::remove_dir(path) {
588 Ok(()) => {}
589 Err(error) if error.kind() == io::ErrorKind::NotFound => {
590 tracing::debug!(path = %path.display(), "folder is already absent");
591 }
592 Err(error) if error.kind() == io::ErrorKind::DirectoryNotEmpty => {
593 tracing::debug!(path = %path.display(), "leaving a folder that holds files");
594 return Ok(());
595 }
596 Err(source) => return Err(FileError::at("remove folder", path, source)),
597 }
598 #[cfg(unix)]
600 match sync_directory(parent(path)) {
601 Ok(()) => {}
602 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
603 Err(source) => {
604 return Err(FileError::AfterRemove { path: path.to_owned(), source: Box::new(source) })
605 }
606 }
607 Ok(())
608}
609
610pub(crate) fn read_optional(path: &Path) -> Result<Option<Vec<u8>>, FileError> {
611 let result = open_reader(path).and_then(|mut file| {
612 let mut bytes = Vec::new();
613 file.read_to_end(&mut bytes)?;
614 Ok(bytes)
615 });
616 match result {
617 Ok(bytes) => Ok(Some(bytes)),
618 Err(source) if source.kind() == io::ErrorKind::NotFound => {
619 tracing::debug!(path = %path.display(), "file is absent");
620 Ok(None)
621 }
622 Err(source) => Err(FileError::at("read file", path, source)),
623 }
624}
625
626#[cfg(any(test, feature = "in-memory-keychain"))]
629pub fn read_existing(path: &Path) -> Result<Vec<u8>, FileError> {
630 read_optional(path)?
631 .ok_or_else(|| FileError::at("read file", path, io::ErrorKind::NotFound.into()))
632}
633
634pub(crate) fn read_json<T: serde::de::DeserializeOwned>(
637 path: &Path,
638 operation: &'static str,
639) -> Result<Option<T>, FileError> {
640 read_optional(path)?
641 .map(|bytes| {
642 serde_json::from_slice(&bytes).map_err(|error| {
643 FileError::at(operation, path, io::Error::new(io::ErrorKind::InvalidData, error))
644 })
645 })
646 .transpose()
647}
648
649fn open_reader(path: &Path) -> io::Result<fs::File> {
650 let mut options = fs::OpenOptions::new();
651 options.read(true);
652 #[cfg(windows)]
653 {
654 use std::os::windows::fs::OpenOptionsExt;
655 use windows_sys::Win32::Storage::FileSystem::{
656 FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
657 };
658 options.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE);
659 }
660 options.open(path)
661}
662
663pub fn replace(path: &Path, bytes: &[u8]) -> Result<(), FileError> {
669 install(prepare(path, bytes, TEMPORARY)?, path)
670}
671
672pub(super) fn remove_temporaries(folder: &Path) -> Result<(), FileError> {
676 remove_named(folder, |name| name.starts_with(TEMPORARY.as_bytes()))
677}
678
679fn remove_named(folder: &Path, named: impl Fn(&[u8]) -> bool) -> Result<(), FileError> {
682 let entries = match fs::read_dir(folder) {
683 Ok(entries) => entries,
684 Err(error) if error.kind() == io::ErrorKind::NotFound => {
685 tracing::debug!(path = %folder.display(), "folder is absent");
686 return Ok(());
687 }
688 Err(source) => return Err(FileError::at("list folder", folder, source)),
689 };
690 for entry in entries {
691 let entry = entry.map_err(|source| FileError::at("list folder", folder, source))?;
692 if named(entry.file_name().as_encoded_bytes()) {
693 remove(&entry.path())?;
694 }
695 }
696 Ok(())
697}
698
699const TEMPORARY: &str = ".coven-write-";
701
702const TEMPORARY_RANDOM: usize = 6;
705
706fn own_temporaries(path: &Path) -> String {
711 let name = path.file_name().expect("an owned file has a name").to_string_lossy();
712 format!("{TEMPORARY}{name}-")
713}
714
715fn install(temp: tempfile::NamedTempFile, path: &Path) -> Result<(), FileError> {
718 #[cfg(unix)]
719 {
720 match temp.persist(path) {
721 Ok(file) => drop(file),
722 Err(error) => {
723 return Err(cleanup(
724 error.file,
725 FileError::at("rename temporary file", path, error.error),
726 ));
727 }
728 }
729 sync_directory(parent(path)).map_err(|source| FileError::AfterReplace {
730 path: path.to_owned(),
731 source: Box::new(source),
732 })
733 }
734 #[cfg(windows)]
735 {
736 let mut temp = temp;
737 if let Err(source) = windows_rename(temp.as_file(), path) {
738 return Err(cleanup(temp, FileError::at("POSIX rename temporary file", path, source)));
739 }
740 temp.disable_cleanup(true);
743 Ok(())
744 }
745}
746
747fn prepare(path: &Path, bytes: &[u8], prefix: &str) -> Result<tempfile::NamedTempFile, FileError> {
748 let mut temp = temporary(path, prefix)?;
749 if let Err(source) = temp.write_all(bytes).and_then(|()| temp.as_file().sync_all()) {
750 return Err(cleanup(temp, FileError::at("write and sync temporary file", path, source)));
751 }
752 Ok(temp)
753}
754
755fn temporary(path: &Path, prefix: &str) -> Result<tempfile::NamedTempFile, FileError> {
756 let directory = fs::canonicalize(parent(path))
759 .map_err(|source| FileError::at("resolve parent directory", path, source))?;
760 let mut builder = tempfile::Builder::new();
761 builder.prefix(prefix).rand_bytes(TEMPORARY_RANDOM);
762 #[cfg(unix)]
763 let temp = builder.tempfile_in(directory);
764 #[cfg(windows)]
765 let temp = builder.make_in(directory, create_new);
766 temp.map_err(|source| FileError::at("create temporary file", path, source))
767}
768
769pub(super) fn create_new(path: &Path) -> io::Result<fs::File> {
770 owned_options().create_new(true).open(path)
771}
772
773fn owned_options() -> fs::OpenOptions {
775 let mut options = fs::OpenOptions::new();
776 options.write(true);
777 #[cfg(windows)]
778 {
779 use std::os::windows::fs::OpenOptionsExt;
780 use windows_sys::Win32::Storage::FileSystem::{
781 DELETE, FILE_ATTRIBUTE_NORMAL, FILE_FLAG_WRITE_THROUGH, FILE_GENERIC_READ,
782 FILE_GENERIC_WRITE, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
783 };
784 options
787 .access_mode(DELETE | FILE_GENERIC_READ | FILE_GENERIC_WRITE)
788 .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
789 .attributes(FILE_ATTRIBUTE_NORMAL)
790 .custom_flags(FILE_FLAG_WRITE_THROUGH);
791 }
792 options
793}
794
795fn cleanup(temp: tempfile::NamedTempFile, operation: FileError) -> FileError {
796 match temp.close() {
797 Ok(()) => operation,
798 Err(cleanup) => {
799 FileError::Cleanup { operation: Box::new(operation), cleanup: Box::new(cleanup) }
800 }
801 }
802}
803
804pub(super) fn parent(path: &Path) -> &Path {
805 match path.parent() {
806 Some(parent) if !parent.as_os_str().is_empty() => parent,
807 _ => Path::new("."),
808 }
809}
810
811#[cfg(unix)]
814pub(crate) fn sync_directory(path: &Path) -> io::Result<()> {
815 fs::File::open(path)?.sync_all()
816}
817
818#[cfg(windows)]
819#[expect(
820 clippy::map_err_ignore,
821 reason = "a rename buffer past u32 bytes means the path is too long"
822)]
823fn windows_rename(file: &fs::File, to: &Path) -> io::Result<()> {
824 use std::mem::{offset_of, size_of, size_of_val, MaybeUninit};
825 use std::os::windows::ffi::OsStrExt;
826 use std::os::windows::io::AsRawHandle;
827 use windows_sys::Win32::Storage::FileSystem::{
828 FileRenameInfoEx, SetFileInformationByHandle, FILE_RENAME_INFO,
829 };
830 use windows_sys::Win32::System::WindowsProgramming::{
831 FILE_RENAME_FLAG_POSIX_SEMANTICS, FILE_RENAME_FLAG_REPLACE_IF_EXISTS,
832 };
833
834 let name = to
835 .file_name()
836 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "file name required"))?;
837 let destination = fs::canonicalize(parent(to))?.join(name);
838 let name: Vec<_> = destination.as_os_str().encode_wide().chain(Some(0)).collect();
839 if name[..name.len() - 1].contains(&0) {
840 return Err(io::Error::new(io::ErrorKind::InvalidInput, "NUL in file name"));
841 }
842 let too_long = || io::Error::new(io::ErrorKind::InvalidInput, "rename path is too long");
843 let buffer_size = size_of::<FILE_RENAME_INFO>()
844 .checked_add(size_of_val(name.as_slice()))
845 .ok_or_else(too_long)?;
846 let buffer_size = u32::try_from(buffer_size).map_err(|_| too_long())?;
847 let mut buffer = vec![
850 MaybeUninit::<FILE_RENAME_INFO>::zeroed();
851 (buffer_size as usize).div_ceil(size_of::<FILE_RENAME_INFO>())
852 ];
853 let info = buffer.as_mut_ptr().cast::<FILE_RENAME_INFO>();
854 let result = unsafe {
860 (*info).Anonymous.Flags =
861 FILE_RENAME_FLAG_POSIX_SEMANTICS | FILE_RENAME_FLAG_REPLACE_IF_EXISTS;
862 (*info).FileNameLength = (size_of_val(name.as_slice()) - size_of::<u16>()) as u32;
863 std::ptr::copy_nonoverlapping(
864 name.as_ptr(),
865 info.cast::<u8>().add(offset_of!(FILE_RENAME_INFO, FileName)).cast::<u16>(),
866 name.len(),
867 );
868 SetFileInformationByHandle(file.as_raw_handle(), FileRenameInfoEx, info.cast(), buffer_size)
869 };
870 if result == 0 {
871 Err(io::Error::last_os_error())
874 } else {
875 Ok(())
876 }
877}
878
879#[cfg(unix)]
883pub(crate) fn rename_new(from: &Path, to: &Path) -> io::Result<()> {
884 use rustix::fs::{renameat_with, RenameFlags, CWD};
885 renameat_with(CWD, from, CWD, to, RenameFlags::NOREPLACE).map_err(Into::into)
886}
887
888#[cfg(windows)]
889pub(crate) fn rename_new(from: &Path, to: &Path) -> io::Result<()> {
890 use windows_sys::Win32::Storage::FileSystem::{MoveFileExW, MOVEFILE_WRITE_THROUGH};
891
892 let from = verbatim(from)?;
895 let to = verbatim(to)?;
896 if unsafe { MoveFileExW(from.as_ptr(), to.as_ptr(), MOVEFILE_WRITE_THROUGH) } == 0 {
899 Err(io::Error::last_os_error())
900 } else {
901 Ok(())
902 }
903}
904
905#[cfg(windows)]
913fn verbatim(path: &Path) -> io::Result<Vec<u16>> {
914 use std::os::windows::ffi::OsStrExt;
915 use std::path::{Component, Prefix};
916
917 let absolute = std::path::absolute(path)?;
918 let Some(Component::Prefix(prefix)) = absolute.components().next() else {
919 return Err(io::Error::new(
920 io::ErrorKind::InvalidInput,
921 "an absolute path without a drive or share",
922 ));
923 };
924 let units = absolute.as_os_str().encode_wide();
925 let units: Vec<u16> = match prefix.kind() {
926 Prefix::Disk(_) => r"\\?\".encode_utf16().chain(units).collect(),
927 Prefix::UNC(..) => r"\\?\UNC".encode_utf16().chain(units.skip(1)).collect(),
929 Prefix::Verbatim(_)
930 | Prefix::VerbatimUNC(..)
931 | Prefix::VerbatimDisk(_)
932 | Prefix::DeviceNS(_) => units.collect(),
933 };
934 Ok(units.into_iter().chain(Some(0)).collect())
935}
936
937pub(super) fn sync_publication(path: &Path) -> Result<(), FileError> {
938 #[cfg(unix)]
939 sync_directory(parent(path)).map_err(|source| FileError::AfterReplace {
940 path: path.to_owned(),
941 source: Box::new(source),
942 })?;
943 #[cfg(windows)]
945 let _ = path;
946 Ok(())
947}
948
949#[cfg(test)]
950#[path = "atomic_file_tests.rs"]
951mod tests;