Skip to main content

elfpak_core/rootfs/
copy.rs

1//! Materialization of a [`BundlePlan`] into a directory tree.
2//!
3//! Nothing is written outside the output root and the source filesystem is only
4//! ever read. A clean output contains only planned entries; without `clean`,
5//! pre-existing unplanned entries are deliberately retained.
6
7use crate::{
8    error::{Error, Result, io},
9    hash::{HashingReader, ensure_matches_plan},
10    plan::{BundlePlan, PlannedFile, PlannedFileKind},
11};
12use std::path::{Path, PathBuf};
13
14/// Explicit reproducible-build timestamp, when configured by the caller.
15fn 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    /// Exclude an existing output directory from the staged replacement.
64    pub fn clean(mut self, clean: bool) -> RootFsBuilder {
65        self.clean = clean;
66        self
67    }
68
69    /// Materialize a plan into a sibling staging directory, then publish it.
70    /// A failed build leaves an existing output untouched and exposes no new
71    /// output when the destination did not exist.
72    pub fn apply(&self, plan: &BundlePlan) -> Result<RootFsReport> {
73        // Capture one time for all planned entries. Reproducible-build callers
74        // can override the ordinary materialization time through SOURCE_DATE_EPOCH.
75        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            // Temporary directories start as 0700. The root of a generated
92            // filesystem should have the same normalized mode as its ordinary
93            // directory entries.
94            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    /// Apply a plan to an isolated directory that is not externally visible.
106    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        // Entries are sorted by destination, so parents always precede children.
116        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                    // Removing first is what keeps the write inside the output
132                    // root: writing onto a pre-existing symlink would follow it.
133                    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        // Directory timestamps are pinned last: writing children updates them.
143        // Deepest first, so a parent is not touched again after it is pinned.
144        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    /// Resolve a plan destination inside the output root, refusing anything that
162    /// would write through a symlink or outside the root.
163    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
186/// Parent used for sibling staging. A bare relative output such as `rootfs`
187/// lives beside a temporary directory in the current working directory.
188fn 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
214/// Clone an existing output into the stage without following symlinks. Regular
215/// files are copied rather than hard-linked. A hard link would leave an
216/// unplanned file in the newly published rootfs sharing an inode with the old
217/// rootfs, so a later writer of the old tree could mutate the new snapshot.
218fn 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    // Creating children changes directory timestamps. Restore metadata from
256    // the bottom up after the complete snapshot has been assembled.
257    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
264/// Replace the visible output only after the complete staged tree exists.
265/// Existing outputs are atomically exchanged when the filesystem supports it;
266/// otherwise a rollback-capable sequence publishes the staged tree.
267fn publish_directory(stage: tempfile::TempDir, output: &Path) -> Result<()> {
268    // Linux can exchange two sibling paths in one rename operation. This
269    // retains a continuously visible output for readers, unlike moving the
270    // old tree aside before publishing the new one. The temporary directory
271    // then names the old tree and `close` removes it after the exchange.
272    if path_exists(output) {
273        return publish_by_exchange(stage, output);
274    }
275
276    use rustix::fs::{CWD, RenameFlags, renameat_with};
277
278    // Do not overwrite a rootfs created between the initial existence check
279    // and publication. A concurrent builder must retry rather than silently
280    // discarding somebody else's output.
281    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
311/// Portable publication path for filesystems where
312/// `renameat2(RENAME_EXCHANGE)` is unavailable, such as WSL's Windows mounts.
313fn 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
348/// Create a directory, replacing anything else that occupies the path —
349/// including a symlink, which a later write would silently follow.
350fn 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
359/// Recreate a symlink verbatim. Plan validation guarantees a target is present.
360fn 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
366/// Write the contents of a planned entry, returning the number of bytes.
367///
368/// Source-backed files are copied rather than read into memory, so an
369/// `--include` of an arbitrarily large file costs no more than a buffer.
370fn 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
403/// Refuse the filesystem root as an output even when `--clean` was not
404/// requested. Materializing there would turn logical bundle destinations such
405/// as `/app/server` into writes to the host filesystem.
406fn guard_output(output: &Path) -> Result<()> {
407    // `canonicalize` cannot resolve a path that has not been created yet, so
408    // normalize an absolute spelling first. Otherwise `/new/..` would evade
409    // the guard and become `/` after `create_dir_all`.
410    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
424/// Refuse to delete something that is obviously not a previous bundle: `--clean`
425/// is meant to replace an output directory, not to wipe a filesystem.
426fn 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
438/// Remove whatever currently occupies `path`, without following symlinks.
439fn remove_existing(path: &Path) -> Result<()> {
440    match std::fs::symlink_metadata(path) {
441        // `is_dir` is false for a symlink to a directory, so the link itself is
442        // unlinked and its target is left alone.
443        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
450/// Reject any existing symlink between the output root and `path`. Checking
451/// only the immediate parent lets `create_dir_all` follow a pre-existing
452/// symlink higher in the path.
453fn has_symlinked_ancestor(output: &Path, path: &Path) -> bool {
454    // Every step drops one component, so the walk is bounded by the depth of
455    // the path it starts from.
456    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/// What was written, counted as it was written.
476#[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
510/// Give every entry the materialization timestamp. Not every filesystem
511/// supports this, and symlink timestamps cannot be set through `std` at all,
512/// so this is best-effort: the tar backend is the byte-reproducible artifact.
513fn 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        // Removing something that is not there is not an error.
560        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}