fix(tui): apply username folders everywhere and resume in place

Move the sanitizer next to the directory helpers so the CLI download
command and the daemon honour use_username_dirs too, not only the TUI.
Resumed downloads keep the folder they were saved with instead of
nesting the username a second time, and toggling the setting applies
to the next download without a restart. Document the config key.
This commit is contained in:
Michel de Graaf
2026-10-22 14:19:18 +02:00
parent 9805b807e5
commit ea884535a8
14 changed files with 130 additions and 69 deletions
+65 -1
View File
@@ -50,9 +50,54 @@ pub fn resolve_shared_directories(dirs: &[String]) -> Vec<String> {
resolved
}
/// The folder a download from `username` lands in: `download_dir` itself, or
/// a per-user subfolder of it when `per_user` is set, as SoulseekQt does.
#[must_use]
pub fn download_dir_for(
download_dir: &str,
username: &str,
per_user: bool,
) -> String {
if !per_user {
return download_dir.to_string();
}
std::path::Path::new(download_dir)
.join(sanitize_path_component(username))
.display()
.to_string()
}
/// A peer-chosen name made safe as one path component: separators and
/// characters Windows refuses become `_`, so `../..` cannot climb out.
fn sanitize_path_component(name: &str) -> String {
let mut out: String = name
.chars()
.map(|c| match c {
'/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_',
c if c.is_control() => '_',
c => c,
})
.collect();
if out.is_empty() || out.ends_with(['.', ' ']) {
out.push('_');
}
if is_reserved(&out) {
out.insert(0, '_');
}
out
}
/// Windows device names (`CON`, `COM1`, …) that cannot be a folder name.
fn is_reserved(name: &str) -> bool {
let stem = name.split('.').next().unwrap_or(name).to_ascii_uppercase();
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
|| (matches!(stem.get(..3), Some("COM" | "LPT"))
&& matches!(stem.as_bytes().get(3..), Some([b'1'..=b'9'])))
}
#[cfg(test)]
mod tests {
use super::resolve_shared_directory;
use super::{download_dir_for, resolve_shared_directory};
use std::sync::atomic::{AtomicU32, Ordering};
fn unique_temp_dir() -> std::path::PathBuf {
@@ -97,4 +142,23 @@ mod tests {
assert!(result.is_err());
let _ = std::fs::remove_dir_all(dir);
}
fn dl(name: &str) -> String {
std::path::Path::new("/dl").join(name).display().to_string()
}
#[test]
fn per_user_folder_is_a_child_of_the_download_dir() {
assert_eq!(download_dir_for("/dl", "alice", false), "/dl");
assert_eq!(download_dir_for("/dl", "alice", true), dl("alice"));
}
#[test]
fn a_hostile_username_cannot_leave_the_download_dir() {
assert_eq!(download_dir_for("/dl", "../..", true), dl(".._.._"));
assert_eq!(download_dir_for("/dl", "/tmp/x", true), dl("_tmp_x"));
assert_eq!(download_dir_for("/dl", "..", true), dl(".._"));
assert_eq!(download_dir_for("/dl", "", true), dl("_"));
assert_eq!(download_dir_for("/dl", "com1", true), dl("_com1"));
}
}