mirror of
https://github.com/ratspeak/rsReticulum
synced 2026-11-22 23:10:33 +00:00
rngit: release names and the home directory follow Windows paths
This commit is contained in:
1 parent
b2b30181e2
commit
1f5dde228f
8 files changed
+404
-272
No files matched your search
@@ -184,7 +184,7 @@ fn main() {
|
||||
};
|
||||
let configdir = std::env::var_os("RNGIT_CONFIG").map(PathBuf::from);
|
||||
let rnsconfig = std::env::var("RNS_CONFIG").ok();
|
||||
let home = PathBuf::from(std::env::var_os("HOME").unwrap_or_default());
|
||||
let home = rns_runtime::platform::home_dir().unwrap_or_default();
|
||||
let configdir = resolve_config_dir(configdir.as_deref(), &home);
|
||||
|
||||
let config = match ClientConfig::load(&configdir) {
|
||||
|
||||
@@ -85,13 +85,16 @@ pub fn prettyhexrep(hash: &[u8]) -> String {
|
||||
format!("<{}>", hex::encode(hash))
|
||||
}
|
||||
|
||||
/// `os.path.expanduser`.
|
||||
/// `os.path.expanduser` for `~` and `~/...`, and `~\...` on Windows.
|
||||
pub fn expand_user(path: &str) -> PathBuf {
|
||||
let home = || std::env::var_os("HOME").map(PathBuf::from);
|
||||
let home = rns_runtime::platform::home_dir;
|
||||
if path == "~" {
|
||||
return home().unwrap_or_else(|| PathBuf::from(path));
|
||||
}
|
||||
match (path.strip_prefix("~/"), home()) {
|
||||
let rest = path
|
||||
.strip_prefix('~')
|
||||
.and_then(|rest| rest.strip_prefix(std::path::is_separator));
|
||||
match (rest, home()) {
|
||||
(Some(rest), Some(home)) => home.join(rest),
|
||||
_ => PathBuf::from(path),
|
||||
}
|
||||
@@ -661,8 +664,7 @@ pub fn fetch_release(
|
||||
"Release manifest validated, signed by {}",
|
||||
prettyhexrep(&manifest.signer)
|
||||
);
|
||||
let manifest_out = format!("{}_{}.rsm", manifest.text("name"), manifest.text("version"));
|
||||
let manifest_out = PathBuf::from(py_basename(&manifest_out));
|
||||
let manifest_out = manifest_file(&manifest.text("name"), &manifest.text("version"));
|
||||
std::fs::write(&manifest_out, &manifest.rsg)
|
||||
.map_err(|e| Fail::Abort(format!("Error fetching release: {e}")))?;
|
||||
|
||||
@@ -756,6 +758,11 @@ pub fn fetch_release(
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
/// The file a fetched manifest is saved as, in the working directory.
|
||||
fn manifest_file(name: &str, version: &str) -> PathBuf {
|
||||
PathBuf::from(py_basename(&format!("{name}_{version}.rsm")))
|
||||
}
|
||||
|
||||
/// `RELEASE_NOTES_TEMPLATE` (`server.py`).
|
||||
const RELEASE_NOTES_TEMPLATE: &str = "# Enter release notes for {TAG}.\n# Lines starting with '#' will be ignored.\n# Save and exit the editor when done, or exit without saving to abort.\n";
|
||||
|
||||
@@ -1100,3 +1107,47 @@ pub fn run_simple(
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::Component;
|
||||
|
||||
fn in_working_directory(path: &Path) -> bool {
|
||||
let mut components = path.components();
|
||||
matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none()
|
||||
}
|
||||
|
||||
/// A fetched manifest or artifact is saved under its base name in the
|
||||
/// working directory, whatever separators or drive the manifest names.
|
||||
#[test]
|
||||
fn fetched_release_files_land_in_the_working_directory() {
|
||||
for (name, windows) in [(r"..\..\x", "x"), (r"C:\Users\me\x", "x"), ("C:x", "x")] {
|
||||
let local = py_basename(name);
|
||||
assert_eq!(local, if cfg!(windows) { windows } else { name });
|
||||
assert!(in_working_directory(Path::new(local)), "{name}");
|
||||
}
|
||||
for (name, windows) in [(r"..\..\x", "x_1.0.rsm"), (r"C:\Users\me\x", "x_1.0.rsm")] {
|
||||
let local = manifest_file(name, "1.0");
|
||||
let expected = if cfg!(windows) {
|
||||
windows.to_string()
|
||||
} else {
|
||||
format!("{name}_1.0.rsm")
|
||||
};
|
||||
assert_eq!(local, PathBuf::from(expected));
|
||||
assert!(in_working_directory(&local), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_user_names_the_home() {
|
||||
if let Some(home) = rns_runtime::platform::home_dir() {
|
||||
assert_eq!(expand_user("~"), home);
|
||||
assert_eq!(expand_user("~/x"), home.join("x"));
|
||||
if cfg!(windows) {
|
||||
assert_eq!(expand_user(r"~\x"), home.join("x"));
|
||||
}
|
||||
}
|
||||
assert_eq!(expand_user("~other/x"), PathBuf::from("~other/x"));
|
||||
}
|
||||
}
|
||||
@@ -225,7 +225,7 @@ pub fn resolve_config_dir(configdir: Option<&Path>) -> PathBuf {
|
||||
if etc.is_dir() && etc.join("config").is_file() {
|
||||
return etc.to_path_buf();
|
||||
}
|
||||
let home = PathBuf::from(std::env::var_os("HOME").unwrap_or_default());
|
||||
let home = rns_runtime::platform::home_dir().unwrap_or_default();
|
||||
let user = home.join(".config/rngit");
|
||||
if user.is_dir() && user.join("config").is_file() {
|
||||
return user;
|
||||
@@ -258,11 +258,13 @@ pub fn load_or_create_identity(
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
/// Python `os.path.expanduser` for `~` and `~/...`.
|
||||
/// Python `os.path.expanduser` for `~` and `~/...`, and `~\...` on Windows.
|
||||
pub fn expand_user(path: &str) -> PathBuf {
|
||||
match path.strip_prefix('~') {
|
||||
Some(rest) if rest.is_empty() || rest.starts_with('/') => {
|
||||
let mut home = std::env::var_os("HOME").unwrap_or_default();
|
||||
Some(rest) if rest.is_empty() || rest.starts_with(std::path::is_separator) => {
|
||||
let mut home = rns_runtime::platform::home_dir()
|
||||
.unwrap_or_default()
|
||||
.into_os_string();
|
||||
home.push(rest);
|
||||
PathBuf::from(home)
|
||||
}
|
||||
|
||||
@@ -82,9 +82,10 @@ fn is_dot_tag(tag: &str) -> bool {
|
||||
matches!(tag, "." | "..")
|
||||
}
|
||||
|
||||
/// `posixpath.basename`: everything after the last `/`, so `"a/"` gives `""`.
|
||||
/// `os.path.basename` on this host: after the last `/`, so `"a/"` gives `""`;
|
||||
/// on Windows also after a `\` or a drive.
|
||||
pub(crate) fn py_basename(path: &str) -> &str {
|
||||
path.rsplit('/').next().unwrap_or(path)
|
||||
rns_runtime::platform::basename(path)
|
||||
}
|
||||
|
||||
/// `os.path.join(base, name)` for one component. A component keeps its own
|
||||
@@ -572,6 +573,13 @@ fn release_fetch(releases_path: &Path, data: &[(Value, Value)]) -> Result<Reply,
|
||||
)));
|
||||
}
|
||||
let tag = basename_of(&tag)?;
|
||||
// On Windows a tag such as `x\..` is `..` only once reduced to its base name.
|
||||
if is_dot_tag(&tag) {
|
||||
return Ok(Reply::Bytes(status(
|
||||
RES_INVALID_REQ,
|
||||
"Invalid tag specified",
|
||||
)));
|
||||
}
|
||||
let artifact = basename_of(&artifact)?;
|
||||
let tag = match resolve_latest(releases_path, &tag) {
|
||||
Ok(tag) => tag,
|
||||
@@ -974,3 +982,73 @@ pub fn handle_release(
|
||||
};
|
||||
Some(Reply::Bytes(reply))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn request(pairs: &[(&str, &str)]) -> Vec<(Value, Value)> {
|
||||
pairs
|
||||
.iter()
|
||||
.map(|(key, value)| (Value::from(*key), Value::from(*value)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A tag names one directory under the releases directory; on Windows its
|
||||
/// base name drops a `\` path or a drive.
|
||||
#[test]
|
||||
fn a_tag_names_one_release_directory() {
|
||||
for (tag, windows) in [(r"..\..\x", "x"), (r"C:\Users\me\x", "x"), ("C:x", "x")] {
|
||||
let found = lookup_tag(&request(&[("tag", tag)]))
|
||||
.ok()
|
||||
.flatten()
|
||||
.expect(tag);
|
||||
assert_eq!(found, if cfg!(windows) { windows } else { tag });
|
||||
let releases = Path::new("releases");
|
||||
assert_eq!(releases.join(&found).parent(), Some(releases), "{tag}");
|
||||
}
|
||||
let dotted = lookup_tag(&request(&[("tag", r"x\..")])).ok().flatten();
|
||||
assert_eq!(dotted.is_none(), cfg!(windows));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fetched_artifact_stays_in_its_release() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let releases = root.path().join("releases");
|
||||
std::fs::create_dir_all(releases.join("x").join("artifacts")).unwrap();
|
||||
std::fs::write(releases.join("x").join("artifacts").join("a.bin"), b"a").unwrap();
|
||||
// What a tag reduced to `..` would reach.
|
||||
std::fs::create_dir_all(root.path().join("artifacts")).unwrap();
|
||||
std::fs::write(root.path().join("artifacts").join("leak.bin"), b"leak").unwrap();
|
||||
let fetch = |tag: &str, artifact: &str| match release_fetch(
|
||||
&releases,
|
||||
&request(&[("tag", tag), ("artifact", artifact)]),
|
||||
) {
|
||||
Ok(Reply::File { metadata, .. }) => Ok(metadata),
|
||||
Ok(Reply::Bytes(reply)) => Err(reply[0]),
|
||||
Err(Raised) => panic!("{tag}: raised"),
|
||||
};
|
||||
let served = Value::Map(vec![(
|
||||
Value::from("name"),
|
||||
Value::Binary(b"a.bin".to_vec()),
|
||||
)]);
|
||||
let served = pack(&served).ok();
|
||||
for (tag, artifact) in [
|
||||
(r"..\..\x", r"..\..\a.bin"),
|
||||
(r"C:\Users\me\x", r"C:\a.bin"),
|
||||
] {
|
||||
let reply = fetch(tag, artifact);
|
||||
if cfg!(windows) {
|
||||
assert_eq!(reply.ok(), served, "{tag}");
|
||||
} else {
|
||||
assert_eq!(reply, Err(RES_NOT_FOUND), "{tag}");
|
||||
}
|
||||
}
|
||||
let dotted = if cfg!(windows) {
|
||||
RES_INVALID_REQ
|
||||
} else {
|
||||
RES_NOT_FOUND
|
||||
};
|
||||
assert_eq!(fetch(r"x\..", "leak.bin"), Err(dotted));
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ mod link_endpoint;
|
||||
pub mod link_manager;
|
||||
pub mod link_session;
|
||||
pub mod link_stamp;
|
||||
mod ntpath;
|
||||
pub mod platform;
|
||||
pub mod probe;
|
||||
pub mod remote_management;
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
//! Lexical `ntpath`: both separators, drive letters, and UNC shares. Plain
|
||||
//! string functions, so every host runs their tests.
|
||||
|
||||
const SEPS: [char; 2] = ['\\', '/'];
|
||||
|
||||
/// `ntpath.splitroot`: drive, root and tail.
|
||||
pub(crate) fn splitroot(path: &str) -> (&str, &str, &str) {
|
||||
let unified = path.replace('/', "\\");
|
||||
if unified.starts_with("\\\\") {
|
||||
// `\\server\share`, `\\?\UNC\server\share`, or a `\\?\` device.
|
||||
let start = if unified
|
||||
.get(..8)
|
||||
.is_some_and(|head| head.eq_ignore_ascii_case("\\\\?\\UNC\\"))
|
||||
{
|
||||
8
|
||||
} else {
|
||||
2
|
||||
};
|
||||
let Some(server) = unified[start..].find('\\').map(|i| start + i) else {
|
||||
return (path, "", "");
|
||||
};
|
||||
let Some(share) = unified[server + 1..].find('\\').map(|i| server + 1 + i) else {
|
||||
return (path, "", "");
|
||||
};
|
||||
(&path[..share], &path[share..share + 1], &path[share + 1..])
|
||||
} else if unified.starts_with('\\') {
|
||||
("", &path[..1], &path[1..])
|
||||
} else if let Some((colon, ':')) = path.char_indices().nth(1) {
|
||||
let drive = colon + 1;
|
||||
if unified[drive..].starts_with('\\') {
|
||||
(&path[..drive], &path[drive..drive + 1], &path[drive + 1..])
|
||||
} else {
|
||||
(&path[..drive], "", &path[drive..])
|
||||
}
|
||||
} else {
|
||||
("", "", path)
|
||||
}
|
||||
}
|
||||
|
||||
/// `ntpath.isabs` as of Python 3.13: a drive with a root, or a UNC or
|
||||
/// device path. A rooted `\x` takes the working drive, as Windows does.
|
||||
fn isabs(path: &str) -> bool {
|
||||
let head: String = path.chars().take(3).collect::<String>().replace('/', "\\");
|
||||
head.starts_with("\\\\") || head.chars().skip(1).eq([':', '\\'])
|
||||
}
|
||||
|
||||
fn fold(name: &str) -> String {
|
||||
name.replace('/', "\\").to_lowercase()
|
||||
}
|
||||
|
||||
/// `ntpath.join` of two paths.
|
||||
fn join<'a>(base: &'a str, path: &'a str) -> String {
|
||||
let (mut drive, mut root, base_tail) = splitroot(base);
|
||||
let mut tail = base_tail.to_string();
|
||||
let (path_drive, path_root, path_tail) = splitroot(path);
|
||||
if !path_root.is_empty() {
|
||||
if !path_drive.is_empty() || drive.is_empty() {
|
||||
drive = path_drive;
|
||||
}
|
||||
root = path_root;
|
||||
tail = path_tail.to_string();
|
||||
} else if !path_drive.is_empty() && fold(path_drive) != fold(drive) {
|
||||
(drive, root, tail) = (path_drive, path_root, path_tail.to_string());
|
||||
} else {
|
||||
if !path_drive.is_empty() {
|
||||
drive = path_drive;
|
||||
}
|
||||
if !tail.is_empty() && !tail.ends_with(SEPS) {
|
||||
tail.push('\\');
|
||||
}
|
||||
tail.push_str(path_tail);
|
||||
}
|
||||
if !tail.is_empty()
|
||||
&& root.is_empty()
|
||||
&& !drive.is_empty()
|
||||
&& !drive.ends_with([':', '\\', '/'])
|
||||
{
|
||||
return format!("{drive}\\{tail}");
|
||||
}
|
||||
format!("{drive}{root}{tail}")
|
||||
}
|
||||
|
||||
/// `ntpath.normpath`.
|
||||
pub(crate) fn normpath(path: &str) -> String {
|
||||
let unified = path.replace('/', "\\");
|
||||
let (drive, root, tail) = splitroot(&unified);
|
||||
let mut comps: Vec<&str> = Vec::new();
|
||||
for comp in tail.split('\\') {
|
||||
match comp {
|
||||
"" | "." => {}
|
||||
".." if comps.last().is_some_and(|last| *last != "..") => {
|
||||
comps.pop();
|
||||
}
|
||||
".." if comps.is_empty() && !root.is_empty() => {}
|
||||
_ => comps.push(comp),
|
||||
}
|
||||
}
|
||||
let prefix = format!("{drive}{root}");
|
||||
if prefix.is_empty() && comps.is_empty() {
|
||||
return ".".into();
|
||||
}
|
||||
format!("{prefix}{}", comps.join("\\"))
|
||||
}
|
||||
|
||||
/// `ntpath.abspath`, lexical only: a path on another drive without a
|
||||
/// root stays relative to that drive's own directory.
|
||||
pub(crate) fn abspath(path: &str, cwd: &str) -> String {
|
||||
if isabs(path) {
|
||||
normpath(path)
|
||||
} else {
|
||||
normpath(&join(cwd, path))
|
||||
}
|
||||
}
|
||||
|
||||
/// `ntpath.expanduser` for `~` and `~\...`; `~user` is left unchanged.
|
||||
pub(crate) fn expanduser(path: &str, home: Option<&str>) -> String {
|
||||
match (path.strip_prefix('~'), home) {
|
||||
(Some(rest), Some(home)) if rest.is_empty() || rest.starts_with(SEPS) => {
|
||||
format!("{home}{rest}")
|
||||
}
|
||||
_ => path.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `ntpath.basename`.
|
||||
pub(crate) fn basename(path: &str) -> &str {
|
||||
let (_, _, tail) = splitroot(path);
|
||||
tail.rsplit(SEPS).next().unwrap_or(tail)
|
||||
}
|
||||
|
||||
/// What `path` names below `dir`, comparing drives and components
|
||||
/// case-insensitively as Windows does; `None` unless strictly below.
|
||||
pub(crate) fn below(path: &str, dir: &str) -> Option<String> {
|
||||
let (path_drive, path_root, path_tail) = splitroot(path);
|
||||
let (dir_drive, dir_root, dir_tail) = splitroot(dir);
|
||||
if fold(path_drive) != fold(dir_drive) || path_root.is_empty() != dir_root.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut comps = path_tail.split(SEPS).filter(|comp| !comp.is_empty());
|
||||
for dir_comp in dir_tail.split(SEPS).filter(|comp| !comp.is_empty()) {
|
||||
if fold(comps.next()?) != fold(dir_comp) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let rest: Vec<&str> = comps.collect();
|
||||
(!rest.is_empty()).then(|| rest.join("\\"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn splits_drives_shares_and_devices() {
|
||||
for (path, split) in [
|
||||
(r"C:\a\b", ("C:", r"\", r"a\b")),
|
||||
("C:/a", ("C:", "/", "a")),
|
||||
("C:a", ("C:", "", "a")),
|
||||
(r"\\server\share\a", (r"\\server\share", r"\", "a")),
|
||||
("//server/share/a", ("//server/share", "/", "a")),
|
||||
(r"\\?\C:\a", (r"\\?\C:", r"\", "a")),
|
||||
(
|
||||
r"\\?\UNC\server\share\a",
|
||||
(r"\\?\UNC\server\share", r"\", "a"),
|
||||
),
|
||||
(r"\\server", (r"\\server", "", "")),
|
||||
(r"\a", ("", r"\", "a")),
|
||||
("a", ("", "", "a")),
|
||||
] {
|
||||
assert_eq!(splitroot(path), split, "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_against_the_working_directory() {
|
||||
let cwd = r"D:\work\dir";
|
||||
for (path, expected) in [
|
||||
("file.bin", r"D:\work\dir\file.bin"),
|
||||
("sub/./x/../file.bin", r"D:\work\dir\sub\file.bin"),
|
||||
(r"..\..\..\up", r"D:\up"),
|
||||
(r"\rooted", r"D:\rooted"),
|
||||
("C:/Temp/.tmpX", r"C:\Temp\.tmpX"),
|
||||
(r"C:\..\x", r"C:\x"),
|
||||
("d:rel", r"d:\work\dir\rel"),
|
||||
("C:rel", "C:rel"),
|
||||
(r"\\server\share\..\x", r"\\server\share\x"),
|
||||
] {
|
||||
assert_eq!(abspath(path, cwd), expected, "{path}");
|
||||
}
|
||||
assert_eq!(abspath("x", r"\\server\share\dir"), r"\\server\share\dir\x");
|
||||
assert_eq!(normpath(""), ".");
|
||||
assert_eq!(normpath(r"a\..\..\b"), r"..\b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expands_the_windows_home() {
|
||||
let home = Some(r"C:\Users\me");
|
||||
assert_eq!(expanduser("~", home), r"C:\Users\me");
|
||||
assert_eq!(expanduser(r"~\files", home), r"C:\Users\me\files");
|
||||
assert_eq!(expanduser("~/files", home), r"C:\Users\me/files");
|
||||
assert_eq!(expanduser(r"~other\files", home), r"~other\files");
|
||||
assert_eq!(expanduser(r"~\files", None), r"~\files");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basename_takes_the_last_name_after_either_separator() {
|
||||
for (path, name) in [
|
||||
(r"C:\jail\file.bin", "file.bin"),
|
||||
(r"dir/sub\file.bin", "file.bin"),
|
||||
(r"..\..\evil.bin", "evil.bin"),
|
||||
("C:evil.bin", "evil.bin"),
|
||||
(r"\\server\share", ""),
|
||||
("plain.bin", "plain.bin"),
|
||||
] {
|
||||
assert_eq!(basename(path), name, "{path}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -106,6 +106,16 @@ pub fn home_dir() -> Option<PathBuf> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `os.path.basename` on this host: `ntpath` on Windows, so either separator
|
||||
/// and a drive end the directory part; `posixpath` elsewhere.
|
||||
pub fn basename(path: &str) -> &str {
|
||||
if cfg!(windows) {
|
||||
crate::ntpath::basename(path)
|
||||
} else {
|
||||
path.rsplit('/').next().unwrap_or(path)
|
||||
}
|
||||
}
|
||||
|
||||
fn windows_home(home: Option<OsString>, userprofile: Option<OsString>) -> Option<PathBuf> {
|
||||
home.into_iter()
|
||||
.chain(userprofile)
|
||||
@@ -183,6 +193,15 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basename_follows_the_host() {
|
||||
for name in [r"..\..\x", r"C:\Users\me\x"] {
|
||||
let expected = if cfg!(windows) { "x" } else { name };
|
||||
assert_eq!(basename(name), expected);
|
||||
}
|
||||
assert_eq!(basename("dir/x"), "x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_home_falls_back_to_the_user_profile() {
|
||||
let profile = Some(OsString::from(r"C:\Users\me"));
|
||||
|
||||
+23
-260
@@ -28,6 +28,7 @@ use crate::lifecycle::ShutdownSignal;
|
||||
use crate::link_manager::{
|
||||
DestinationRequest, LinkManager, RequestOutcome, ResourceFileCompletion,
|
||||
};
|
||||
use crate::ntpath;
|
||||
use crate::resource_source::{PreparedResourceSource, ResourceOptions, ResourceSource};
|
||||
use crate::resource_spool::ResourceSpool;
|
||||
use rns_identity::destination::AllowPolicy;
|
||||
@@ -326,11 +327,6 @@ fn escapes_jail(path: &str, jail: &str) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// `os.path.basename`.
|
||||
fn basename(path: &str) -> &str {
|
||||
path.rsplit('/').next().unwrap_or(path)
|
||||
}
|
||||
|
||||
// rncp's paths follow the host's `os.path`: `ntpath` on Windows, where the
|
||||
// POSIX string handling cannot name a drive and refuses every jailed fetch.
|
||||
|
||||
@@ -347,185 +343,28 @@ fn host_jail(jail: &str) -> String {
|
||||
fn host_fetch_request_path(jail: Option<&str>, data: &str) -> Option<String> {
|
||||
let (home, cwd) = (process_home(), process_cwd());
|
||||
if cfg!(windows) {
|
||||
ntpath::fetch_request_path(jail, data, home.as_deref(), &cwd)
|
||||
nt_fetch_request_path(jail, data, home.as_deref(), &cwd)
|
||||
} else {
|
||||
fetch_request_path(jail, data, home.as_deref(), &cwd)
|
||||
}
|
||||
}
|
||||
|
||||
fn host_basename(path: &str) -> &str {
|
||||
if cfg!(windows) {
|
||||
ntpath::basename(path)
|
||||
} else {
|
||||
basename(path)
|
||||
}
|
||||
}
|
||||
|
||||
/// Lexical `ntpath`: both separators, drive letters and UNC shares. Plain
|
||||
/// string functions, so every host runs their tests.
|
||||
mod ntpath {
|
||||
const SEPS: [char; 2] = ['\\', '/'];
|
||||
|
||||
/// `ntpath.splitroot`: drive, root and tail.
|
||||
pub(super) fn splitroot(path: &str) -> (&str, &str, &str) {
|
||||
let unified = path.replace('/', "\\");
|
||||
if unified.starts_with("\\\\") {
|
||||
// `\\server\share`, `\\?\UNC\server\share`, or a `\\?\` device.
|
||||
let start = if unified
|
||||
.get(..8)
|
||||
.is_some_and(|head| head.eq_ignore_ascii_case("\\\\?\\UNC\\"))
|
||||
{
|
||||
8
|
||||
} else {
|
||||
2
|
||||
};
|
||||
let Some(server) = unified[start..].find('\\').map(|i| start + i) else {
|
||||
return (path, "", "");
|
||||
};
|
||||
let Some(share) = unified[server + 1..].find('\\').map(|i| server + 1 + i) else {
|
||||
return (path, "", "");
|
||||
};
|
||||
(&path[..share], &path[share..share + 1], &path[share + 1..])
|
||||
} else if unified.starts_with('\\') {
|
||||
("", &path[..1], &path[1..])
|
||||
} else if let Some((colon, ':')) = path.char_indices().nth(1) {
|
||||
let drive = colon + 1;
|
||||
if unified[drive..].starts_with('\\') {
|
||||
(&path[..drive], &path[drive..drive + 1], &path[drive + 1..])
|
||||
} else {
|
||||
(&path[..drive], "", &path[drive..])
|
||||
}
|
||||
} else {
|
||||
("", "", path)
|
||||
}
|
||||
}
|
||||
|
||||
/// `ntpath.isabs` as of Python 3.13: a drive with a root, or a UNC or
|
||||
/// device path. A rooted `\x` takes the working drive, as Windows does.
|
||||
fn isabs(path: &str) -> bool {
|
||||
let head: String = path.chars().take(3).collect::<String>().replace('/', "\\");
|
||||
head.starts_with("\\\\") || head.chars().skip(1).eq([':', '\\'])
|
||||
}
|
||||
|
||||
fn fold(name: &str) -> String {
|
||||
name.replace('/', "\\").to_lowercase()
|
||||
}
|
||||
|
||||
/// `ntpath.join` of two paths.
|
||||
fn join<'a>(base: &'a str, path: &'a str) -> String {
|
||||
let (mut drive, mut root, base_tail) = splitroot(base);
|
||||
let mut tail = base_tail.to_string();
|
||||
let (path_drive, path_root, path_tail) = splitroot(path);
|
||||
if !path_root.is_empty() {
|
||||
if !path_drive.is_empty() || drive.is_empty() {
|
||||
drive = path_drive;
|
||||
}
|
||||
root = path_root;
|
||||
tail = path_tail.to_string();
|
||||
} else if !path_drive.is_empty() && fold(path_drive) != fold(drive) {
|
||||
(drive, root, tail) = (path_drive, path_root, path_tail.to_string());
|
||||
} else {
|
||||
if !path_drive.is_empty() {
|
||||
drive = path_drive;
|
||||
}
|
||||
if !tail.is_empty() && !tail.ends_with(SEPS) {
|
||||
tail.push('\\');
|
||||
}
|
||||
tail.push_str(path_tail);
|
||||
}
|
||||
if !tail.is_empty()
|
||||
&& root.is_empty()
|
||||
&& !drive.is_empty()
|
||||
&& !drive.ends_with([':', '\\', '/'])
|
||||
{
|
||||
return format!("{drive}\\{tail}");
|
||||
}
|
||||
format!("{drive}{root}{tail}")
|
||||
}
|
||||
|
||||
/// `ntpath.normpath`.
|
||||
pub(super) fn normpath(path: &str) -> String {
|
||||
let unified = path.replace('/', "\\");
|
||||
let (drive, root, tail) = splitroot(&unified);
|
||||
let mut comps: Vec<&str> = Vec::new();
|
||||
for comp in tail.split('\\') {
|
||||
match comp {
|
||||
"" | "." => {}
|
||||
".." if comps.last().is_some_and(|last| *last != "..") => {
|
||||
comps.pop();
|
||||
}
|
||||
".." if comps.is_empty() && !root.is_empty() => {}
|
||||
_ => comps.push(comp),
|
||||
}
|
||||
}
|
||||
let prefix = format!("{drive}{root}");
|
||||
if prefix.is_empty() && comps.is_empty() {
|
||||
return ".".into();
|
||||
}
|
||||
format!("{prefix}{}", comps.join("\\"))
|
||||
}
|
||||
|
||||
/// `ntpath.abspath`, lexical only: a path on another drive without a
|
||||
/// root stays relative to that drive's own directory.
|
||||
pub(super) fn abspath(path: &str, cwd: &str) -> String {
|
||||
if isabs(path) {
|
||||
normpath(path)
|
||||
} else {
|
||||
normpath(&join(cwd, path))
|
||||
}
|
||||
}
|
||||
|
||||
/// `ntpath.expanduser` for `~` and `~\...`; `~user` is left unchanged.
|
||||
pub(super) fn expanduser(path: &str, home: Option<&str>) -> String {
|
||||
match (path.strip_prefix('~'), home) {
|
||||
(Some(rest), Some(home)) if rest.is_empty() || rest.starts_with(SEPS) => {
|
||||
format!("{home}{rest}")
|
||||
}
|
||||
_ => path.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `ntpath.basename`.
|
||||
pub(super) fn basename(path: &str) -> &str {
|
||||
let (_, _, tail) = splitroot(path);
|
||||
tail.rsplit(SEPS).next().unwrap_or(tail)
|
||||
}
|
||||
|
||||
/// What `path` names below `dir`, comparing drives and components
|
||||
/// case-insensitively as Windows does; `None` unless strictly below.
|
||||
pub(super) fn below(path: &str, dir: &str) -> Option<String> {
|
||||
let (path_drive, path_root, path_tail) = splitroot(path);
|
||||
let (dir_drive, dir_root, dir_tail) = splitroot(dir);
|
||||
if fold(path_drive) != fold(dir_drive) || path_root.is_empty() != dir_root.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut comps = path_tail.split(SEPS).filter(|comp| !comp.is_empty());
|
||||
for dir_comp in dir_tail.split(SEPS).filter(|comp| !comp.is_empty()) {
|
||||
if fold(comps.next()?) != fold(dir_comp) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let rest: Vec<&str> = comps.collect();
|
||||
(!rest.is_empty()).then(|| rest.join("\\"))
|
||||
}
|
||||
|
||||
/// rncp.py's jail rule on Windows: a request already under the jail is
|
||||
/// taken relative to it, and the result must stay strictly inside by
|
||||
/// component. `jail` is already absolute and normalised.
|
||||
pub(super) fn fetch_request_path(
|
||||
jail: Option<&str>,
|
||||
data: &str,
|
||||
home: Option<&str>,
|
||||
cwd: &str,
|
||||
) -> Option<String> {
|
||||
match jail {
|
||||
Some(jail) => {
|
||||
let data = below(data, jail).unwrap_or_else(|| data.to_string());
|
||||
let path = abspath(&expanduser(&format!("{jail}\\{data}"), home), cwd);
|
||||
below(&path, jail).is_some().then_some(path)
|
||||
}
|
||||
None => Some(abspath(&expanduser(data, home), cwd)),
|
||||
/// rncp.py's jail rule on Windows: a request already under the jail is
|
||||
/// taken relative to it, and the result must stay strictly inside by
|
||||
/// component. `jail` is already absolute and normalised.
|
||||
fn nt_fetch_request_path(
|
||||
jail: Option<&str>,
|
||||
data: &str,
|
||||
home: Option<&str>,
|
||||
cwd: &str,
|
||||
) -> Option<String> {
|
||||
match jail {
|
||||
Some(jail) => {
|
||||
let data = ntpath::below(data, jail).unwrap_or_else(|| data.to_string());
|
||||
let path = ntpath::abspath(&ntpath::expanduser(&format!("{jail}\\{data}"), home), cwd);
|
||||
ntpath::below(&path, jail).is_some().then_some(path)
|
||||
}
|
||||
None => Some(ntpath::abspath(&ntpath::expanduser(data, home), cwd)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -832,7 +671,7 @@ fn serve_fetch(
|
||||
return RequestOutcome::ReplyValue(FetchReply::NotFound.packed());
|
||||
};
|
||||
let bytes = file.metadata().map_or(0, |meta| meta.len() as usize);
|
||||
let name = host_basename(&path).to_string();
|
||||
let name = crate::platform::basename(&path).to_string();
|
||||
let metadata = pack_metadata(&name);
|
||||
let _ = events.try_send(RncpEvent::FetchServing {
|
||||
link_id,
|
||||
@@ -897,7 +736,7 @@ async fn save_received_file(
|
||||
|
||||
fn save_path_for(save_dir: &Path, file_name: &str, overwrite: bool) -> Result<PathBuf, String> {
|
||||
// rncp.py: the basename must name an entry directly in save_dir.
|
||||
let basename = host_basename(file_name).to_string();
|
||||
let basename = crate::platform::basename(file_name).to_string();
|
||||
if basename.is_empty() || basename == "." || basename == ".." {
|
||||
return Err(format!("invalid save path for {file_name:?}"));
|
||||
}
|
||||
@@ -2389,82 +2228,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rncp_paths_follow_the_host() {
|
||||
let name = r"dir\file.bin";
|
||||
let expected = if cfg!(windows) { "file.bin" } else { name };
|
||||
assert_eq!(host_basename(name), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ntpath_splits_drives_shares_and_devices() {
|
||||
for (path, split) in [
|
||||
(r"C:\a\b", ("C:", r"\", r"a\b")),
|
||||
("C:/a", ("C:", "/", "a")),
|
||||
("C:a", ("C:", "", "a")),
|
||||
(r"\\server\share\a", (r"\\server\share", r"\", "a")),
|
||||
("//server/share/a", ("//server/share", "/", "a")),
|
||||
(r"\\?\C:\a", (r"\\?\C:", r"\", "a")),
|
||||
(
|
||||
r"\\?\UNC\server\share\a",
|
||||
(r"\\?\UNC\server\share", r"\", "a"),
|
||||
),
|
||||
(r"\\server", (r"\\server", "", "")),
|
||||
(r"\a", ("", r"\", "a")),
|
||||
("a", ("", "", "a")),
|
||||
] {
|
||||
assert_eq!(ntpath::splitroot(path), split, "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ntpath_resolves_against_the_working_directory() {
|
||||
let cwd = r"D:\work\dir";
|
||||
for (path, expected) in [
|
||||
("file.bin", r"D:\work\dir\file.bin"),
|
||||
("sub/./x/../file.bin", r"D:\work\dir\sub\file.bin"),
|
||||
(r"..\..\..\up", r"D:\up"),
|
||||
(r"\rooted", r"D:\rooted"),
|
||||
("C:/Temp/.tmpX", r"C:\Temp\.tmpX"),
|
||||
(r"C:\..\x", r"C:\x"),
|
||||
("d:rel", r"d:\work\dir\rel"),
|
||||
("C:rel", "C:rel"),
|
||||
(r"\\server\share\..\x", r"\\server\share\x"),
|
||||
] {
|
||||
assert_eq!(ntpath::abspath(path, cwd), expected, "{path}");
|
||||
}
|
||||
assert_eq!(
|
||||
ntpath::abspath("x", r"\\server\share\dir"),
|
||||
r"\\server\share\dir\x"
|
||||
);
|
||||
assert_eq!(ntpath::normpath(""), ".");
|
||||
assert_eq!(ntpath::normpath(r"a\..\..\b"), r"..\b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ntpath_expands_the_windows_home() {
|
||||
let home = Some(r"C:\Users\me");
|
||||
assert_eq!(ntpath::expanduser("~", home), r"C:\Users\me");
|
||||
assert_eq!(ntpath::expanduser(r"~\files", home), r"C:\Users\me\files");
|
||||
assert_eq!(ntpath::expanduser("~/files", home), r"C:\Users\me/files");
|
||||
assert_eq!(ntpath::expanduser(r"~other\files", home), r"~other\files");
|
||||
assert_eq!(ntpath::expanduser(r"~\files", None), r"~\files");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ntpath_basename_takes_the_last_name_after_either_separator() {
|
||||
for (path, name) in [
|
||||
(r"C:\jail\file.bin", "file.bin"),
|
||||
(r"dir/sub\file.bin", "file.bin"),
|
||||
(r"..\..\evil.bin", "evil.bin"),
|
||||
("C:evil.bin", "evil.bin"),
|
||||
(r"\\server\share", ""),
|
||||
("plain.bin", "plain.bin"),
|
||||
] {
|
||||
assert_eq!(ntpath::basename(path), name, "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ntpath_jail_holds_fetches_by_component() {
|
||||
// The Windows CI jail: a temporary directory on another drive.
|
||||
@@ -2472,7 +2235,7 @@ mod tests {
|
||||
let tmp = r"C:\Users\RUNNER~1\AppData\Local\Temp\.tmpAbC123";
|
||||
let jail = ntpath::abspath(&ntpath::expanduser(tmp, None), cwd);
|
||||
assert_eq!(jail, tmp);
|
||||
let fetch = |data: &str| ntpath::fetch_request_path(Some(&jail), data, None, cwd);
|
||||
let fetch = |data: &str| nt_fetch_request_path(Some(&jail), data, None, cwd);
|
||||
let inside = |rest: &str| Some(format!(r"{jail}\{rest}"));
|
||||
assert_eq!(fetch("file.bin"), inside("file.bin"));
|
||||
assert_eq!(fetch("sub/file.bin"), inside(r"sub\file.bin"));
|
||||
@@ -2500,16 +2263,16 @@ mod tests {
|
||||
}
|
||||
|
||||
let share = r"\\server\share\jail";
|
||||
let fetch = |data: &str| ntpath::fetch_request_path(Some(share), data, None, cwd);
|
||||
let fetch = |data: &str| nt_fetch_request_path(Some(share), data, None, cwd);
|
||||
assert_eq!(fetch("x/y"), Some(r"\\server\share\jail\x\y".into()));
|
||||
assert_eq!(fetch(r"..\..\other\x"), None);
|
||||
assert_eq!(fetch(r"..\jail-other\x"), None);
|
||||
assert_eq!(
|
||||
ntpath::fetch_request_path(Some(r"C:\"), "x", None, cwd),
|
||||
nt_fetch_request_path(Some(r"C:\"), "x", None, cwd),
|
||||
Some(r"C:\x".into())
|
||||
);
|
||||
assert_eq!(
|
||||
ntpath::fetch_request_path(None, r"~\x.bin", Some(r"C:\Users\me"), cwd),
|
||||
nt_fetch_request_path(None, r"~\x.bin", Some(r"C:\Users\me"), cwd),
|
||||
Some(r"C:\Users\me\x.bin".into())
|
||||
);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user