//! M2 decisions 1–3. Blocking streaming; callers must serialize batches and run at most
//! two `download` calls at once. `run_batch` intentionally uses one worker.
use crate::{
Result,
net::Stream,
portal::{Release, mirror_url},
store,
};
use sha1::{Digest, Sha1};
use std::{
fs::{self, File, OpenOptions},
io::{Read, Write},
path::{Path, PathBuf},
sync::atomic::{AtomicBool, Ordering},
time::{Duration, Instant},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Progress {
pub bytes: u64,
pub total: Option<u64>,
/// Zero for the first attempt, then 1 and 2 for network retries.
pub retry: u8,
}
/// Only this module can construct one. Dropping it cleans up its own unfinished file.
#[derive(Debug)]
pub struct VerifiedTemp {
pub(crate) name: String,
pub(crate) release: Release,
pub(crate) path: PathBuf,
digest: String,
size: u64,
check_archive: bool,
}
impl VerifiedTemp {
pub fn path(&self) -> &Path {
&self.path
}
pub fn name(&self) -> &str {
&self.name
}
pub fn release(&self) -> &Release {
&self.release
}
}
impl Drop for VerifiedTemp {
fn drop(&mut self) {
// Decision 3: never delete a final zip, backup, folder or pre-existing temp.
let _ = fs::remove_file(&self.path);
}
}
pub(crate) fn safe_component(name: &str) -> Result<()> {
let reserved = name.split('.').next().unwrap_or("").to_ascii_uppercase();
if name.is_empty()
|| name == "."
|| name == ".."
|| name.ends_with(['.', ' '])
|| name
.chars()
.any(|c| c.is_control() || "<>:\"/\\|?*".contains(c))
|| matches!(reserved.as_str(), "CON" | "PRN" | "AUX" | "NUL")
|| ["COM", "LPT"].iter().any(|p| {
reserved
.strip_prefix(p)
.is_some_and(|s| s.len() == 1 && matches!(s.as_bytes()[0], b'1'..=b'9'))
})
{
return Err(format!("Unsafe Windows filename: {name:?}").into());
}
Ok(())
}
pub(crate) fn validate_release(name: &str, release: &Release) -> Result<()> {
validate_identity(name, release)?;
if release.sha1.len() != 40 || !release.sha1.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err("Missing or invalid portal sha1".into());
}
Ok(())
}
pub(crate) fn validate_identity(name: &str, release: &Release) -> Result<()> {
safe_component(name)?;
let parts: Vec<_> = release.version.split('.').collect();
if !(2..=3).contains(&parts.len())
|| parts
.iter()
.any(|p| p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit()))
{
return Err("Invalid release version".into());
}
Ok(())
}
pub(crate) fn ordinary(path: &Path) -> Result<fs::Metadata> {
let meta = fs::symlink_metadata(path)?;
#[cfg(windows)]
let reparse = {
use std::os::windows::fs::MetadataExt;
meta.file_attributes() & 0x400 != 0
};
#[cfg(not(windows))]
let reparse = false;
if meta.file_type().is_symlink() || reparse {
return Err(format!("Refusing a link/reparse point: {}", path.display()).into());
}
Ok(meta)
}
pub(crate) fn stopped(running: &dyn Fn() -> bool) -> Result<()> {
if running() {
return Err(store::RUNNING_MESSAGE.into());
}
Ok(())
}
pub fn download(
name: &str,
release: &Release,
mods_dir: &Path,
transport: &dyn Stream,
progress: &mut dyn FnMut(Progress),
cancel: &AtomicBool,
) -> Result<VerifiedTemp> {
download_with_check(
name,
release,
mods_dir,
transport,
progress,
cancel,
&store::is_factorio_running,
)
}
pub fn download_with_check(
name: &str,
release: &Release,
mods_dir: &Path,
transport: &dyn Stream,
progress: &mut dyn FnMut(Progress),
cancel: &AtomicBool,
running: &dyn Fn() -> bool,
) -> Result<VerifiedTemp> {
download_with_policy(
name,
release,
mods_dir,
transport,
progress,
cancel,
Checks {
sha1: true,
running,
},
)
}
pub struct Checks<'a> {
pub sha1: bool,
pub running: &'a dyn Fn() -> bool,
}
pub fn download_with_policy(
name: &str,
release: &Release,
mods_dir: &Path,
transport: &dyn Stream,
progress: &mut dyn FnMut(Progress),
cancel: &AtomicBool,
checks: Checks<'_>,
) -> Result<VerifiedTemp> {
let running = checks.running;
if checks.sha1 {
validate_release(name, release)?;
} else {
validate_identity(name, release)?;
}
if !ordinary(mods_dir)?.is_dir() {
return Err("Mods path is not a directory".into());
}
let path = mods_dir.join(format!("{name}_{}.zip.fmm-part", release.version));
let url = mirror_url(name, &release.version);
for retry in 0..=2 {
stopped(running)?;
check_cancel(cancel)?;
// Decision 3: create_new protects another download's temp; never truncate it.
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)?;
let mut temp = VerifiedTemp {
name: name.into(),
release: release.clone(),
path: path.clone(),
digest: String::new(),
size: 0,
check_archive: !checks.sha1,
};
let mut response = match transport.get(&url) {
Ok(response) => response,
Err(error) => {
drop(file);
remove_temp(&temp)?;
if retry == 2 || !error.retryable {
return Err(error.into());
}
continue;
}
};
if response.status != 200 {
return Err(if response.status == 404 {
"Not on the mirror yet (HTTP 404)".into()
} else {
format!("Mirror returned HTTP {}", response.status).into()
});
}
let mut hash = Sha1::new();
let mut bytes = 0;
let mut buffer = [0; 64 * 1024];
let mut next_running_check = Instant::now();
progress(Progress {
bytes,
total: response.total,
retry,
});
let read_error = loop {
check_cancel(cancel)?;
let count = match response.reader.read(&mut buffer) {
Ok(0) => {
break response.total.filter(|total| bytes != *total).map(|_| {
std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"Truncated download (Content-Length mismatch)",
)
});
}
Ok(count) => count,
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
Err(error) => break Some(error),
};
// tasklist is a process: bound probes while streaming the ignored temp file.
// The pre-download, sync and final-promotion checks always run afresh.
if Instant::now() >= next_running_check {
stopped(running)?;
next_running_check = Instant::now() + Duration::from_secs(1);
}
check_cancel(cancel)?;
file.write_all(&buffer[..count])?;
hash.update(&buffer[..count]);
bytes += count as u64;
progress(Progress {
bytes,
total: response.total,
retry,
});
};
drop(response);
if let Some(error) = read_error {
drop(file);
remove_temp(&temp)?;
if retry == 2 {
return Err(error.into());
}
continue;
}
check_cancel(cancel)?;
if release.file_size.is_some_and(|expected| expected != bytes) {
return Err("Incomplete download: portal file size mismatch".into());
}
temp.digest = format!("{:x}", hash.finalize());
temp.size = bytes;
if checks.sha1 && !temp.digest.eq_ignore_ascii_case(&release.sha1) {
return Err("sha1 mismatch: download rejected".into());
}
stopped(running)?;
file.sync_all()?;
drop(file);
if temp.check_archive {
verify_archive(&temp)?;
}
return Ok(temp);
}
unreachable!()
}
fn check_cancel(cancel: &AtomicBool) -> Result<()> {
if cancel.load(Ordering::Relaxed) {
return Err("Download cancelled".into());
}
Ok(())
}
// Decision 3: explicit removal on retry detects cleanup failures before reusing a name.
fn remove_temp(temp: &VerifiedTemp) -> Result<()> {
fs::remove_file(&temp.path)?;
Ok(())
}
pub(crate) fn verify(temp: &VerifiedTemp) -> Result<()> {
if !ordinary(&temp.path)?.is_file() {
return Err("Verified temp is not a file".into());
}
let mut file = File::open(&temp.path)?;
let mut hash = Sha1::new();
let mut buffer = [0; 64 * 1024];
loop {
let count = file.read(&mut buffer)?;
if count == 0 {
break;
}
hash.update(&buffer[..count]);
}
if !format!("{:x}", hash.finalize()).eq_ignore_ascii_case(&temp.digest)
|| file.metadata()?.len() != temp.size
{
return Err("Verified temp changed: sha1 mismatch".into());
}
if temp.check_archive {
verify_archive(temp)?;
}
Ok(())
}
fn verify_archive(temp: &VerifiedTemp) -> Result<()> {
let mut zip = zip::ZipArchive::new(File::open(&temp.path)?)?;
let expected = format!("{}_{}/info.json", temp.name, temp.release.version);
let mut found = false;
for index in 0..zip.len() {
let mut file = zip.by_index(index)?;
if file.name()? == expected {
if found {
return Err("Duplicate info.json in downloaded zip".into());
}
found = true;
let mut bytes = Vec::new();
(&mut file).take(1024 * 1024 + 1).read_to_end(&mut bytes)?;
if bytes.len() > 1024 * 1024 {
return Err("Downloaded info.json is too large".into());
}
let info: serde_json::Value = serde_json::from_slice(&bytes)?;
if info["name"].as_str() != Some(temp.name.as_str())
|| info["version"].as_str() != Some(temp.release.version.as_str())
{
return Err("Downloaded info.json name or version does not match".into());
}
} else {
std::io::copy(&mut file, &mut std::io::sink())?;
}
}
if !found {
return Err("Downloaded zip has no matching info.json".into());
}
Ok(())
}
/// Startup only, before any downloads start. Never follows links or descends folders.
pub fn clean_temp(mods_dir: &Path) -> Result<usize> {
ordinary(mods_dir)?;
let mut removed = 0;
for entry in fs::read_dir(mods_dir)? {
let entry = entry?;
if entry
.file_name()
.to_string_lossy()
.ends_with(".zip.fmm-part")
&& ordinary(&entry.path())?.is_file()
{
fs::remove_file(entry.path())?;
removed += 1;
}
}
Ok(removed)
}
/// Production cleanup keeps install containment and per-effect running checks on Linux and macOS.
pub fn clean_temp_for(paths: &crate::paths::FactorioPaths) -> Result<usize> {
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
clean_temp_checked(paths, &store::is_factorio_running)
}
#[cfg(windows)]
{
clean_temp(&paths.mods_dir)
}
#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
{
let _ = paths;
Err("Mod effects are unsupported on this platform".into())
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub fn clean_temp_checked(
paths: &crate::paths::FactorioPaths,
running: &dyn Fn() -> bool,
) -> Result<usize> {
if paths.mods_dir != paths.user_dir.join("mods") {
return Err("Invalid mods folder".into());
}
ordinary(&paths.user_dir)?;
ordinary(&paths.mods_dir)?;
if paths.install_dir.exists()
&& fs::canonicalize(&paths.mods_dir)?.starts_with(fs::canonicalize(&paths.install_dir)?)
{
return Err(
"Refusing writes inside the game install; select a separate data folder".into(),
);
}
let mut removed = 0;
for entry in fs::read_dir(&paths.mods_dir)? {
let entry = entry?;
if entry
.file_name()
.to_string_lossy()
.ends_with(".zip.fmm-part")
&& ordinary(&entry.path())?.is_file()
{
stopped(running)?;
fs::remove_file(entry.path())?;
removed += 1;
}
}
Ok(removed)
}