fix: make filesystem writes and downloads cancellation-safe
This commit is contained in:
1 parent
615d3fb8fc
commit
7362354109
18 files changed
+410
-274
No files matched your search
Generated
+11
-34
@@ -1001,16 +1001,6 @@ dependencies = [
|
|||||||
"dirs-sys",
|
"dirs-sys",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "dirs-next"
|
|
||||||
version = "2.0.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "b98cf8ebf19c3d1b223e151f99a4f9f0690dca41414773390fc824184ac833e1"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
"dirs-sys-next",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "dirs-sys"
|
name = "dirs-sys"
|
||||||
version = "0.5.0"
|
version = "0.5.0"
|
||||||
@@ -1019,21 +1009,10 @@ checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"libc",
|
"libc",
|
||||||
"option-ext",
|
"option-ext",
|
||||||
"redox_users 0.5.2",
|
"redox_users",
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "dirs-sys-next"
|
|
||||||
version = "0.1.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d"
|
|
||||||
dependencies = [
|
|
||||||
"libc",
|
|
||||||
"redox_users 0.4.6",
|
|
||||||
"winapi",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "dispatch2"
|
name = "dispatch2"
|
||||||
version = "0.3.1"
|
version = "0.3.1"
|
||||||
@@ -1100,6 +1079,12 @@ version = "1.2.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
|
checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "dunce"
|
||||||
|
version = "1.0.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "either"
|
name = "either"
|
||||||
version = "1.15.0"
|
version = "1.15.0"
|
||||||
@@ -2879,6 +2864,7 @@ version = "5.3.4"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9f3bab717c29a857abf75fcef718d441ec7cb2725f937343c734740a985d37fd"
|
checksum = "9f3bab717c29a857abf75fcef718d441ec7cb2725f937343c734740a985d37fd"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"dunce",
|
||||||
"is-wsl",
|
"is-wsl",
|
||||||
"libc",
|
"libc",
|
||||||
"pathdiff",
|
"pathdiff",
|
||||||
@@ -3721,17 +3707,6 @@ dependencies = [
|
|||||||
"bitflags 2.13.1",
|
"bitflags 2.13.1",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "redox_users"
|
|
||||||
version = "0.4.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43"
|
|
||||||
dependencies = [
|
|
||||||
"getrandom 0.2.17",
|
|
||||||
"libredox",
|
|
||||||
"thiserror 1.0.69",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "redox_users"
|
name = "redox_users"
|
||||||
version = "0.5.2"
|
version = "0.5.2"
|
||||||
@@ -3890,7 +3865,6 @@ dependencies = [
|
|||||||
"config",
|
"config",
|
||||||
"crossterm 0.29.0",
|
"crossterm 0.29.0",
|
||||||
"dirs",
|
"dirs",
|
||||||
"dirs-next",
|
|
||||||
"display-info",
|
"display-info",
|
||||||
"fast-strip-ansi",
|
"fast-strip-ansi",
|
||||||
"fastnbt",
|
"fastnbt",
|
||||||
@@ -3899,6 +3873,7 @@ dependencies = [
|
|||||||
"html-to-markdown-rs",
|
"html-to-markdown-rs",
|
||||||
"image",
|
"image",
|
||||||
"insta",
|
"insta",
|
||||||
|
"libc",
|
||||||
"libcasr",
|
"libcasr",
|
||||||
"log",
|
"log",
|
||||||
"minecraft-msa-auth",
|
"minecraft-msa-auth",
|
||||||
@@ -3918,6 +3893,7 @@ dependencies = [
|
|||||||
"serde_json",
|
"serde_json",
|
||||||
"sha1 0.10.7",
|
"sha1 0.10.7",
|
||||||
"sha2",
|
"sha2",
|
||||||
|
"shlex",
|
||||||
"tachyonfx",
|
"tachyonfx",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"thiserror 2.0.18",
|
"thiserror 2.0.18",
|
||||||
@@ -3936,6 +3912,7 @@ dependencies = [
|
|||||||
"tui-widget-list",
|
"tui-widget-list",
|
||||||
"unicode-segmentation",
|
"unicode-segmentation",
|
||||||
"which",
|
"which",
|
||||||
|
"windows-sys 0.61.2",
|
||||||
"wiremock",
|
"wiremock",
|
||||||
"zip",
|
"zip",
|
||||||
]
|
]
|
||||||
|
|||||||
+8
-4
@@ -30,7 +30,6 @@ color-eyre = "0.6.3"
|
|||||||
config = "0.15.6"
|
config = "0.15.6"
|
||||||
crossterm = "0.29.0"
|
crossterm = "0.29.0"
|
||||||
display-info = "0.5.9"
|
display-info = "0.5.9"
|
||||||
dirs-next = "2.0.0"
|
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
ratatui = { version = "0.30.0", features = ["serde", "unstable-rendered-line-info"] }
|
ratatui = { version = "0.30.0", features = ["serde", "unstable-rendered-line-info"] }
|
||||||
ratatui-themekit = { version = "0.6", features = ["serde"] }
|
ratatui-themekit = { version = "0.6", features = ["serde"] }
|
||||||
@@ -64,7 +63,7 @@ image = { version = "0.25", default-features = false, features = ["gif", "jpeg",
|
|||||||
zip = "8.5.1"
|
zip = "8.5.1"
|
||||||
minecraft-msa-auth = "0.4.0"
|
minecraft-msa-auth = "0.4.0"
|
||||||
oauth2 = "5.0.0"
|
oauth2 = "5.0.0"
|
||||||
open = "5"
|
open = { version = "5", features = ["shellexecute-on-windows"] }
|
||||||
which = "8.0.2"
|
which = "8.0.2"
|
||||||
dirs = "6.0.0"
|
dirs = "6.0.0"
|
||||||
notify = "8"
|
notify = "8"
|
||||||
@@ -74,7 +73,14 @@ libcasr = "2.13"
|
|||||||
fs2 = "0.4"
|
fs2 = "0.4"
|
||||||
fastnbt = "2.6.2"
|
fastnbt = "2.6.2"
|
||||||
flate2 = "1.1.9"
|
flate2 = "1.1.9"
|
||||||
|
tempfile = "3"
|
||||||
|
|
||||||
|
[target.'cfg(unix)'.dependencies]
|
||||||
|
libc = "0.2"
|
||||||
|
shlex = "1.3"
|
||||||
|
|
||||||
|
[target.'cfg(windows)'.dependencies]
|
||||||
|
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_System_JobObjects", "Win32_System_Threading", "Win32_System_Diagnostics_ToolHelp", "Win32_UI_Shell"] }
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
codegen-units = 1
|
codegen-units = 1
|
||||||
@@ -87,8 +93,6 @@ inherits = "release"
|
|||||||
lto = "thin"
|
lto = "thin"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempfile = "3"
|
|
||||||
insta = "1"
|
insta = "1"
|
||||||
wiremock = "0.6"
|
wiremock = "0.6"
|
||||||
rstest = "0.23"
|
rstest = "0.23"
|
||||||
image = { version = "0.25", default-features = false, features = ["png", "webp"] }
|
|
||||||
+2
-2
@@ -14,7 +14,7 @@ pub use settings::Config;
|
|||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn get_config_path() -> PathBuf {
|
pub fn get_config_path() -> PathBuf {
|
||||||
dirs_next::config_dir()
|
dirs::config_dir()
|
||||||
.unwrap_or_else(|| PathBuf::from("."))
|
.unwrap_or_else(|| PathBuf::from("."))
|
||||||
.join("rmcl")
|
.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> {
|
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);
|
return Ok(false);
|
||||||
};
|
};
|
||||||
migrate_legacy_data_paths_from(path, &data_dir)
|
migrate_legacy_data_paths_from(path, &data_dir)
|
||||||
|
|||||||
@@ -212,7 +212,7 @@ pub struct Paths {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn default_instances_dir() -> String {
|
fn default_instances_dir() -> String {
|
||||||
dirs_next::data_dir()
|
dirs::data_dir()
|
||||||
.unwrap_or_else(|| PathBuf::from("."))
|
.unwrap_or_else(|| PathBuf::from("."))
|
||||||
.join("rmcl")
|
.join("rmcl")
|
||||||
.join("instances")
|
.join("instances")
|
||||||
@@ -225,7 +225,7 @@ fn is_default_instances_dir(path: &str) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn default_meta_dir() -> String {
|
fn default_meta_dir() -> String {
|
||||||
dirs_next::data_dir()
|
dirs::data_dir()
|
||||||
.unwrap_or_else(|| PathBuf::from("."))
|
.unwrap_or_else(|| PathBuf::from("."))
|
||||||
.join("rmcl")
|
.join("rmcl")
|
||||||
.join("meta")
|
.join("meta")
|
||||||
@@ -249,11 +249,11 @@ impl Default for Paths {
|
|||||||
|
|
||||||
pub fn resolve_path(raw: &str) -> PathBuf {
|
pub fn resolve_path(raw: &str) -> PathBuf {
|
||||||
if let Some(stripped) = raw.strip_prefix("~/") {
|
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);
|
return home.join(stripped);
|
||||||
}
|
}
|
||||||
} else if raw == "~"
|
} else if raw == "~"
|
||||||
&& let Some(home) = dirs_next::home_dir()
|
&& let Some(home) = dirs::home_dir()
|
||||||
{
|
{
|
||||||
return home;
|
return home;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ pub fn desktop_path(name: &str) -> Option<PathBuf> {
|
|||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
{
|
{
|
||||||
dirs_next::data_dir().map(|d| {
|
dirs::data_dir().map(|d| {
|
||||||
d.join("applications")
|
d.join("applications")
|
||||||
.join(format!("rmcl-{sanitized}.desktop"))
|
.join(format!("rmcl-{sanitized}.desktop"))
|
||||||
})
|
})
|
||||||
@@ -36,7 +36,7 @@ pub fn desktop_path(name: &str) -> Option<PathBuf> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn icon_path() -> 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> {
|
fn ensure_icon() -> Option<PathBuf> {
|
||||||
|
|||||||
@@ -149,7 +149,7 @@ fn java_roots() -> Vec<PathBuf> {
|
|||||||
roots.push(PathBuf::from(prefix).join(formula));
|
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("Library/Java/JavaVirtualMachines"));
|
||||||
roots.push(home.join(".sdkman/candidates/java"));
|
roots.push(home.join(".sdkman/candidates/java"));
|
||||||
roots.push(home.join(".asdf/installs/java"));
|
roots.push(home.join(".asdf/installs/java"));
|
||||||
@@ -162,7 +162,7 @@ fn java_roots() -> Vec<PathBuf> {
|
|||||||
PathBuf::from("/opt/java"),
|
PathBuf::from("/opt/java"),
|
||||||
PathBuf::from("/opt/jdk"),
|
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(".sdkman/candidates/java"));
|
||||||
roots.push(home.join(".jdks"));
|
roots.push(home.join(".jdks"));
|
||||||
roots.push(home.join(".asdf/installs/java"));
|
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> {
|
pub(crate) fn validate_name(name: &str) -> Result<(), InstanceError> {
|
||||||
if name.is_empty() || name.len() > 64 {
|
if name.is_empty() || name.len() > 64 {
|
||||||
return Err(InstanceError::InvalidName(format!(
|
return Err(InstanceError::InvalidName(format!(
|
||||||
@@ -636,19 +635,43 @@ pub(crate) fn validate_name(name: &str) -> Result<(), InstanceError> {
|
|||||||
name
|
name
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
if name.contains('/')
|
if name.starts_with('.') || !portable_component(name) {
|
||||||
|| name.contains('\\')
|
|
||||||
|| name.starts_with('.')
|
|
||||||
|| name.chars().any(char::is_control)
|
|
||||||
{
|
|
||||||
return Err(InstanceError::InvalidName(format!(
|
return Err(InstanceError::InvalidName(format!(
|
||||||
"Name contains invalid characters: {:?}",
|
"Name contains invalid characters or is reserved: {:?}",
|
||||||
name
|
name
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
Ok(())
|
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)]
|
#[cfg(test)]
|
||||||
#[path = "tests/manager.rs"]
|
#[path = "tests/manager.rs"]
|
||||||
mod tests;
|
mod tests;
|
||||||
@@ -273,3 +273,41 @@ fn touch_last_played_updates_field() {
|
|||||||
"last_played should be roughly now, got age {age:?}"
|
"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";
|
const NEW_NAME: &str = "rmcl";
|
||||||
|
|
||||||
pub fn run_legacy_rename() {
|
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));
|
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);
|
let new_data = dir.join(NEW_NAME);
|
||||||
rename_top_level(&dir.join(OLD_NAME), &new_data);
|
rename_top_level(&dir.join(OLD_NAME), &new_data);
|
||||||
cleanup_instance_leftovers(&new_data.join("instances"));
|
cleanup_instance_leftovers(&new_data.join("instances"));
|
||||||
rewrite_linux_desktop_entries(&dir, &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));
|
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"));
|
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()
|
&& !data_dir.join(OLD_NAME).exists()
|
||||||
&& let Err(error) =
|
&& let Err(error) =
|
||||||
crate::config::migrate_legacy_data_paths(&config_dir.join(NEW_NAME).join("config.toml"))
|
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,
|
api_key: &str,
|
||||||
url: &str,
|
url: &str,
|
||||||
) -> Result<T, NetError> {
|
) -> 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>(
|
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,
|
url: &str,
|
||||||
body: &B,
|
body: &B,
|
||||||
) -> Result<T, NetError> {
|
) -> Result<T, NetError> {
|
||||||
authenticated_request(url, || {
|
super::request_json_with_retry(url, || {
|
||||||
client
|
client
|
||||||
.inner()
|
.inner()
|
||||||
.post(url)
|
.post(url)
|
||||||
@@ -251,33 +252,6 @@ async fn post<B: serde::Serialize + ?Sized, T: serde::de::DeserializeOwned>(
|
|||||||
.await
|
.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)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
pub async fn search_discovery(
|
pub async fn search_discovery(
|
||||||
client: &HttpClient,
|
client: &HttpClient,
|
||||||
|
|||||||
+57
-75
@@ -13,11 +13,9 @@ use reqwest::Client;
|
|||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use serde::de::DeserializeOwned;
|
use serde::de::DeserializeOwned;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
pub const MAX_PROVIDER_ASSET_BYTES: usize = 16 * 1024 * 1024;
|
pub const MAX_PROVIDER_ASSET_BYTES: usize = 16 * 1024 * 1024;
|
||||||
static NEXT_DOWNLOAD_ID: AtomicU64 = AtomicU64::new(1);
|
|
||||||
|
|
||||||
#[derive(Debug, Error)]
|
#[derive(Debug, Error)]
|
||||||
pub enum NetError {
|
pub enum NetError {
|
||||||
@@ -61,7 +59,8 @@ impl HttpClient {
|
|||||||
let user_agent = format!("rmcl/{} (Minecraft Launcher)", env!("CARGO_PKG_VERSION"));
|
let user_agent = format!("rmcl/{} (Minecraft Launcher)", env!("CARGO_PKG_VERSION"));
|
||||||
let client = Client::builder()
|
let client = Client::builder()
|
||||||
.user_agent(user_agent.clone())
|
.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()
|
.build()
|
||||||
.unwrap_or_else(|e| {
|
.unwrap_or_else(|e| {
|
||||||
tracing::warn!(
|
tracing::warn!(
|
||||||
@@ -138,34 +137,10 @@ impl HttpClient {
|
|||||||
B: Serialize + ?Sized,
|
B: Serialize + ?Sized,
|
||||||
T: DeserializeOwned,
|
T: DeserializeOwned,
|
||||||
{
|
{
|
||||||
for attempt in 0..=MAX_RETRIES {
|
request_json_with_retry(url, || self.inner.post(url).json(body)).await
|
||||||
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")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// fetch JSON and also keep the raw bytes. used by install paths that
|
// Cache upstream bytes so fields outside our deserialized types survive.
|
||||||
// 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).
|
|
||||||
pub async fn get_json_with_raw<T: DeserializeOwned>(
|
pub async fn get_json_with_raw<T: DeserializeOwned>(
|
||||||
&self,
|
&self,
|
||||||
url: &str,
|
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>
|
async fn get_with_retry<T, F, Fut>(client: &HttpClient, url: &str, decode: F) -> Result<T, NetError>
|
||||||
where
|
where
|
||||||
F: Fn(reqwest::Response) -> Fut,
|
F: Fn(reqwest::Response) -> Fut,
|
||||||
Fut: std::future::Future<Output = Result<T, NetError>>,
|
Fut: std::future::Future<Output = Result<T, NetError>>,
|
||||||
{
|
{
|
||||||
for attempt in 0..=MAX_RETRIES {
|
request_with_retry(url, || client.inner.get(url), decode).await
|
||||||
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")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const MAX_RETRIES: u32 = 3;
|
const MAX_RETRIES: u32 = 3;
|
||||||
@@ -305,27 +302,18 @@ async fn download_file_once(
|
|||||||
let total = response.content_length().unwrap_or(0);
|
let total = response.content_length().unwrap_or(0);
|
||||||
tracing::trace!("Download content length for {}: {}", url, total);
|
tracing::trace!("Download content length for {}: {}", url, total);
|
||||||
|
|
||||||
if let Some(parent) = dest.parent() {
|
let parent = dest
|
||||||
|
.parent()
|
||||||
|
.filter(|parent| !parent.as_os_str().is_empty())
|
||||||
|
.unwrap_or(Path::new("."));
|
||||||
tokio::fs::create_dir_all(parent).await?;
|
tokio::fs::create_dir_all(parent).await?;
|
||||||
}
|
let temporary = tempfile::Builder::new()
|
||||||
|
.prefix(".rmcl-download-")
|
||||||
let temporary = dest.with_file_name(format!(
|
.tempfile_in(parent)?;
|
||||||
".{}.{}.{}.download",
|
let mut file = tokio::fs::File::from_std(temporary.reopen()?);
|
||||||
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 mut downloaded: u64 = 0;
|
let mut downloaded: u64 = 0;
|
||||||
let mut stream = response;
|
let mut stream = response;
|
||||||
|
|
||||||
let result = async {
|
|
||||||
while let Some(chunk) = stream.chunk().await? {
|
while let Some(chunk) = stream.chunk().await? {
|
||||||
file.write_all(&chunk).await?;
|
file.write_all(&chunk).await?;
|
||||||
downloaded += chunk.len() as u64;
|
downloaded += chunk.len() as u64;
|
||||||
@@ -333,15 +321,9 @@ async fn download_file_once(
|
|||||||
}
|
}
|
||||||
file.flush().await?;
|
file.flush().await?;
|
||||||
drop(file);
|
drop(file);
|
||||||
tokio::fs::rename(&temporary, dest).await?;
|
temporary.persist(dest).map_err(|error| error.error)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
.await;
|
|
||||||
if result.is_err() {
|
|
||||||
let _ = tokio::fs::remove_file(&temporary).await;
|
|
||||||
}
|
|
||||||
result
|
|
||||||
}
|
|
||||||
|
|
||||||
// body decode errors and timeouts are worth retrying, but a 404 or disk
|
// body decode errors and timeouts are worth retrying, but a 404 or disk
|
||||||
// error isn't. Parse errors stay non-retryable: by the time we hit one
|
// error isn't. Parse errors stay non-retryable: by the time we hit one
|
||||||
|
|||||||
+28
-61
@@ -537,25 +537,8 @@ pub async fn download_version_file(
|
|||||||
path.display()
|
path.display()
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
let temporary = destination.join(format!(".{}.{}.rmcl-download", file.filename, version.id));
|
let temporary = staged_version_file(client, file, destination).await?;
|
||||||
if temporary.exists() {
|
temporary.persist(&path).map_err(|error| error.error)?;
|
||||||
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();
|
|
||||||
Ok(DownloadOutcome::Downloaded(path))
|
Ok(DownloadOutcome::Downloaded(path))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -573,19 +556,21 @@ pub async fn download_version_file_for_update(
|
|||||||
return download_version_file(client, version, destination).await;
|
return download_version_file(client, version, destination).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
let temporary = destination.join(format!(".{}.{}.rmcl-download", file.filename, version.id));
|
let temporary = staged_version_file(client, file, destination).await?;
|
||||||
let backup = destination.join(format!(".{}.{}.rmcl-backup", file.filename, version.id));
|
temporary.persist(&target).map_err(|error| error.error)?;
|
||||||
if backup.exists() {
|
Ok(DownloadOutcome::Downloaded(target))
|
||||||
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?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 =
|
let progress =
|
||||||
crate::feedback::progress::ProgressTask::start(format!("Downloading {}", file.filename));
|
crate::feedback::progress::ProgressTask::start(format!("Downloading {}", file.filename));
|
||||||
crate::net::download_file(client, &file.url, &temporary, |current, total| {
|
crate::net::download_file(client, &file.url, &temporary, |current, total| {
|
||||||
@@ -593,22 +578,16 @@ pub async fn download_version_file_for_update(
|
|||||||
})
|
})
|
||||||
.await?;
|
.await?;
|
||||||
if !verify_version_file(&temporary, file)? {
|
if !verify_version_file(&temporary, file)? {
|
||||||
let _ = tokio::fs::remove_file(&temporary).await;
|
|
||||||
return Err(crate::net::NetError::Parse(format!(
|
return Err(crate::net::NetError::Parse(format!(
|
||||||
"Downloaded file '{}' failed its size or hash verification",
|
"Downloaded file '{}' failed its size or hash verification",
|
||||||
file.filename
|
file.filename
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
replace_installed_file(&temporary, &target, installed_path, &backup).await?;
|
Ok(temporary)
|
||||||
progress.finish();
|
|
||||||
Ok(DownloadOutcome::Downloaded(target))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn validate_path_component(value: &str, label: &str) -> Result<(), crate::net::NetError> {
|
fn validate_path_component(value: &str, label: &str) -> Result<(), crate::net::NetError> {
|
||||||
let mut components = std::path::Path::new(value).components();
|
if !crate::instance::manager::portable_component(value) {
|
||||||
if !matches!(components.next(), Some(std::path::Component::Normal(_)))
|
|
||||||
|| components.next().is_some()
|
|
||||||
{
|
|
||||||
return Err(crate::net::NetError::Parse(format!(
|
return Err(crate::net::NetError::Parse(format!(
|
||||||
"Invalid {label} '{value}'"
|
"Invalid {label} '{value}'"
|
||||||
)));
|
)));
|
||||||
@@ -634,24 +613,6 @@ fn verify_version_file(
|
|||||||
Ok(true)
|
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(
|
pub async fn fetch_version(
|
||||||
client: &crate::net::HttpClient,
|
client: &crate::net::HttpClient,
|
||||||
version_id: &str,
|
version_id: &str,
|
||||||
@@ -690,16 +651,22 @@ pub async fn resolve_version_files(
|
|||||||
.await
|
.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(
|
pub async fn download_mrpack(
|
||||||
client: &crate::net::HttpClient,
|
client: &crate::net::HttpClient,
|
||||||
version: &VersionInfo,
|
version: &VersionInfo,
|
||||||
dest: &std::path::Path,
|
dest: &std::path::Path,
|
||||||
) -> Result<std::path::PathBuf, crate::net::NetError> {
|
) -> 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),
|
DownloadOutcome::Downloaded(path) | DownloadOutcome::SkippedExisting(path) => Ok(path),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+63
-13
@@ -318,7 +318,7 @@ async fn content_download_rejects_an_unverifiable_existing_filename() {
|
|||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn content_download_rejects_provider_path_components() {
|
async fn content_download_rejects_provider_path_components() {
|
||||||
let directory = tempfile::tempdir().unwrap();
|
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(),
|
url: "https://example.test/escape.jar".to_owned(),
|
||||||
filename: "../escape.jar".to_owned(),
|
filename: "../escape.jar".to_owned(),
|
||||||
size: 1,
|
size: 1,
|
||||||
@@ -326,11 +326,21 @@ async fn content_download_rejects_provider_path_components() {
|
|||||||
hashes: HashMap::new(),
|
hashes: HashMap::new(),
|
||||||
}]);
|
}]);
|
||||||
|
|
||||||
let error = download_version_file(&crate::net::HttpClient::new(), &version, directory.path())
|
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
|
.await
|
||||||
.unwrap_err();
|
.unwrap_err();
|
||||||
|
|
||||||
assert!(error.to_string().contains("Invalid provider filename"));
|
assert!(error.to_string().contains("Invalid provider filename"));
|
||||||
|
}
|
||||||
assert!(
|
assert!(
|
||||||
!directory
|
!directory
|
||||||
.path()
|
.path()
|
||||||
@@ -343,19 +353,63 @@ async fn content_download_rejects_provider_path_components() {
|
|||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn staged_update_replaces_the_old_file_and_cleans_its_backup() {
|
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 directory = tempfile::tempdir().unwrap();
|
||||||
let installed = directory.path().join("example.jar");
|
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(&installed, b"old version").unwrap();
|
||||||
std::fs::write(&temporary, b"new version").unwrap();
|
let version = version_with_files(vec![VersionFile {
|
||||||
|
url: format!("{}/pack", server.uri()),
|
||||||
replace_installed_file(&temporary, &installed, &installed, &backup)
|
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
|
.await
|
||||||
.unwrap();
|
.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);
|
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]
|
#[test]
|
||||||
@@ -416,10 +470,6 @@ fn discovery_sort_maps_to_modrinth_indexes() {
|
|||||||
assert_eq!(discovery_index(DiscoverySort::Newest, ""), "newest");
|
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]
|
#[rstest::rstest]
|
||||||
#[case::ascii_unreserved("abcXYZ0-9_.~", "abcXYZ0-9_.~")]
|
#[case::ascii_unreserved("abcXYZ0-9_.~", "abcXYZ0-9_.~")]
|
||||||
#[case::space("hello world", "hello%20world")]
|
#[case::space("hello world", "hello%20world")]
|
||||||
|
|||||||
+1
-1
@@ -5,7 +5,7 @@ use std::io;
|
|||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
mod filesystem;
|
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 use filesystem::{write_atomic, write_atomic_private};
|
||||||
|
|
||||||
pub const MINECRAFT_DIR_NAME: &str = "minecraft";
|
pub const MINECRAFT_DIR_NAME: &str = "minecraft";
|
||||||
|
|||||||
+35
-30
@@ -3,9 +3,6 @@
|
|||||||
|
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::path::Path;
|
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<()> {
|
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||||
write_atomic_with_mode(path, bytes, false)
|
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<()> {
|
fn write_atomic_with_mode(path: &Path, bytes: &[u8], private: bool) -> io::Result<()> {
|
||||||
|
use std::io::Write;
|
||||||
|
|
||||||
let parent = path
|
let parent = path
|
||||||
.parent()
|
.parent()
|
||||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no 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)?;
|
std::fs::create_dir_all(parent)?;
|
||||||
let id = TEMP_FILE_ID.fetch_add(1, Ordering::Relaxed);
|
let mut builder = tempfile::Builder::new();
|
||||||
let name = path
|
builder.prefix(".rmcl-write-");
|
||||||
.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)]
|
#[cfg(unix)]
|
||||||
if private {
|
if !private {
|
||||||
use std::os::unix::fs::OpenOptionsExt;
|
use std::os::unix::fs::PermissionsExt;
|
||||||
options.mode(0o600);
|
builder.permissions(std::fs::Permissions::from_mode(0o666));
|
||||||
}
|
}
|
||||||
#[cfg(not(unix))]
|
#[cfg(not(unix))]
|
||||||
let _ = private;
|
let _ = private;
|
||||||
let mut file = options.open(&temporary)?;
|
let mut file = builder.tempfile_in(parent)?;
|
||||||
file.write_all(bytes)?;
|
file.write_all(bytes)?;
|
||||||
file.sync_all()?;
|
file.as_file().sync_all()?;
|
||||||
drop(file);
|
file.persist(path).map(|_| ()).map_err(|error| error.error)
|
||||||
std::fs::rename(&temporary, path)
|
|
||||||
})();
|
|
||||||
if result.is_err() {
|
|
||||||
let _ = std::fs::remove_file(&temporary);
|
|
||||||
}
|
}
|
||||||
result
|
|
||||||
|
#[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)]
|
#[cfg(unix)]
|
||||||
pub(crate) fn copy_symlink(source: &Path, destination: &Path) -> io::Result<()> {
|
pub(crate) fn copy_symlink_target(
|
||||||
std::os::unix::fs::symlink(std::fs::read_link(source)?, destination)
|
_source: &Path,
|
||||||
|
destination: &Path,
|
||||||
|
target: &Path,
|
||||||
|
) -> io::Result<()> {
|
||||||
|
std::os::unix::fs::symlink(target, destination)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
pub(crate) fn copy_symlink(source: &Path, destination: &Path) -> io::Result<()> {
|
pub(crate) fn copy_symlink_target(
|
||||||
let target = std::fs::read_link(source)?;
|
source: &Path,
|
||||||
if source.is_dir() {
|
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)
|
std::os::windows::fs::symlink_dir(target, destination)
|
||||||
} else {
|
} else {
|
||||||
std::os::windows::fs::symlink_file(target, destination)
|
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(path.join("keep")).unwrap(), b"old");
|
||||||
assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 1);
|
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
|
// returns a WorkerGuard that must be held alive for the duration of the
|
||||||
// program, otherwise the file logging thread gets dropped immediately.
|
// program, otherwise the file logging thread gets dropped immediately.
|
||||||
pub fn init() -> WorkerGuard {
|
pub fn init() -> WorkerGuard {
|
||||||
let log_dir = match dirs_next::cache_dir() {
|
let log_dir = match dirs::cache_dir() {
|
||||||
Some(d) => d.join("rmcl"),
|
Some(d) => d.join("rmcl"),
|
||||||
None => std::path::PathBuf::from("./cache"),
|
None => std::path::PathBuf::from("./cache"),
|
||||||
};
|
};
|
||||||
|
|||||||
+105
-4
@@ -77,8 +77,6 @@ async fn get_json_retries_rate_limit() {
|
|||||||
async fn get_json_fails_fast_on_4xx() {
|
async fn get_json_fails_fast_on_4xx() {
|
||||||
let server = MockServer::start().await;
|
let server = MockServer::start().await;
|
||||||
|
|
||||||
// expect(1) makes wiremock panic on drop if the mock matches more than
|
|
||||||
// once. that's how we assert "no retries" without watching the clock.
|
|
||||||
Mock::given(method("GET"))
|
Mock::given(method("GET"))
|
||||||
.and(path("/api"))
|
.and(path("/api"))
|
||||||
.respond_with(ResponseTemplate::new(404))
|
.respond_with(ResponseTemplate::new(404))
|
||||||
@@ -101,8 +99,6 @@ async fn get_json_fails_fast_on_4xx() {
|
|||||||
async fn get_json_gives_up_after_max_retries() {
|
async fn get_json_gives_up_after_max_retries() {
|
||||||
let server = MockServer::start().await;
|
let server = MockServer::start().await;
|
||||||
|
|
||||||
// MAX_RETRIES = 3 means we expect exactly 4 attempts before giving up.
|
|
||||||
// expect(4) asserts that.
|
|
||||||
Mock::given(method("GET"))
|
Mock::given(method("GET"))
|
||||||
.and(path("/api"))
|
.and(path("/api"))
|
||||||
.respond_with(ResponseTemplate::new(503))
|
.respond_with(ResponseTemplate::new(503))
|
||||||
@@ -192,3 +188,108 @@ async fn download_file_fails_fast_on_4xx() {
|
|||||||
"expected 404 in error, got: {err:?}"
|
"expected 404 in error, got: {err:?}"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn cancelled_downloads_preserve_the_destination_and_remove_all_staging_files() {
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
|
||||||
|
for verified in [false, true] {
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let address = listener.local_addr().unwrap();
|
||||||
|
let server = tokio::spawn(async move {
|
||||||
|
let (mut connection, _) = listener.accept().await.unwrap();
|
||||||
|
let mut request = [0; 4096];
|
||||||
|
assert!(connection.read(&mut request).await.unwrap() > 0);
|
||||||
|
connection
|
||||||
|
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\nConnection: close\r\n\r\nx")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
std::future::pending::<()>().await;
|
||||||
|
});
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let destination = temp.path().join("content.jar");
|
||||||
|
std::fs::write(&destination, b"original").unwrap();
|
||||||
|
let directory = temp.path().to_owned();
|
||||||
|
let target = destination.clone();
|
||||||
|
let download = tokio::spawn(async move {
|
||||||
|
let client = client_without_timeout();
|
||||||
|
let url = format!("http://{address}/content.jar");
|
||||||
|
if verified {
|
||||||
|
let version = serde_json::from_value(json!({
|
||||||
|
"id": "version", "name": "Version", "version_number": "1",
|
||||||
|
"game_versions": [], "loaders": [],
|
||||||
|
"files": [{"url": url, "filename": "content.jar", "size": 100, "primary": true}]
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
rmcl::net::modrinth::download_version_file_for_update(
|
||||||
|
&client, &version, &directory, &target,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map(|_| ())
|
||||||
|
} else {
|
||||||
|
download_file(&client, &url, &target, |_, _| {}).await
|
||||||
|
}
|
||||||
|
});
|
||||||
|
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||||
|
loop {
|
||||||
|
if std::fs::read_dir(temp.path()).unwrap().any(|entry| {
|
||||||
|
let entry = entry.unwrap();
|
||||||
|
entry.path() != destination && entry.metadata().unwrap().len() == 1
|
||||||
|
}) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
!download.is_finished(),
|
||||||
|
"download finished before cancellation"
|
||||||
|
);
|
||||||
|
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
download.abort();
|
||||||
|
assert!(download.await.unwrap_err().is_cancelled());
|
||||||
|
server.abort();
|
||||||
|
assert!(server.await.unwrap_err().is_cancelled());
|
||||||
|
assert_eq!(std::fs::read(&destination).unwrap(), b"original");
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_dir(temp.path()).unwrap().count(),
|
||||||
|
1,
|
||||||
|
"verified={verified}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn flowing_downloads_can_take_longer_than_thirty_seconds() {
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let address = listener.local_addr().unwrap();
|
||||||
|
let server = tokio::spawn(async move {
|
||||||
|
let (mut connection, _) = listener.accept().await.unwrap();
|
||||||
|
let mut request = [0; 4096];
|
||||||
|
assert!(connection.read(&mut request).await.unwrap() > 0);
|
||||||
|
connection
|
||||||
|
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 8\r\nConnection: close\r\n\r\nx")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
for _ in 0..7 {
|
||||||
|
tokio::time::sleep(std::time::Duration::from_millis(4500)).await;
|
||||||
|
if connection.write_all(b"x").await.is_err() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let path = temp.path().join("slow.bin");
|
||||||
|
let result = download_file(
|
||||||
|
&HttpClient::new(),
|
||||||
|
&format!("http://{address}/slow"),
|
||||||
|
&path,
|
||||||
|
|_, _| {},
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
server.await.unwrap();
|
||||||
|
result.unwrap();
|
||||||
|
assert_eq!(std::fs::read(path).unwrap(), b"xxxxxxxx");
|
||||||
|
}
|
||||||
Reference in new issue
Block a user