mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-23 11:25:56 +00:00
Merge branch 'review/pr4' into release/0.6.0
This commit is contained in:
commit
beb3b03010
4 files changed
+75
-6
No files matched your search
@@ -341,9 +341,23 @@ pub struct SnapshotInfo {
|
||||
}
|
||||
|
||||
pub(crate) fn take_snapshot(meta_dir: &Path, scope: Scope, reason: &str, files: &[(PathBuf, Vec<u8>)]) -> Result<String> {
|
||||
let id = format!("{}-{}", chrono::Utc::now().format("%Y%m%d-%H%M%S%3f"), scope.name());
|
||||
let dir = snapshot_root(meta_dir).join(&id);
|
||||
fs::create_dir_all(&dir)?;
|
||||
let root = snapshot_root(meta_dir);
|
||||
fs::create_dir_all(&root)?;
|
||||
// The id is a timestamp to the millisecond. Two snapshots of the same scope can land in the same one (a restore
|
||||
// snapshots the current state just before reading the snapshot it restores), and reusing the folder would overwrite
|
||||
// the files about to be restored. Take a fresh folder, with a numeric suffix when the name is already used.
|
||||
let base = format!("{}-{}", chrono::Utc::now().format("%Y%m%d-%H%M%S%3f"), scope.name());
|
||||
let (id, dir) = (1u32..)
|
||||
.map(|n| if n == 1 { base.clone() } else { format!("{base}-{n}") })
|
||||
.find_map(|id| {
|
||||
let dir = root.join(&id);
|
||||
match fs::create_dir(&dir) {
|
||||
Ok(()) => Some(Ok((id, dir))),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => None,
|
||||
Err(e) => Some(Err(e)),
|
||||
}
|
||||
})
|
||||
.expect("the suffix range is unbounded")?;
|
||||
let mut entries = Vec::new();
|
||||
for (i, (path, bytes)) in files.iter().enumerate() {
|
||||
let stored = format!("{i}_{}", path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default());
|
||||
@@ -748,6 +762,21 @@ Spellbook.New = 5
|
||||
assert!(restore_snapshot(&meta, "../evil").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshots_taken_in_the_same_millisecond_keep_their_own_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
for i in 0..40 {
|
||||
let path = dir.path().join("worldserver.conf");
|
||||
let id = take_snapshot(dir.path(), Scope::Server, "test", &[(path, format!("version {i}").into_bytes())]).unwrap();
|
||||
assert!(ids.insert(id.clone()), "snapshot id {id} was handed out twice");
|
||||
}
|
||||
for info in list_snapshots(dir.path()) {
|
||||
assert_eq!(info.files.len(), 1);
|
||||
}
|
||||
assert_eq!(list_snapshots(dir.path()).len(), 40.min(KEEP_SNAPSHOTS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_repeated_key_with_the_same_effective_value_is_not_drift() {
|
||||
let (_d, root, _m) = fixture();
|
||||
|
||||
@@ -27,11 +27,14 @@ pub fn normalize_lexical(path: &Path) -> PathBuf {
|
||||
|
||||
fn key(path: &Path) -> Vec<String> {
|
||||
path.components()
|
||||
.map(|c| c.as_os_str().to_string_lossy().to_lowercase())
|
||||
.map(|c| {
|
||||
let c = c.as_os_str().to_string_lossy();
|
||||
if cfg!(windows) { c.to_lowercase() } else { c.into_owned() }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Case-insensitive component-wise prefix test (Windows semantics).
|
||||
/// Component-wise prefix test: case-insensitive on Windows, exact elsewhere (`/srv/CoA` and `/srv/coa` are two folders).
|
||||
pub fn starts_with_ci(path: &Path, prefix: &Path) -> bool {
|
||||
let (p, q) = (key(path), key(prefix));
|
||||
p.len() >= q.len() && p[..q.len()] == q[..]
|
||||
|
||||
@@ -298,11 +298,15 @@ pub fn extract(parts_dir: &Path, manifest: &Manifest, dest: &Path, progress: &dy
|
||||
let mut hasher = Sha256::new();
|
||||
let mut buf = vec![0u8; 1 << 20];
|
||||
let mut size = 0u64;
|
||||
let mut head = Vec::with_capacity(4);
|
||||
loop {
|
||||
let n = entry.read(&mut buf)?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
if head.len() < 4 {
|
||||
head.extend_from_slice(&buf[..n.min(4 - head.len())]);
|
||||
}
|
||||
size += n as u64;
|
||||
if size > want.size {
|
||||
return Err(Error::HashMismatch { path: rel, expected: format!("{} bytes", want.size), actual: "more".into() });
|
||||
@@ -315,6 +319,13 @@ pub fn extract(parts_dir: &Path, manifest: &Manifest, dest: &Path, progress: &dy
|
||||
if size != want.size || !actual.eq_ignore_ascii_case(&want.sha256) {
|
||||
return Err(Error::HashMismatch { path: rel, expected: want.sha256.clone(), actual });
|
||||
}
|
||||
// The archive does not carry per-file modes, so a Linux binary or script would be extracted unusable.
|
||||
// Recognise them by content (ELF header or `#!`); Windows has no execute bit and ignores this.
|
||||
#[cfg(unix)]
|
||||
if head.starts_with(b"\x7fELF") || head.starts_with(b"#!") {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::set_permissions(&target, fs::Permissions::from_mode(0o755))?;
|
||||
}
|
||||
done += size;
|
||||
progress(done, archive.unpacked_size);
|
||||
}
|
||||
@@ -373,6 +384,31 @@ mod tests {
|
||||
(d, src)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn extract_makes_binaries_and_scripts_executable_and_nothing_else() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let src = d.path().join("src");
|
||||
for (p, c) in [
|
||||
("Core/worldserver", &b"\x7fELF\x02\x01\x01 binary"[..]),
|
||||
("Scripts/tool.sh", &b"#!/bin/sh\necho hi\n"[..]),
|
||||
("Core/configs/worldserver.conf.dist", &b"Setting = 1\n"[..]),
|
||||
] {
|
||||
let f = src.join(p);
|
||||
fs::create_dir_all(f.parent().unwrap()).unwrap();
|
||||
fs::write(f, c).unwrap();
|
||||
}
|
||||
let out = d.path().join("out");
|
||||
let m = build(&src, &out, &opts(64 * 1024), &|_| {}).unwrap();
|
||||
let dest = d.path().join("dest");
|
||||
extract(&out, &m, &dest, &|_, _| {}).unwrap();
|
||||
let mode = |p: &str| fs::metadata(dest.join(p)).unwrap().permissions().mode() & 0o111;
|
||||
assert_ne!(mode("Core/worldserver"), 0, "ELF binary must be executable");
|
||||
assert_ne!(mode("Scripts/tool.sh"), 0, "script with a shebang must be executable");
|
||||
assert_eq!(mode("Core/configs/worldserver.conf.dist"), 0, "plain files stay non-executable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_split_extract_roundtrip_excludes_noise_and_secrets() {
|
||||
let (d, src) = source();
|
||||
|
||||
@@ -267,6 +267,7 @@ mod tests {
|
||||
fn drive_root_and_missing_folder_are_rejected() {
|
||||
let meta = InstallMeta::new(InstallKind::New, Path::new("C:/nope"));
|
||||
assert!(MetaDir::create(Path::new("C:/definitely/missing/folder"), &meta).is_err());
|
||||
assert!(metadata_dir_for(Path::new("C:/")).is_err());
|
||||
let root = if cfg!(windows) { "C:/" } else { "/" };
|
||||
assert!(metadata_dir_for(Path::new(root)).is_err());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user