diff --git a/crates/ide-ssh/Cargo.toml b/crates/ide-ssh/Cargo.toml index 125c71fcdc..5f6b0ed911 100644 --- a/crates/ide-ssh/Cargo.toml +++ b/crates/ide-ssh/Cargo.toml @@ -32,5 +32,5 @@ tokio-rustls = { version = "0.26", default-features = false } testing = ["keyring-core/sample"] [dev-dependencies] -tokio = { workspace = true, features = ["rt-multi-thread", "macros"] } +tokio = { workspace = true, features = ["rt-multi-thread", "macros", "net", "io-util"] } keyring-core = { workspace = true, features = ["sample"] } diff --git a/crates/ide-ssh/src/ftp.rs b/crates/ide-ssh/src/ftp.rs index 6b30f32efc..a0b21c1043 100644 --- a/crates/ide-ssh/src/ftp.rs +++ b/crates/ide-ssh/src/ftp.rs @@ -84,6 +84,19 @@ fn mfmt_time(seconds: u32) -> String { format!("{year:04}{month:02}{day:02}{:02}{:02}{:02}", rem / 3600, rem / 60 % 60, rem % 60) } +/// A folder known only to exist: no size, time or permissions. +fn folder(name: &str, path: &str) -> RemoteEntry { + RemoteEntry { + name: name.to_owned(), + path: path.to_owned(), + is_dir: true, + is_symlink: false, + size: 0, + mtime: None, + permissions: String::new(), + } +} + /// One logged-in FTP control connection; operations take turns on it. pub struct FtpFs { ftp: tokio::sync::Mutex, @@ -172,19 +185,18 @@ impl FtpFs { pub async fn stat(&self, path: &str) -> IdeResult> { let path = path.trim_end_matches('/'); let Some(dir) = parent(path) else { - return Ok(self.is_dir("/").await.then(|| RemoteEntry { - name: "/".into(), - path: "/".into(), - is_dir: true, - is_symlink: false, - size: 0, - mtime: None, - permissions: String::new(), - })); + return Ok(self.is_dir("/").await.then(|| folder("/", "/"))); }; let name = &path[dir.len()..].trim_start_matches('/'); + // The login folder's parent is often off limits, and a refused listing can leave the + // server unable to open the next data connection (bunny.net over FTPS). + if path == self.home.trim_end_matches('/') { + return Ok(self.is_dir(path).await.then(|| folder(name, path))); + } match self.list(dir).await { Ok(entries) => Ok(entries.into_iter().find(|e| e.name == *name)), + // Servers that lock the user into a folder may refuse to list its parent. + Err(_) if self.is_dir(path).await => Ok(Some(folder(name, path))), Err(e) if e.kind == ErrorKind::NotFound => Ok(None), Err(e) => Err(e), } @@ -192,9 +204,12 @@ impl FtpFs { /// Entries of `dir`, folders first, then by name; symlinks to folders count as folders. pub async fn list(&self, dir: &str) -> IdeResult> { + // Some servers (bunny.net Storage) list a folder only when its path ends with `/`. + let target = if dir.ends_with('/') { dir.to_owned() } else { format!("{dir}/") }; let lines = { let mut ftp = self.ftp.lock().await; - if self.mlsd { ftp.mlsd(Some(dir)).await } else { ftp.list(Some(dir)).await }.map_err(|e| err(dir, e))? + if self.mlsd { ftp.mlsd(Some(&target)).await } else { ftp.list(Some(&target)).await } + .map_err(|e| err(dir, e))? }; let mut out = Vec::new(); for line in lines { @@ -393,4 +408,99 @@ mod tests { assert_eq!(mfmt_time(951_782_400), "20000229000000"); assert_eq!(mfmt_time(1_794_484_245), "20261112115045"); } + + /// A server that locks the user into `/zone/` but shows its real path (bunny.net Storage): + /// it refuses `LIST /` and folder paths without a trailing `/`, and answers `LIST /locked/` with `550`. + async fn locked_in_server() -> (u16, Arc>>) { + use tokio::io::{AsyncBufReadExt, BufReader}; + use tokio::net::TcpListener; + + let control = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = control.local_addr().unwrap().port(); + let seen = Arc::new(std::sync::Mutex::new(Vec::new())); + let log = seen.clone(); + tokio::spawn(async move { + let (stream, _) = control.accept().await.unwrap(); + let (read, mut write) = stream.into_split(); + let mut lines = BufReader::new(read).lines(); + let mut data: Option = None; + write.write_all(b"220 Service Ready.\r\n").await.unwrap(); + while let Ok(Some(line)) = lines.next_line().await { + log.lock().unwrap().push(line.clone()); + let (cmd, arg) = line.split_once(' ').unwrap_or((line.as_str(), "")); + let reply: String = match (cmd.to_ascii_uppercase().as_str(), arg) { + ("USER", _) => "331 Password required\r\n".into(), + ("PASS", _) => "230 User logged in\r\n".into(), + ("TYPE", _) => "200 Type set\r\n".into(), + ("PWD", _) => "257 \"/zone/\" is current directory.\r\n".into(), + ("FEAT", _) => "211-Extensions supported:\r\n UTF8\r\n211 End\r\n".into(), + ("CWD", "/zone" | "/zone/" | "/zone/data" | "/shared" | "/locked/home") => "250 OK\r\n".into(), + ("CWD", _) => "550 No such folder\r\n".into(), + ("PASV", _) => { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let p = listener.local_addr().unwrap().port(); + data = Some(listener); + format!("227 Entering Passive Mode (127,0,0,1,{},{})\r\n", p >> 8, p & 0xff) + } + ("LIST", target) => { + let (mut conn, _) = data.take().unwrap().accept().await.unwrap(); + match target { + "/zone/" => { + write.write_all(b"150 Opening Ascii mode data transfer for LIST\r\n").await.unwrap(); + conn.write_all(b"drwxr-xr-x 1 zone zone 0 Jan 01 00:00 data\r\n").await.unwrap(); + drop(conn); + "226 Transfer complete\r\n".into() + } + "/locked/" => "550 Permission denied\r\n".into(), + _ => "450 Requested file action not taken\r\n".into(), + } + } + ("QUIT", _) => { + write.write_all(b"221 Bye\r\n").await.unwrap(); + break; + } + _ => "502 Command not implemented\r\n".into(), + }; + write.write_all(reply.as_bytes()).await.unwrap(); + } + }); + (port, seen) + } + + #[tokio::test] + async fn stat_falls_back_to_cwd_when_the_parent_cannot_be_listed() { + let (port, seen) = locked_in_server().await; + let connection = + FtpConnection { host: "127.0.0.1".into(), port: Some(port), user: "zone".into(), passive: true }; + let fs = FtpFs::connect(&connection, false, Some("pw".into())).await.unwrap(); + + // The login folder: `CWD` only, its parent is never listed. + let home = fs.stat("/zone/").await.unwrap().expect("the login folder"); + assert!(home.is_dir); + assert_eq!((home.name.as_str(), home.path.as_str()), ("zone", "/zone")); + assert_eq!((home.size, home.mtime, home.permissions.as_str()), (0, None, "")); + assert!(!seen.lock().unwrap().iter().any(|c| c == "LIST /")); + + // Another folder whose parent is refused. + let shared = fs.stat("/shared").await.unwrap().expect("a folder found with CWD"); + assert!(shared.is_dir); + assert_eq!((shared.name.as_str(), shared.path.as_str()), ("shared", "/shared")); + + // The parent listing works: no `CWD` fallback. + let data = fs.stat("/zone/data").await.unwrap().expect("a listed folder"); + assert!(data.is_dir); + assert!(!seen.lock().unwrap().iter().any(|c| c == "CWD /zone/data")); + + // Both fail: the listing error, not the `CWD` one. + let missing = fs.stat("/missing").await.unwrap_err(); + assert_eq!(missing.message, "/: 450 Requested file action not taken"); + + // A parent answered with `550`: the fallback runs, and without it the path doesn't exist. + assert!(fs.stat("/locked/home").await.unwrap().is_some_and(|e| e.is_dir)); + assert!(fs.stat("/locked/none").await.unwrap().is_none()); + + let names: Vec<_> = fs.list("/zone").await.unwrap().into_iter().map(|e| e.name).collect(); + assert_eq!(names, ["data"]); + fs.close().await; + } }