1use std::fs::{self, File, OpenOptions};
19use std::io::Write as _;
20use std::path::{Path, PathBuf};
21
22pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), AtomicError> {
39 AtomicWrite::new(bytes).write(path)
40}
41
42pub(crate) fn validate_unix_mode(mode: Option<u32>) -> std::io::Result<()> {
43 if let Some(mode) = mode
44 && mode & !0o777 != 0
45 {
46 return Err(std::io::Error::new(
47 std::io::ErrorKind::InvalidInput,
48 format!("unix mode {mode:o} contains bits outside 0o777"),
49 ));
50 }
51 Ok(())
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56enum InstallMode {
57 Replace,
60 NewOnly,
63}
64
65#[derive(Debug, Clone)]
96pub struct AtomicWrite<'a> {
97 bytes: &'a [u8],
98 install_mode: InstallMode,
99 unix_mode: Option<u32>,
100 caller_guarded: Option<Option<fs::Permissions>>,
104}
105
106impl<'a> AtomicWrite<'a> {
107 pub fn new(bytes: &'a [u8]) -> Self {
109 Self {
110 bytes,
111 install_mode: InstallMode::Replace,
112 unix_mode: None,
113 caller_guarded: None,
114 }
115 }
116
117 #[cfg(unix)]
120 #[must_use]
121 pub fn mode(mut self, bits: u32) -> Self {
122 self.unix_mode = Some(bits);
123 self
124 }
125
126 #[must_use]
130 pub fn new_only(mut self) -> Self {
131 self.install_mode = InstallMode::NewOnly;
132 self
133 }
134
135 pub fn write(self, path: &Path) -> Result<(), AtomicError> {
141 self.write_with(path, |file, bytes| file.write_all(bytes))
142 }
143
144 pub(crate) fn with_unix_mode(mut self, unix_mode: Option<u32>) -> Self {
147 self.unix_mode = unix_mode;
148 self
149 }
150
151 pub(crate) fn with_permissions(mut self, permissions: Option<fs::Permissions>) -> Self {
155 self.caller_guarded = Some(permissions);
156 self
157 }
158
159 fn write_with(
160 mut self,
161 path: &Path,
162 write: impl FnOnce(&mut File, &[u8]) -> std::io::Result<()>,
163 ) -> Result<(), AtomicError> {
164 validate_unix_mode(self.unix_mode)
165 .map_err(|error| AtomicError::at(AtomicStep::Guard, path, error))?;
166 if let Some(permissions) = self.caller_guarded.take() {
167 return install_with_writer(path, &self, permissions, write);
168 }
169 let permissions = if self.install_mode == InstallMode::NewOnly {
172 None
173 } else {
174 match fs::symlink_metadata(path) {
175 Ok(metadata) if metadata.file_type().is_file() => Some(metadata.permissions()),
176 Ok(_) => {
177 return Err(AtomicError::at(
178 AtomicStep::Guard,
179 path,
180 std::io::Error::new(
181 std::io::ErrorKind::InvalidInput,
182 "atomic target must be a regular file, not a symlink, directory, or special file",
183 ),
184 ));
185 }
186 Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
187 Err(error) => return Err(AtomicError::at(AtomicStep::Guard, path, error)),
188 }
189 };
190 install_with_writer(path, &self, permissions, write)
191 }
192}
193
194#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub enum AtomicStep {
197 Guard,
199 NoParent,
201 NonUtf8Name,
203 Temp,
205 TempExhausted,
207 Write,
209 PreservePermissions,
211 #[cfg(unix)]
216 SetPermissions,
217 Sync,
219 Install,
221 SyncParent,
223}
224
225#[derive(Debug)]
227pub struct AtomicError {
228 pub step: AtomicStep,
230 pub path: PathBuf,
233 pub source: Option<std::io::Error>,
235}
236
237impl AtomicError {
238 fn at(step: AtomicStep, path: &Path, source: std::io::Error) -> Self {
239 Self {
240 step,
241 path: path.to_path_buf(),
242 source: Some(source),
243 }
244 }
245
246 pub fn target_exists(&self) -> bool {
250 self.step == AtomicStep::Install
251 && self
252 .source
253 .as_ref()
254 .is_some_and(|error| error.kind() == std::io::ErrorKind::AlreadyExists)
255 }
256
257 pub fn commit_uncertain(&self) -> bool {
264 self.step == AtomicStep::SyncParent
265 }
266}
267
268impl std::fmt::Display for AtomicError {
269 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
270 let path = self.path.display();
271 let phrase = match self.step {
272 AtomicStep::Guard => "inspect",
273 AtomicStep::NoParent => {
274 return write!(formatter, "has no parent directory for `{path}`");
275 }
276 AtomicStep::NonUtf8Name => {
277 return write!(formatter, "path is not valid UTF-8: `{path}`");
278 }
279 AtomicStep::TempExhausted => {
280 return write!(formatter, "could not allocate temporary file in `{path}`");
281 }
282 AtomicStep::Temp => "temporary file in",
283 AtomicStep::Write => "write",
284 AtomicStep::PreservePermissions => "preserve permissions",
285 #[cfg(unix)]
286 AtomicStep::SetPermissions => "set permissions on",
287 AtomicStep::Sync => "fsync",
288 AtomicStep::Install => "install",
289 AtomicStep::SyncParent => "fsync parent directory",
290 };
291 write!(formatter, "{phrase} `{path}`")?;
292 match &self.source {
293 Some(source) => write!(formatter, ": {source}"),
294 None => Ok(()),
295 }
296 }
297}
298
299const MAX_NAME_BYTES: usize = 255;
301
302fn temp_file_name(file_name: &str, pid: u32, attempt: u32) -> String {
311 let suffix = format!(".afdata.{pid}.{attempt}.tmp");
312 let budget = MAX_NAME_BYTES.saturating_sub(suffix.len() + 1);
314 let stem = &file_name[..file_name.floor_char_boundary(budget)];
315 format!(".{stem}{suffix}")
316}
317
318fn parent_and_name(path: &Path) -> Result<(&Path, String), AtomicError> {
322 let parent = match path.parent() {
323 Some(parent) if parent.as_os_str().is_empty() => Path::new("."),
324 Some(parent) => parent,
325 None => {
326 return Err(AtomicError {
327 step: AtomicStep::NoParent,
328 path: path.to_path_buf(),
329 source: None,
330 });
331 }
332 };
333 let file_name = path
334 .file_name()
335 .and_then(|name| name.to_str())
336 .ok_or_else(|| AtomicError {
337 step: AtomicStep::NonUtf8Name,
338 path: path.to_path_buf(),
339 source: None,
340 })?
341 .to_string();
342 Ok((parent, file_name))
343}
344
345fn allocate_private_temp(parent: &Path, file_name: &str) -> Result<(PathBuf, File), AtomicError> {
346 let pid = std::process::id();
347 for attempt in 0..32_u32 {
348 let candidate = parent.join(temp_file_name(file_name, pid, attempt));
349 let mut options = OpenOptions::new();
350 options.write(true).create_new(true);
351 #[cfg(unix)]
352 {
353 use std::os::unix::fs::OpenOptionsExt as _;
354 options.mode(0o600);
357 }
358 match options.open(&candidate) {
359 Ok(file) => return Ok((candidate, file)),
360 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
361 Err(error) => return Err(AtomicError::at(AtomicStep::Temp, parent, error)),
362 }
363 }
364 Err(AtomicError {
365 step: AtomicStep::TempExhausted,
366 path: parent.to_path_buf(),
367 source: None,
368 })
369}
370
371#[cfg(unix)]
372fn sync_parent(parent: &Path) -> Result<(), AtomicError> {
373 File::open(parent)
374 .and_then(|directory| directory.sync_all())
375 .map_err(|error| AtomicError::at(AtomicStep::SyncParent, parent, error))
376}
377
378#[cfg(not(unix))]
379fn sync_parent(_parent: &Path) -> Result<(), AtomicError> {
380 Ok(())
383}
384
385fn write_temp(
386 mut temp_file: File,
387 temp_path: &Path,
388 target: &Path,
389 request: &AtomicWrite<'_>,
390 permissions: Option<fs::Permissions>,
391 write: impl FnOnce(&mut File, &[u8]) -> std::io::Result<()>,
392) -> Result<(), AtomicError> {
393 write(&mut temp_file, request.bytes)
394 .map_err(|error| AtomicError::at(AtomicStep::Write, target, error))?;
395 if let Some(permissions) = permissions {
396 temp_file
397 .set_permissions(permissions)
398 .map_err(|error| AtomicError::at(AtomicStep::PreservePermissions, target, error))?;
399 }
400 #[cfg(unix)]
401 if let Some(unix_mode) = request.unix_mode {
402 use std::os::unix::fs::PermissionsExt as _;
403 temp_file
404 .set_permissions(fs::Permissions::from_mode(unix_mode))
405 .map_err(|error| AtomicError::at(AtomicStep::SetPermissions, target, error))?;
406 }
407 temp_file
408 .sync_all()
409 .map_err(|error| AtomicError::at(AtomicStep::Sync, temp_path, error))
410}
411
412fn install_with_writer(
420 path: &Path,
421 request: &AtomicWrite<'_>,
422 permissions: Option<fs::Permissions>,
423 write: impl FnOnce(&mut File, &[u8]) -> std::io::Result<()>,
424) -> Result<(), AtomicError> {
425 let (parent, file_name) = parent_and_name(path)?;
426 let (temp_path, temp_file) = allocate_private_temp(parent, &file_name)?;
427 let result = (|| -> Result<(), AtomicError> {
428 write_temp(temp_file, &temp_path, path, request, permissions, write)?;
429 match request.install_mode {
430 InstallMode::Replace => {
431 fs::rename(&temp_path, path)
432 .map_err(|error| AtomicError::at(AtomicStep::Install, path, error))?;
433 }
434 InstallMode::NewOnly => {
435 fs::hard_link(&temp_path, path)
436 .map_err(|error| AtomicError::at(AtomicStep::Install, path, error))?;
437 let _ = fs::remove_file(&temp_path);
442 }
443 }
444 sync_parent(parent)?;
445 Ok(())
446 })();
447 if let Err(error) = &result {
448 if !error.commit_uncertain() {
451 let _ = fs::remove_file(&temp_path);
452 }
453 }
454 result
455}
456
457impl std::error::Error for AtomicError {
458 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
459 self.source.as_ref().map(|error| error as _)
460 }
461}
462
463#[cfg(test)]
464mod tests {
465 #![allow(clippy::unwrap_used, clippy::panic, clippy::expect_used)]
466 use super::*;
467
468 #[test]
469 fn temp_name_stays_within_one_path_component() {
470 let long = "x".repeat(400);
471 let name = temp_file_name(&long, 1234, 0);
472 assert!(name.len() <= MAX_NAME_BYTES, "{} bytes", name.len());
473 assert!(name.starts_with('.'));
474 assert!(name.ends_with(".tmp"));
475 }
476
477 #[test]
478 fn temp_name_truncates_on_a_character_boundary() {
479 let long = "é".repeat(300);
480 let name = temp_file_name(&long, 1234, 0);
481 assert!(name.is_char_boundary(name.len()));
482 assert!(name.len() <= MAX_NAME_BYTES);
483 }
484
485 #[test]
486 fn bare_relative_paths_use_the_current_directory() {
487 let (parent, file_name) = parent_and_name(Path::new("config.json")).unwrap();
488
489 assert_eq!(parent, Path::new("."));
490 assert_eq!(file_name, "config.json");
491 }
492
493 #[test]
494 fn replace_installs_new_bytes_and_leaves_no_temporary_file() {
495 let dir = tempfile::tempdir().unwrap();
496 let path = dir.path().join("config.json");
497 fs::write(&path, b"old").unwrap();
498
499 AtomicWrite::new(b"new").write(&path).unwrap();
500
501 assert_eq!(fs::read(&path).unwrap(), b"new");
502 let strays: Vec<_> = fs::read_dir(dir.path())
503 .unwrap()
504 .filter_map(Result::ok)
505 .filter(|entry| entry.file_name().to_string_lossy().ends_with(".tmp"))
506 .collect();
507 assert!(strays.is_empty(), "temporary files left behind");
508 }
509
510 #[test]
511 fn new_only_refuses_an_existing_target_without_touching_it() {
512 let dir = tempfile::tempdir().unwrap();
513 let path = dir.path().join("config.json");
514 fs::write(&path, b"original").unwrap();
515
516 let error = AtomicWrite::new(b"new")
517 .new_only()
518 .write(&path)
519 .unwrap_err();
520
521 assert!(error.target_exists());
522 assert_eq!(fs::read(&path).unwrap(), b"original");
523 }
524
525 #[cfg(unix)]
526 #[test]
527 fn replace_swaps_a_symlink_rather_than_following_it() {
528 use std::os::unix::fs::symlink;
529
530 let dir = tempfile::tempdir().unwrap();
531 let outside = dir.path().join("outside.txt");
532 fs::write(&outside, b"untouched").unwrap();
533 let link = dir.path().join("link.txt");
534 symlink(&outside, &link).unwrap();
535
536 AtomicWrite::new(b"new")
537 .with_permissions(None)
538 .write(&link)
539 .unwrap();
540
541 assert_eq!(fs::read(&outside).unwrap(), b"untouched");
542 assert!(
543 !fs::symlink_metadata(&link)
544 .unwrap()
545 .file_type()
546 .is_symlink()
547 );
548 assert_eq!(fs::read(&link).unwrap(), b"new");
549 }
550
551 #[cfg(unix)]
552 #[test]
553 fn explicit_unix_mode_wins_over_the_private_temporary_mode() {
554 use std::os::unix::fs::PermissionsExt as _;
555
556 let dir = tempfile::tempdir().unwrap();
557 let path = dir.path().join("readable.md");
558
559 AtomicWrite::new(b"body").mode(0o644).write(&path).unwrap();
560
561 let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
562 assert_eq!(mode, 0o644);
563 }
564
565 #[test]
566 fn a_missing_parent_directory_fails_before_any_write() {
567 let dir = tempfile::tempdir().unwrap();
568 let path = dir.path().join("absent").join("config.json");
569
570 let error = AtomicWrite::new(b"new").write(&path).unwrap_err();
571
572 assert_eq!(error.step, AtomicStep::Temp);
573 assert!(!error.commit_uncertain());
574 assert!(!path.exists());
575 }
576 #[test]
577 fn failed_writes_preserve_previous_bytes_and_remove_temporary_file() {
578 let dir = tempfile::tempdir().unwrap();
579 let path = dir.path().join("state.json");
580 fs::write(&path, b"old complete value").unwrap();
581 for error in [
582 std::io::Error::from_raw_os_error(28),
583 std::io::Error::from(std::io::ErrorKind::Interrupted),
584 std::io::Error::from(std::io::ErrorKind::WriteZero),
585 ] {
586 let error = AtomicWrite::new(b"new")
587 .write_with(&path, |file, _| {
588 file.write_all(b"partial")?;
589 Err(error)
590 })
591 .unwrap_err();
592 assert_eq!(error.step, AtomicStep::Write);
593 assert!(!error.commit_uncertain());
594 assert_eq!(fs::read(&path).unwrap(), b"old complete value");
595 assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
596 }
597 }
598
599 #[test]
600 fn write_all_retries_short_writes_and_interruptions_before_publish() {
601 struct ShortWriter<'a> {
602 file: &'a mut File,
603 interrupted: bool,
604 }
605 impl std::io::Write for ShortWriter<'_> {
606 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
607 if !self.interrupted {
608 self.interrupted = true;
609 return Err(std::io::ErrorKind::Interrupted.into());
610 }
611 self.file.write(&bytes[..bytes.len().min(2)])
612 }
613 fn flush(&mut self) -> std::io::Result<()> {
614 self.file.flush()
615 }
616 }
617 let dir = tempfile::tempdir().unwrap();
618 let path = dir.path().join("state.json");
619 let bytes = b"new complete value";
620 AtomicWrite::new(bytes)
621 .write_with(&path, |file, bytes| {
622 ShortWriter {
623 file,
624 interrupted: false,
625 }
626 .write_all(bytes)
627 })
628 .unwrap();
629 assert_eq!(fs::read(&path).unwrap(), bytes);
630 }
631
632 #[test]
633 fn interrupted_process_leaves_uncommitted_temporary_file_not_target() {
634 const CHILD_PATH: &str = "AFDATA_TEST_INTERRUPTED_ATOMIC_PATH";
635 if let Some(path) = std::env::var_os(CHILD_PATH) {
636 let _ = AtomicWrite::new(b"new").write_with(Path::new(&path), |file, _| {
637 file.write_all(b"partial")?;
638 file.sync_all()?;
639 std::process::exit(86);
640 });
641 panic!("child did not reach the interrupted write");
642 }
643 let dir = tempfile::tempdir().unwrap();
644 let path = dir.path().join("state.json");
645 write_atomic(&path, b"old complete value").unwrap();
646 let status = std::process::Command::new(std::env::current_exe().unwrap())
647 .args(["--exact", "atomic_file::tests::interrupted_process_leaves_uncommitted_temporary_file_not_target"])
648 .env(CHILD_PATH, &path).status().unwrap();
649 assert_eq!(status.code(), Some(86));
650 assert_eq!(fs::read(&path).unwrap(), b"old complete value");
651 assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 2);
652 write_atomic(&path, b"new complete value").unwrap();
653 assert_eq!(fs::read(&path).unwrap(), b"new complete value");
654 }
655
656 #[cfg(unix)]
657 #[test]
658 fn public_write_refuses_a_symlink_target() {
659 let dir = tempfile::tempdir().unwrap();
660 let outside = dir.path().join("outside");
661 fs::write(&outside, b"untouched").unwrap();
662 let link = dir.path().join("link");
663 std::os::unix::fs::symlink(&outside, &link).unwrap();
664 let error = AtomicWrite::new(b"x").write(&link).unwrap_err();
665 assert_eq!(error.step, AtomicStep::Guard);
666 assert_eq!(fs::read(&outside).unwrap(), b"untouched");
667 }
668
669 #[cfg(unix)]
670 fn mode_of(path: &Path) -> u32 {
671 use std::os::unix::fs::PermissionsExt as _;
672 fs::metadata(path).unwrap().permissions().mode() & 0o777
673 }
674
675 #[cfg(unix)]
676 #[test]
677 fn mode_applies_to_a_new_file_and_overrides_an_existing_one() {
678 let dir = tempfile::tempdir().unwrap();
679 let fresh = dir.path().join("fresh");
680 AtomicWrite::new(b"x").mode(0o640).write(&fresh).unwrap();
681 assert_eq!(mode_of(&fresh), 0o640);
682
683 let existing = dir.path().join("existing");
684 write_atomic(&existing, b"old").unwrap();
685 AtomicWrite::new(b"new")
686 .mode(0o604)
687 .write(&existing)
688 .unwrap();
689 assert_eq!(mode_of(&existing), 0o604);
690 assert_eq!(fs::read(&existing).unwrap(), b"new");
691 }
692
693 #[cfg(unix)]
694 #[test]
695 fn default_write_keeps_existing_mode_and_starts_new_files_private() {
696 use std::os::unix::fs::PermissionsExt as _;
697 let dir = tempfile::tempdir().unwrap();
698 let existing = dir.path().join("existing");
699 fs::write(&existing, b"old").unwrap();
700 fs::set_permissions(&existing, fs::Permissions::from_mode(0o644)).unwrap();
701 write_atomic(&existing, b"new").unwrap();
702 assert_eq!(mode_of(&existing), 0o644);
703
704 let fresh = dir.path().join("fresh");
705 write_atomic(&fresh, b"x").unwrap();
706 assert_eq!(mode_of(&fresh), 0o600);
707 }
708
709 #[test]
710 fn new_only_creates_an_absent_target_and_leaves_no_temporary_file() {
711 let dir = tempfile::tempdir().unwrap();
712 let path = dir.path().join("fresh.json");
713 AtomicWrite::new(b"created")
714 .new_only()
715 .write(&path)
716 .unwrap();
717 assert_eq!(fs::read(&path).unwrap(), b"created");
718 assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
719 }
720
721 #[test]
722 fn public_new_only_refuses_an_existing_target_byte_identical() {
723 let dir = tempfile::tempdir().unwrap();
724 let path = dir.path().join("keep.json");
725 fs::write(&path, b"original").unwrap();
726 let error = AtomicWrite::new(b"other")
727 .new_only()
728 .write(&path)
729 .unwrap_err();
730 assert!(error.target_exists());
731 assert!(!error.commit_uncertain());
732 assert_eq!(fs::read(&path).unwrap(), b"original");
733 assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
734 }
735}