1use 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::{
18 self, GateClient, Head, Request, Route, ANY, LD_JSON, MAX_LISTING_BYTES, SUSPENDED,
19};
20use crate::listing::{self, Child};
21use crate::origin::GateTarget;
22use crate::output::sanitize;
23use crate::private_file;
24use crate::session::Session;
25
26pub const MAX_EXPORT_ENTRIES: u64 = 100_000;
29
30pub const MAX_EXPORT_BYTES: u64 = 64 * 1024 * 1024 * 1024;
33
34pub const MANIFEST_FORMAT: &str = "stratum-pod-export";
36
37pub const MANIFEST_FORMAT_VERSION: u64 = 1;
39
40pub const MANIFEST_SUFFIX: &str = ".manifest.json";
42
43const ZSTD_LEVEL: i32 = 3;
45
46#[derive(Debug, Clone, Default)]
48pub struct ExportOptions {
49 pub output: PathBuf,
52 pub force: bool,
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58enum Kind {
59 Container,
60 Resource,
61 Acl,
62}
63
64impl Kind {
65 fn as_str(self) -> &'static str {
66 match self {
67 Self::Container => "container",
68 Self::Resource => "resource",
69 Self::Acl => "acl",
70 }
71 }
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76enum Reason {
77 Listed,
79 Beside,
82}
83
84#[derive(Debug, Clone)]
86struct Entry {
87 path: PodPath,
88 kind: Kind,
89 size: u64,
90 sha256: Option<Sha256Digest>,
91 content_type: Option<String>,
92 etag: Option<String>,
93}
94
95impl Entry {
96 fn to_json(&self) -> Json {
97 json!({
98 "path": self.path,
99 "archive_path": archive_path(&self.path),
100 "kind": self.kind.as_str(),
101 "size": self.size,
102 "sha256": self.sha256,
103 "content_type": self.content_type,
104 })
105 }
106}
107
108fn archive_path(path: &PodPath) -> &str {
111 path.as_str().trim_start_matches('/')
112}
113
114#[derive(Debug)]
116struct Targets {
117 archive: PathBuf,
118 manifest: PathBuf,
119 directory: PathBuf,
120 archive_temp: PathBuf,
121 manifest_temp: PathBuf,
122 manifest_aside: PathBuf,
124 spool: PathBuf,
125}
126
127impl Targets {
128 fn new(archive: &Path) -> Result<Self, CliError> {
129 let name = archive
130 .file_name()
131 .and_then(|n| n.to_str())
132 .filter(|n| !n.is_empty())
133 .ok_or_else(|| CliError::Usage("-o must name an archive file".to_owned()))?;
134 let directory = match archive.parent() {
135 Some(parent) if !parent.as_os_str().is_empty() => parent.to_owned(),
136 _ => PathBuf::from("."),
137 };
138 let tag = hex::encode(&client::random_32()?[..6]);
139 let mut manifest = archive.as_os_str().to_owned();
140 manifest.push(MANIFEST_SUFFIX);
141 Ok(Self {
142 archive: archive.to_owned(),
143 manifest: PathBuf::from(manifest),
144 archive_temp: directory.join(format!(".{name}.partial-{tag}")),
145 manifest_temp: directory.join(format!(".{name}.manifest-{tag}")),
146 manifest_aside: directory.join(format!(".{name}.manifest-old-{tag}")),
147 spool: directory.join(format!(".{name}.spool-{tag}")),
148 directory,
149 })
150 }
151}
152
153#[derive(Debug, Default)]
155struct Cleanup(Vec<PathBuf>);
156
157impl Drop for Cleanup {
158 fn drop(&mut self) {
159 for path in &self.0 {
160 let _removed = fs::remove_file(path);
162 }
163 }
164}
165
166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
168enum Access {
169 Write,
171 ReadWrite,
173}
174
175fn create_private(path: &Path, access: Access) -> Result<File, CliError> {
177 OpenOptions::new()
178 .read(access == Access::ReadWrite)
179 .write(true)
180 .create_new(true)
181 .mode(0o600)
182 .open(path)
183 .map_err(|err| CliError::Local(format!("creating {} failed: {err}", path.display())))
184}
185
186struct Hashing<W> {
188 inner: W,
189 hasher: Sha256,
190 size: u64,
191}
192
193impl<W: Write> Write for Hashing<W> {
194 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
195 let written = self.inner.write(buf)?;
196 self.hasher.update(&buf[..written]);
197 self.size = self
198 .size
199 .saturating_add(u64::try_from(written).unwrap_or(u64::MAX));
200 Ok(written)
201 }
202
203 fn flush(&mut self) -> io::Result<()> {
204 self.inner.flush()
205 }
206}
207
208type Archive = tar::Builder<zstd::stream::write::Encoder<'static, Hashing<BufWriter<File>>>>;
210
211#[derive(Debug, Clone)]
213struct Skipped {
214 listed_in: Option<PodPath>,
215 id: String,
216 reason: String,
217}
218
219struct Walk<'a> {
221 gate: GateClient,
222 key: &'a NostrSecretKey,
223 root: PodPath,
224 archive: Archive,
225 spool: File,
226 created_at: UnixTime,
227 entries: Vec<Entry>,
228 visited: BTreeSet<PodPath>,
229 listings: BTreeMap<PodPath, BTreeSet<PodPath>>,
230 skipped: Vec<Skipped>,
231 vanished: Vec<PodPath>,
232 changed: Vec<(PodPath, String)>,
233 unverified: Vec<(PodPath, u16)>,
234 total_bytes: u64,
235}
236
237impl Walk<'_> {
238 fn run(&mut self) -> Result<(), CliError> {
240 let root = self.root.clone();
241 let root_acl = root
242 .acl_path()
243 .ok_or_else(|| CliError::Local("the pod root has no ACL path".to_owned()))?;
244 self.visited.insert(root.clone());
245 self.visited.insert(root_acl.clone());
246 self.fetch(&root_acl, Reason::Beside, None)?;
247 let mut queue = VecDeque::from([root.clone()]);
248 while let Some(container) = queue.pop_front() {
249 let Some(children) = self.list(&container)? else {
250 continue;
251 };
252 self.add_container(&container)?;
253 if container != root {
254 if let Some(acl) = container.acl_path() {
255 if self.visited.insert(acl.clone()) {
256 self.fetch(&acl, Reason::Beside, Some(&container))?;
257 }
258 }
259 }
260 let mut accepted = BTreeSet::new();
261 for child in children {
262 let path = match child {
263 Child::Accepted(path) => path,
264 Child::Refused { id, reason } => {
265 self.skipped.push(Skipped {
266 listed_in: Some(container.clone()),
267 id,
268 reason,
269 });
270 continue;
271 }
272 };
273 accepted.insert(path.clone());
274 if !self.visited.insert(path.clone()) {
275 continue;
276 }
277 if path.is_container() {
278 queue.push_back(path);
279 continue;
280 }
281 let present = self.fetch(&path, Reason::Listed, Some(&container))?;
282 if present {
283 if let Some(acl) = path.acl_path() {
284 if self.visited.insert(acl.clone()) {
285 self.fetch(&acl, Reason::Beside, Some(&container))?;
286 }
287 }
288 }
289 }
290 self.listings.insert(container, accepted);
291 }
292 Ok(())
293 }
294
295 fn list(&mut self, container: &PodPath) -> Result<Option<Vec<Child>>, CliError> {
297 let response = self.gate.fetch(
298 &Request::new("GET", container.as_str(), LD_JSON),
299 Some(self.key),
300 MAX_LISTING_BYTES,
301 )?;
302 let head = &response.head;
303 if head.is_success() {
304 let origin = self.gate.target().origin().clone();
305 return listing::children(&origin, container, &response.body).map(Some);
306 }
307 if *container == self.root {
308 return Err(response.into_error(Route::Pod));
309 }
310 if head.status == 404 {
311 self.vanished.push(container.clone());
312 return Ok(None);
313 }
314 if head.is_redirect() {
315 self.skip_redirect(container, None);
316 return Ok(None);
317 }
318 Err(response.into_error(Route::Pod))
319 }
320
321 fn skip_redirect(&mut self, path: &PodPath, listed_in: Option<&PodPath>) {
323 self.skipped.push(Skipped {
324 listed_in: listed_in.cloned(),
325 id: path.to_string(),
326 reason: "answered with a redirect, which is not followed".to_owned(),
327 });
328 }
329
330 fn count_entry(&self) -> Result<(), CliError> {
332 check_entry_limit(u64::try_from(self.entries.len()).unwrap_or(u64::MAX))
333 }
334
335 fn add_container(&mut self, container: &PodPath) -> Result<(), CliError> {
337 self.count_entry()?;
338 let mut header = tar::Header::new_gnu();
339 header.set_entry_type(tar::EntryType::Directory);
340 header.set_size(0);
341 header.set_mode(0o700);
342 header.set_mtime(self.created_at.as_secs());
343 self.archive
344 .append_data(&mut header, archive_path(container), io::empty())
345 .map_err(|err| archive_error(&err))?;
346 self.entries.push(Entry {
347 path: container.clone(),
348 kind: Kind::Container,
349 size: 0,
350 sha256: None,
351 content_type: None,
352 etag: None,
353 });
354 Ok(())
355 }
356
357 fn fetch(
360 &mut self,
361 path: &PodPath,
362 reason: Reason,
363 listed_in: Option<&PodPath>,
364 ) -> Result<bool, CliError> {
365 self.count_entry()?;
366 self.spool
367 .set_len(0)
368 .and_then(|()| self.spool.seek(SeekFrom::Start(0)).map(drop))
369 .map_err(|err| spool_error(&err))?;
370 let request = Request::new("GET", path.as_str(), ANY);
371 let (head, outcome) = {
372 let mut sink = BufWriter::new(&self.spool);
373 let result =
374 self.gate
375 .stream(&request, self.key, &mut sink, gate::MAX_RESOURCE_BYTES)?;
376 sink.flush().map_err(|err| spool_error(&err))?;
377 result
378 };
379 let streamed = match outcome {
380 Ok(streamed) => streamed,
381 Err(body) => {
382 if head.status == 404 {
383 if reason == Reason::Listed {
384 self.vanished.push(path.clone());
385 }
386 return Ok(false);
387 }
388 if head.is_redirect() {
389 self.skip_redirect(path, listed_in);
390 return Ok(false);
391 }
392 return Err(gate::error_from(&head, &body, Route::Pod));
393 }
394 };
395 self.total_bytes = self.total_bytes.saturating_add(streamed.size);
396 check_byte_limit(self.total_bytes)?;
397 if let Some(tag) = head.etag.as_deref().and_then(sha256_tag) {
398 if tag != streamed.sha256 {
399 self.changed.push((
400 path.clone(),
401 "the bytes received do not match the entity tag sent with them".to_owned(),
402 ));
403 }
404 }
405 self.spool
406 .seek(SeekFrom::Start(0))
407 .map_err(|err| spool_error(&err))?;
408 let mut header = tar::Header::new_gnu();
409 header.set_entry_type(tar::EntryType::Regular);
410 header.set_size(streamed.size);
411 header.set_mode(0o600);
412 header.set_mtime(self.created_at.as_secs());
413 self.archive
414 .append_data(
415 &mut header,
416 archive_path(path),
417 (&self.spool).take(streamed.size),
418 )
419 .map_err(|err| archive_error(&err))?;
420 let kind = if path.acl_path().is_none() {
421 Kind::Acl
422 } else {
423 Kind::Resource
424 };
425 self.entries.push(Entry {
426 path: path.clone(),
427 kind,
428 size: streamed.size,
429 sha256: Some(streamed.sha256),
430 content_type: head.content_type.as_deref().map(sanitize),
431 etag: head.etag,
432 });
433 Ok(true)
434 }
435
436 fn abort_if_suspended(&self) -> Result<(), CliError> {
440 let response = self.gate.fetch(
441 &Request::new("GET", self.root.as_str(), LD_JSON),
442 Some(self.key),
443 MAX_LISTING_BYTES,
444 )?;
445 if gate::envelope_code(&response.body).as_deref() == Some(SUSPENDED) {
446 return Err(response.into_error(Route::Pod));
447 }
448 Ok(())
449 }
450
451 fn verify(&mut self) -> Result<(), CliError> {
455 let files: Vec<Entry> = self
456 .entries
457 .iter()
458 .filter(|entry| entry.kind != Kind::Container)
459 .cloned()
460 .collect();
461 for entry in files {
462 let response = self.gate.fetch(
463 &Request::new("HEAD", entry.path.as_str(), ANY),
464 Some(self.key),
465 MAX_RESPONSE_BYTES,
466 )?;
467 let head: &Head = &response.head;
468 if head.status == 403 {
469 self.abort_if_suspended()?;
472 }
473 if head.status == 404 {
474 self.vanished.push(entry.path);
475 } else if head.is_success() {
476 if let Some(now) = &head.etag {
477 let before = entry.etag.as_deref().and_then(sha256_tag).or(entry.sha256);
478 let differs = match (sha256_tag(now), before) {
479 (Some(now), Some(before)) => now != before,
480 _ => entry.etag.as_deref() != Some(now.as_str()),
481 };
482 if differs {
483 self.changed.push((
484 entry.path,
485 "its entity tag changed during the export".to_owned(),
486 ));
487 }
488 }
489 } else {
490 self.unverified.push((entry.path, head.status));
491 }
492 }
493 let listings = std::mem::take(&mut self.listings);
494 for (container, before) in &listings {
495 let response = self.gate.fetch(
496 &Request::new("GET", container.as_str(), LD_JSON),
497 Some(self.key),
498 MAX_LISTING_BYTES,
499 )?;
500 if response.head.status == 404 {
501 self.vanished.push(container.clone());
502 continue;
503 }
504 if gate::envelope_code(&response.body).as_deref() == Some(SUSPENDED) {
505 return Err(response.into_error(Route::Pod));
506 }
507 if !response.head.is_success() {
508 self.unverified
509 .push((container.clone(), response.head.status));
510 continue;
511 }
512 let origin = self.gate.target().origin().clone();
513 let now: BTreeSet<PodPath> = listing::children(&origin, container, &response.body)?
514 .into_iter()
515 .filter_map(|child| match child {
516 Child::Accepted(path) => Some(path),
517 Child::Refused { .. } => None,
518 })
519 .collect();
520 if now != *before {
521 self.changed.push((
522 container.clone(),
523 "its listing changed during the export".to_owned(),
524 ));
525 }
526 }
527 self.listings = listings;
528 Ok(())
529 }
530}
531
532fn check_entry_limit(held: u64) -> Result<(), CliError> {
534 if held >= MAX_EXPORT_ENTRIES {
535 return Err(CliError::Local(format!(
536 "export stopped: the pod holds more than {MAX_EXPORT_ENTRIES} entries; \
537 nothing was written"
538 )));
539 }
540 Ok(())
541}
542
543fn check_byte_limit(total: u64) -> Result<(), CliError> {
545 if total > MAX_EXPORT_BYTES {
546 return Err(CliError::Local(format!(
547 "export stopped: the pod holds more than {MAX_EXPORT_BYTES} bytes (64 GiB); \
548 nothing was written"
549 )));
550 }
551 Ok(())
552}
553
554fn sha256_tag(etag: &str) -> Option<Sha256Digest> {
557 let tag = etag.strip_prefix("W/").unwrap_or(etag);
558 tag.strip_prefix('"')?.strip_suffix('"')?.parse().ok()
559}
560
561fn archive_error(err: &io::Error) -> CliError {
563 CliError::Local(format!("writing the archive failed: {err}"))
564}
565
566fn spool_error(err: &io::Error) -> CliError {
568 CliError::Local(format!("the export's temporary file failed: {err}"))
569}
570
571fn check_absent(path: &Path) -> Result<(), CliError> {
575 if fs::symlink_metadata(path).is_ok() {
576 return Err(CliError::Local(format!(
577 "{} already exists; pass --force to replace it",
578 path.display()
579 )));
580 }
581 Ok(())
582}
583
584#[derive(Debug)]
586struct Findings {
587 root: PodPath,
588 entries: Vec<Entry>,
589 skipped: Vec<Skipped>,
590 vanished: Vec<PodPath>,
591 changed: Vec<(PodPath, String)>,
592 unverified: Vec<(PodPath, u16)>,
593 total_bytes: u64,
594}
595
596impl Findings {
597 fn from_walk(walk: Walk<'_>) -> (Archive, Self) {
599 let findings = Self {
600 root: walk.root,
601 entries: walk.entries,
602 skipped: walk.skipped,
603 vanished: walk.vanished,
604 changed: walk.changed,
605 unverified: walk.unverified,
606 total_bytes: walk.total_bytes,
607 };
608 (walk.archive, findings)
609 }
610
611 fn acls(&self) -> Vec<&PodPath> {
613 self.entries
614 .iter()
615 .filter(|entry| entry.kind == Kind::Acl)
616 .map(|entry| &entry.path)
617 .collect()
618 }
619
620 fn is_complete(&self) -> bool {
622 self.changed.is_empty() && self.vanished.is_empty() && self.skipped.is_empty()
623 }
624
625 fn json_members(&self) -> serde_json::Map<String, Json> {
627 let mut map = serde_json::Map::new();
628 map.insert("total_bytes".to_owned(), json!(self.total_bytes));
629 map.insert("acls".to_owned(), json!(self.acls()));
630 map.insert(
631 "changed".to_owned(),
632 self.changed
633 .iter()
634 .map(|(path, why)| json!({"path": path, "reason": why}))
635 .collect(),
636 );
637 map.insert("vanished".to_owned(), json!(self.vanished));
638 map.insert(
639 "skipped".to_owned(),
640 self.skipped
641 .iter()
642 .map(|s| json!({"listed_in": s.listed_in, "id": s.id, "reason": s.reason}))
643 .collect(),
644 );
645 map.insert(
646 "unverified".to_owned(),
647 self.unverified
648 .iter()
649 .map(|(path, status)| json!({"path": path, "status": status}))
650 .collect(),
651 );
652 map
653 }
654}
655
656fn finish_archive(archive: Archive) -> Result<(u64, Sha256Digest), CliError> {
659 let encoder = archive.into_inner().map_err(|err| archive_error(&err))?;
660 let mut hashing = encoder.finish().map_err(|err| archive_error(&err))?;
661 hashing.flush().map_err(|err| archive_error(&err))?;
662 let size = hashing.size;
663 let digest: [u8; 32] = hashing.hasher.finalize().into();
664 let file = hashing
665 .inner
666 .into_inner()
667 .map_err(|err| archive_error(err.error()))?;
668 file.sync_all().map_err(|err| archive_error(&err))?;
669 Ok((size, Sha256Digest::from_bytes(digest)))
670}
671
672#[derive(Debug, Clone, Copy, PartialEq, Eq)]
674enum Existing {
675 Keep,
677 Replace,
679}
680
681fn install(
684 targets: &Targets,
685 manifest: &Json,
686 existing: Existing,
687 cleanup: &mut Cleanup,
688) -> Result<(), CliError> {
689 let mut text = serde_json::to_vec_pretty(manifest)
690 .map_err(|err| CliError::Local(format!("encoding the manifest failed: {err}")))?;
691 text.push(b'\n');
692 let mut file = create_private(&targets.manifest_temp, Access::Write)?;
693 cleanup.0.push(targets.manifest_temp.clone());
694 file.write_all(&text)
695 .and_then(|()| file.sync_all())
696 .map_err(|err| CliError::Local(format!("writing the manifest failed: {err}")))?;
697 drop(file);
698 place(targets, existing)
699}
700
701fn place(targets: &Targets, existing: Existing) -> Result<(), CliError> {
723 match existing {
724 Existing::Keep => place_new(targets)?,
725 Existing::Replace => place_replacing(targets)?,
726 }
727 sync_directory(targets, "the archive and its manifest are in place")
728}
729
730fn place_new(targets: &Targets) -> Result<(), CliError> {
732 let refused = |path: &Path, err: &io::Error| {
733 if err.kind() == io::ErrorKind::AlreadyExists {
734 CliError::Local(format!(
735 "{} already exists; pass --force to replace it",
736 path.display()
737 ))
738 } else {
739 CliError::Local(format!(
740 "moving {} into place failed: {err}",
741 path.display()
742 ))
743 }
744 };
745 let ours = fs::symlink_metadata(&targets.archive_temp)
746 .map_err(|err| refused(&targets.archive, &err))?;
747 private_file::place_new(&targets.archive_temp, &targets.archive)
748 .map_err(|err| refused(&targets.archive, &err))?;
749 if let Err(err) = private_file::place_new(&targets.manifest_temp, &targets.manifest) {
750 if let Ok(now) = fs::symlink_metadata(&targets.archive) {
752 if (now.dev(), now.ino()) == (ours.dev(), ours.ino()) {
753 let _removed = fs::remove_file(&targets.archive);
754 }
755 }
756 return Err(refused(&targets.manifest, &err));
757 }
758 Ok(())
759}
760
761fn place_replacing(targets: &Targets) -> Result<(), CliError> {
763 let aside = match fs::rename(&targets.manifest, &targets.manifest_aside) {
764 Ok(()) => {
765 sync_directory(targets, "the old manifest is set aside")?;
766 Some(&targets.manifest_aside)
767 }
768 Err(err) if err.kind() == io::ErrorKind::NotFound => None,
769 Err(err) => {
770 return Err(CliError::Local(format!(
771 "moving the old manifest {} aside failed: {err}",
772 targets.manifest.display()
773 )))
774 }
775 };
776 if let Err(err) = fs::rename(&targets.archive_temp, &targets.archive) {
777 let restored = aside.map_or(Ok(()), |old| fs::rename(old, &targets.manifest));
778 let note = match restored {
779 Ok(()) => String::new(),
780 Err(restore) => format!(
781 "; restoring the old manifest from {} failed: {restore}",
782 targets.manifest_aside.display()
783 ),
784 };
785 return Err(CliError::Local(format!(
786 "moving the archive into place at {} failed: {err}{note}",
787 targets.archive.display()
788 )));
789 }
790 if let Some(old) = aside {
791 let _removed = fs::remove_file(old);
793 }
794 fs::rename(&targets.manifest_temp, &targets.manifest).map_err(|err| {
795 CliError::Local(format!(
796 "the archive is in place at {}, but moving its manifest into place at {} failed: \
797 {err}; no manifest is beside it",
798 targets.archive.display(),
799 targets.manifest.display()
800 ))
801 })
802}
803
804fn sync_directory(targets: &Targets, done: &str) -> Result<(), CliError> {
806 File::open(&targets.directory)
807 .and_then(|dir| dir.sync_all())
808 .map_err(|err| {
809 CliError::Local(format!(
810 "{done}, but syncing {} failed: {err}",
811 targets.directory.display()
812 ))
813 })
814}
815
816impl Session {
817 pub fn export(&self, target: &GateTarget, options: &ExportOptions) -> Result<u8, CliError> {
861 let key = self.key()?;
862 let me = key.public();
863 let targets = Targets::new(&options.output)?;
864 if !options.force {
865 check_absent(&targets.archive)?;
866 check_absent(&targets.manifest)?;
867 }
868
869 let mut cleanup = Cleanup::default();
870 let archive_file = create_private(&targets.archive_temp, Access::Write)?;
871 cleanup.0.push(targets.archive_temp.clone());
872 let spool = create_private(&targets.spool, Access::ReadWrite)?;
873 cleanup.0.push(targets.spool.clone());
874 let encoder = zstd::stream::write::Encoder::new(
875 Hashing {
876 inner: BufWriter::new(archive_file),
877 hasher: Sha256::new(),
878 size: 0,
879 },
880 ZSTD_LEVEL,
881 )
882 .map_err(|err| archive_error(&err))?;
883 let created_at = client::now()?;
884 let mut walk = Walk {
885 gate: GateClient::new(target.clone()).with_busy_retries(*self.output()),
886 key: &key,
887 root: PodPath::pod_root(&me),
888 archive: tar::Builder::new(encoder),
889 spool,
890 created_at,
891 entries: Vec::new(),
892 visited: BTreeSet::new(),
893 listings: BTreeMap::new(),
894 skipped: Vec::new(),
895 vanished: Vec::new(),
896 changed: Vec::new(),
897 unverified: Vec::new(),
898 total_bytes: 0,
899 };
900 self.output()
901 .note(&format!("exporting {} from {}", walk.root, target.origin()))?;
902 walk.run()?;
903 walk.verify()?;
904 let (archive, findings) = Findings::from_walk(walk);
905 let (archive_size, archive_sha256) = finish_archive(archive)?;
906
907 let archive_name = targets
908 .archive
909 .file_name()
910 .map(|n| n.to_string_lossy().into_owned())
911 .unwrap_or_default();
912 let mut manifest = json!({
913 "format": MANIFEST_FORMAT,
914 "format_version": MANIFEST_FORMAT_VERSION,
915 "origin": target.origin().as_str(),
916 "owner": me,
917 "pod_root": findings.root,
918 "created_at": created_at,
919 "archive": {"name": archive_name, "size": archive_size, "sha256": archive_sha256},
920 "entries": findings.entries.iter().map(Entry::to_json).collect::<Vec<_>>(),
921 });
922 if let Json::Object(map) = &mut manifest {
923 map.extend(findings.json_members());
924 }
925 let existing = if options.force {
926 Existing::Replace
927 } else {
928 Existing::Keep
929 };
930 install(&targets, &manifest, existing, &mut cleanup)?;
931 drop(cleanup);
932 self.report_export(&targets, archive_size, archive_sha256, &findings)
933 }
934
935 fn report_export(
937 &self,
938 targets: &Targets,
939 archive_size: u64,
940 archive_sha256: Sha256Digest,
941 findings: &Findings,
942 ) -> Result<u8, CliError> {
943 let mut report = json!({
944 "archive": targets.archive.display().to_string(),
945 "manifest": targets.manifest.display().to_string(),
946 "archive_size": archive_size,
947 "archive_sha256": archive_sha256,
948 "entries": findings.entries.len(),
949 });
950 if let Json::Object(map) = &mut report {
951 map.extend(findings.json_members());
952 }
953 self.output().json(&report)?;
954 self.output().line(&format!(
955 "archive: {} ({archive_size} bytes, sha256 {archive_sha256})",
956 targets.archive.display()
957 ))?;
958 self.output()
959 .line(&format!("manifest: {}", targets.manifest.display()))?;
960 self.output().line(&format!(
961 "entries: {} ({} bytes of content, {} ACLs)",
962 findings.entries.len(),
963 findings.total_bytes,
964 findings.acls().len()
965 ))?;
966 for (path, why) in &findings.changed {
967 self.output().line(&format!("changed: {path}: {why}"))?;
968 }
969 for path in &findings.vanished {
970 self.output().line(&format!("vanished: {path}"))?;
971 }
972 for s in &findings.skipped {
973 let place = s
974 .listed_in
975 .as_ref()
976 .map(|p| format!(" (listed in {p})"))
977 .unwrap_or_default();
978 self.output()
979 .line(&format!("skipped: {:?}{place}: {}", s.id, s.reason))?;
980 }
981 for (path, status) in &findings.unverified {
982 self.output()
983 .line(&format!("not rechecked: {path}: HTTP {status}"))?;
984 }
985 if findings.is_complete() {
986 return Ok(exit::OK);
987 }
988 Err(CliError::ExportIncomplete(format!(
989 "the archive is written, but {} entries changed, {} vanished and {} listed children \
990 were skipped during the walk; the manifest lists them",
991 findings.changed.len(),
992 findings.vanished.len(),
993 findings.skipped.len()
994 )))
995 }
996}
997
998#[cfg(test)]
999mod tests {
1000 use super::*;
1001
1002 #[test]
1003 fn entity_tags_are_read_as_quoted_digests() {
1004 let hex = "ab".repeat(32);
1005 let digest: Sha256Digest = hex.parse().expect("digest");
1006 assert_eq!(sha256_tag(&format!("\"{hex}\"")), Some(digest));
1007 assert_eq!(sha256_tag(&format!("W/\"{hex}\"")), Some(digest));
1008 assert_eq!(sha256_tag(&hex), None);
1009 assert_eq!(sha256_tag("\"abc\""), None);
1010 }
1011
1012 #[test]
1013 fn the_walk_stops_at_the_limits() {
1014 assert!(check_entry_limit(MAX_EXPORT_ENTRIES - 1).is_ok());
1015 let err = check_entry_limit(MAX_EXPORT_ENTRIES).expect_err("the 100,001st entry");
1016 assert!(err.to_string().contains("100000 entries"), "{err}");
1017 assert!(check_byte_limit(MAX_EXPORT_BYTES).is_ok());
1018 let err = check_byte_limit(MAX_EXPORT_BYTES + 1).expect_err("one byte over 64 GiB");
1019 assert!(err.to_string().contains("64 GiB"), "{err}");
1020 assert_eq!(err.exit_code(), exit::FAILURE);
1021 }
1022
1023 #[test]
1024 fn targets_sit_beside_the_archive() {
1025 let targets = Targets::new(Path::new("out/pod.tar.zst")).expect("targets");
1026 assert_eq!(targets.manifest, Path::new("out/pod.tar.zst.manifest.json"));
1027 assert_eq!(targets.directory, Path::new("out"));
1028 assert!(targets
1029 .archive_temp
1030 .to_string_lossy()
1031 .starts_with("out/.pod.tar.zst.partial-"));
1032 let bare = Targets::new(Path::new("pod.tar.zst")).expect("targets");
1033 assert_eq!(bare.directory, Path::new("."));
1034 }
1035 fn staged(archive: &[u8]) -> (tempfile::TempDir, Targets) {
1039 let dir = tempfile::tempdir().expect("tempdir");
1040 let targets = Targets::new(&dir.path().join("pod.tar.zst")).expect("targets");
1041 fs::write(&targets.archive_temp, archive).expect("archive");
1042 fs::write(&targets.manifest_temp, manifest_for(archive)).expect("manifest");
1043 (dir, targets)
1044 }
1045
1046 fn manifest_for(archive: &[u8]) -> Vec<u8> {
1048 json!({"archive": {"sha256": Sha256Digest::of(archive)}})
1049 .to_string()
1050 .into_bytes()
1051 }
1052
1053 fn pair_is_consistent(targets: &Targets) -> bool {
1055 let Ok(manifest) = fs::read(&targets.manifest) else {
1056 return true;
1057 };
1058 let Ok(archive) = fs::read(&targets.archive) else {
1059 return false;
1060 };
1061 let manifest: Json = serde_json::from_slice(&manifest).expect("manifest json");
1062 manifest["archive"]["sha256"] == json!(Sha256Digest::of(&archive))
1063 }
1064
1065 fn names(dir: &Path) -> Vec<String> {
1067 let mut names: Vec<String> = fs::read_dir(dir)
1068 .expect("read dir")
1069 .map(|entry| {
1070 entry
1071 .expect("entry")
1072 .file_name()
1073 .to_string_lossy()
1074 .into_owned()
1075 })
1076 .collect();
1077 names.sort();
1078 names
1079 }
1080
1081 #[test]
1082 fn an_archive_appearing_after_the_check_is_never_replaced() {
1083 let (_dir, targets) = staged(b"new");
1084 fs::write(&targets.archive, b"theirs").expect("theirs");
1085 let err = place(&targets, Existing::Keep).expect_err("refused");
1086 assert!(err.to_string().contains("already exists"), "{err}");
1087 assert_eq!(
1088 fs::read(&targets.archive).expect("archive"),
1089 b"theirs",
1090 "kept"
1091 );
1092 assert!(
1093 fs::metadata(&targets.manifest).is_err(),
1094 "no manifest beside it"
1095 );
1096 }
1097
1098 #[test]
1099 fn a_manifest_appearing_after_the_check_is_never_replaced() {
1100 let (_dir, targets) = staged(b"new");
1101 fs::write(&targets.manifest, b"theirs").expect("theirs");
1102 let err = place(&targets, Existing::Keep).expect_err("refused");
1103 assert!(err.to_string().contains("already exists"), "{err}");
1104 assert_eq!(
1105 fs::read(&targets.manifest).expect("manifest"),
1106 b"theirs",
1107 "kept"
1108 );
1109 assert!(
1110 fs::metadata(&targets.archive).is_err(),
1111 "the archive placed a moment earlier is withdrawn"
1112 );
1113 }
1114
1115 #[test]
1116 fn a_failed_manifest_step_never_leaves_a_new_archive_beside_an_old_manifest() {
1117 let (dir, targets) = staged(b"new");
1118 fs::write(&targets.archive, b"old").expect("old archive");
1119 fs::write(&targets.manifest, manifest_for(b"old")).expect("old manifest");
1120 fs::remove_file(&targets.manifest_temp).expect("make the manifest step fail");
1121 let err = place(&targets, Existing::Replace).expect_err("the manifest step fails");
1122 assert!(err.to_string().contains("no manifest"), "{err}");
1123 assert!(pair_is_consistent(&targets), "{:?}", names(dir.path()));
1124 let visible: Vec<String> = names(dir.path())
1125 .into_iter()
1126 .filter(|name| !name.starts_with('.'))
1127 .collect();
1128 assert_eq!(
1129 visible,
1130 ["pod.tar.zst"],
1131 "the archive alone, with no manifest"
1132 );
1133 }
1134
1135 #[test]
1136 fn a_failed_archive_step_keeps_the_old_pair() {
1137 let (dir, targets) = staged(b"new");
1138 fs::create_dir(&targets.archive).expect("dir");
1140 fs::write(targets.archive.join("x"), b"x").expect("x");
1141 fs::write(&targets.manifest, manifest_for(b"old")).expect("old manifest");
1142 let err = place(&targets, Existing::Replace).expect_err("the archive step fails");
1143 assert!(err.to_string().contains("moving the archive"), "{err}");
1144 assert_eq!(
1145 fs::read(&targets.manifest).expect("manifest"),
1146 manifest_for(b"old"),
1147 "the old manifest is back: {:?}",
1148 names(dir.path())
1149 );
1150 }
1151
1152 #[test]
1153 fn a_forced_export_replaces_the_pair() {
1154 let (dir, targets) = staged(b"new");
1155 fs::write(&targets.archive, b"old").expect("old archive");
1156 fs::write(&targets.manifest, manifest_for(b"old")).expect("old manifest");
1157 place(&targets, Existing::Replace).expect("placed");
1158 assert_eq!(fs::read(&targets.archive).expect("archive"), b"new", "new");
1159 assert!(pair_is_consistent(&targets), "the manifest describes it");
1160 assert_eq!(
1161 names(dir.path()),
1162 ["pod.tar.zst", "pod.tar.zst.manifest.json"],
1163 "nothing else is left"
1164 );
1165 }
1166}