Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,3 +185,7 @@ The full text is in [LEGAL.md](LEGAL.md). The app shows it on first start and as
## License

GPL-3.0-or-later. See [LICENSE](LICENSE). Third-party components keep their own licenses.

### Save protection before build changes

Updates and rollbacks of managed game builds first make a verified checkpoint of the active save (including a configured shared saves folder). The backup appears in Favourites in the save picker. A failed backup stops the build change. No save is restored automatically and no checkpoint is deleted automatically. Standalone programs have unknown save layouts; back those up manually. Close any game running outside VILauncher before changing builds.
34 changes: 33 additions & 1 deletion src-tauri/src/launcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2372,6 +2372,9 @@ fn install(
updating: bool,
l: &mut Launch,
) -> Result<(), String> {
if updating {
backup_before_port_change(job, ctx, p, "update")?;
}
let ws = workspace();
std::fs::create_dir_all(ws.join("repos"))
.map_err(|e| format!("cannot make {}: {e}", ws.display()))?;
Expand Down Expand Up @@ -2601,9 +2604,38 @@ fn build_project(
Ok(())
}

/// Deletes `p`'s download and build (and its shader cache); its saves stay.
/// Protect the active managed save before an update or rollback.
fn backup_before_port_change(
job: &Arc<Mutex<Job>>,
ctx: &Ctx,
p: &Project,
operation: &str,
) -> Result<(), String> {
if p.runs_standalone() {
job.lock().unwrap().log.push(
"Standalone program: save location unknown; back up its saves manually.".into(),
);
return Ok(());
}
let data = project_data(&p.repo);
if shared_saves().is_some() && !data.is_dir() {
return Err("Save backup failed: the shared saves folder is unavailable.".into());
}
job.lock().unwrap().log.push("Checking active save before changing the build.".into());
ctx.request_repaint();
let line = match saves::before_change(&workspace(), &data, operation) {
Ok(Some(path)) => format!("Verified save checkpoint: {}", path.display()),
Ok(None) => "No active save files to back up.".into(),
Err(error) => return Err(format!("Stopped before changing build: save backup failed: {error}")),
};
job.lock().unwrap().log.push(line);
ctx.request_repaint();
Ok(())
}

/// Swaps the installed build with the previous one (the one before the last update).
fn rollback(job: &Arc<Mutex<Job>>, ctx: &Ctx, p: &Project) -> Result<(), String> {
backup_before_port_change(job, ctx, p, "rollback")?;
stage(job, ctx, msg_str!("Restoring the previous build"));
previous::swap(&previous_dir(&p.repo), &built_file(&p.repo))
}
Expand Down
148 changes: 148 additions & 0 deletions src-tauri/src/saves.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,10 +224,158 @@ pub fn checkpoint(root: &Path, name: &str, source: &Path) -> io::Result<PathBuf>
Ok(destination)
}

// Hash every file and include directories, rejecting links and reparse points.
// A backup is only published after the source and copy agree.
type SaveFingerprint = std::collections::BTreeMap<PathBuf, Option<[u8; 32]>>;

fn checked_metadata(path: &Path) -> io::Result<fs::Metadata> {
let metadata = fs::symlink_metadata(path)?;
#[cfg(windows)]
let redirected = {
use std::os::windows::fs::MetadataExt;
metadata.file_attributes() & 0x400 != 0
};
#[cfg(not(windows))]
let redirected = false;
if redirected || metadata.file_type().is_symlink() {
return Err(io::Error::new(ErrorKind::InvalidData, "Redirected save entry"));
}
Ok(metadata)
}

fn fingerprint(root: &Path) -> io::Result<SaveFingerprint> {
fn walk(root: &Path, dir: &Path, entries: &mut SaveFingerprint) -> io::Result<()> {
use std::io::Read;
if !checked_metadata(dir)?.is_dir() {
return Err(io::Error::new(ErrorKind::InvalidData, "Expected save directory"));
}
for entry in fs::read_dir(dir)? {
let path = entry?.path();
let relative = path.strip_prefix(root).map_err(io::Error::other)?.to_owned();
let metadata = checked_metadata(&path)?;
if metadata.is_dir() {
entries.insert(relative, None);
walk(root, &path, entries)?;
} else if metadata.is_file() {
let mut file = fs::File::open(&path)?;
let mut hash = ring::digest::Context::new(&ring::digest::SHA256);
let mut buffer = [0; 65536];
loop {
let n = file.read(&mut buffer)?;
if n == 0 {
break;
}
hash.update(&buffer[..n]);
}
let mut digest = [0; 32];
digest.copy_from_slice(hash.finish().as_ref());
entries.insert(relative, Some(digest));
} else {
return Err(io::Error::new(ErrorKind::InvalidData, "Unsupported save entry"));
}
}
Ok(())
}
let mut entries = SaveFingerprint::new();
walk(root, root, &mut entries)?;
Ok(entries)
}

