1use std::fs;
31use std::io;
32use std::path::{Component, Path, PathBuf};
33use std::process::Command;
34use std::time::{SystemTime, UNIX_EPOCH};
35
36use rucc_sysroot::{Kernel, KernelManifest, Manifest, Sysroot, sha256};
37use rucc_tuple::TargetTuple;
38
39use crate::{CliError, err};
40
41#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum Before {
44 Nothing,
46 TheSame,
50 Different(String),
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Installed {
58 pub root: PathBuf,
61 pub digest: String,
63 pub files: usize,
65 pub before: Before,
67}
68
69pub fn verify(archive: &Path, expected: &str) -> Result<(), CliError> {
82 let bytes = fs::read(archive).map_err(|why| err(format!("{}: {why}", archive.display())))?;
83 let found = sha256::hex(&bytes);
84 if found == expected {
85 return Ok(());
86 }
87 Err(err(format!(
88 "{} has sha256 {found} where this release pins {expected}, so it is not the artifact this \
89 build knows about",
90 archive.display()
91 )))
92}
93
94pub fn install(
107 archive: &Path,
108 expected: &str,
109 target: TargetTuple,
110 cache: &Path,
111) -> Result<Installed, CliError> {
112 verify(archive, expected)?;
113 staged(cache, &target.to_canonical_string(), |staging| {
114 install_staged(archive, target, cache, staging)
115 })
116}
117
118pub fn install_kernel(archive: &Path, expected: &str, cache: &Path) -> Result<Installed, CliError> {
130 verify(archive, expected)?;
131 staged(cache, "kernel-headers", |staging| install_kernel_staged(archive, cache, staging))
132}
133
134fn staged(
140 cache: &Path,
141 name: &str,
142 work: impl FnOnce(&Path) -> Result<Installed, CliError>,
143) -> Result<Installed, CliError> {
144 let staging = staging_dir(cache, name);
145 fs::create_dir_all(&staging).map_err(|why| err(format!("{}: {why}", staging.display())))?;
146 let outcome = work(&staging);
147 if outcome.is_err() {
148 let _ = fs::remove_dir_all(&staging);
149 }
150 outcome
151}
152
153fn record(archive: &Path, staging: &Path) -> Result<String, CliError> {
155 let record = staging.join("manifest");
156 fs::read_to_string(&record).map_err(|why| {
157 if why.kind() == io::ErrorKind::NotFound {
158 err(format!(
159 "{} has no manifest in it, so there is nothing to check its files against",
160 archive.display()
161 ))
162 } else {
163 err(format!("{}: {why}", record.display()))
164 }
165 })
166}
167
168fn install_staged(
170 archive: &Path,
171 target: TargetTuple,
172 cache: &Path,
173 staging: &Path,
174) -> Result<Installed, CliError> {
175 unpack(archive, staging)?;
176 let text = record(archive, staging)?;
177 let manifest =
178 Manifest::parse(&text).map_err(|why| err(format!("{}: {why}", archive.display())))?;
179
180 if manifest.target() != target {
181 return Err(err(format!(
182 "{} is a sysroot for {}, which is not {}",
183 archive.display(),
184 manifest.target().to_canonical_string(),
185 target.to_canonical_string()
186 )));
187 }
188
189 let recorded: Vec<(&str, &str)> = manifest
190 .inputs()
191 .iter()
192 .map(|input| (input.path.as_str(), input.sha256.as_str()))
193 .collect();
194 check(staging, &recorded).map_err(|why| err(format!("{}: {why}", archive.display())))?;
195
196 let digest = manifest.digest();
197 let root = Sysroot::in_cache(cache, target).root().to_path_buf();
198 let before = swap(staging, &root, &digest, existing(&root))?;
199 Ok(Installed { root, digest, files: recorded.len(), before })
200}
201
202fn install_kernel_staged(
205 archive: &Path,
206 cache: &Path,
207 staging: &Path,
208) -> Result<Installed, CliError> {
209 unpack(archive, staging)?;
210 let text = record(archive, staging)?;
211 let manifest =
212 KernelManifest::parse(&text).map_err(|why| err(format!("{}: {why}", archive.display())))?;
213
214 let recorded: Vec<(&str, &str)> =
215 manifest.files().iter().map(|file| (file.path.as_str(), file.sha256.as_str())).collect();
216 check(staging, &recorded).map_err(|why| err(format!("{}: {why}", archive.display())))?;
217
218 let digest = manifest.digest();
219 let root = Kernel::in_cache(cache);
220 let before = swap(staging, &root, &digest, existing_kernel(&root))?;
221 Ok(Installed { root, digest, files: recorded.len(), before })
222}
223
224fn staging_dir(cache: &Path, name: &str) -> PathBuf {
231 let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
232 let unique = format!("{name}-{}-{}", std::process::id(), now.as_nanos());
233 cache.join("staging").join(unique)
234}
235
236fn unpack(archive: &Path, into: &Path) -> Result<(), CliError> {
244 let output =
245 Command::new("tar").arg("-xzf").arg(archive).arg("-C").arg(into).output().map_err(
246 |why| err(format!("could not run `tar`, which is how an artifact is unpacked: {why}")),
247 )?;
248 if output.status.success() {
249 return Ok(());
250 }
251 let said = String::from_utf8_lossy(&output.stderr);
252 let said = said.trim();
253 let detail = if said.is_empty() { String::new() } else { format!(": {said}") };
254 Err(err(format!("`tar` could not unpack {}{detail}", archive.display())))
255}
256
257fn check(tree: &Path, files: &[(&str, &str)]) -> Result<(), String> {
267 let mut problems: Vec<String> = Vec::new();
268 let mut recorded: Vec<&str> = Vec::new();
269
270 for &(path, sha256) in files {
271 recorded.push(path);
272 let at = match relative(tree, path) {
273 Ok(at) => at,
274 Err(why) => {
275 problems.push(why);
276 continue;
277 }
278 };
279 match fs::read(&at) {
280 Ok(bytes) => {
281 let found = sha256::hex(&bytes);
282 if found != sha256 {
283 problems
284 .push(format!("{path} has sha256 {found} where the record says {sha256}"));
285 }
286 }
287 Err(why) if why.kind() == io::ErrorKind::NotFound => {
288 problems.push(format!("{path} is in the record and not in the archive"));
289 }
290 Err(why) => problems.push(format!("{path}: {why}")),
291 }
292 }
293
294 let mut found = Vec::new();
295 walk(tree, String::new(), &mut found).map_err(|why| format!("{}: {why}", tree.display()))?;
296 recorded.sort_unstable();
297 for path in &found {
298 if path == "manifest" {
301 continue;
302 }
303 if recorded.binary_search(&path.as_str()).is_err() {
304 problems.push(format!("{path} is in the archive and not in the record"));
305 }
306 }
307
308 if problems.is_empty() {
309 return Ok(());
310 }
311 problems.sort();
312 let first = &problems[0];
313 if problems.len() == 1 {
314 return Err(format!("the archive does not match its own manifest: {first}"));
315 }
316 Err(format!(
317 "the archive does not match its own manifest: {first}, and {} more files disagree",
318 problems.len() - 1
319 ))
320}
321
322fn relative(tree: &Path, path: &str) -> Result<PathBuf, String> {
328 let candidate = Path::new(path);
329 let ordinary = candidate.components().all(|part| matches!(part, Component::Normal(_)));
330 if !ordinary {
331 return Err(format!("{path} is not a path inside a sysroot"));
332 }
333 Ok(tree.join(candidate))
334}
335
336fn walk(dir: &Path, prefix: String, out: &mut Vec<String>) -> io::Result<()> {
343 for entry in fs::read_dir(dir)? {
344 let entry = entry?;
345 let name = entry.file_name().to_string_lossy().into_owned();
346 let path = if prefix.is_empty() { name } else { format!("{prefix}/{name}") };
347 if entry.file_type()?.is_dir() {
348 walk(&entry.path(), path, out)?;
349 } else {
350 out.push(path);
351 }
352 }
353 Ok(())
354}
355
356fn swap(
367 staging: &Path,
368 root: &Path,
369 digest: &str,
370 there: Option<String>,
371) -> Result<Before, CliError> {
372 let before = match there {
373 Some(found) if found == digest => {
374 let _ = fs::remove_dir_all(staging);
375 return Ok(Before::TheSame);
376 }
377 Some(found) => Before::Different(found),
378 None => Before::Nothing,
379 };
380
381 if let Some(parent) = root.parent() {
382 fs::create_dir_all(parent).map_err(|why| err(format!("{}: {why}", parent.display())))?;
383 }
384
385 let aside = root.with_extension(format!("old.{}", std::process::id()));
389 if before != Before::Nothing {
390 let _ = fs::remove_dir_all(&aside);
391 fs::rename(root, &aside)
392 .map_err(|why| err(format!("could not move {} aside: {why}", root.display())))?;
393 }
394 let renamed = fs::rename(staging, root);
395 if let Err(why) = renamed {
396 if before != Before::Nothing {
399 let _ = fs::rename(&aside, root);
400 }
401 return Err(err(format!("could not put {} in place: {why}", root.display())));
402 }
403 if before != Before::Nothing {
404 let _ = fs::remove_dir_all(&aside);
405 }
406 Ok(before)
407}
408
409fn existing(root: &Path) -> Option<String> {
415 let text = fs::read_to_string(root.join("manifest")).ok()?;
416 Manifest::parse(&text).ok().map(|manifest| manifest.digest())
417}
418
419fn existing_kernel(root: &Path) -> Option<String> {
421 let text = fs::read_to_string(root.join("manifest")).ok()?;
422 KernelManifest::parse(&text).ok().map(|manifest| manifest.digest())
423}
424
425#[cfg(test)]
426mod tests {
427 use super::{Before, Installed, check, install, install_kernel, relative, verify, walk};
428 use rucc_sysroot::{Input, KernelFile, KernelManifest, Licence, Manifest, Provenance, sha256};
429 use rucc_tuple::{TargetTuple, Version};
430 use std::path::{Path, PathBuf};
431 use std::process::Command;
432
433 struct Tree(PathBuf);
435
436 impl Drop for Tree {
437 fn drop(&mut self) {
438 let _ = std::fs::remove_dir_all(&self.0);
439 }
440 }
441
442 impl Tree {
443 fn new(name: &str) -> Tree {
444 let dir =
445 std::env::temp_dir().join(format!("rucc-install-{}-{name}", std::process::id()));
446 let _ = std::fs::remove_dir_all(&dir);
447 std::fs::create_dir_all(&dir).expect("a temporary directory should be writable");
448 Tree(dir)
449 }
450
451 fn write(&self, path: &str, text: &str) {
452 let at = self.0.join(path);
453 if let Some(parent) = at.parent() {
454 std::fs::create_dir_all(parent).expect("a subdirectory should be creatable");
455 }
456 std::fs::write(&at, text).expect("a temporary file should be writable");
457 }
458 }
459
460 fn target() -> TargetTuple {
462 "x86_64-linux-musl".parse().expect("a tuple the table knows")
463 }
464
465 fn manifest_for(files: &[(&str, &str)]) -> Manifest {
467 let mut manifest = Manifest::new(target());
468 for (path, text) in files {
469 manifest.push(Input {
470 path: (*path).to_owned(),
471 source: "musl-1.2.5".to_owned(),
472 url: "https://musl.libc.org/releases/musl-1.2.5.tar.gz".to_owned(),
473 sha256: sha256::hex(text.as_bytes()),
474 licence: Licence::Mit,
475 provenance: Provenance::Bundled,
476 });
477 }
478 manifest
479 }
480
481 fn artifact(tree: &Tree, files: &[(&str, &str)], manifest: &Manifest) -> (PathBuf, String) {
486 artifact_with(tree, files, &manifest.render())
487 }
488
489 fn artifact_with(tree: &Tree, files: &[(&str, &str)], record: &str) -> (PathBuf, String) {
491 let staged = tree.0.join("staged");
492 std::fs::create_dir_all(&staged).expect("a staging directory should be creatable");
493 for (path, text) in files {
494 let at = staged.join(path);
495 if let Some(parent) = at.parent() {
496 std::fs::create_dir_all(parent).expect("a subdirectory should be creatable");
497 }
498 std::fs::write(&at, text).expect("a file should be writable");
499 }
500 std::fs::write(staged.join("manifest"), record).expect("the manifest should be writable");
501
502 let archive = tree.0.join("artifact.tar.gz");
503 let status = Command::new("tar")
504 .arg("-czf")
505 .arg(&archive)
506 .arg("-C")
507 .arg(&staged)
508 .arg(".")
509 .status()
510 .expect("tar should be on a machine that runs these tests");
511 assert!(status.success(), "tar should be able to write an archive");
512 std::fs::remove_dir_all(&staged).expect("the staged tree should be removable");
513
514 let bytes = std::fs::read(&archive).expect("the archive should be readable");
515 let hash = sha256::hex(&bytes);
516 (archive, hash)
517 }
518
519 const FILES: &[(&str, &str)] =
520 &[("include/stdio.h", "int puts(const char *);\n"), ("lib/libc.so", "not really\n")];
521
522 #[test]
523 fn an_artifact_that_matches_its_record_is_installed() {
524 let tree = Tree::new("good");
525 let manifest = manifest_for(FILES);
526 let (archive, hash) = artifact(&tree, FILES, &manifest);
527 let cache = tree.0.join("cache");
528
529 let done = install(&archive, &hash, target(), &cache).expect("this one should install");
530 assert_eq!(done.before, Before::Nothing);
531 assert_eq!(done.files, 2);
532 assert_eq!(done.digest, manifest.digest());
533 assert_eq!(done.root, cache.join("sysroots").join("x86_64-linux-musl"));
534
535 assert!(done.root.join("include/stdio.h").is_file());
538 assert_eq!(
539 std::fs::read_to_string(done.root.join("manifest")).expect("a manifest"),
540 manifest.render()
541 );
542 let left: Vec<PathBuf> = std::fs::read_dir(cache.join("staging"))
545 .expect("the staging directory")
546 .map(|entry| entry.expect("an entry").path())
547 .collect();
548 assert_eq!(left, Vec::<PathBuf>::new(), "a staging tree was left behind");
549 }
550
551 #[test]
562 fn a_fetch_of_an_artifact_that_is_already_on_the_machine_installs_it() {
563 let tree = Tree::new("fetch");
564 let manifest = manifest_for(FILES);
565 let (built, hash) = artifact(&tree, FILES, &manifest);
566 let cache = tree.0.join("cache");
567
568 let pinned = rucc_sysroot::Pinned {
572 tuple: "x86_64-linux-musl",
573 url: "https://example.invalid/rucc-sysroot-x86_64-linux-musl.tar.gz",
574 sha256: String::leak(hash),
575 };
576 let at = pinned.archive_in(&cache);
578 std::fs::create_dir_all(at.parent().expect("a parent")).expect("a downloads directory");
579 std::fs::copy(&built, &at).expect("the artifact should be placeable");
580
581 let kernel_manifest = kernel_manifest_for(KERNEL_FILES);
583 let (built, hash) = artifact_with(&tree, KERNEL_FILES, &kernel_manifest.render());
584 let kernel = rucc_sysroot::Pinned {
585 tuple: "kernel-headers",
586 url: "https://example.invalid/rucc-kernel-headers.tar.gz",
587 sha256: String::leak(hash),
588 };
589 let at = kernel.archive_in(&cache);
590 std::fs::create_dir_all(at.parent().expect("a parent")).expect("a downloads directory");
591 std::fs::copy(&built, &at).expect("the artifact should be placeable");
592
593 assert_eq!(crate::fetch_sysroot(&pinned, Some(&kernel), target(), &cache), 0);
594 let root = cache.join("sysroots").join("x86_64-linux-musl");
595 assert!(root.join("include/stdio.h").is_file());
596 assert_eq!(
597 std::fs::read_to_string(root.join("manifest")).expect("a manifest"),
598 manifest.render()
599 );
600 assert!(cache.join("kernel-headers/x86/asm/unistd.h").is_file());
601 assert_eq!(crate::fetch_sysroot(&pinned, Some(&kernel), target(), &cache), 0);
604 assert_eq!(crate::fetch_sysroot(&pinned, None, target(), &cache), 0);
606 }
607
608 #[test]
609 fn the_same_artifact_twice_does_not_move_anything() {
610 let tree = Tree::new("again");
611 let manifest = manifest_for(FILES);
612 let (archive, hash) = artifact(&tree, FILES, &manifest);
613 let cache = tree.0.join("cache");
614
615 let first = install(&archive, &hash, target(), &cache).expect("the first install");
616 let second = install(&archive, &hash, target(), &cache).expect("the second install");
617 assert_eq!(second.before, Before::TheSame);
618 assert_eq!(second.root, first.root);
619 assert_eq!(second.digest, first.digest);
620 }
621
622 #[test]
623 fn a_hash_that_does_not_match_is_refused_before_anything_is_unpacked() {
624 let tree = Tree::new("hash");
625 let manifest = manifest_for(FILES);
626 let (archive, _) = artifact(&tree, FILES, &manifest);
627 let cache = tree.0.join("cache");
628
629 let wrong = "0".repeat(64);
630 let why =
631 install(&archive, &wrong, target(), &cache).expect_err("this is not the artifact");
632 assert!(why.message.contains("where this release pins"), "{}", why.message);
633 assert!(!cache.exists(), "a refused artifact should not have reached the cache");
636 }
637
638 #[test]
639 fn an_artifact_for_another_target_is_refused() {
640 let tree = Tree::new("target");
641 let mut manifest = Manifest::new("aarch64-linux-musl".parse().expect("a tuple"));
642 for (path, text) in FILES {
643 manifest.push(Input {
644 path: (*path).to_owned(),
645 source: "musl-1.2.5".to_owned(),
646 url: "https://musl.libc.org/releases/musl-1.2.5.tar.gz".to_owned(),
647 sha256: sha256::hex(text.as_bytes()),
648 licence: Licence::Mit,
649 provenance: Provenance::Bundled,
650 });
651 }
652 let (archive, hash) = artifact(&tree, FILES, &manifest);
653 let cache = tree.0.join("cache");
654
655 let why = install(&archive, &hash, target(), &cache).expect_err("the wrong target");
656 assert!(why.message.contains("aarch64-linux-musl"), "{}", why.message);
657 assert!(why.message.contains("x86_64-linux-musl"), "{}", why.message);
658 assert!(!cache.join("sysroots").exists(), "nothing should have been installed");
659 }
660
661 #[test]
662 fn an_archive_with_no_record_in_it_is_refused() {
663 let tree = Tree::new("bare");
664 let staged = tree.0.join("staged");
665 std::fs::create_dir_all(&staged).expect("a directory");
666 std::fs::write(staged.join("include.h"), "int x;\n").expect("a file");
667 let archive = tree.0.join("bare.tar.gz");
668 let status = Command::new("tar")
669 .arg("-czf")
670 .arg(&archive)
671 .arg("-C")
672 .arg(&staged)
673 .arg(".")
674 .status()
675 .expect("tar should run");
676 assert!(status.success());
677 let hash = sha256::hex(&std::fs::read(&archive).expect("readable"));
678 let cache = tree.0.join("cache");
679
680 let why = install(&archive, &hash, target(), &cache).expect_err("no manifest");
681 assert!(why.message.contains("has no manifest in it"), "{}", why.message);
682 }
683
684 #[test]
685 fn a_file_the_record_does_not_name_is_refused() {
686 let tree = Tree::new("extra");
689 let manifest = manifest_for(FILES);
690 let mut with_extra: Vec<(&str, &str)> = FILES.to_vec();
691 with_extra.push(("lib/surprise.o", "nobody wrote this down\n"));
692 let (archive, hash) = artifact(&tree, &with_extra, &manifest);
693 let cache = tree.0.join("cache");
694
695 let why = install(&archive, &hash, target(), &cache).expect_err("an unrecorded file");
696 assert!(why.message.contains("lib/surprise.o"), "{}", why.message);
697 assert!(why.message.contains("not in the record"), "{}", why.message);
698 }
699
700 #[test]
701 fn a_file_whose_bytes_changed_is_refused_and_so_is_one_that_is_missing() {
702 let tree = Tree::new("bytes");
703 let manifest = manifest_for(&[("include/stdio.h", "what the record says\n")]);
706 let (archive, hash) = artifact(&tree, &[("include/stdio.h", "what is there\n")], &manifest);
707 let cache = tree.0.join("cache");
708 let why = install(&archive, &hash, target(), &cache).expect_err("changed bytes");
709 assert!(why.message.contains("include/stdio.h has sha256"), "{}", why.message);
710 assert!(why.message.contains("where the record says"), "{}", why.message);
711
712 let gone = Tree::new("gone");
713 let manifest = manifest_for(FILES);
714 let (archive, hash) = artifact(&gone, &FILES[..1], &manifest);
715 let cache = gone.0.join("cache");
716 let why = install(&archive, &hash, target(), &cache).expect_err("a missing file");
717 assert!(why.message.contains("lib/libc.so"), "{}", why.message);
718 assert!(why.message.contains("not in the archive"), "{}", why.message);
719 }
720
721 #[test]
722 fn more_than_one_disagreement_says_how_many() {
723 let tree = Tree::new("count");
725 let manifest = manifest_for(&[("a.h", "one\n"), ("b.h", "two\n"), ("c.h", "three\n")]);
726 let (archive, hash) = artifact(
727 &tree,
728 &[("a.h", "not one\n"), ("b.h", "not two\n"), ("c.h", "three\n")],
729 &manifest,
730 );
731 let cache = tree.0.join("cache");
732
733 let why = install(&archive, &hash, target(), &cache).expect_err("two files disagree");
734 assert!(why.message.contains("and 1 more files disagree"), "{}", why.message);
735 }
736
737 #[test]
738 fn an_install_over_a_different_sysroot_says_what_it_replaced() {
739 let tree = Tree::new("replace");
740 let cache = tree.0.join("cache");
741 let first = manifest_for(&[("include/stdio.h", "the old one\n")]);
742 let (archive, hash) = artifact(&tree, &[("include/stdio.h", "the old one\n")], &first);
743 let done = install(&archive, &hash, target(), &cache).expect("the first install");
744 let was = done.digest.clone();
745
746 let second = Tree::new("replace-second");
747 let manifest = manifest_for(&[("include/stdio.h", "the new one\n")]);
748 let (archive, hash) = artifact(&second, &[("include/stdio.h", "the new one\n")], &manifest);
749 let done = install(&archive, &hash, target(), &cache).expect("the second install");
750
751 assert_eq!(done.before, Before::Different(was));
752 assert_eq!(
753 std::fs::read_to_string(done.root.join("include/stdio.h")).expect("the new file"),
754 "the new one\n"
755 );
756 let kept: Vec<String> = std::fs::read_dir(cache.join("sysroots"))
759 .expect("the sysroots directory")
760 .map(|entry| entry.expect("an entry").file_name().to_string_lossy().into_owned())
761 .collect();
762 assert_eq!(kept, vec!["x86_64-linux-musl".to_owned()]);
763 }
764
765 fn kernel_manifest_for(files: &[(&str, &str)]) -> KernelManifest {
767 let mut manifest = KernelManifest::new(Version::new(6, 19));
768 for (path, text) in files {
769 manifest.push(KernelFile {
770 path: (*path).to_owned(),
771 source: "linux-6.19".to_owned(),
772 sha256: sha256::hex(text.as_bytes()),
773 licence: Licence::LinuxUapi,
774 });
775 }
776 manifest
777 }
778
779 const KERNEL_FILES: &[(&str, &str)] = &[
780 ("generic/linux/types.h", "#define _LINUX_TYPES_H\n"),
781 ("x86/asm/unistd.h", "#define __NR_read 0\n"),
782 ];
783
784 #[test]
785 fn the_kernel_tree_is_installed_beside_the_sysroots_and_not_under_them() {
786 let tree = Tree::new("kernel");
787 let manifest = kernel_manifest_for(KERNEL_FILES);
788 let (archive, hash) = artifact_with(&tree, KERNEL_FILES, &manifest.render());
789 let cache = tree.0.join("cache");
790
791 let done = install_kernel(&archive, &hash, &cache).expect("this one should install");
792 assert_eq!(done.root, cache.join("kernel-headers"));
793 assert_eq!(done.files, 2);
794 assert_eq!(done.digest, manifest.digest());
795 assert_eq!(done.before, Before::Nothing);
796 let x86 = rucc_sysroot::Kernel::for_target(&cache, target()).expect("a Linux target");
798 assert!(x86.arch_include().join("asm/unistd.h").is_file());
799 assert!(x86.generic_include().join("linux/types.h").is_file());
800
801 let again = install_kernel(&archive, &hash, &cache).expect("the second install");
802 assert_eq!(again.before, Before::TheSame);
803 }
804
805 #[test]
806 fn a_sysroot_is_not_a_kernel_tree_and_a_kernel_tree_is_not_a_sysroot() {
807 let tree = Tree::new("crossed");
811 let sysroot = manifest_for(FILES);
812 let (archive, hash) = artifact(&tree, FILES, &sysroot);
813 let cache = tree.0.join("cache");
814 let why = install_kernel(&archive, &hash, &cache).expect_err("a sysroot");
815 assert!(why.message.contains("kernel tree's record"), "{}", why.message);
816 assert!(!cache.join("kernel-headers").exists());
817
818 let other = Tree::new("crossed-kernel");
819 let kernel = kernel_manifest_for(KERNEL_FILES);
820 let (archive, hash) = artifact_with(&other, KERNEL_FILES, &kernel.render());
821 let cache = other.0.join("cache");
822 install(&archive, &hash, target(), &cache).expect_err("a kernel tree");
823 assert!(!cache.join("sysroots").exists());
824 }
825
826 #[test]
827 fn a_kernel_tree_with_a_file_its_record_does_not_name_is_refused() {
828 let tree = Tree::new("kernel-extra");
829 let manifest = kernel_manifest_for(KERNEL_FILES);
830 let mut with_extra: Vec<(&str, &str)> = KERNEL_FILES.to_vec();
831 with_extra.push(("arm64/asm/surprise.h", "nobody wrote this down\n"));
832 let (archive, hash) = artifact_with(&tree, &with_extra, &manifest.render());
833 let cache = tree.0.join("cache");
834 let why = install_kernel(&archive, &hash, &cache).expect_err("an unrecorded file");
835 assert!(why.message.contains("arm64/asm/surprise.h"), "{}", why.message);
836 }
837
838 #[test]
839 fn a_record_that_names_a_path_outside_the_tree_is_refused() {
840 assert!(relative(Path::new("/cache/sysroots/t"), "include/stdio.h").is_ok());
843 for path in ["../outside.h", "/etc/passwd", "include/../../outside.h"] {
844 let why = relative(Path::new("/cache/sysroots/t"), path)
845 .expect_err("this is not a path inside a sysroot");
846 assert!(why.contains(path), "{why}");
847 }
848 }
849
850 #[test]
851 fn the_walk_names_files_the_way_a_manifest_does() {
852 let tree = Tree::new("walk");
855 tree.write("include/sys/types.h", "typedef int t;\n");
856 tree.write("manifest", "rucc sysroot manifest 3\n");
857 let mut found = Vec::new();
858 walk(&tree.0, String::new(), &mut found).expect("the walk should work");
859 found.sort();
860 assert_eq!(found, vec!["include/sys/types.h".to_owned(), "manifest".to_owned()]);
861 }
862
863 #[test]
864 fn verify_is_the_hash_of_the_file_and_says_both_when_it_is_not() {
865 let tree = Tree::new("verify");
866 tree.write("thing", "bytes\n");
867 let at = tree.0.join("thing");
868 let hash = sha256::hex(b"bytes\n");
869 assert!(verify(&at, &hash).is_ok());
870 let why = verify(&at, &"f".repeat(64)).expect_err("a mismatch");
871 assert!(why.message.contains(&hash), "{}", why.message);
872 assert!(why.message.contains(&"f".repeat(64)), "{}", why.message);
873
874 let why = verify(&tree.0.join("absent"), &hash).expect_err("nothing to hash");
876 assert!(!why.message.contains("where this release pins"), "{}", why.message);
877 }
878
879 #[test]
880 fn the_check_passes_a_tree_that_matches() {
881 let tree = Tree::new("check");
883 for (path, text) in FILES {
884 tree.write(path, text);
885 }
886 tree.write("manifest", "rucc sysroot manifest 3\n");
887 let manifest = manifest_for(FILES);
888 let recorded: Vec<(&str, &str)> =
889 manifest.inputs().iter().map(|i| (i.path.as_str(), i.sha256.as_str())).collect();
890 assert_eq!(check(&tree.0, &recorded), Ok(()));
891 std::fs::create_dir_all(tree.0.join("lib/empty")).expect("a directory");
894 assert_eq!(check(&tree.0, &recorded), Ok(()));
895 }
896
897 #[test]
898 fn installed_says_where_and_what() {
899 let made = Installed {
902 root: PathBuf::from("/cache/sysroots/x86_64-linux-musl"),
903 digest: "0".repeat(64),
904 files: 3,
905 before: Before::Nothing,
906 };
907 assert_eq!(made.files, 3);
908 assert_eq!(made.before, Before::Nothing);
909 }
910}