Skip to main content

stratum_node_cli/
export.rs

1//! `stratum export`: a walk of the caller's own pod into a `.tar.zst`
2//! archive and a manifest beside it.
3
4use std::collections::{BTreeMap, BTreeSet, VecDeque};
5use std::fs::{self, File, OpenOptions};
6use std::io::{self, BufWriter, Read as _, Seek as _, SeekFrom, Write};
7use std::os::unix::fs::{MetadataExt as _, OpenOptionsExt as _};
8use std::path::{Path, PathBuf};
9
10use serde_json::{json, Value as Json};
11use sha2::{Digest as _, Sha256};
12use stratum_node_core::{NostrSecretKey, PodPath, Sha256Digest, UnixTime};
13
14use crate::client::{self, MAX_RESPONSE_BYTES};
15use crate::error::CliError;
16use crate::exit;
17use crate::gate::{self, GateClient, Head, Request, Route, ANY, LD_JSON, MAX_LISTING_BYTES};
18use crate::listing::{self, Child};
19use crate::origin::GateTarget;
20use crate::output::sanitize;
21use crate::private_file;
22use crate::session::Session;
23
24/// The most entries an export holds before it stops: containers, resources
25/// and ACLs together.
26pub const MAX_EXPORT_ENTRIES: u64 = 100_000;
27
28/// The most bytes of resource content an export holds before it stops:
29/// 64 GiB.
30pub const MAX_EXPORT_BYTES: u64 = 64 * 1024 * 1024 * 1024;
31
32/// The `format` member of an export manifest.
33pub const MANIFEST_FORMAT: &str = "stratum-pod-export";
34
35/// The `format_version` member of an export manifest.
36pub const MANIFEST_FORMAT_VERSION: u64 = 1;
37
38/// The suffix appended to the archive's file name for the manifest.
39pub const MANIFEST_SUFFIX: &str = ".manifest.json";
40
41/// The zstd compression level: the library's default trade-off.
42const ZSTD_LEVEL: i32 = 3;
43
44/// Options for [`Session::export`].
45#[derive(Debug, Clone, Default)]
46pub struct ExportOptions {
47    /// The archive to write (`-o`), conventionally `<name>.tar.zst`. The
48    /// manifest is written beside it as `<archive>.manifest.json`.
49    pub output: PathBuf,
50    /// Replace an existing archive and manifest (`--force`).
51    pub force: bool,
52}
53
54/// What an archived entry is.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56enum Kind {
57    Container,
58    Resource,
59    Acl,
60}
61
62impl Kind {
63    fn as_str(self) -> &'static str {
64        match self {
65            Self::Container => "container",
66            Self::Resource => "resource",
67            Self::Acl => "acl",
68        }
69    }
70}
71
72/// Why an entry is being fetched, which decides what a 404 means.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74enum Reason {
75    /// It was named in a listing: a 404 means it vanished.
76    Listed,
77    /// It is the ACL beside a container or resource: a 404 means there is
78    /// none.
79    Beside,
80}
81
82/// One archived entry.
83#[derive(Debug, Clone)]
84struct Entry {
85    path: PodPath,
86    kind: Kind,
87    size: u64,
88    sha256: Option<Sha256Digest>,
89    content_type: Option<String>,
90    etag: Option<String>,
91}
92
93impl Entry {
94    fn to_json(&self) -> Json {
95        json!({
96            "path": self.path,
97            "archive_path": archive_path(&self.path),
98            "kind": self.kind.as_str(),
99            "size": self.size,
100            "sha256": self.sha256,
101            "content_type": self.content_type,
102        })
103    }
104}
105
106/// The archive path of a pod path: the path without its leading `/`, so
107/// the archive unpacks to `pods/<pk>/…` and `pods/<pk>.acl`.
108fn archive_path(path: &PodPath) -> &str {
109    path.as_str().trim_start_matches('/')
110}
111
112/// The files an export writes, and the temporary names it writes them under.
113#[derive(Debug)]
114struct Targets {
115    archive: PathBuf,
116    manifest: PathBuf,
117    directory: PathBuf,
118    archive_temp: PathBuf,
119    manifest_temp: PathBuf,
120    /// Where `--force` sets the old manifest aside while the archive moves.
121    manifest_aside: PathBuf,
122    spool: PathBuf,
123}
124
125impl Targets {
126    fn new(archive: &Path) -> Result<Self, CliError> {
127        let name = archive
128            .file_name()
129            .and_then(|n| n.to_str())
130            .filter(|n| !n.is_empty())
131            .ok_or_else(|| CliError::Usage("-o must name an archive file".to_owned()))?;
132        let directory = match archive.parent() {
133            Some(parent) if !parent.as_os_str().is_empty() => parent.to_owned(),
134            _ => PathBuf::from("."),
135        };
136        let tag = hex::encode(&client::random_32()?[..6]);
137        let mut manifest = archive.as_os_str().to_owned();
138        manifest.push(MANIFEST_SUFFIX);
139        Ok(Self {
140            archive: archive.to_owned(),
141            manifest: PathBuf::from(manifest),
142            archive_temp: directory.join(format!(".{name}.partial-{tag}")),
143            manifest_temp: directory.join(format!(".{name}.manifest-{tag}")),
144            manifest_aside: directory.join(format!(".{name}.manifest-old-{tag}")),
145            spool: directory.join(format!(".{name}.spool-{tag}")),
146            directory,
147        })
148    }
149}
150
151/// Removes the temporary files of an export that did not finish.
152#[derive(Debug, Default)]
153struct Cleanup(Vec<PathBuf>);
154
155impl Drop for Cleanup {
156    fn drop(&mut self) {
157        for path in &self.0 {
158            // Best effort: these are our own temporary files.
159            let _removed = fs::remove_file(path);
160        }
161    }
162}
163
164/// How a temporary file is opened.
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166enum Access {
167    /// Written only: the archive and the manifest.
168    Write,
169    /// Written and read back: the spool.
170    ReadWrite,
171}
172
173/// Creates a new `0600` file; an existing one is never opened.
174fn create_private(path: &Path, access: Access) -> Result<File, CliError> {
175    OpenOptions::new()
176        .read(access == Access::ReadWrite)
177        .write(true)
178        .create_new(true)
179        .mode(0o600)
180        .open(path)
181        .map_err(|err| CliError::Local(format!("creating {} failed: {err}", path.display())))
182}
183
184/// A writer that hashes and counts what passes through it.
185struct Hashing<W> {
186    inner: W,
187    hasher: Sha256,
188    size: u64,
189}
190
191impl<W: Write> Write for Hashing<W> {
192    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
193        let written = self.inner.write(buf)?;
194        self.hasher.update(&buf[..written]);
195        self.size = self
196            .size
197            .saturating_add(u64::try_from(written).unwrap_or(u64::MAX));
198        Ok(written)
199    }
200
201    fn flush(&mut self) -> io::Result<()> {
202        self.inner.flush()
203    }
204}
205
206/// The archive being written.
207type Archive = tar::Builder<zstd::stream::write::Encoder<'static, Hashing<BufWriter<File>>>>;
208
209/// Something listed that the walk did not follow.
210#[derive(Debug, Clone)]
211struct Skipped {
212    listed_in: Option<PodPath>,
213    id: String,
214    reason: String,
215}
216
217/// The state of one walk.
218struct Walk<'a> {
219    gate: GateClient,
220    key: &'a NostrSecretKey,
221    root: PodPath,
222    archive: Archive,
223    spool: File,
224    created_at: UnixTime,
225    entries: Vec<Entry>,
226    visited: BTreeSet<PodPath>,
227    listings: BTreeMap<PodPath, BTreeSet<PodPath>>,
228    skipped: Vec<Skipped>,
229    vanished: Vec<PodPath>,
230    changed: Vec<(PodPath, String)>,
231    unverified: Vec<(PodPath, u16)>,
232    total_bytes: u64,
233}
234
235impl Walk<'_> {
236    /// Walks the pod breadth first from its root.
237    fn run(&mut self) -> Result<(), CliError> {
238        let root = self.root.clone();
239        let root_acl = root
240            .acl_path()
241            .ok_or_else(|| CliError::Local("the pod root has no ACL path".to_owned()))?;
242        self.visited.insert(root.clone());
243        self.visited.insert(root_acl.clone());
244        self.fetch(&root_acl, Reason::Beside, None)?;
245        let mut queue = VecDeque::from([root.clone()]);
246        while let Some(container) = queue.pop_front() {
247            let Some(children) = self.list(&container)? else {
248                continue;
249            };
250            self.add_container(&container)?;
251            if container != root {
252                if let Some(acl) = container.acl_path() {
253                    if self.visited.insert(acl.clone()) {
254                        self.fetch(&acl, Reason::Beside, Some(&container))?;
255                    }
256                }
257            }
258            let mut accepted = BTreeSet::new();
259            for child in children {
260                let path = match child {
261                    Child::Accepted(path) => path,
262                    Child::Refused { id, reason } => {
263                        self.skipped.push(Skipped {
264                            listed_in: Some(container.clone()),
265                            id,
266                            reason,
267                        });
268                        continue;
269                    }
270                };
271                accepted.insert(path.clone());
272                if !self.visited.insert(path.clone()) {
273                    continue;
274                }
275                if path.is_container() {
276                    queue.push_back(path);
277                    continue;
278                }
279                let present = self.fetch(&path, Reason::Listed, Some(&container))?;
280                if present {
281                    if let Some(acl) = path.acl_path() {
282                        if self.visited.insert(acl.clone()) {
283                            self.fetch(&acl, Reason::Beside, Some(&container))?;
284                        }
285                    }
286                }
287            }
288            self.listings.insert(container, accepted);
289        }
290        Ok(())
291    }
292
293    /// Reads a container's listing; `None` when it vanished or redirected.
294    fn list(&mut self, container: &PodPath) -> Result<Option<Vec<Child>>, CliError> {
295        let response = self.gate.fetch(
296            &Request::new("GET", container.as_str(), LD_JSON),
297            Some(self.key),
298            MAX_LISTING_BYTES,
299        )?;
300        let head = &response.head;
301        if head.is_success() {
302            let origin = self.gate.target().origin().clone();
303            return listing::children(&origin, container, &response.body).map(Some);
304        }
305        if *container == self.root {
306            return Err(response.into_error(Route::Pod));
307        }
308        if head.status == 404 {
309            self.vanished.push(container.clone());
310            return Ok(None);
311        }
312        if head.is_redirect() {
313            self.skip_redirect(container, None);
314            return Ok(None);
315        }
316        Err(response.into_error(Route::Pod))
317    }
318
319    /// Records a redirect, which is never followed.
320    fn skip_redirect(&mut self, path: &PodPath, listed_in: Option<&PodPath>) {
321        self.skipped.push(Skipped {
322            listed_in: listed_in.cloned(),
323            id: path.to_string(),
324            reason: "answered with a redirect, which is not followed".to_owned(),
325        });
326    }
327
328    /// Refuses one more entry when the archive already holds the most.
329    fn count_entry(&self) -> Result<(), CliError> {
330        check_entry_limit(u64::try_from(self.entries.len()).unwrap_or(u64::MAX))
331    }
332
333    /// Adds a container's directory entry.
334    fn add_container(&mut self, container: &PodPath) -> Result<(), CliError> {
335        self.count_entry()?;
336        let mut header = tar::Header::new_gnu();
337        header.set_entry_type(tar::EntryType::Directory);
338        header.set_size(0);
339        header.set_mode(0o700);
340        header.set_mtime(self.created_at.as_secs());
341        self.archive
342            .append_data(&mut header, archive_path(container), io::empty())
343            .map_err(|err| archive_error(&err))?;
344        self.entries.push(Entry {
345            path: container.clone(),
346            kind: Kind::Container,
347            size: 0,
348            sha256: None,
349            content_type: None,
350            etag: None,
351        });
352        Ok(())
353    }
354
355    /// Fetches a resource or ACL into the archive. Returns `false` when it
356    /// is absent (a 404) or was skipped.
357    fn fetch(
358        &mut self,
359        path: &PodPath,
360        reason: Reason,
361        listed_in: Option<&PodPath>,
362    ) -> Result<bool, CliError> {
363        self.count_entry()?;
364        self.spool
365            .set_len(0)
366            .and_then(|()| self.spool.seek(SeekFrom::Start(0)).map(drop))
367            .map_err(|err| spool_error(&err))?;
368        let request = Request::new("GET", path.as_str(), ANY);
369        let (head, outcome) = {
370            let mut sink = BufWriter::new(&self.spool);
371            let result =
372                self.gate
373                    .stream(&request, self.key, &mut sink, gate::MAX_RESOURCE_BYTES)?;
374            sink.flush().map_err(|err| spool_error(&err))?;
375            result
376        };
377        let streamed = match outcome {
378            Ok(streamed) => streamed,
379            Err(body) => {
380                if head.status == 404 {
381                    if reason == Reason::Listed {
382                        self.vanished.push(path.clone());
383                    }
384                    return Ok(false);
385                }
386                if head.is_redirect() {
387                    self.skip_redirect(path, listed_in);
388                    return Ok(false);
389                }
390                return Err(gate::error_from(&head, &body, Route::Pod));
391            }
392        };
393        self.total_bytes = self.total_bytes.saturating_add(streamed.size);
394        check_byte_limit(self.total_bytes)?;
395        if let Some(tag) = head.etag.as_deref().and_then(sha256_tag) {
396            if tag != streamed.sha256 {
397                self.changed.push((
398                    path.clone(),
399                    "the bytes received do not match the entity tag sent with them".to_owned(),
400                ));
401            }
402        }
403        self.spool
404            .seek(SeekFrom::Start(0))
405            .map_err(|err| spool_error(&err))?;
406        let mut header = tar::Header::new_gnu();
407        header.set_entry_type(tar::EntryType::Regular);
408        header.set_size(streamed.size);
409        header.set_mode(0o600);
410        header.set_mtime(self.created_at.as_secs());
411        self.archive
412            .append_data(
413                &mut header,
414                archive_path(path),
415                (&self.spool).take(streamed.size),
416            )
417            .map_err(|err| archive_error(&err))?;
418        let kind = if path.acl_path().is_none() {
419            Kind::Acl
420        } else {
421            Kind::Resource
422        };
423        self.entries.push(Entry {
424            path: path.clone(),
425            kind,
426            size: streamed.size,
427            sha256: Some(streamed.sha256),
428            content_type: head.content_type.as_deref().map(sanitize),
429            etag: head.etag,
430        });
431        Ok(true)
432    }
433
434    /// After the walk: asks again for every resource's entity tag and every
435    /// container's listing, and records what changed or vanished meanwhile.
436    fn verify(&mut self) -> Result<(), CliError> {
437        let files: Vec<Entry> = self
438            .entries
439            .iter()
440            .filter(|entry| entry.kind != Kind::Container)
441            .cloned()
442            .collect();
443        for entry in files {
444            let response = self.gate.fetch(
445                &Request::new("HEAD", entry.path.as_str(), ANY),
446                Some(self.key),
447                MAX_RESPONSE_BYTES,
448            )?;
449            let head: &Head = &response.head;
450            if head.status == 404 {
451                self.vanished.push(entry.path);
452            } else if head.is_success() {
453                if let Some(now) = &head.etag {
454                    let before = entry.etag.as_deref().and_then(sha256_tag).or(entry.sha256);
455                    let differs = match (sha256_tag(now), before) {
456                        (Some(now), Some(before)) => now != before,
457                        _ => entry.etag.as_deref() != Some(now.as_str()),
458                    };
459                    if differs {
460                        self.changed.push((
461                            entry.path,
462                            "its entity tag changed during the export".to_owned(),
463                        ));
464                    }
465                }
466            } else {
467                self.unverified.push((entry.path, head.status));
468            }
469        }
470        let listings = std::mem::take(&mut self.listings);
471        for (container, before) in &listings {
472            let response = self.gate.fetch(
473                &Request::new("GET", container.as_str(), LD_JSON),
474                Some(self.key),
475                MAX_LISTING_BYTES,
476            )?;
477            if response.head.status == 404 {
478                self.vanished.push(container.clone());
479                continue;
480            }
481            if !response.head.is_success() {
482                self.unverified
483                    .push((container.clone(), response.head.status));
484                continue;
485            }
486            let origin = self.gate.target().origin().clone();
487            let now: BTreeSet<PodPath> = listing::children(&origin, container, &response.body)?
488                .into_iter()
489                .filter_map(|child| match child {
490                    Child::Accepted(path) => Some(path),
491                    Child::Refused { .. } => None,
492                })
493                .collect();
494            if now != *before {
495                self.changed.push((
496                    container.clone(),
497                    "its listing changed during the export".to_owned(),
498                ));
499            }
500        }
501        self.listings = listings;
502        Ok(())
503    }
504}
505
506/// Refuses another entry when `held` entries are already archived.
507fn check_entry_limit(held: u64) -> Result<(), CliError> {
508    if held >= MAX_EXPORT_ENTRIES {
509        return Err(CliError::Local(format!(
510            "export stopped: the pod holds more than {MAX_EXPORT_ENTRIES} entries; \
511             nothing was written"
512        )));
513    }
514    Ok(())
515}
516
517/// Refuses a walk whose content has grown to `total` bytes, past the limit.
518fn check_byte_limit(total: u64) -> Result<(), CliError> {
519    if total > MAX_EXPORT_BYTES {
520        return Err(CliError::Local(format!(
521            "export stopped: the pod holds more than {MAX_EXPORT_BYTES} bytes (64 GiB); \
522             nothing was written"
523        )));
524    }
525    Ok(())
526}
527
528/// Reads an entity tag that is the quoted SHA-256 of the body, as the pod
529/// server sends; `None` for any other tag.
530fn sha256_tag(etag: &str) -> Option<Sha256Digest> {
531    let tag = etag.strip_prefix("W/").unwrap_or(etag);
532    tag.strip_prefix('"')?.strip_suffix('"')?.parse().ok()
533}
534
535/// Maps a failure to write the archive.
536fn archive_error(err: &io::Error) -> CliError {
537    CliError::Local(format!("writing the archive failed: {err}"))
538}
539
540/// Maps a failure of the spool file.
541fn spool_error(err: &io::Error) -> CliError {
542    CliError::Local(format!("the export's temporary file failed: {err}"))
543}
544
545/// Refuses an existing file before any work is done. This is an early,
546/// friendly refusal only: [`place`] is what guarantees that nothing that
547/// appears later is replaced.
548fn check_absent(path: &Path) -> Result<(), CliError> {
549    if fs::symlink_metadata(path).is_ok() {
550        return Err(CliError::Local(format!(
551            "{} already exists; pass --force to replace it",
552            path.display()
553        )));
554    }
555    Ok(())
556}
557
558/// What a finished walk found, for the manifest and the report.
559#[derive(Debug)]
560struct Findings {
561    root: PodPath,
562    entries: Vec<Entry>,
563    skipped: Vec<Skipped>,
564    vanished: Vec<PodPath>,
565    changed: Vec<(PodPath, String)>,
566    unverified: Vec<(PodPath, u16)>,
567    total_bytes: u64,
568}
569
570impl Findings {
571    /// Splits a finished walk into the archive and what it found.
572    fn from_walk(walk: Walk<'_>) -> (Archive, Self) {
573        let findings = Self {
574            root: walk.root,
575            entries: walk.entries,
576            skipped: walk.skipped,
577            vanished: walk.vanished,
578            changed: walk.changed,
579            unverified: walk.unverified,
580            total_bytes: walk.total_bytes,
581        };
582        (walk.archive, findings)
583    }
584
585    /// The ACLs that exist.
586    fn acls(&self) -> Vec<&PodPath> {
587        self.entries
588            .iter()
589            .filter(|entry| entry.kind == Kind::Acl)
590            .map(|entry| &entry.path)
591            .collect()
592    }
593
594    /// Returns `true` when nothing changed, vanished or was skipped.
595    fn is_complete(&self) -> bool {
596        self.changed.is_empty() && self.vanished.is_empty() && self.skipped.is_empty()
597    }
598
599    /// The members the manifest and the report share.
600    fn json_members(&self) -> serde_json::Map<String, Json> {
601        let mut map = serde_json::Map::new();
602        map.insert("total_bytes".to_owned(), json!(self.total_bytes));
603        map.insert("acls".to_owned(), json!(self.acls()));
604        map.insert(
605            "changed".to_owned(),
606            self.changed
607                .iter()
608                .map(|(path, why)| json!({"path": path, "reason": why}))
609                .collect(),
610        );
611        map.insert("vanished".to_owned(), json!(self.vanished));
612        map.insert(
613            "skipped".to_owned(),
614            self.skipped
615                .iter()
616                .map(|s| json!({"listed_in": s.listed_in, "id": s.id, "reason": s.reason}))
617                .collect(),
618        );
619        map.insert(
620            "unverified".to_owned(),
621            self.unverified
622                .iter()
623                .map(|(path, status)| json!({"path": path, "status": status}))
624                .collect(),
625        );
626        map
627    }
628}
629
630/// Finishes the tar stream and the zstd frame, syncs the file, and returns
631/// the archive's size and SHA-256.
632fn finish_archive(archive: Archive) -> Result<(u64, Sha256Digest), CliError> {
633    let encoder = archive.into_inner().map_err(|err| archive_error(&err))?;
634    let mut hashing = encoder.finish().map_err(|err| archive_error(&err))?;
635    hashing.flush().map_err(|err| archive_error(&err))?;
636    let size = hashing.size;
637    let digest: [u8; 32] = hashing.hasher.finalize().into();
638    let file = hashing
639        .inner
640        .into_inner()
641        .map_err(|err| archive_error(err.error()))?;
642    file.sync_all().map_err(|err| archive_error(&err))?;
643    Ok((size, Sha256Digest::from_bytes(digest)))
644}
645
646/// What an export does with files already at its final names.
647#[derive(Debug, Clone, Copy, PartialEq, Eq)]
648enum Existing {
649    /// Never replace them (the default).
650    Keep,
651    /// Replace them (`--force`).
652    Replace,
653}
654
655/// Writes the manifest under its temporary name, then puts both files in
656/// place with [`place`].
657fn install(
658    targets: &Targets,
659    manifest: &Json,
660    existing: Existing,
661    cleanup: &mut Cleanup,
662) -> Result<(), CliError> {
663    let mut text = serde_json::to_vec_pretty(manifest)
664        .map_err(|err| CliError::Local(format!("encoding the manifest failed: {err}")))?;
665    text.push(b'\n');
666    let mut file = create_private(&targets.manifest_temp, Access::Write)?;
667    cleanup.0.push(targets.manifest_temp.clone());
668    file.write_all(&text)
669        .and_then(|()| file.sync_all())
670        .map_err(|err| CliError::Local(format!("writing the manifest failed: {err}")))?;
671    drop(file);
672    place(targets, existing)
673}
674
675/// Puts the archive and then its manifest in place and syncs the directory.
676///
677/// The manifest is the commit point: it is always placed last, so a
678/// manifest under the final name always describes the archive beside it.
679/// An archive with no manifest is an export that did not finish.
680///
681/// With [`Existing::Keep`], both files are placed with [`private_file::place_new`],
682/// which never replaces anything: a file that appeared at either name after
683/// the absence check (another export, say) is kept, and the export fails.
684/// If the manifest's name is taken, the archive placed a moment before is
685/// withdrawn again.
686///
687/// With [`Existing::Replace`] (`--force`), two files cannot be replaced in
688/// one atomic step, so the old manifest is first moved aside (and the directory synced), then the
689/// archive and the manifest are renamed over the old files. If the archive
690/// cannot be moved, the old manifest is moved back and the old pair is as
691/// it was. If the manifest cannot be moved, the old one is discarded, as it
692/// describes an archive that is gone, and the new archive stays with no
693/// manifest. A crash between the steps leaves either the old archive or the
694/// new one with no manifest, and at most a hidden `.<name>.manifest-old-…`
695/// file. Concurrent forced exports to the same name are not coordinated.
696fn place(targets: &Targets, existing: Existing) -> Result<(), CliError> {
697    match existing {
698        Existing::Keep => place_new(targets)?,
699        Existing::Replace => place_replacing(targets)?,
700    }
701    sync_directory(targets, "the archive and its manifest are in place")
702}
703
704/// [`place`] with [`Existing::Keep`].
705fn place_new(targets: &Targets) -> Result<(), CliError> {
706    let refused = |path: &Path, err: &io::Error| {
707        if err.kind() == io::ErrorKind::AlreadyExists {
708            CliError::Local(format!(
709                "{} already exists; pass --force to replace it",
710                path.display()
711            ))
712        } else {
713            CliError::Local(format!(
714                "moving {} into place failed: {err}",
715                path.display()
716            ))
717        }
718    };
719    let ours = fs::symlink_metadata(&targets.archive_temp)
720        .map_err(|err| refused(&targets.archive, &err))?;
721    private_file::place_new(&targets.archive_temp, &targets.archive)
722        .map_err(|err| refused(&targets.archive, &err))?;
723    if let Err(err) = private_file::place_new(&targets.manifest_temp, &targets.manifest) {
724        // Withdraw the archive, but only if the name still holds our file.
725        if let Ok(now) = fs::symlink_metadata(&targets.archive) {
726            if (now.dev(), now.ino()) == (ours.dev(), ours.ino()) {
727                let _removed = fs::remove_file(&targets.archive);
728            }
729        }
730        return Err(refused(&targets.manifest, &err));
731    }
732    Ok(())
733}
734
735/// [`place`] with [`Existing::Replace`].
736fn place_replacing(targets: &Targets) -> Result<(), CliError> {
737    let aside = match fs::rename(&targets.manifest, &targets.manifest_aside) {
738        Ok(()) => {
739            sync_directory(targets, "the old manifest is set aside")?;
740            Some(&targets.manifest_aside)
741        }
742        Err(err) if err.kind() == io::ErrorKind::NotFound => None,
743        Err(err) => {
744            return Err(CliError::Local(format!(
745                "moving the old manifest {} aside failed: {err}",
746                targets.manifest.display()
747            )))
748        }
749    };
750    if let Err(err) = fs::rename(&targets.archive_temp, &targets.archive) {
751        let restored = aside.map_or(Ok(()), |old| fs::rename(old, &targets.manifest));
752        let note = match restored {
753            Ok(()) => String::new(),
754            Err(restore) => format!(
755                "; restoring the old manifest from {} failed: {restore}",
756                targets.manifest_aside.display()
757            ),
758        };
759        return Err(CliError::Local(format!(
760            "moving the archive into place at {} failed: {err}{note}",
761            targets.archive.display()
762        )));
763    }
764    if let Some(old) = aside {
765        // Best effort: it describes an archive that has just been replaced.
766        let _removed = fs::remove_file(old);
767    }
768    fs::rename(&targets.manifest_temp, &targets.manifest).map_err(|err| {
769        CliError::Local(format!(
770            "the archive is in place at {}, but moving its manifest into place at {} failed: \
771             {err}; no manifest is beside it",
772            targets.archive.display(),
773            targets.manifest.display()
774        ))
775    })
776}
777
778/// Syncs the target directory, so the renames so far are durable.
779fn sync_directory(targets: &Targets, done: &str) -> Result<(), CliError> {
780    File::open(&targets.directory)
781        .and_then(|dir| dir.sync_all())
782        .map_err(|err| {
783            CliError::Local(format!(
784                "{done}, but syncing {} failed: {err}",
785                targets.directory.display()
786            ))
787        })
788}
789
790impl Session {
791    /// `stratum export -o <archive.tar.zst> [--force]`: walks the caller's
792    /// own pod over signed requests and writes it as a tar archive
793    /// compressed with zstd, with a manifest beside it.
794    ///
795    /// The walk starts at the pod root `/pods/<pk>/` and fetches the root
796    /// ACL `/pods/<pk>.acl`. Each child a listing names under `ldp:contains`
797    /// is resolved against the listing's own address and followed only if
798    /// the result is on the canonical origin, parses as a pod path under the
799    /// Step 2 rules, is in the caller's own pod and lies under the container
800    /// listed; anything else is skipped and reported. Redirects are never
801    /// followed. For every container and resource the ACL beside it is
802    /// asked for (a 404 means none). No entry is fetched twice.
803    ///
804    /// The archive holds `pods/<pk>/…` (containers as directories) and
805    /// `pods/<pk>.acl`, so it unpacks to the bytes that were written. The
806    /// manifest, `<archive>.manifest.json`, lists every entry's path, kind,
807    /// size, SHA-256 and content type, which ACLs exist, the archive's own
808    /// size and SHA-256, and what was skipped. The export is not a snapshot:
809    /// after the walk each resource's entity tag and each container's
810    /// listing is asked for again, and entries that changed or vanished are
811    /// reported. The walk stops with an error at 100,000 entries or 64 GiB.
812    ///
813    /// Both files are written under temporary names in the target directory
814    /// (mode `0600`) and moved into place only once complete, the archive
815    /// first and the manifest last. A manifest present beside the archive
816    /// therefore always describes that archive; an archive with no manifest
817    /// is an export that did not finish and should not be trusted. Without
818    /// `force`, nothing is ever replaced, including a file that appears at
819    /// either name while the export runs: the export fails instead, and an
820    /// archive it had already placed is withdrawn. With `force`, the old
821    /// manifest is set aside before the archive is replaced, and put back if
822    /// the archive cannot be moved; the limit is that a failure or crash
823    /// between the two moves leaves the new (or old) archive with no
824    /// manifest, never with a mismatched one. Concurrent forced exports to
825    /// the same name are not coordinated.
826    ///
827    /// # Errors
828    ///
829    /// [`CliError::Local`] when a target exists without `force` (checked
830    /// before the walk and again when the files are placed), a limit is
831    /// reached or a file cannot be written; [`CliError::ExportIncomplete`]
832    /// (after both files are written) when anything changed, vanished or
833    /// was skipped; and key, transport and server errors.
834    pub fn export(&self, target: &GateTarget, options: &ExportOptions) -> Result<u8, CliError> {
835        let key = self.key()?;
836        let me = key.public();
837        let targets = Targets::new(&options.output)?;
838        if !options.force {
839            check_absent(&targets.archive)?;
840            check_absent(&targets.manifest)?;
841        }
842
843        let mut cleanup = Cleanup::default();
844        let archive_file = create_private(&targets.archive_temp, Access::Write)?;
845        cleanup.0.push(targets.archive_temp.clone());
846        let spool = create_private(&targets.spool, Access::ReadWrite)?;
847        cleanup.0.push(targets.spool.clone());
848        let encoder = zstd::stream::write::Encoder::new(
849            Hashing {
850                inner: BufWriter::new(archive_file),
851                hasher: Sha256::new(),
852                size: 0,
853            },
854            ZSTD_LEVEL,
855        )
856        .map_err(|err| archive_error(&err))?;
857        let created_at = client::now()?;
858        let mut walk = Walk {
859            gate: GateClient::new(target.clone()).with_busy_retries(*self.output()),
860            key: &key,
861            root: PodPath::pod_root(&me),
862            archive: tar::Builder::new(encoder),
863            spool,
864            created_at,
865            entries: Vec::new(),
866            visited: BTreeSet::new(),
867            listings: BTreeMap::new(),
868            skipped: Vec::new(),
869            vanished: Vec::new(),
870            changed: Vec::new(),
871            unverified: Vec::new(),
872            total_bytes: 0,
873        };
874        self.output()
875            .note(&format!("exporting {} from {}", walk.root, target.origin()))?;
876        walk.run()?;
877        walk.verify()?;
878        let (archive, findings) = Findings::from_walk(walk);
879        let (archive_size, archive_sha256) = finish_archive(archive)?;
880
881        let archive_name = targets
882            .archive
883            .file_name()
884            .map(|n| n.to_string_lossy().into_owned())
885            .unwrap_or_default();
886        let mut manifest = json!({
887            "format": MANIFEST_FORMAT,
888            "format_version": MANIFEST_FORMAT_VERSION,
889            "origin": target.origin().as_str(),
890            "owner": me,
891            "pod_root": findings.root,
892            "created_at": created_at,
893            "archive": {"name": archive_name, "size": archive_size, "sha256": archive_sha256},
894            "entries": findings.entries.iter().map(Entry::to_json).collect::<Vec<_>>(),
895        });
896        if let Json::Object(map) = &mut manifest {
897            map.extend(findings.json_members());
898        }
899        let existing = if options.force {
900            Existing::Replace
901        } else {
902            Existing::Keep
903        };
904        install(&targets, &manifest, existing, &mut cleanup)?;
905        drop(cleanup);
906        self.report_export(&targets, archive_size, archive_sha256, &findings)
907    }
908
909    /// Prints what an export wrote and found.
910    fn report_export(
911        &self,
912        targets: &Targets,
913        archive_size: u64,
914        archive_sha256: Sha256Digest,
915        findings: &Findings,
916    ) -> Result<u8, CliError> {
917        let mut report = json!({
918            "archive": targets.archive.display().to_string(),
919            "manifest": targets.manifest.display().to_string(),
920            "archive_size": archive_size,
921            "archive_sha256": archive_sha256,
922            "entries": findings.entries.len(),
923        });
924        if let Json::Object(map) = &mut report {
925            map.extend(findings.json_members());
926        }
927        self.output().json(&report)?;
928        self.output().line(&format!(
929            "archive: {} ({archive_size} bytes, sha256 {archive_sha256})",
930            targets.archive.display()
931        ))?;
932        self.output()
933            .line(&format!("manifest: {}", targets.manifest.display()))?;
934        self.output().line(&format!(
935            "entries: {} ({} bytes of content, {} ACLs)",
936            findings.entries.len(),
937            findings.total_bytes,
938            findings.acls().len()
939        ))?;
940        for (path, why) in &findings.changed {
941            self.output().line(&format!("changed: {path}: {why}"))?;
942        }
943        for path in &findings.vanished {
944            self.output().line(&format!("vanished: {path}"))?;
945        }
946        for s in &findings.skipped {
947            let place = s
948                .listed_in
949                .as_ref()
950                .map(|p| format!(" (listed in {p})"))
951                .unwrap_or_default();
952            self.output()
953                .line(&format!("skipped: {:?}{place}: {}", s.id, s.reason))?;
954        }
955        for (path, status) in &findings.unverified {
956            self.output()
957                .line(&format!("not rechecked: {path}: HTTP {status}"))?;
958        }
959        if findings.is_complete() {
960            return Ok(exit::OK);
961        }
962        Err(CliError::ExportIncomplete(format!(
963            "the archive is written, but {} entries changed, {} vanished and {} listed children \
964             were skipped during the walk; the manifest lists them",
965            findings.changed.len(),
966            findings.vanished.len(),
967            findings.skipped.len()
968        )))
969    }
970}
971
972#[cfg(test)]
973mod tests {
974    use super::*;
975
976    #[test]
977    fn entity_tags_are_read_as_quoted_digests() {
978        let hex = "ab".repeat(32);
979        let digest: Sha256Digest = hex.parse().expect("digest");
980        assert_eq!(sha256_tag(&format!("\"{hex}\"")), Some(digest));
981        assert_eq!(sha256_tag(&format!("W/\"{hex}\"")), Some(digest));
982        assert_eq!(sha256_tag(&hex), None);
983        assert_eq!(sha256_tag("\"abc\""), None);
984    }
985
986    #[test]
987    fn the_walk_stops_at_the_limits() {
988        assert!(check_entry_limit(MAX_EXPORT_ENTRIES - 1).is_ok());
989        let err = check_entry_limit(MAX_EXPORT_ENTRIES).expect_err("the 100,001st entry");
990        assert!(err.to_string().contains("100000 entries"), "{err}");
991        assert!(check_byte_limit(MAX_EXPORT_BYTES).is_ok());
992        let err = check_byte_limit(MAX_EXPORT_BYTES + 1).expect_err("one byte over 64 GiB");
993        assert!(err.to_string().contains("64 GiB"), "{err}");
994        assert_eq!(err.exit_code(), exit::FAILURE);
995    }
996
997    #[test]
998    fn targets_sit_beside_the_archive() {
999        let targets = Targets::new(Path::new("out/pod.tar.zst")).expect("targets");
1000        assert_eq!(targets.manifest, Path::new("out/pod.tar.zst.manifest.json"));
1001        assert_eq!(targets.directory, Path::new("out"));
1002        assert!(targets
1003            .archive_temp
1004            .to_string_lossy()
1005            .starts_with("out/.pod.tar.zst.partial-"));
1006        let bare = Targets::new(Path::new("pod.tar.zst")).expect("targets");
1007        assert_eq!(bare.directory, Path::new("."));
1008    }
1009    /// An export's targets in a fresh directory, with both temporary files
1010    /// written: an archive holding `archive` and a manifest naming its
1011    /// SHA-256.
1012    fn staged(archive: &[u8]) -> (tempfile::TempDir, Targets) {
1013        let dir = tempfile::tempdir().expect("tempdir");
1014        let targets = Targets::new(&dir.path().join("pod.tar.zst")).expect("targets");
1015        fs::write(&targets.archive_temp, archive).expect("archive");
1016        fs::write(&targets.manifest_temp, manifest_for(archive)).expect("manifest");
1017        (dir, targets)
1018    }
1019
1020    /// A manifest that describes `archive`.
1021    fn manifest_for(archive: &[u8]) -> Vec<u8> {
1022        json!({"archive": {"sha256": Sha256Digest::of(archive)}})
1023            .to_string()
1024            .into_bytes()
1025    }
1026
1027    /// Whether the manifest beside the archive, if any, describes it.
1028    fn pair_is_consistent(targets: &Targets) -> bool {
1029        let Ok(manifest) = fs::read(&targets.manifest) else {
1030            return true;
1031        };
1032        let Ok(archive) = fs::read(&targets.archive) else {
1033            return false;
1034        };
1035        let manifest: Json = serde_json::from_slice(&manifest).expect("manifest json");
1036        manifest["archive"]["sha256"] == json!(Sha256Digest::of(&archive))
1037    }
1038
1039    /// The names in `dir`, sorted.
1040    fn names(dir: &Path) -> Vec<String> {
1041        let mut names: Vec<String> = fs::read_dir(dir)
1042            .expect("read dir")
1043            .map(|entry| {
1044                entry
1045                    .expect("entry")
1046                    .file_name()
1047                    .to_string_lossy()
1048                    .into_owned()
1049            })
1050            .collect();
1051        names.sort();
1052        names
1053    }
1054
1055    #[test]
1056    fn an_archive_appearing_after_the_check_is_never_replaced() {
1057        let (_dir, targets) = staged(b"new");
1058        fs::write(&targets.archive, b"theirs").expect("theirs");
1059        let err = place(&targets, Existing::Keep).expect_err("refused");
1060        assert!(err.to_string().contains("already exists"), "{err}");
1061        assert_eq!(
1062            fs::read(&targets.archive).expect("archive"),
1063            b"theirs",
1064            "kept"
1065        );
1066        assert!(
1067            fs::metadata(&targets.manifest).is_err(),
1068            "no manifest beside it"
1069        );
1070    }
1071
1072    #[test]
1073    fn a_manifest_appearing_after_the_check_is_never_replaced() {
1074        let (_dir, targets) = staged(b"new");
1075        fs::write(&targets.manifest, b"theirs").expect("theirs");
1076        let err = place(&targets, Existing::Keep).expect_err("refused");
1077        assert!(err.to_string().contains("already exists"), "{err}");
1078        assert_eq!(
1079            fs::read(&targets.manifest).expect("manifest"),
1080            b"theirs",
1081            "kept"
1082        );
1083        assert!(
1084            fs::metadata(&targets.archive).is_err(),
1085            "the archive placed a moment earlier is withdrawn"
1086        );
1087    }
1088
1089    #[test]
1090    fn a_failed_manifest_step_never_leaves_a_new_archive_beside_an_old_manifest() {
1091        let (dir, targets) = staged(b"new");
1092        fs::write(&targets.archive, b"old").expect("old archive");
1093        fs::write(&targets.manifest, manifest_for(b"old")).expect("old manifest");
1094        fs::remove_file(&targets.manifest_temp).expect("make the manifest step fail");
1095        let err = place(&targets, Existing::Replace).expect_err("the manifest step fails");
1096        assert!(err.to_string().contains("no manifest"), "{err}");
1097        assert!(pair_is_consistent(&targets), "{:?}", names(dir.path()));
1098        let visible: Vec<String> = names(dir.path())
1099            .into_iter()
1100            .filter(|name| !name.starts_with('.'))
1101            .collect();
1102        assert_eq!(
1103            visible,
1104            ["pod.tar.zst"],
1105            "the archive alone, with no manifest"
1106        );
1107    }
1108
1109    #[test]
1110    fn a_failed_archive_step_keeps_the_old_pair() {
1111        let (dir, targets) = staged(b"new");
1112        // A non-empty directory at the archive's name makes its rename fail.
1113        fs::create_dir(&targets.archive).expect("dir");
1114        fs::write(targets.archive.join("x"), b"x").expect("x");
1115        fs::write(&targets.manifest, manifest_for(b"old")).expect("old manifest");
1116        let err = place(&targets, Existing::Replace).expect_err("the archive step fails");
1117        assert!(err.to_string().contains("moving the archive"), "{err}");
1118        assert_eq!(
1119            fs::read(&targets.manifest).expect("manifest"),
1120            manifest_for(b"old"),
1121            "the old manifest is back: {:?}",
1122            names(dir.path())
1123        );
1124    }
1125
1126    #[test]
1127    fn a_forced_export_replaces_the_pair() {
1128        let (dir, targets) = staged(b"new");
1129        fs::write(&targets.archive, b"old").expect("old archive");
1130        fs::write(&targets.manifest, manifest_for(b"old")).expect("old manifest");
1131        place(&targets, Existing::Replace).expect("placed");
1132        assert_eq!(fs::read(&targets.archive).expect("archive"), b"new", "new");
1133        assert!(pair_is_consistent(&targets), "the manifest describes it");
1134        assert_eq!(
1135            names(dir.path()),
1136            ["pod.tar.zst", "pod.tar.zst.manifest.json"],
1137            "nothing else is left"
1138        );
1139    }
1140}