/// Save a verified, independent checkpoint before replacing a build.
/// No active profile is changed; an incomplete copy never appears in Favourites.
pub fn before_change(
workspace: &Path,
project: &Path,
operation: &str,
) -> io::Result<Option<PathBuf>> {
let active = active_data(project)?;
let source = active.join(SAVE_PATH);
match fs::symlink_metadata(&source) {
Ok(_) => {}
Err(error) if error.kind() == ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error),
}
let project_real = project.canonicalize()?;
let active_real = active.canonicalize()?;
let source_real = source.canonicalize()?;
if active_real != project_real.join(active.strip_prefix(project).map_err(io::Error::other)?)
|| source_real != active_real.join(SAVE_PATH)
{
return Err(io::Error::new(ErrorKind::InvalidData, "Redirected active save folder"));
}
let before = fingerprint(&source)?;
if !before.values().any(Option::is_some) {
return Ok(None);
}
let root = workspace.join("checkpoints");
fs::create_dir_all(&root)?;
if root.canonicalize()? != workspace.canonicalize()?.join("checkpoints")
|| root.canonicalize()?.starts_with(&source_real)
{
return Err(io::Error::new(ErrorKind::InvalidInput, "Unsafe checkpoint destination"));
}
let id = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(io::Error::other)?
.as_nanos();
let pid = std::process::id();
let pending = root.join(format!(".pending-{pid}-{id}"));
let destination = root.join(format!("Checkpoint - Before {operation} {pid}-{id}"));
fs::create_dir(&pending)?;
let result = (|| {
copy_tree(&source, &pending)?;
if fingerprint(&pending)? != before || fingerprint(&source)? != before {
return Err(io::Error::new(ErrorKind::InvalidData, "Save changed during backup"));
}
if destination.try_exists()? {
return Err(io::Error::new(ErrorKind::AlreadyExists, "Checkpoint already exists"));
}
fs::rename(&pending, &destination)?;
Ok(Some(destination))
})();
if result.is_err() {
let _ = fs::remove_dir_all(&pending);
}
result
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn backup_preserves_active_profile_and_uses_shared_source() -> io::Result<()> {
let root = std::env::temp_dir().join(format!(
"vilauncher-backup-{}-{}",
std::process::id(),
SystemTime::now().duration_since(UNIX_EPOCH).map_err(io::Error::other)?.as_nanos()
));
fs::create_dir(&root)?;
let result = (|| {
let workspace = root.join("workspace");
let shared = root.join("shared");
fs::create_dir_all(&workspace)?;
assert!(before_change(&workspace, &shared, "update")?.is_none());
let active = prepare(&shared, &LaunchSave::Fresh)?;
let source = active.join(SAVE_PATH);
fs::create_dir_all(source.join("slot"))?;
fs::write(source.join("slot/data"), b"original")?;
let first = before_change(&workspace, &shared, "update")?.unwrap();
let second = before_change(&workspace, &shared, "rollback")?.unwrap();
assert_ne!(first, second);
assert_eq!(fingerprint(&first)?, fingerprint(&source)?);
assert_eq!(active_data(&shared)?, active);
fs::write(source.join("slot/data"), b"changed")?;
assert_eq!(fs::read(first.join("slot/data"))?, b"original");
fs::write(shared.join("active-save"), b"invalid")?;
assert!(before_change(&workspace, &shared, "update").is_err());
assert_eq!(fs::read_dir(workspace.join("checkpoints"))?.count(), 2);
Ok(())
})();
fs::remove_dir_all(root)?;
result
}

#[test]
fn deleting_a_checkpoint_preserves_its_contents_and_rejects_other_folders() -> io::Result<()> {
let root =
Expand Down