1use crate::{
8 error::{Error, Result, io},
9 hash::{HashingReader, ensure_matches_plan},
10 plan::{BundlePlan, PlannedFile, PlannedFileKind},
11};
12use std::path::{Path, PathBuf};
13
14fn source_date_epoch() -> Result<Option<std::time::SystemTime>> {
16 let Some(seconds) = configured_source_date_epoch_secs()? else {
17 return Ok(None);
18 };
19 std::time::UNIX_EPOCH
20 .checked_add(std::time::Duration::from_secs(seconds))
21 .map(Some)
22 .ok_or_else(|| Error::Config {
23 message: "SOURCE_DATE_EPOCH is outside the supported system-time range".to_string(),
24 })
25}
26
27pub(crate) fn source_date_epoch_secs() -> Result<u64> {
28 Ok(configured_source_date_epoch_secs()?.unwrap_or(0))
29}
30
31fn configured_source_date_epoch_secs() -> Result<Option<u64>> {
32 match std::env::var("SOURCE_DATE_EPOCH") {
33 Ok(value) => value
34 .trim()
35 .parse::<u64>()
36 .map(Some)
37 .map_err(|_| Error::Config {
38 message: format!(
39 "invalid SOURCE_DATE_EPOCH `{value}` (expected an unsigned integer)"
40 ),
41 }),
42 Err(std::env::VarError::NotPresent) => Ok(None),
43 Err(std::env::VarError::NotUnicode(_)) => Err(Error::Config {
44 message: "SOURCE_DATE_EPOCH is not valid Unicode".to_string(),
45 }),
46 }
47}
48
49#[derive(Debug)]
50pub struct RootFsBuilder {
51 output: PathBuf,
52 clean: bool,
53}
54
55impl RootFsBuilder {
56 pub fn new(output: impl Into<PathBuf>) -> RootFsBuilder {
57 RootFsBuilder {
58 output: output.into(),
59 clean: false,
60 }
61 }
62
63 pub fn clean(mut self, clean: bool) -> RootFsBuilder {
65 self.clean = clean;
66 self
67 }
68
69 pub fn apply(&self, plan: &BundlePlan) -> Result<RootFsReport> {
73 let timestamp = source_date_epoch()?.unwrap_or_else(std::time::SystemTime::now);
76 guard_output(&self.output)?;
77 let parent = output_parent(&self.output);
78 std::fs::create_dir_all(parent).map_err(|e| io(parent, e))?;
79
80 let stage = tempfile::Builder::new()
81 .prefix(".elfpak-rootfs-")
82 .tempdir_in(parent)
83 .map_err(|e| io(parent, e))?;
84
85 if path_exists(&self.output) {
86 ensure_directory(&self.output)?;
87 }
88 if path_exists(&self.output) && !self.clean {
89 clone_tree(&self.output, stage.path())?;
90 } else {
91 set_mode(stage.path(), 0o755)?;
95 }
96 if self.clean && path_exists(&self.output) {
97 guard_clean(&self.output)?;
98 }
99
100 let report = self.apply_into(plan, stage.path(), timestamp)?;
101 publish_directory(stage, &self.output)?;
102 Ok(report)
103 }
104
105 fn apply_into(
107 &self,
108 plan: &BundlePlan,
109 output: &Path,
110 timestamp: std::time::SystemTime,
111 ) -> Result<RootFsReport> {
112 let output = output.canonicalize().map_err(|e| io(output, e))?;
113
114 let mut report = RootFsReport::default();
115 for file in &plan.files {
117 file.assert_well_formed();
118 let target = self.target_path(&output, file)?;
119 assert!(target.starts_with(&output));
120
121 match file.kind {
122 PlannedFileKind::Directory => {
123 write_directory(&target, file.mode)?;
124 report.directories += 1;
125 }
126 PlannedFileKind::Symlink => {
127 write_symlink(&target, file.link_target.as_deref())?;
128 report.symlinks += 1;
129 }
130 _ => {
131 remove_existing(&target)?;
134 report.bytes += write_file(&target, file)?;
135 set_mode(&target, file.mode)?;
136 pin_times(&target, timestamp);
137 report.files += 1;
138 }
139 }
140 }
141
142 for file in plan
145 .files
146 .iter()
147 .rev()
148 .filter(|f| f.kind == PlannedFileKind::Directory)
149 {
150 pin_times(
151 &crate::paths::join_under(&output, &file.destination),
152 timestamp,
153 );
154 }
155
156 let entries = report.files + report.directories + report.symlinks;
157 assert_eq!(entries as usize, plan.files.len());
158 Ok(report)
159 }
160
161 fn target_path(&self, output: &Path, file: &PlannedFile) -> Result<PathBuf> {
164 assert!(file.destination.is_absolute());
165
166 let target = crate::paths::join_under(output, &file.destination);
167 if !target.starts_with(output) {
168 return Err(Error::PathEscape {
169 path: file.destination.clone(),
170 kind: "output",
171 });
172 }
173 if let Some(parent) = target.parent() {
174 if has_symlinked_ancestor(output, parent) {
175 return Err(Error::PathEscape {
176 path: file.destination.clone(),
177 kind: "output",
178 });
179 }
180 std::fs::create_dir_all(parent).map_err(|e| io(parent, e))?;
181 }
182 Ok(target)
183 }
184}
185
186fn output_parent(output: &Path) -> &Path {
189 output
190 .parent()
191 .filter(|parent| !parent.as_os_str().is_empty())
192 .unwrap_or_else(|| Path::new("."))
193}
194
195fn path_exists(path: &Path) -> bool {
196 std::fs::symlink_metadata(path).is_ok()
197}
198
199fn ensure_directory(path: &Path) -> Result<()> {
200 let metadata = std::fs::symlink_metadata(path).map_err(|e| io(path, e))?;
201 if metadata.is_symlink() {
202 return Err(Error::Config {
203 message: format!("output `{}` must not be a symlink", path.display()),
204 });
205 }
206 if metadata.is_dir() {
207 return Ok(());
208 }
209 Err(Error::Config {
210 message: format!("output `{}` is not a directory", path.display()),
211 })
212}
213
214fn clone_tree(source: &Path, destination: &Path) -> Result<()> {
219 let mut stack = vec![(source.to_path_buf(), destination.to_path_buf())];
220 let mut directories = Vec::new();
221
222 while let Some((source_dir, destination_dir)) = stack.pop() {
223 let source_metadata = std::fs::metadata(&source_dir).map_err(|e| io(&source_dir, e))?;
224 directories.push((destination_dir.clone(), source_metadata));
225
226 for entry in std::fs::read_dir(&source_dir).map_err(|e| io(&source_dir, e))? {
227 let entry = entry.map_err(|e| io(&source_dir, e))?;
228 let source_path = entry.path();
229 let destination_path = destination_dir.join(entry.file_name());
230 let metadata =
231 std::fs::symlink_metadata(&source_path).map_err(|e| io(&source_path, e))?;
232
233 if metadata.is_symlink() {
234 let target = std::fs::read_link(&source_path).map_err(|e| io(&source_path, e))?;
235 std::os::unix::fs::symlink(target, &destination_path)
236 .map_err(|e| io(&destination_path, e))?;
237 } else if metadata.is_dir() {
238 std::fs::create_dir(&destination_path).map_err(|e| io(&destination_path, e))?;
239 stack.push((source_path, destination_path));
240 } else if metadata.is_file() {
241 std::fs::copy(&source_path, &destination_path)
242 .map_err(|e| io(&destination_path, e))?;
243 set_permissions_from(&destination_path, &metadata)?;
244 } else {
245 return Err(Error::Config {
246 message: format!(
247 "existing output contains unsupported entry `{}`",
248 source_path.display()
249 ),
250 });
251 }
252 }
253 }
254
255 for (path, metadata) in directories.into_iter().rev() {
258 set_permissions_from(&path, &metadata)?;
259 set_times_from(&path, &metadata);
260 }
261 Ok(())
262}
263
264fn publish_directory(stage: tempfile::TempDir, output: &Path) -> Result<()> {
268 if path_exists(output) {
273 return publish_by_exchange(stage, output);
274 }
275
276 use rustix::fs::{CWD, RenameFlags, renameat_with};
277
278 renameat_with(CWD, stage.path(), CWD, output, RenameFlags::NOREPLACE)
282 .map_err(|e| io(output, e.into()))
283}
284
285fn publish_by_exchange(stage: tempfile::TempDir, output: &Path) -> Result<()> {
286 use rustix::fs::{CWD, RenameFlags, renameat_with};
287
288 let exchange = renameat_with(CWD, stage.path(), CWD, output, RenameFlags::EXCHANGE);
289 finish_exchange(stage, output, exchange)
290}
291
292fn finish_exchange(
293 stage: tempfile::TempDir,
294 output: &Path,
295 exchange: std::result::Result<(), rustix::io::Errno>,
296) -> Result<()> {
297 if let Err(error) = exchange {
298 if matches!(
299 error,
300 rustix::io::Errno::INVAL | rustix::io::Errno::NOSYS | rustix::io::Errno::OPNOTSUPP
301 ) {
302 return publish_directory_legacy(stage, output);
303 }
304 return Err(io(output, error.into()));
305 }
306
307 let old_path = stage.path().to_path_buf();
308 stage.close().map_err(|e| io(&old_path, e))
309}
310
311fn publish_directory_legacy(stage: tempfile::TempDir, output: &Path) -> Result<()> {
314 let backup = if path_exists(output) {
315 let reservation = tempfile::Builder::new()
316 .prefix(".elfpak-backup-")
317 .tempdir_in(output_parent(output))
318 .map_err(|e| io(output, e))?;
319 let path = reservation.path().to_path_buf();
320 reservation.close().map_err(|e| io(&path, e))?;
321 std::fs::rename(output, &path).map_err(|e| io(output, e))?;
322 Some(path)
323 } else {
324 None
325 };
326
327 if let Err(error) = std::fs::rename(stage.path(), output) {
328 if let Some(backup) = &backup
329 && let Err(rollback) = std::fs::rename(backup, output)
330 {
331 return Err(Error::Config {
332 message: format!(
333 "failed to publish `{}` ({error}) and failed to restore its backup `{}` ({rollback})",
334 output.display(),
335 backup.display()
336 ),
337 });
338 }
339 return Err(io(output, error));
340 }
341
342 if let Some(backup) = backup {
343 remove_existing(&backup)?;
344 }
345 Ok(())
346}
347
348fn write_directory(target: &Path, mode: u32) -> Result<()> {
351 let existing = std::fs::symlink_metadata(target).ok();
352 if !existing.is_some_and(|metadata| metadata.is_dir()) {
353 remove_existing(target)?;
354 std::fs::create_dir_all(target).map_err(|e| io(target, e))?;
355 }
356 set_mode(target, mode)
357}
358
359fn write_symlink(target: &Path, link_target: Option<&Path>) -> Result<()> {
361 let link_target = link_target.expect("validated symlinks have a target");
362 remove_existing(target)?;
363 std::os::unix::fs::symlink(link_target, target).map_err(|e| io(target, e))
364}
365
366fn write_file(target: &Path, file: &PlannedFile) -> Result<u64> {
371 match (&file.content, &file.source) {
372 (Some(content), None) => {
373 assert_eq!(content.len() as u64, file.size);
374 std::fs::write(target, content).map_err(|e| io(target, e))?;
375 Ok(content.len() as u64)
376 }
377 (None, Some(source)) => {
378 let input = std::fs::File::open(source).map_err(|e| io(source, e))?;
379 let mut input = HashingReader::new(std::io::BufReader::new(input));
380 let mut output = std::fs::File::create(target).map_err(|e| io(target, e))?;
381 let copy_result = std::io::copy(&mut input, &mut output).map_err(|e| io(source, e));
382 drop(output);
383 let (digest, size) = input.finish();
384
385 if let Err(error) = copy_result {
386 let _ = remove_existing(target);
387 return Err(error);
388 }
389 let expected = file
390 .sha256
391 .as_ref()
392 .expect("validated regular files have a digest");
393 if let Err(error) = ensure_matches_plan(source, expected, file.size, digest, size) {
394 let _ = remove_existing(target);
395 return Err(error);
396 }
397 Ok(size)
398 }
399 _ => unreachable!("validated regular files have exactly one content source"),
400 }
401}
402
403fn guard_output(output: &Path) -> Result<()> {
407 let absolute = std::path::absolute(output).map_err(|e| io(output, e))?;
411 let lexical = crate::paths::normalize_absolute(&absolute);
412 let resolved = output.canonicalize().unwrap_or(lexical);
413 if resolved.parent().is_none() {
414 return Err(Error::Config {
415 message: format!(
416 "refusing to materialize a bundle at filesystem root `{}`",
417 resolved.display()
418 ),
419 });
420 }
421 Ok(())
422}
423
424fn guard_clean(output: &Path) -> Result<()> {
427 let resolved = output
428 .canonicalize()
429 .unwrap_or_else(|_| output.to_path_buf());
430 if resolved.parent().is_none() {
431 return Err(Error::Config {
432 message: format!("refusing to --clean `{}`", resolved.display()),
433 });
434 }
435 Ok(())
436}
437
438fn remove_existing(path: &Path) -> Result<()> {
440 match std::fs::symlink_metadata(path) {
441 Ok(metadata) if metadata.is_dir() => std::fs::remove_dir_all(path).map_err(|e| io(path, e)),
444 Ok(_) => std::fs::remove_file(path).map_err(|e| io(path, e)),
445 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
446 Err(e) => Err(io(path, e)),
447 }
448}
449
450fn has_symlinked_ancestor(output: &Path, path: &Path) -> bool {
454 let depth = path.components().count();
457 let mut steps = 0usize;
458 let mut current = path;
459 while current != output {
460 steps += 1;
461 assert!(steps <= depth);
462
463 match std::fs::symlink_metadata(current) {
464 Ok(metadata) if metadata.is_symlink() => return true,
465 Ok(_) | Err(_) => {}
466 }
467 let Some(parent) = current.parent() else {
468 break;
469 };
470 current = parent;
471 }
472 false
473}
474
475#[derive(Debug, Default, Clone, Copy)]
477pub struct RootFsReport {
478 pub files: u32,
479 pub directories: u32,
480 pub symlinks: u32,
481 pub bytes: u64,
482}
483
484fn set_mode(path: &Path, mode: u32) -> Result<()> {
485 use std::os::unix::fs::PermissionsExt;
486
487 assert!(mode <= 0o7777);
488 std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).map_err(|e| io(path, e))
489}
490
491fn set_permissions_from(path: &Path, metadata: &std::fs::Metadata) -> Result<()> {
492 std::fs::set_permissions(path, metadata.permissions()).map_err(|e| io(path, e))
493}
494
495fn set_times_from(path: &Path, metadata: &std::fs::Metadata) {
496 let (Ok(accessed), Ok(modified), Ok(file)) = (
497 metadata.accessed(),
498 metadata.modified(),
499 std::fs::File::open(path),
500 ) else {
501 return;
502 };
503 let _ = file.set_times(
504 std::fs::FileTimes::new()
505 .set_accessed(accessed)
506 .set_modified(modified),
507 );
508}
509
510fn pin_times(path: &Path, time: std::time::SystemTime) {
514 let Ok(file) = std::fs::File::open(path) else {
515 return;
516 };
517 let _ = file.set_times(
518 std::fs::FileTimes::new()
519 .set_accessed(time)
520 .set_modified(time),
521 );
522}
523
524#[cfg(test)]
525mod tests {
526 use super::{
527 ensure_directory, finish_exchange, guard_clean, guard_output, has_symlinked_ancestor,
528 remove_existing,
529 };
530 use std::path::Path;
531
532 #[test]
533 fn detects_a_symlink_above_a_missing_parent() {
534 let temp = tempfile::tempdir().unwrap();
535 let output = temp.path().join("output");
536 let outside = temp.path().join("outside");
537 std::fs::create_dir_all(&output).unwrap();
538 std::fs::create_dir(&outside).unwrap();
539 std::os::unix::fs::symlink(&outside, output.join("nested")).unwrap();
540
541 assert!(has_symlinked_ancestor(
542 &output,
543 &output.join("nested/deeper")
544 ));
545 }
546
547 #[test]
548 fn removing_a_symlink_leaves_its_target_alone() {
549 let temp = tempfile::tempdir().unwrap();
550 let target = temp.path().join("target");
551 let link = temp.path().join("link");
552 std::fs::write(&target, b"keep me").unwrap();
553 std::os::unix::fs::symlink(&target, &link).unwrap();
554
555 remove_existing(&link).unwrap();
556 assert!(!link.exists());
557 assert_eq!(std::fs::read(&target).unwrap(), b"keep me");
558
559 remove_existing(&link).unwrap();
561 }
562
563 #[test]
564 fn clean_refuses_to_delete_a_filesystem_root() {
565 let err = guard_clean(Path::new("/")).unwrap_err();
566 assert_eq!(err.code(), "E4001");
567 let temp = tempfile::tempdir().unwrap();
568 guard_clean(&temp.path().join("rootfs")).unwrap();
569 }
570
571 #[test]
572 fn materialization_refuses_a_filesystem_root() {
573 let err = guard_output(Path::new("/")).unwrap_err();
574 assert_eq!(err.code(), "E4001");
575 let err = guard_output(Path::new("/new-rootfs/..")).unwrap_err();
576 assert_eq!(err.code(), "E4001");
577 let temp = tempfile::tempdir().unwrap();
578 guard_output(&temp.path().join("rootfs")).unwrap();
579 }
580
581 #[test]
582 fn an_output_root_symlink_is_rejected() {
583 let temp = tempfile::tempdir().unwrap();
584 let target = temp.path().join("target");
585 let output = temp.path().join("output");
586 std::fs::create_dir(&target).unwrap();
587 std::os::unix::fs::symlink(&target, &output).unwrap();
588
589 assert!(ensure_directory(&output).is_err());
590 }
591
592 #[test]
593 fn unsupported_atomic_exchange_falls_back_to_portable_publication() {
594 let temp = tempfile::tempdir().unwrap();
595 let output = temp.path().join("output");
596 std::fs::create_dir(&output).unwrap();
597 std::fs::write(output.join("old"), b"old").unwrap();
598
599 let stage = tempfile::Builder::new()
600 .prefix(".elfpak-rootfs-")
601 .tempdir_in(temp.path())
602 .unwrap();
603 std::fs::write(stage.path().join("new"), b"new").unwrap();
604
605 finish_exchange(stage, &output, Err(rustix::io::Errno::INVAL)).unwrap();
606
607 assert_eq!(std::fs::read(output.join("new")).unwrap(), b"new");
608 assert!(!output.join("old").exists());
609 }
610
611 #[test]
612 fn unrelated_exchange_errors_leave_the_existing_output_untouched() {
613 let temp = tempfile::tempdir().unwrap();
614 let output = temp.path().join("output");
615 std::fs::create_dir(&output).unwrap();
616 std::fs::write(output.join("old"), b"old").unwrap();
617
618 let stage = tempfile::Builder::new()
619 .prefix(".elfpak-rootfs-")
620 .tempdir_in(temp.path())
621 .unwrap();
622 std::fs::write(stage.path().join("new"), b"new").unwrap();
623
624 assert!(finish_exchange(stage, &output, Err(rustix::io::Errno::PERM)).is_err());
625
626 assert_eq!(std::fs::read(output.join("old")).unwrap(), b"old");
627 assert!(!output.join("new").exists());
628 }
629}