fix: make filesystem writes and downloads cancellation-safe
This commit is contained in:
1 parent
615d3fb8fc
commit
7362354109
18 files changed
+427
-291
No files matched your search
+2
-2
@@ -14,7 +14,7 @@ pub use settings::Config;
|
||||
|
||||
#[must_use]
|
||||
pub fn get_config_path() -> PathBuf {
|
||||
dirs_next::config_dir()
|
||||
dirs::config_dir()
|
||||
.unwrap_or_else(|| PathBuf::from("."))
|
||||
.join("rmcl")
|
||||
}
|
||||
@@ -86,7 +86,7 @@ pub(crate) fn upgrade_config_file(path: &std::path::Path) -> io::Result<bool> {
|
||||
}
|
||||
|
||||
pub(crate) fn migrate_legacy_data_paths(path: &std::path::Path) -> io::Result<bool> {
|
||||
let Some(data_dir) = dirs_next::data_dir() else {
|
||||
let Some(data_dir) = dirs::data_dir() else {
|
||||
return Ok(false);
|
||||
};
|
||||
migrate_legacy_data_paths_from(path, &data_dir)
|
||||
|
||||
@@ -212,7 +212,7 @@ pub struct Paths {
|
||||
}
|
||||
|
||||
fn default_instances_dir() -> String {
|
||||
dirs_next::data_dir()
|
||||
dirs::data_dir()
|
||||
.unwrap_or_else(|| PathBuf::from("."))
|
||||
.join("rmcl")
|
||||
.join("instances")
|
||||
@@ -225,7 +225,7 @@ fn is_default_instances_dir(path: &str) -> bool {
|
||||
}
|
||||
|
||||
fn default_meta_dir() -> String {
|
||||
dirs_next::data_dir()
|
||||
dirs::data_dir()
|
||||
.unwrap_or_else(|| PathBuf::from("."))
|
||||
.join("rmcl")
|
||||
.join("meta")
|
||||
@@ -249,11 +249,11 @@ impl Default for Paths {
|
||||
|
||||
pub fn resolve_path(raw: &str) -> PathBuf {
|
||||
if let Some(stripped) = raw.strip_prefix("~/") {
|
||||
if let Some(home) = dirs_next::home_dir() {
|
||||
if let Some(home) = dirs::home_dir() {
|
||||
return home.join(stripped);
|
||||
}
|
||||
} else if raw == "~"
|
||||
&& let Some(home) = dirs_next::home_dir()
|
||||
&& let Some(home) = dirs::home_dir()
|
||||
{
|
||||
return home;
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ pub fn desktop_path(name: &str) -> Option<PathBuf> {
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
dirs_next::data_dir().map(|d| {
|
||||
dirs::data_dir().map(|d| {
|
||||
d.join("applications")
|
||||
.join(format!("rmcl-{sanitized}.desktop"))
|
||||
})
|
||||
@@ -36,7 +36,7 @@ pub fn desktop_path(name: &str) -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
pub fn icon_path() -> Option<PathBuf> {
|
||||
dirs_next::data_dir().map(|d| d.join("rmcl").join("icon.svg"))
|
||||
dirs::data_dir().map(|d| d.join("rmcl").join("icon.svg"))
|
||||
}
|
||||
|
||||
fn ensure_icon() -> Option<PathBuf> {
|
||||
|
||||
@@ -149,7 +149,7 @@ fn java_roots() -> Vec<PathBuf> {
|
||||
roots.push(PathBuf::from(prefix).join(formula));
|
||||
}
|
||||
}
|
||||
if let Some(home) = dirs_next::home_dir() {
|
||||
if let Some(home) = dirs::home_dir() {
|
||||
roots.push(home.join("Library/Java/JavaVirtualMachines"));
|
||||
roots.push(home.join(".sdkman/candidates/java"));
|
||||
roots.push(home.join(".asdf/installs/java"));
|
||||
@@ -162,7 +162,7 @@ fn java_roots() -> Vec<PathBuf> {
|
||||
PathBuf::from("/opt/java"),
|
||||
PathBuf::from("/opt/jdk"),
|
||||
]);
|
||||
if let Some(home) = dirs_next::home_dir() {
|
||||
if let Some(home) = dirs::home_dir() {
|
||||
roots.push(home.join(".sdkman/candidates/java"));
|
||||
roots.push(home.join(".jdks"));
|
||||
roots.push(home.join(".asdf/installs/java"));
|
||||
|
||||
+30
-7
@@ -628,7 +628,6 @@ impl InstanceManager {
|
||||
}
|
||||
}
|
||||
|
||||
// guard against path traversal and other filesystem shenanigans
|
||||
pub(crate) fn validate_name(name: &str) -> Result<(), InstanceError> {
|
||||
if name.is_empty() || name.len() > 64 {
|
||||
return Err(InstanceError::InvalidName(format!(
|
||||
@@ -636,19 +635,43 @@ pub(crate) fn validate_name(name: &str) -> Result<(), InstanceError> {
|
||||
name
|
||||
)));
|
||||
}
|
||||
if name.contains('/')
|
||||
|| name.contains('\\')
|
||||
|| name.starts_with('.')
|
||||
|| name.chars().any(char::is_control)
|
||||
{
|
||||
if name.starts_with('.') || !portable_component(name) {
|
||||
return Err(InstanceError::InvalidName(format!(
|
||||
"Name contains invalid characters: {:?}",
|
||||
"Name contains invalid characters or is reserved: {:?}",
|
||||
name
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn portable_component(name: &str) -> bool {
|
||||
if name.is_empty()
|
||||
|| name.ends_with([' ', '.'])
|
||||
|| name.chars().any(|c| {
|
||||
c.is_control() || matches!(c, '/' | '\\' | ':' | '<' | '>' | '"' | '|' | '?' | '*')
|
||||
})
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let stem = name
|
||||
.split('.')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.trim_end_matches(' ')
|
||||
.to_ascii_uppercase();
|
||||
!matches!(
|
||||
stem.as_str(),
|
||||
"CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$"
|
||||
) && !["COM", "LPT"].into_iter().any(|prefix| {
|
||||
stem.strip_prefix(prefix).is_some_and(|suffix| {
|
||||
matches!(
|
||||
suffix,
|
||||
"1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests/manager.rs"]
|
||||
mod tests;
|
||||
@@ -273,3 +273,41 @@ fn touch_last_played_updates_field() {
|
||||
"last_played should be roughly now, got age {age:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instance_names_are_portable_components() {
|
||||
for name in [
|
||||
"C:victim",
|
||||
"C:",
|
||||
"a:b",
|
||||
"CON",
|
||||
"con.txt",
|
||||
"CON .txt",
|
||||
"AUX.jar",
|
||||
"NUL",
|
||||
"PRN",
|
||||
"COM1",
|
||||
"lpt9.log",
|
||||
"COM¹",
|
||||
"LPT².txt",
|
||||
"CLOCK$",
|
||||
"CONIN$",
|
||||
"CONOUT$",
|
||||
"trailing.",
|
||||
"trailing ",
|
||||
"bad?name",
|
||||
"bad*name",
|
||||
"bad\"name",
|
||||
"bad<name",
|
||||
"bad>name",
|
||||
"bad|name",
|
||||
r"path\name",
|
||||
".",
|
||||
"..",
|
||||
] {
|
||||
assert!(validate_name(name).is_err(), "{name}");
|
||||
}
|
||||
for name in ["CONifer", "COM0", "COM10", "世界", "%USERNAME%", "My Pack"] {
|
||||
assert!(validate_name(name).is_ok(), "{name}");
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -12,22 +12,22 @@ const OLD_NAME: &str = "mcl";
|
||||
const NEW_NAME: &str = "rmcl";
|
||||
|
||||
pub fn run_legacy_rename() {
|
||||
if let Some(dir) = dirs_next::config_dir() {
|
||||
if let Some(dir) = dirs::config_dir() {
|
||||
rename_top_level(&dir.join(OLD_NAME), &dir.join(NEW_NAME));
|
||||
}
|
||||
if let Some(dir) = dirs_next::data_dir() {
|
||||
if let Some(dir) = dirs::data_dir() {
|
||||
let new_data = dir.join(NEW_NAME);
|
||||
rename_top_level(&dir.join(OLD_NAME), &new_data);
|
||||
cleanup_instance_leftovers(&new_data.join("instances"));
|
||||
rewrite_linux_desktop_entries(&dir, &new_data.join("instances"));
|
||||
}
|
||||
if let Some(dir) = dirs_next::cache_dir() {
|
||||
if let Some(dir) = dirs::cache_dir() {
|
||||
rename_top_level(&dir.join(OLD_NAME), &dir.join(NEW_NAME));
|
||||
}
|
||||
if let (Some(desk), Some(data)) = (dirs::desktop_dir(), dirs_next::data_dir()) {
|
||||
if let (Some(desk), Some(data)) = (dirs::desktop_dir(), dirs::data_dir()) {
|
||||
rewrite_native_desktop_shortcuts(&desk, &data.join(NEW_NAME).join("instances"));
|
||||
}
|
||||
if let (Some(config_dir), Some(data_dir)) = (dirs_next::config_dir(), dirs_next::data_dir())
|
||||
if let (Some(config_dir), Some(data_dir)) = (dirs::config_dir(), dirs::data_dir())
|
||||
&& !data_dir.join(OLD_NAME).exists()
|
||||
&& let Err(error) =
|
||||
crate::config::migrate_legacy_data_paths(&config_dir.join(NEW_NAME).join("config.toml"))
|
||||
|
||||
+3
-29
@@ -232,7 +232,8 @@ async fn get<T: serde::de::DeserializeOwned>(
|
||||
api_key: &str,
|
||||
url: &str,
|
||||
) -> Result<T, NetError> {
|
||||
authenticated_request(url, || client.inner().get(url).header("x-api-key", api_key)).await
|
||||
super::request_json_with_retry(url, || client.inner().get(url).header("x-api-key", api_key))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn post<B: serde::Serialize + ?Sized, T: serde::de::DeserializeOwned>(
|
||||
@@ -241,7 +242,7 @@ async fn post<B: serde::Serialize + ?Sized, T: serde::de::DeserializeOwned>(
|
||||
url: &str,
|
||||
body: &B,
|
||||
) -> Result<T, NetError> {
|
||||
authenticated_request(url, || {
|
||||
super::request_json_with_retry(url, || {
|
||||
client
|
||||
.inner()
|
||||
.post(url)
|
||||
@@ -251,33 +252,6 @@ async fn post<B: serde::Serialize + ?Sized, T: serde::de::DeserializeOwned>(
|
||||
.await
|
||||
}
|
||||
|
||||
async fn authenticated_request<T: serde::de::DeserializeOwned>(
|
||||
url: &str,
|
||||
build: impl Fn() -> reqwest::RequestBuilder,
|
||||
) -> Result<T, NetError> {
|
||||
for attempt in 0..=super::MAX_RETRIES {
|
||||
let result = async {
|
||||
let response = build().send().await?;
|
||||
if !response.status().is_success() {
|
||||
return Err(NetError::StatusError {
|
||||
status: response.status().as_u16(),
|
||||
url: url.to_owned(),
|
||||
});
|
||||
}
|
||||
Ok(response.json().await?)
|
||||
}
|
||||
.await;
|
||||
match result {
|
||||
Ok(value) => return Ok(value),
|
||||
Err(error) if error.is_retryable() && attempt < super::MAX_RETRIES => {
|
||||
super::sleep_before_retry("request", url, attempt, &error).await;
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
unreachable!("retry loop returns on success or final error")
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn search_discovery(
|
||||
client: &HttpClient,
|
||||
|
||||
+65
-83
@@ -13,11 +13,9 @@ use reqwest::Client;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use thiserror::Error;
|
||||
|
||||
pub const MAX_PROVIDER_ASSET_BYTES: usize = 16 * 1024 * 1024;
|
||||
static NEXT_DOWNLOAD_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum NetError {
|
||||
@@ -61,7 +59,8 @@ impl HttpClient {
|
||||
let user_agent = format!("rmcl/{} (Minecraft Launcher)", env!("CARGO_PKG_VERSION"));
|
||||
let client = Client::builder()
|
||||
.user_agent(user_agent.clone())
|
||||
.timeout(std::time::Duration::from_secs(30))
|
||||
.connect_timeout(std::time::Duration::from_secs(30))
|
||||
.read_timeout(std::time::Duration::from_secs(30))
|
||||
.build()
|
||||
.unwrap_or_else(|e| {
|
||||
tracing::warn!(
|
||||
@@ -138,34 +137,10 @@ impl HttpClient {
|
||||
B: Serialize + ?Sized,
|
||||
T: DeserializeOwned,
|
||||
{
|
||||
for attempt in 0..=MAX_RETRIES {
|
||||
tracing::trace!("HTTP POST {}", url);
|
||||
let result = async {
|
||||
let response = self.inner.post(url).json(body).send().await?;
|
||||
if !response.status().is_success() {
|
||||
return Err(NetError::StatusError {
|
||||
status: response.status().as_u16(),
|
||||
url: url.to_owned(),
|
||||
});
|
||||
}
|
||||
Ok(response.json().await?)
|
||||
}
|
||||
.await;
|
||||
match result {
|
||||
Ok(value) => return Ok(value),
|
||||
Err(error) if error.is_retryable() && attempt < MAX_RETRIES => {
|
||||
sleep_before_retry("request", url, attempt, &error).await;
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
unreachable!("retry loop returns on success or final error")
|
||||
request_json_with_retry(url, || self.inner.post(url).json(body)).await
|
||||
}
|
||||
|
||||
// fetch JSON and also keep the raw bytes. used by install paths that
|
||||
// want both the parsed shape (for downloading libraries from it) and
|
||||
// the original bytes (to write byte-for-byte to the loader-profiles
|
||||
// cache, so any field we don't know about survives).
|
||||
// Cache upstream bytes so fields outside our deserialized types survive.
|
||||
pub async fn get_json_with_raw<T: DeserializeOwned>(
|
||||
&self,
|
||||
url: &str,
|
||||
@@ -180,33 +155,55 @@ impl HttpClient {
|
||||
}
|
||||
}
|
||||
|
||||
async fn request_json_with_retry<T: DeserializeOwned>(
|
||||
url: &str,
|
||||
build: impl Fn() -> reqwest::RequestBuilder,
|
||||
) -> Result<T, NetError> {
|
||||
request_with_retry(
|
||||
url,
|
||||
build,
|
||||
|response| async move { Ok(response.json().await?) },
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn request_with_retry<T, Fut>(
|
||||
url: &str,
|
||||
build: impl Fn() -> reqwest::RequestBuilder,
|
||||
decode: impl Fn(reqwest::Response) -> Fut,
|
||||
) -> Result<T, NetError>
|
||||
where
|
||||
Fut: std::future::Future<Output = Result<T, NetError>>,
|
||||
{
|
||||
for attempt in 0..=MAX_RETRIES {
|
||||
let result = async {
|
||||
let response = build().send().await?;
|
||||
if !response.status().is_success() {
|
||||
return Err(NetError::StatusError {
|
||||
status: response.status().as_u16(),
|
||||
url: url.to_owned(),
|
||||
});
|
||||
}
|
||||
decode(response).await
|
||||
}
|
||||
.await;
|
||||
match result {
|
||||
Ok(value) => return Ok(value),
|
||||
Err(error) if error.is_retryable() && attempt < MAX_RETRIES => {
|
||||
sleep_before_retry("request", url, attempt, &error).await
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
unreachable!("retry loop returns on success or final error")
|
||||
}
|
||||
|
||||
async fn get_with_retry<T, F, Fut>(client: &HttpClient, url: &str, decode: F) -> Result<T, NetError>
|
||||
where
|
||||
F: Fn(reqwest::Response) -> Fut,
|
||||
Fut: std::future::Future<Output = Result<T, NetError>>,
|
||||
{
|
||||
for attempt in 0..=MAX_RETRIES {
|
||||
match client.get(url).await {
|
||||
Ok(resp) => match decode(resp).await {
|
||||
Ok(value) => return Ok(value),
|
||||
Err(e) if e.is_retryable() => {
|
||||
if attempt == MAX_RETRIES {
|
||||
return Err(e);
|
||||
}
|
||||
sleep_before_retry("request", url, attempt, &e).await;
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
},
|
||||
Err(e) if e.is_retryable() => {
|
||||
if attempt == MAX_RETRIES {
|
||||
return Err(e);
|
||||
}
|
||||
sleep_before_retry("request", url, attempt, &e).await;
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
unreachable!("retry loop returns on success or final error")
|
||||
request_with_retry(url, || client.inner.get(url), decode).await
|
||||
}
|
||||
|
||||
const MAX_RETRIES: u32 = 3;
|
||||
@@ -305,42 +302,27 @@ async fn download_file_once(
|
||||
let total = response.content_length().unwrap_or(0);
|
||||
tracing::trace!("Download content length for {}: {}", url, total);
|
||||
|
||||
if let Some(parent) = dest.parent() {
|
||||
tokio::fs::create_dir_all(parent).await?;
|
||||
}
|
||||
|
||||
let temporary = dest.with_file_name(format!(
|
||||
".{}.{}.{}.download",
|
||||
dest.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or("file"),
|
||||
std::process::id(),
|
||||
NEXT_DOWNLOAD_ID.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
let mut file = tokio::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temporary)
|
||||
.await?;
|
||||
let parent = dest
|
||||
.parent()
|
||||
.filter(|parent| !parent.as_os_str().is_empty())
|
||||
.unwrap_or(Path::new("."));
|
||||
tokio::fs::create_dir_all(parent).await?;
|
||||
let temporary = tempfile::Builder::new()
|
||||
.prefix(".rmcl-download-")
|
||||
.tempfile_in(parent)?;
|
||||
let mut file = tokio::fs::File::from_std(temporary.reopen()?);
|
||||
let mut downloaded: u64 = 0;
|
||||
let mut stream = response;
|
||||
|
||||
let result = async {
|
||||
while let Some(chunk) = stream.chunk().await? {
|
||||
file.write_all(&chunk).await?;
|
||||
downloaded += chunk.len() as u64;
|
||||
progress_cb(downloaded, total);
|
||||
}
|
||||
file.flush().await?;
|
||||
drop(file);
|
||||
tokio::fs::rename(&temporary, dest).await?;
|
||||
Ok(())
|
||||
while let Some(chunk) = stream.chunk().await? {
|
||||
file.write_all(&chunk).await?;
|
||||
downloaded += chunk.len() as u64;
|
||||
progress_cb(downloaded, total);
|
||||
}
|
||||
.await;
|
||||
if result.is_err() {
|
||||
let _ = tokio::fs::remove_file(&temporary).await;
|
||||
}
|
||||
result
|
||||
file.flush().await?;
|
||||
drop(file);
|
||||
temporary.persist(dest).map_err(|error| error.error)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// body decode errors and timeouts are worth retrying, but a 404 or disk
|
||||
|
||||
+29
-62
@@ -537,25 +537,8 @@ pub async fn download_version_file(
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
let temporary = destination.join(format!(".{}.{}.rmcl-download", file.filename, version.id));
|
||||
if temporary.exists() {
|
||||
tokio::fs::remove_file(&temporary).await?;
|
||||
}
|
||||
let progress =
|
||||
crate::feedback::progress::ProgressTask::start(format!("Downloading {}", file.filename));
|
||||
crate::net::download_file(client, &file.url, &temporary, |current, total| {
|
||||
progress.set_progress(current, total);
|
||||
})
|
||||
.await?;
|
||||
if !verify_version_file(&temporary, file)? {
|
||||
let _ = tokio::fs::remove_file(&temporary).await;
|
||||
return Err(crate::net::NetError::Parse(format!(
|
||||
"Downloaded file '{}' failed its size or hash verification",
|
||||
file.filename
|
||||
)));
|
||||
}
|
||||
tokio::fs::rename(&temporary, &path).await?;
|
||||
progress.finish();
|
||||
let temporary = staged_version_file(client, file, destination).await?;
|
||||
temporary.persist(&path).map_err(|error| error.error)?;
|
||||
Ok(DownloadOutcome::Downloaded(path))
|
||||
}
|
||||
|
||||
@@ -573,19 +556,21 @@ pub async fn download_version_file_for_update(
|
||||
return download_version_file(client, version, destination).await;
|
||||
}
|
||||
|
||||
let temporary = destination.join(format!(".{}.{}.rmcl-download", file.filename, version.id));
|
||||
let backup = destination.join(format!(".{}.{}.rmcl-backup", file.filename, version.id));
|
||||
if backup.exists() {
|
||||
if !installed_path.exists() {
|
||||
tokio::fs::rename(&backup, installed_path).await?;
|
||||
} else {
|
||||
tokio::fs::remove_file(&backup).await?;
|
||||
}
|
||||
}
|
||||
if temporary.exists() {
|
||||
tokio::fs::remove_file(&temporary).await?;
|
||||
}
|
||||
let temporary = staged_version_file(client, file, destination).await?;
|
||||
temporary.persist(&target).map_err(|error| error.error)?;
|
||||
Ok(DownloadOutcome::Downloaded(target))
|
||||
}
|
||||
|
||||
async fn staged_version_file(
|
||||
client: &crate::net::HttpClient,
|
||||
file: &VersionFile,
|
||||
destination: &std::path::Path,
|
||||
) -> Result<tempfile::TempPath, crate::net::NetError> {
|
||||
tokio::fs::create_dir_all(destination).await?;
|
||||
let temporary = tempfile::Builder::new()
|
||||
.prefix(".rmcl-verified-")
|
||||
.tempfile_in(destination)?
|
||||
.into_temp_path();
|
||||
let progress =
|
||||
crate::feedback::progress::ProgressTask::start(format!("Downloading {}", file.filename));
|
||||
crate::net::download_file(client, &file.url, &temporary, |current, total| {
|
||||
@@ -593,22 +578,16 @@ pub async fn download_version_file_for_update(
|
||||
})
|
||||
.await?;
|
||||
if !verify_version_file(&temporary, file)? {
|
||||
let _ = tokio::fs::remove_file(&temporary).await;
|
||||
return Err(crate::net::NetError::Parse(format!(
|
||||
"Downloaded file '{}' failed its size or hash verification",
|
||||
file.filename
|
||||
)));
|
||||
}
|
||||
replace_installed_file(&temporary, &target, installed_path, &backup).await?;
|
||||
progress.finish();
|
||||
Ok(DownloadOutcome::Downloaded(target))
|
||||
Ok(temporary)
|
||||
}
|
||||
|
||||
fn validate_path_component(value: &str, label: &str) -> Result<(), crate::net::NetError> {
|
||||
let mut components = std::path::Path::new(value).components();
|
||||
if !matches!(components.next(), Some(std::path::Component::Normal(_)))
|
||||
|| components.next().is_some()
|
||||
{
|
||||
if !crate::instance::manager::portable_component(value) {
|
||||
return Err(crate::net::NetError::Parse(format!(
|
||||
"Invalid {label} '{value}'"
|
||||
)));
|
||||
@@ -634,24 +613,6 @@ fn verify_version_file(
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
async fn replace_installed_file(
|
||||
temporary: &std::path::Path,
|
||||
target: &std::path::Path,
|
||||
installed_path: &std::path::Path,
|
||||
backup: &std::path::Path,
|
||||
) -> Result<(), crate::net::NetError> {
|
||||
tokio::fs::rename(installed_path, &backup).await?;
|
||||
if let Err(error) = tokio::fs::rename(&temporary, &target).await {
|
||||
let _ = tokio::fs::rename(&backup, installed_path).await;
|
||||
let _ = tokio::fs::remove_file(&temporary).await;
|
||||
return Err(error.into());
|
||||
}
|
||||
if let Err(error) = tokio::fs::remove_file(&backup).await {
|
||||
tracing::warn!("Failed to remove provider update backup: {error}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn fetch_version(
|
||||
client: &crate::net::HttpClient,
|
||||
version_id: &str,
|
||||
@@ -690,16 +651,22 @@ pub async fn resolve_version_files(
|
||||
.await
|
||||
}
|
||||
|
||||
// grabs the primary file from a version, falling back to the first file
|
||||
// if none is marked primary (some projects are sloppy about that).
|
||||
// routes through the shared verified download (temp file + size/hash check
|
||||
// + rename) so a truncated or corrupted .mrpack is never left in place.
|
||||
pub async fn download_mrpack(
|
||||
client: &crate::net::HttpClient,
|
||||
version: &VersionInfo,
|
||||
dest: &std::path::Path,
|
||||
) -> Result<std::path::PathBuf, crate::net::NetError> {
|
||||
match download_version_file(client, version, dest).await? {
|
||||
validate_path_component(&version.id, "provider version id")?;
|
||||
let cache = dest.join(&version.id);
|
||||
let file = select_primary_file(version)?;
|
||||
validate_path_component(&file.filename, "provider filename")?;
|
||||
let path = cache.join(&file.filename);
|
||||
if path.exists() && !verify_version_file(&path, file)? {
|
||||
return match download_version_file_for_update(client, version, &cache, &path).await? {
|
||||
DownloadOutcome::Downloaded(path) | DownloadOutcome::SkippedExisting(path) => Ok(path),
|
||||
};
|
||||
}
|
||||
match download_version_file(client, version, &cache).await? {
|
||||
DownloadOutcome::Downloaded(path) | DownloadOutcome::SkippedExisting(path) => Ok(path),
|
||||
}
|
||||
}
|
||||
|
||||
+66
-16
@@ -318,7 +318,7 @@ async fn content_download_rejects_an_unverifiable_existing_filename() {
|
||||
#[tokio::test]
|
||||
async fn content_download_rejects_provider_path_components() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let version = version_with_files(vec![VersionFile {
|
||||
let mut version = version_with_files(vec![VersionFile {
|
||||
url: "https://example.test/escape.jar".to_owned(),
|
||||
filename: "../escape.jar".to_owned(),
|
||||
size: 1,
|
||||
@@ -326,11 +326,21 @@ async fn content_download_rejects_provider_path_components() {
|
||||
hashes: HashMap::new(),
|
||||
}]);
|
||||
|
||||
let error = download_version_file(&crate::net::HttpClient::new(), &version, directory.path())
|
||||
.await
|
||||
.unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("Invalid provider filename"));
|
||||
for filename in [
|
||||
"../escape.jar",
|
||||
r"..\escape.jar",
|
||||
"existing.jar:stream",
|
||||
"C:escape.jar",
|
||||
"NUL.jar",
|
||||
"content.jar.",
|
||||
] {
|
||||
version.files[0].filename = filename.to_owned();
|
||||
let error =
|
||||
download_version_file(&crate::net::HttpClient::new(), &version, directory.path())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("Invalid provider filename"));
|
||||
}
|
||||
assert!(
|
||||
!directory
|
||||
.path()
|
||||
@@ -343,19 +353,63 @@ async fn content_download_rejects_provider_path_components() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn staged_update_replaces_the_old_file_and_cleans_its_backup() {
|
||||
use sha1::Digest;
|
||||
use wiremock::{Mock, MockServer, ResponseTemplate, matchers::path};
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path("/pack"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"new version".to_vec()))
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let installed = directory.path().join("example.jar");
|
||||
let temporary = directory.path().join(".example.jar.rmcl-download");
|
||||
let backup = directory.path().join(".example.jar.rmcl-backup");
|
||||
std::fs::write(&installed, b"old version").unwrap();
|
||||
std::fs::write(&temporary, b"new version").unwrap();
|
||||
|
||||
replace_installed_file(&temporary, &installed, &installed, &backup)
|
||||
let version = version_with_files(vec![VersionFile {
|
||||
url: format!("{}/pack", server.uri()),
|
||||
filename: "example.jar".to_owned(),
|
||||
size: 11,
|
||||
primary: true,
|
||||
hashes: HashMap::from([(
|
||||
"sha1".to_owned(),
|
||||
format!("{:x}", sha1::Sha1::digest(b"new version")),
|
||||
)]),
|
||||
}]);
|
||||
let client = crate::net::HttpClient::new();
|
||||
download_version_file_for_update(&client, &version, directory.path(), &installed)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(std::fs::read(installed).unwrap(), b"new version");
|
||||
assert_eq!(std::fs::read(&installed).unwrap(), b"new version");
|
||||
assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1);
|
||||
let cached = directory.path().join(&version.id).join("example.jar");
|
||||
std::fs::create_dir_all(cached.parent().unwrap()).unwrap();
|
||||
std::fs::write(&cached, b"corrupt cached pack").unwrap();
|
||||
assert_eq!(
|
||||
download_mrpack(&client, &version, directory.path())
|
||||
.await
|
||||
.unwrap(),
|
||||
cached
|
||||
);
|
||||
assert_eq!(std::fs::read(&cached).unwrap(), b"new version");
|
||||
Mock::given(path("/different-pack"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"other version".to_vec()))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let mut other = version.clone();
|
||||
other.id = "another-version".to_owned();
|
||||
other.files[0].url = format!("{}/different-pack", server.uri());
|
||||
other.files[0].size = 13;
|
||||
other.files[0].hashes = HashMap::from([(
|
||||
"sha1".to_owned(),
|
||||
format!("{:x}", sha1::Sha1::digest(b"other version")),
|
||||
)]);
|
||||
let other_path = download_mrpack(&client, &other, directory.path())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_ne!(other_path, cached);
|
||||
assert_eq!(std::fs::read(&cached).unwrap(), b"new version");
|
||||
assert_eq!(std::fs::read(other_path).unwrap(), b"other version");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -416,10 +470,6 @@ fn discovery_sort_maps_to_modrinth_indexes() {
|
||||
assert_eq!(discovery_index(DiscoverySort::Newest, ""), "newest");
|
||||
}
|
||||
|
||||
// covers each branch of url_encode: unreserved bytes pass through; the
|
||||
// reserved set + spaces + non-ascii bytes get percent-encoded. emoji
|
||||
// exercises multi-byte UTF-8 since the encoder operates on bytes, not
|
||||
// chars, so each byte of the codepoint encodes separately.
|
||||
#[rstest::rstest]
|
||||
#[case::ascii_unreserved("abcXYZ0-9_.~", "abcXYZ0-9_.~")]
|
||||
#[case::space("hello world", "hello%20world")]
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
mod filesystem;
|
||||
pub(crate) use filesystem::copy_symlink;
|
||||
pub(crate) use filesystem::{copy_symlink, copy_symlink_target};
|
||||
pub use filesystem::{write_atomic, write_atomic_private};
|
||||
|
||||
pub const MINECRAFT_DIR_NAME: &str = "minecraft";
|
||||
|
||||
+40
-35
@@ -3,9 +3,6 @@
|
||||
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
static TEMP_FILE_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
write_atomic_with_mode(path, bytes, false)
|
||||
@@ -16,49 +13,57 @@ pub fn write_atomic_private(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
}
|
||||
|
||||
fn write_atomic_with_mode(path: &Path, bytes: &[u8], private: bool) -> io::Result<()> {
|
||||
use std::io::Write;
|
||||
|
||||
let parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?;
|
||||
let parent = if parent.as_os_str().is_empty() {
|
||||
Path::new(".")
|
||||
} else {
|
||||
parent
|
||||
};
|
||||
std::fs::create_dir_all(parent)?;
|
||||
let id = TEMP_FILE_ID.fetch_add(1, Ordering::Relaxed);
|
||||
let name = path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or("data");
|
||||
let temporary = parent.join(format!(".{name}.{}.{}.tmp", std::process::id(), id));
|
||||
let result = (|| {
|
||||
use std::io::Write;
|
||||
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.create_new(true).write(true);
|
||||
#[cfg(unix)]
|
||||
if private {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = private;
|
||||
let mut file = options.open(&temporary)?;
|
||||
file.write_all(bytes)?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
std::fs::rename(&temporary, path)
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
let mut builder = tempfile::Builder::new();
|
||||
builder.prefix(".rmcl-write-");
|
||||
#[cfg(unix)]
|
||||
if !private {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
builder.permissions(std::fs::Permissions::from_mode(0o666));
|
||||
}
|
||||
result
|
||||
#[cfg(not(unix))]
|
||||
let _ = private;
|
||||
let mut file = builder.tempfile_in(parent)?;
|
||||
file.write_all(bytes)?;
|
||||
file.as_file().sync_all()?;
|
||||
file.persist(path).map(|_| ()).map_err(|error| error.error)
|
||||
}
|
||||
|
||||
#[cfg(any(unix, windows))]
|
||||
pub(crate) fn copy_symlink(source: &Path, destination: &Path) -> io::Result<()> {
|
||||
copy_symlink_target(source, destination, &std::fs::read_link(source)?)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn copy_symlink(source: &Path, destination: &Path) -> io::Result<()> {
|
||||
std::os::unix::fs::symlink(std::fs::read_link(source)?, destination)
|
||||
pub(crate) fn copy_symlink_target(
|
||||
_source: &Path,
|
||||
destination: &Path,
|
||||
target: &Path,
|
||||
) -> io::Result<()> {
|
||||
std::os::unix::fs::symlink(target, destination)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn copy_symlink(source: &Path, destination: &Path) -> io::Result<()> {
|
||||
let target = std::fs::read_link(source)?;
|
||||
if source.is_dir() {
|
||||
pub(crate) fn copy_symlink_target(
|
||||
source: &Path,
|
||||
destination: &Path,
|
||||
target: &Path,
|
||||
) -> io::Result<()> {
|
||||
use std::os::windows::fs::FileTypeExt;
|
||||
if std::fs::symlink_metadata(source)?
|
||||
.file_type()
|
||||
.is_symlink_dir()
|
||||
{
|
||||
std::os::windows::fs::symlink_dir(target, destination)
|
||||
} else {
|
||||
std::os::windows::fs::symlink_file(target, destination)
|
||||
|
||||
@@ -80,3 +80,18 @@ fn failed_atomic_replacement_keeps_the_destination_and_removes_staging() {
|
||||
assert_eq!(std::fs::read(path.join("keep")).unwrap(), b"old");
|
||||
assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn private_atomic_writes_keep_credentials_owner_only() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("accounts.json");
|
||||
std::fs::write(&path, b"old").unwrap();
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
|
||||
write_atomic_private(&path, b"new").unwrap();
|
||||
assert_eq!(
|
||||
std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
|
||||
0o600
|
||||
);
|
||||
}
|
||||
+1
-1
@@ -40,7 +40,7 @@ fn push_app_log(line: String) {
|
||||
// returns a WorkerGuard that must be held alive for the duration of the
|
||||
// program, otherwise the file logging thread gets dropped immediately.
|
||||
pub fn init() -> WorkerGuard {
|
||||
let log_dir = match dirs_next::cache_dir() {
|
||||
let log_dir = match dirs::cache_dir() {
|
||||
Some(d) => d.join("rmcl"),
|
||||
None => std::path::PathBuf::from("./cache"),
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user