1#[cfg(unix)]
2use std::fs::Permissions;
3#[cfg(unix)]
4use std::os::unix::{
5 fs::{MetadataExt as _, OpenOptionsExt as _, PermissionsExt as _},
6 io::AsRawFd as _,
7};
8#[cfg(target_os = "macos")]
9use std::ptr::null_mut;
10use std::{
11 ffi::OsString,
12 fmt::Display,
13 fs::{File, Metadata, OpenOptions, hard_link, remove_file, symlink_metadata},
14 io::{
15 Error as IoError, ErrorKind, Read as _, Result as IoResult, Seek as _, SeekFrom,
16 Write as _, copy,
17 },
18 path::{Path, PathBuf},
19 process::id,
20 sync::atomic::{AtomicU64, Ordering},
21};
22#[cfg(any(target_os = "linux", target_os = "macos"))]
23use std::{
24 ffi::{CStr, CString},
25 os::unix::ffi::OsStrExt as _,
26};
27
28#[cfg(target_os = "linux")]
29use libc::{AT_FDCWD, RENAME_EXCHANGE, SYS_renameat2, syscall};
30#[cfg(target_os = "macos")]
31use libc::{COPYFILE_ACL, COPYFILE_XATTR, RENAME_SWAP, fcopyfile, renamex_np};
32#[cfg(unix)]
33use libc::{O_CLOEXEC, O_NOFOLLOW, O_NONBLOCK, fchown};
34
35#[cfg(unix)]
36use crate::utils::BoolExt;
37#[cfg(target_os = "macos")]
38use crate::warn;
39use crate::{Err, Error, Result, debug_warn, err};
40
41type Origin<'a> = (&'a File, &'a Metadata);
42
43static TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);
44
45struct TempGuard {
46 path: PathBuf,
47 armed: bool,
48}
49
50pub(super) fn write_atomic(path: &Path, content: &[u8], force: bool) -> Result {
51 write_atomic_inner(path, content, force, || {})
52}
53
54#[cfg(test)]
55pub(super) fn write_atomic_with_precommit(
56 path: &Path,
57 content: &[u8],
58 force: bool,
59 before_commit: impl FnOnce(),
60) -> Result {
61 write_atomic_inner(path, content, force, before_commit)
62}
63
64fn write_atomic_inner(
65 path: &Path,
66 content: &[u8],
67 force: bool,
68 before_commit: impl FnOnce(),
69) -> Result {
70 let parent = path
71 .parent()
72 .filter(|parent| !parent.as_os_str().is_empty())
73 .unwrap_or_else(|| Path::new("."));
74
75 let metadata = match symlink_metadata(path) {
76 | Err(error) if error.kind() == ErrorKind::NotFound => None,
77 | Ok(metadata) => Some(metadata),
78 | Err(error) => return Err(fs_error(&error, "inspect output", path)),
79 };
80
81 match metadata {
82 | Some(metadata) if is_nonregular(&metadata) => {
83 Err!("Output is not a regular file: {}.", path.display())
84 },
85 | Some(_) if !force => Err!("Output already exists: {}.", path.display()),
86 | Some(_) => write_replacement(parent, path, content, before_commit),
87 | None => write_new(parent, path, content, before_commit),
88 }
89}
90
91fn write_new(parent: &Path, path: &Path, content: &[u8], before_commit: impl FnOnce()) -> Result {
92 let mut output = create_synced_temp(parent, path, content, None)?;
93
94 before_commit();
95 install_noreplace(&output.path, path, "output")?;
96
97 cleanup_after_commit(&mut output);
98 sync_after_commit(parent, path);
99
100 Ok(())
101}
102
103fn write_replacement(
104 parent: &Path,
105 path: &Path,
106 content: &[u8],
107 before_commit: impl FnOnce(),
108) -> Result {
109 let backup = backup_path(path);
110
111 if entry_exists(&backup)? {
112 return Err!("Backup already exists: {}.", backup.display());
113 }
114
115 let (mut source, metadata) = open_target(path)?;
116 let mut output = create_synced_temp(parent, path, content, Some((&source, &metadata)))?;
117 let (mut backup_guard, mut backup_file) =
118 copy_backup(parent, &backup, &mut source, &metadata)?;
119
120 install_noreplace(&backup_guard.path, &backup, "backup")?;
121 sync_parent(parent)
122 .map_err(|error| {
123 err!("Failed to synchronize staged backup `{}`: {error}", backup.display())
124 })
125 .map_err(|error| discard_backup(&backup, parent, error))?;
126
127 before_commit();
128 exchange(&output.path, path).map_err(|error| discard_backup(&backup, parent, error))?;
129 validate_displaced(
130 &output.path,
131 &metadata,
132 &mut source,
133 &mut backup_file,
134 &backup_guard.path,
135 )
136 .map_err(|error| {
137 rollback_replacement(&mut output, &mut backup_guard, path, &backup, error)
138 })?;
139
140 preserve_backup_attributes(&source, &backup_file, &backup);
141 cleanup_after_commit(&mut output);
142 cleanup_after_commit(&mut backup_guard);
143 sync_after_commit(parent, path);
144
145 Ok(())
146}
147
148fn create_synced_temp(
149 parent: &Path,
150 target: &Path,
151 content: &[u8],
152 origin: Option<Origin<'_>>,
153) -> Result<TempGuard> {
154 let (path, mut file) = create_temp(parent, target)?;
155 let guard = TempGuard { path, armed: true };
156
157 file.write_all(content)
158 .map_err(|error| fs_error(&error, "write temporary output", &guard.path))?;
159
160 set_output_metadata(&file, origin.map(|(_, metadata)| metadata), &guard.path)?;
161
162 if let Some((source, _)) = origin {
163 copy_security_attributes(source, &file, &guard.path)?;
164 }
165
166 file.sync_all()
167 .map_err(|error| fs_error(&error, "synchronize temporary output", &guard.path))?;
168
169 Ok(guard)
170}
171
172fn copy_backup(
173 parent: &Path,
174 backup: &Path,
175 source: &mut File,
176 metadata: &Metadata,
177) -> Result<(TempGuard, File)> {
178 let (path, mut file) = create_temp(parent, backup)?;
179 let guard = TempGuard { path, armed: true };
180
181 copy(source, &mut file)
182 .map_err(|error| fs_pair_error(&error, "copy output", backup, &guard.path))?;
183
184 set_output_metadata(&file, Some(metadata), &guard.path)?;
185
186 file.sync_all()
187 .map_err(|error| fs_error(&error, "synchronize temporary backup", &guard.path))?;
188
189 Ok((guard, file))
190}
191
192fn open_target(path: &Path) -> Result<(File, Metadata)> {
193 let mut options = OpenOptions::new();
194
195 options.read(true);
196
197 #[cfg(unix)]
198 options.custom_flags(O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK);
199
200 let file = options
201 .open(path)
202 .map_err(|error| fs_error(&error, "open output", path))?;
203
204 let metadata = file
205 .metadata()
206 .map_err(|error| fs_error(&error, "inspect opened output", path))?;
207
208 if is_nonregular(&metadata) {
209 return Err!("Output is not a regular file: {}.", path.display());
210 }
211
212 Ok((file, metadata))
213}
214
215fn validate_displaced(
216 displaced: &Path,
217 metadata: &Metadata,
218 source: &mut File,
219 backup: &mut File,
220 backup_path: &Path,
221) -> Result {
222 let displaced_metadata = symlink_metadata(displaced)
223 .map_err(|error| fs_error(&error, "inspect displaced output", displaced))?;
224
225 if !same_file(metadata, &displaced_metadata) {
226 return Err!("Output changed while its replacement was being prepared.");
227 }
228
229 if !same_contents(source, backup, displaced, backup_path)? {
230 return Err!("Output contents changed while its replacement was being prepared.");
231 }
232
233 Ok(())
234}
235
236fn same_contents(
237 left: &mut File,
238 right: &mut File,
239 left_path: &Path,
240 right_path: &Path,
241) -> Result<bool> {
242 left.seek(SeekFrom::Start(0))
243 .map_err(|error| fs_error(&error, "rewind displaced output", left_path))?;
244
245 right
246 .seek(SeekFrom::Start(0))
247 .map_err(|error| fs_error(&error, "rewind temporary backup", right_path))?;
248
249 let mut left_buf = [0_u8; 4096];
250 let mut right_buf = [0_u8; 4096];
251
252 loop {
253 let left_len = left
254 .read(&mut left_buf)
255 .map_err(|error| fs_error(&error, "read displaced output", left_path))?;
256
257 let right_len = right
258 .read(&mut right_buf)
259 .map_err(|error| fs_error(&error, "read temporary backup", right_path))?;
260
261 if left_len != right_len {
262 return Ok(false);
263 }
264
265 if left_buf[..left_len] != right_buf[..left_len] {
266 return Ok(false);
267 }
268
269 if left_len == 0 {
270 return Ok(true);
271 }
272 }
273}
274
275fn rollback_replacement(
276 output: &mut TempGuard,
277 backup_guard: &mut TempGuard,
278 path: &Path,
279 backup: &Path,
280 cause: Error,
281) -> Error {
282 if let Err(recovery_error) = exchange(&output.path, path) {
283 output.armed = false;
284 backup_guard.armed = false;
285
286 return err!(
287 "Output `{}` changed after replacement validation failed: {cause} Restoring it also \
288 failed: {recovery_error} Recover from `{}`; the displaced target remains at `{}`.",
289 path.display(),
290 backup.display(),
291 output.path.display(),
292 );
293 }
294
295 let parent = backup
296 .parent()
297 .filter(|parent| !parent.as_os_str().is_empty())
298 .unwrap_or_else(|| Path::new("."));
299
300 discard_backup(backup, parent, cause)
301}
302
303fn discard_backup(backup: &Path, parent: &Path, cause: Error) -> Error {
304 match remove_file(backup) {
305 | Ok(()) => {},
306 | Err(error) if error.kind() == ErrorKind::NotFound => {},
307 | Err(error) => {
308 return err!(
309 "{cause} Output was not changed, but the staged backup remains at `{}` because \
310 it could not be removed: {error}",
311 backup.display(),
312 );
313 },
314 }
315
316 if let Err(error) = sync_parent(parent) {
317 return err!(
318 "{cause} Output was not changed, but backup cleanup could not be synchronized: \
319 {error}",
320 );
321 }
322
323 cause
324}
325
326fn install_noreplace(source: &Path, target: &Path, kind: &str) -> Result {
327 match hard_link(source, target) {
328 | Ok(()) => Ok(()),
329 | Err(error) if error.kind() != ErrorKind::AlreadyExists =>
330 Err(fs_pair_error(&error, format_args!("install {kind}"), source, target)),
331 | Err(_) => {
332 Err!("{} already exists: {}.", title(kind), target.display())
333 },
334 }
335}
336
337fn title(kind: &str) -> &str {
338 match kind {
339 | "output" => "Output",
340 | "backup" => "Backup",
341 | _ => "Destination",
342 }
343}
344
345#[cfg(any(target_os = "linux", target_os = "macos"))]
346fn exchange(left: &Path, right: &Path) -> Result {
347 let left_name = path_cstring(left)?;
348 let right_name = path_cstring(right)?;
349
350 swap(&left_name, &right_name).map_err(|error| fs_pair_error(&error, "exchange", left, right))
351}
352
353#[cfg(not(any(target_os = "linux", target_os = "macos")))]
354fn exchange(left: &Path, right: &Path) -> Result {
355 Err!(
356 "Safe forced replacement of `{}` with `{}` is unsupported on this platform.",
357 right.display(),
358 left.display(),
359 )
360}
361
362#[cfg(target_os = "linux")]
365fn swap(left: &CStr, right: &CStr) -> IoResult<()> {
366 let result = unsafe {
369 syscall(
370 SYS_renameat2,
371 AT_FDCWD,
372 left.as_ptr(),
373 AT_FDCWD,
374 right.as_ptr(),
375 RENAME_EXCHANGE,
376 )
377 };
378
379 (result == 0)
380 .then_some(())
381 .ok_or_else(IoError::last_os_error)
382}
383
384#[cfg(target_os = "macos")]
385fn swap(left: &CStr, right: &CStr) -> IoResult<()> {
386 let result = unsafe { renamex_np(left.as_ptr(), right.as_ptr(), RENAME_SWAP) };
389
390 (result == 0)
391 .then_some(())
392 .ok_or_else(IoError::last_os_error)
393}
394
395#[cfg(any(target_os = "linux", target_os = "macos"))]
396pub(super) fn path_cstring(path: &Path) -> Result<CString> {
397 CString::new(path.as_os_str().as_bytes())
398 .map_err(|error| err!("Invalid output path `{}`: {error}", path.display()))
399}
400
401#[cfg(unix)]
402fn same_file(left: &Metadata, right: &Metadata) -> bool {
403 left.dev() == right.dev() && left.ino() == right.ino()
404}
405
406#[cfg(not(unix))]
407fn same_file(_left: &Metadata, _right: &Metadata) -> bool { false }
408
409#[expect(
410 clippy::filetype_is_file,
411 reason = "Every nonregular output target must be rejected, including devices and sockets."
412)]
413fn is_nonregular(metadata: &Metadata) -> bool { !metadata.file_type().is_file() }
414
415fn create_temp(parent: &Path, target: &Path) -> Result<(PathBuf, File)> {
416 let filename = target
417 .file_name()
418 .ok_or_else(|| err!("Output path has no file name: {}.", target.display()))?;
419
420 loop {
421 let sequence = TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed);
422 let mut name = OsString::from(".");
423
424 name.push(filename);
425 name.push(format!(".{}.{}.tmp", id(), sequence));
426 let path = parent.join(name);
427 let mut options = OpenOptions::new();
428
429 options.read(true).write(true).create_new(true);
430
431 #[cfg(unix)]
432 options.mode(0o600);
433
434 match options.open(&path) {
435 | Ok(file) => return Ok((path, file)),
436 | Err(error) if error.kind() == ErrorKind::AlreadyExists => {},
437 | Err(error) => return Err(fs_error(&error, "create temporary output", &path)),
438 }
439 }
440}
441
442fn backup_path(path: &Path) -> PathBuf {
443 let mut backup = path.as_os_str().to_owned();
444
445 backup.push(".bak");
446
447 backup.into()
448}
449
450#[cfg(unix)]
451fn set_output_metadata(file: &File, metadata: Option<&Metadata>, path: &Path) -> Result {
452 let Some(metadata) = metadata else {
453 file.set_permissions(Permissions::from_mode(0o600))
454 .map_err(|error| fs_error(&error, "set temporary output permissions", path))?;
455
456 return Ok(());
457 };
458
459 set_output_owner(file, metadata, path)?;
460
461 file.set_permissions(Permissions::from_mode(metadata.mode()))
462 .map_err(|error| {
463 fs_error(&error, "preserve output permissions on temporary file", path)
464 })?;
465
466 Ok(())
467}
468
469#[cfg(not(unix))]
470fn set_output_metadata(file: &File, metadata: Option<&Metadata>, path: &Path) -> Result {
471 if let Some(metadata) = metadata {
472 file.set_permissions(metadata.permissions())
473 .map_err(|error| {
474 fs_error(&error, "preserve output permissions on temporary file", path)
475 })?;
476 }
477
478 Ok(())
479}
480
481#[cfg(unix)]
482fn set_output_owner(file: &File, origin: &Metadata, path: &Path) -> Result {
483 let staged = file
484 .metadata()
485 .map_err(|error| fs_error(&error, "inspect temporary output", path))?;
486
487 let (uid, gid) = (origin.uid(), origin.gid());
488
489 if staged.uid() == uid && staged.gid() == gid {
491 return Ok(());
492 }
493
494 let result = unsafe { fchown(file.as_raw_fd(), uid, gid) };
496
497 (result == 0)
498 .then_some(())
499 .ok_or_else(IoError::last_os_error)
500 .map_err(|error| owner_error(&error, &staged, origin, path))
501}
502
503#[cfg(unix)]
504pub(super) fn owner_error(
505 error: &IoError,
506 staged: &Metadata,
507 origin: &Metadata,
508 path: &Path,
509) -> Error {
510 let hint = (error.kind() == ErrorKind::PermissionDenied).copy_or(
511 "",
512 " Changing ownership requires privilege the service does not have, or a sandbox is \
513 blocking the chown syscall.",
514 );
515
516 err!(
517 "Failed to change ownership of temporary file `{}` from uid {} gid {} to uid {} gid {}: \
518 {error}.{hint}",
519 path.display(),
520 staged.uid(),
521 staged.gid(),
522 origin.uid(),
523 origin.gid(),
524 )
525}
526
527#[cfg(target_os = "macos")]
530fn preserve_backup_attributes(source: &File, backup: &File, path: &Path) {
531 copy_security_attributes(source, backup, path)
532 .and_then(|()| {
533 backup
534 .sync_all()
535 .map_err(|error| fs_error(&error, "synchronize backup attributes", path))
536 })
537 .inspect_err(|error| {
538 warn!(
539 ?error,
540 path = %path.display(),
541 "Backup was installed, but its security attributes could not be preserved.",
542 );
543 })
544 .ok();
545}
546
547#[cfg(not(target_os = "macos"))]
548fn preserve_backup_attributes(_source: &File, _backup: &File, _path: &Path) {}
549
550#[cfg(target_os = "macos")]
551fn copy_security_attributes(source: &File, output: &File, path: &Path) -> Result {
552 let result = unsafe {
555 fcopyfile(
556 source.as_raw_fd(),
557 output.as_raw_fd(),
558 null_mut(),
559 COPYFILE_ACL | COPYFILE_XATTR,
560 )
561 };
562
563 (result == 0)
564 .then_some(())
565 .ok_or_else(IoError::last_os_error)
566 .map_err(|error| fs_error(&error, "preserve security attributes", path))
567}
568
569#[cfg(not(target_os = "macos"))]
570fn copy_security_attributes(_source: &File, _output: &File, _path: &Path) -> Result { Ok(()) }
571
572#[cfg(unix)]
573fn sync_parent(parent: &Path) -> Result {
574 let directory =
575 File::open(parent).map_err(|error| fs_error(&error, "open output directory", parent))?;
576
577 directory
578 .sync_all()
579 .map_err(|error| fs_error(&error, "synchronize output directory", parent))?;
580
581 Ok(())
582}
583
584#[cfg(not(unix))]
585fn sync_parent(_parent: &Path) -> Result { Ok(()) }
586
587fn sync_after_commit(parent: &Path, path: &Path) {
588 sync_parent(parent)
589 .inspect_err(|error| {
590 debug_warn!(
591 ?error,
592 path = %path.display(),
593 "Config output was installed, but its directory could not be synchronized.",
594 );
595 })
596 .ok();
597}
598
599fn cleanup_after_commit(guard: &mut TempGuard) {
600 guard
601 .remove()
602 .inspect_err(|error| {
603 debug_warn!(
604 ?error,
605 path = %guard.path.display(),
606 "Config output was installed, but a temporary file could not be removed.",
607 );
608 })
609 .ok();
610}
611
612fn entry_exists(path: &Path) -> Result<bool> {
613 match symlink_metadata(path) {
614 | Ok(_) => Ok(true),
615 | Err(error) if error.kind() == ErrorKind::NotFound => Ok(false),
616 | Err(error) => Err(fs_error(&error, "inspect backup path", path)),
617 }
618}
619
620fn fs_error(error: &IoError, operation: &str, path: &Path) -> Error {
621 err!("Failed to {operation} `{}`: {error}", path.display())
622}
623
624fn fs_pair_error(
625 error: &IoError,
626 operation: impl Display,
627 source: &Path,
628 target: &Path,
629) -> Error {
630 err!(
631 "Failed to {operation} `{}` as `{}`: {error}",
632 source.display(),
633 target.display(),
634 )
635}
636
637impl TempGuard {
638 fn remove(&mut self) -> IoResult<()> {
639 match remove_file(&self.path) {
640 | Ok(()) => self.armed = false,
641 | Err(error) if error.kind() == ErrorKind::NotFound => self.armed = false,
642 | Err(error) => return Err(error),
643 }
644
645 Ok(())
646 }
647}
648
649impl Drop for TempGuard {
650 fn drop(&mut self) {
651 if !self.armed {
652 return;
653 }
654
655 match remove_file(&self.path) {
656 | Ok(()) => {},
657 | Err(error) if error.kind() == ErrorKind::NotFound => {},
658 | Err(error) => {
659 debug_warn!(
660 ?error,
661 path = %self.path.display(),
662 "Failed to remove temporary config output.",
663 );
664 },
665 }
666 }
667}