From 2062d47bccc056d768016dc5b4ab5f80c5644f89 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 22 Nov 2026 08:27:54 +0800 Subject: [PATCH] =?UTF-8?q?fix(remote):=20fs.readFile=20=E4=B8=8D=E9=98=BB?= =?UTF-8?q?=E5=A1=9E=E5=9C=A8=E5=91=BD=E5=90=8D=E7=AE=A1=E9=81=93=E4=B8=8A?= =?UTF-8?q?=EF=BC=8C=E5=8F=AA=E8=AF=BB=E5=8F=96=E6=99=AE=E9=80=9A=E6=96=87?= =?UTF-8?q?=E4=BB=B6=20(1lck/Lithe-IDEA#2270)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 以 O_NONBLOCK | O_NOCTTY 打开后检查打开的句柄:目录仍是 IS_A_DIRECTORY, 套接字、命名管道和设备返回 UNSUPPORTED(与 fs.copy 顶层拒绝特殊文件同一个码), 不再让没有写端的命名管道一直占住工作线程,也消除 stat 与打开之间被换成特殊文件的竞态。 --- .../contracts/remote-workspace-protocol-v1.md | 7 +- rust/crates/remote/src/server/fs.rs | 86 ++++++++++++++++++- 2 files changed, 91 insertions(+), 2 deletions(-) diff --git a/rust/contracts/remote-workspace-protocol-v1.md b/rust/contracts/remote-workspace-protocol-v1.md index 06681617..e79d40d2 100644 --- a/rust/contracts/remote-workspace-protocol-v1.md +++ b/rust/contracts/remote-workspace-protocol-v1.md @@ -123,7 +123,7 @@ subscribe before creating the resource. | `server.state` | — | running `processes` (`processId`, `pid`, `argv`, `label?`, `runningMs`, `leaderExited`), `terminals` (`terminalId`, `pid`, `argv`, `label?`, `runningMs`, `columns`, `rows`), `watches` | | `fs.stat` | `path` | metadata of the path itself (links not followed) | | `fs.readDir` | `path` | `entries` sorted by name byte order, `skippedNonUtf8` | -| `fs.readFile` | `path`, `offset`, `length` (≤ 8 MiB) | `data`, `eof`, `metadata` | +| `fs.readFile` | `path`, `offset`, `length` (≤ 8 MiB) | `data`, `eof`, `metadata`; only a regular file is read | | `fs.writeFile` | `path`, `data` (≤ 8 MiB), `expected?`, `overwrite`, `createParents` | metadata after the write | | `fs.createDir` | `path`, `recursive`, `mode?` (at most `0o7777`) | `null` | | `fs.remove` | `path`, `recursive` | `null`; links are removed, never followed | @@ -162,6 +162,11 @@ subscribe before creating the resource. | `listener.list` | — | `listeners` by `listenerId`: `listenerId`, `port`, `connections`, `failedConnections` | | `ports.listening` | — | `ports` sorted by `address` and `port`, one entry for each: `address`, `port`, and `pid` and `process` (the command name) when the server's user can inspect the owning process | +`fs.readFile` opens the path without blocking and checks the type of the +opened file, so a FIFO without a writer never holds the request and a path +replaced between `fs.stat` and the read is still checked. A directory fails +with `IS_A_DIRECTORY`; sockets, FIFOs and devices fail with `UNSUPPORTED`. + `fs.copy` refuses, with `INVALID_REQUEST`, to copy a file onto itself — directly, through a symbolic link in either direction or onto a hard link — and to copy a directory into itself after resolving links. Sockets, FIFOs and diff --git a/rust/crates/remote/src/server/fs.rs b/rust/crates/remote/src/server/fs.rs index c515ae2c..8a730ca4 100644 --- a/rust/crates/remote/src/server/fs.rs +++ b/rust/crates/remote/src/server/fs.rs @@ -180,7 +180,17 @@ fn read_file(params: ReadFileParams) -> Result { return Err(too_large(params.length)); } let path = host_path(¶ms.path)?; - let mut file = File::open(&path).map_err(|error| io_error(error, ¶ms.path))?; + // Opening a FIFO for reading blocks until a writer appears, which would + // hold a worker thread forever. O_NONBLOCK makes that open return at once, + // and checking the opened handle (not the path) means the type check and + // the read cover the same file even if the path is replaced in between. + // O_NOCTTY keeps a terminal device from becoming the daemon's controlling + // terminal. O_NONBLOCK has no effect on reads from a regular file. + let mut file = OpenOptions::new() + .read(true) + .custom_flags(libc::O_NONBLOCK | libc::O_NOCTTY) + .open(&path) + .map_err(|error| io_error(error, ¶ms.path))?; let metadata = file .metadata() .map_err(|error| io_error(error, ¶ms.path))?; @@ -190,6 +200,12 @@ fn read_file(params: ReadFileParams) -> Result { "cannot read a directory", )); } + if !metadata.is_file() { + return Err(RemoteError::new( + ErrorCode::Unsupported, + "sockets, FIFOs and devices cannot be read", + )); + } file.seek(SeekFrom::Start(params.offset)) .map_err(|error| io_error(error, ¶ms.path))?; let mut data = Vec::new(); @@ -646,6 +662,74 @@ mod tests { assert_eq!(file.metadata().unwrap().permissions().mode() & 0o777, 0o600); } + fn read_whole(path: &Path) -> Result { + read_file(ReadFileParams { + path: path.to_str().unwrap().to_owned(), + offset: 0, + length: 16, + }) + } + + // A FIFO with no writer must be refused at once instead of blocking the + // worker thread in open(2) until some process opens the other end. + #[test] + fn reading_a_fifo_without_a_writer_is_refused_without_blocking() { + let directory = std::env::temp_dir().join(format!( + "lithe-remote-fs-fifo-{}-{}", + std::process::id(), + TEMPORARY_FILE_COUNTER.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&directory).unwrap(); + let _cleanup = RemoveOnDrop(directory.clone()); + let fifo = directory.join("pipe"); + let status = std::process::Command::new("mkfifo") + .arg(&fifo) + .status() + .unwrap(); + assert!(status.success()); + + let (sender, receiver) = std::sync::mpsc::channel(); + let reader_path = fifo.clone(); + let reader = std::thread::spawn(move || { + let _ = sender.send(read_whole(&reader_path).map(|_| ())); + }); + let outcome = match receiver.recv_timeout(std::time::Duration::from_secs(10)) { + Ok(outcome) => outcome, + Err(_) => { + // Release the blocked reader so the thread and directory are + // cleaned up before the test fails. + drop(OpenOptions::new().write(true).open(&fifo)); + let _ = reader.join(); + panic!("fs.readFile blocked on a FIFO without a writer"); + } + }; + reader.join().unwrap(); + assert_eq!(outcome.unwrap_err().code, ErrorCode::Unsupported); + } + + #[test] + fn reading_a_device_is_refused_and_a_regular_file_still_reads() { + let error = read_whole(Path::new("/dev/zero")).unwrap_err(); + assert_eq!(error.code, ErrorCode::Unsupported); + + let directory = std::env::temp_dir().join(format!( + "lithe-remote-fs-read-{}-{}", + std::process::id(), + TEMPORARY_FILE_COUNTER.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&directory).unwrap(); + let _cleanup = RemoveOnDrop(directory.clone()); + assert_eq!( + read_whole(&directory).unwrap_err().code, + ErrorCode::IsADirectory + ); + let file = directory.join("plain"); + fs::write(&file, b"hello").unwrap(); + let result = read_whole(&file).unwrap(); + assert!(result.eof); + assert_eq!(decode_bytes(&result.data).unwrap(), b"hello"); + } + struct RemoveOnDrop(PathBuf); impl Drop for RemoveOnDrop {