agentmux_srv/server/editor_handlers/
file_io.rs1use std::path::Path;
9
10use super::{editor_may_change, is_a_home, remote_fs};
11use crate::backend::base::expand_home_dir_safe;
12use crate::backend::rpc_types::{
13 CommandReadEditorFileData, CommandReadEditorFileResult, CommandWriteEditorFileData, CreateEditorDirReq,
14 CreateEditorDirResult, CreateEditorFileReq, CreateEditorFileResult, DeleteEditorFileReq, DirEntry, ListEditorDirReq,
15 ListEditorDirResult, OpenInShellReq,
16};
17use crate::backend::text_encoding::DecodedFile;
18
19const MAX_EDITOR_FILE_BYTES: usize = 10_000_000;
21
22fn read_result(decoded: DecodedFile, read_only: bool) -> CommandReadEditorFileResult {
25 CommandReadEditorFileResult {
26 content: decoded.content,
27 encoding: decoded.encoding,
28 bom: decoded.bom.to_string(),
29 line_ending: decoded.line_ending.to_string(),
30 had_decode_errors: decoded.had_decode_errors,
31 read_only,
32 }
33}
34
35pub(super) async fn read_remote_file(
37 connection: &str,
38 cmd: &CommandReadEditorFileData,
39 auth_key: &str,
40) -> Result<CommandReadEditorFileResult, String> {
41 let r = remote_fs::Remote { connection, block_id: cmd.block_id.as_deref(), auth_key };
42 let (bytes, read_only) = remote_fs::read_file(r, &cmd.path).await.map_err(|e| format!("readeditorfile: {e}"))?;
43 Ok(read_result(crate::backend::text_encoding::decode_file(&bytes), read_only))
44}
45
46pub(super) fn read_local_file(path: &str) -> Result<CommandReadEditorFileResult, String> {
49 let expanded = expand_home_dir_safe(path);
50 let path = expanded.as_path();
51 let metadata = std::fs::metadata(path).map_err(|e| format!("readeditorfile: {e}"))?;
52 if metadata.len() > MAX_EDITOR_FILE_BYTES as u64 {
53 return Err("File too large (>10MB)".to_string());
54 }
55 let bytes = std::fs::read(path).map_err(|e| format!("readeditorfile: {e}"))?;
56 Ok(read_result(crate::backend::text_encoding::decode_file(&bytes), metadata.permissions().readonly()))
57}
58
59fn encode_content(cmd: &CommandWriteEditorFileData) -> (Vec<u8>, bool) {
63 crate::backend::text_encoding::encode_file(
64 &cmd.content,
65 cmd.encoding.as_deref().unwrap_or(""),
66 cmd.bom.as_deref().unwrap_or("none"),
67 cmd.line_ending.as_deref().unwrap_or("lf"),
68 )
69}
70
71pub(super) async fn write_remote_file(connection: &str, cmd: &CommandWriteEditorFileData, auth_key: &str) -> Result<(), String> {
73 let (out_bytes, had_unmappable) = encode_content(cmd);
74 if had_unmappable {
75 return Err("writeeditorfile: file contains characters that can't be represented in its encoding — save it as UTF-8 instead".to_string());
76 }
77 let r = remote_fs::Remote { connection, block_id: cmd.block_id.as_deref(), auth_key };
78 remote_fs::write_file(r, &cmd.path, out_bytes).await
79}
80
81pub(super) fn write_local_file(home: &Path, cmd: &CommandWriteEditorFileData) -> Result<(), String> {
83 let expanded = expand_home_dir_safe(&cmd.path);
84 let path = expanded.as_path();
85 let canonical_home = home.canonicalize().map_err(|e| format!("writeeditorfile: home dir: {e}"))?;
86
87 let canonical = path
89 .canonicalize()
90 .or_else(|_| {
91 path.parent()
92 .and_then(|p| p.canonicalize().ok())
93 .map(|p| p.join(path.file_name().unwrap_or_default()))
94 .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "invalid path"))
95 })
96 .map_err(|e| format!("writeeditorfile: {e}"))?;
97
98 if !editor_may_change(&canonical, &canonical_home) {
99 return Err(format!("writeeditorfile: path {} is outside home directory", canonical.display()));
100 }
101
102 let (out_bytes, had_unmappable) = encode_content(cmd);
103 if had_unmappable {
107 let enc = cmd.encoding.as_deref().filter(|s| !s.is_empty()).unwrap_or("its current encoding");
108 return Err(format!("writeeditorfile: file contains characters that can't be represented in {enc} — save it as UTF-8 instead"));
109 }
110 std::fs::write(&canonical, &out_bytes).map_err(|e| format!("writeeditorfile: {e}"))?;
111 tracing::info!(path = %canonical.display(), bytes = out_bytes.len(), "editor file saved");
112 Ok(())
113}
114
115pub(super) fn check_write_size(cmd: &CommandWriteEditorFileData) -> Result<(), String> {
117 if cmd.content.len() > MAX_EDITOR_FILE_BYTES {
118 return Err("Content too large (>10MB)".to_string());
119 }
120 Ok(())
121}
122
123pub(super) fn list_dir(cmd: &ListEditorDirReq) -> Result<ListEditorDirResult, String> {
126 let expanded = expand_home_dir_safe(&cmd.path);
127 let canonical = expanded.canonicalize().map_err(|e| format!("listeditordir: {e}"))?;
128 let read_dir = std::fs::read_dir(&canonical).map_err(|e| format!("listeditordir: {e}"))?;
129
130 let mut entries: Vec<DirEntry> = read_dir.flatten().map(|entry| dir_entry(&entry)).collect();
131 entries.sort_by(|a, b| match (a.is_dir, b.is_dir) {
133 (true, false) => std::cmp::Ordering::Less,
134 (false, true) => std::cmp::Ordering::Greater,
135 _ => a.name.to_lowercase().cmp(&b.name.to_lowercase()),
136 });
137 Ok(ListEditorDirResult { path: canonical.to_string_lossy().into_owned(), entries })
138}
139
140fn dir_entry(entry: &std::fs::DirEntry) -> DirEntry {
144 let name = entry.file_name().to_string_lossy().to_string();
145 let is_symlink = entry.file_type().map(|t| t.is_symlink()).unwrap_or(false);
146 let metadata = entry.metadata().ok();
147 let is_dir = metadata.as_ref().map(|m| m.is_dir()).unwrap_or(false);
148 let size = metadata.as_ref().and_then(|m| if !m.is_dir() { Some(m.len()) } else { None });
149 let mtime = metadata
150 .as_ref()
151 .and_then(|m| m.modified().ok())
152 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
153 .map(|d| d.as_millis() as u64);
154 DirEntry { name, is_dir, is_symlink, size, mtime }
155}
156
157pub(super) fn is_plain_name(name: &str) -> bool {
163 !(name.contains('/') || name.contains('\\') || name.contains('\0') || name == "." || name == ".." || name.is_empty())
164}
165
166pub(super) fn reveal_in_shell(home: &Path, cmd: &OpenInShellReq) -> Result<(), String> {
168 let expanded = expand_home_dir_safe(&cmd.path);
169 let path = expanded.as_path();
170 let canonical_home = home.canonicalize().map_err(|e| format!("openinshell: home: {e}"))?;
171 let canonical = path.canonicalize().map_err(|e| format!("openinshell: {e}"))?;
172 if !editor_may_change(&canonical, &canonical_home) {
173 return Err("openinshell: path outside home directory".to_string());
174 }
175 #[cfg(target_os = "windows")]
179 {
180 let mut cmd = std::process::Command::new("explorer.exe");
181 crate::backend::pane_env::sanitize_external_std_command(&mut cmd);
182 let _ = cmd.arg(format!("/select,{}", canonical.display())).spawn();
183 }
184 #[cfg(target_os = "macos")]
185 {
186 let mut cmd = std::process::Command::new("open");
187 crate::backend::pane_env::sanitize_external_std_command(&mut cmd);
188 let _ = cmd.arg("-R").arg(&canonical).spawn();
189 }
190 #[cfg(target_os = "linux")]
191 {
192 std::thread::spawn(move || {
197 let _ = crate::backend::fs_ops::platform::reveal(&canonical);
198 });
199 }
200 Ok(())
201}
202
203pub(super) fn create_file(home: &Path, cmd: &CreateEditorFileReq) -> Result<CreateEditorFileResult, String> {
205 let expanded = expand_home_dir_safe(&cmd.parent_path);
206 let canonical_home = home.canonicalize().map_err(|e| format!("createeditorfile: home: {e}"))?;
207 let canonical_parent = expanded.as_path().canonicalize().map_err(|e| format!("createeditorfile: {e}"))?;
208 if !editor_may_change(&canonical_parent, &canonical_home) {
209 return Err("createeditorfile: path outside home directory".to_string());
210 }
211 if !is_plain_name(&cmd.name) {
212 return Err("createeditorfile: name must be a plain filename".to_string());
213 }
214 let file_path = canonical_parent.join(&cmd.name);
215 if file_path.exists() {
216 return Err("createeditorfile: file already exists".to_string());
217 }
218 match std::fs::OpenOptions::new().write(true).create_new(true).open(&file_path) {
220 Ok(_) => Ok(CreateEditorFileResult { file_path: file_path.to_string_lossy().into_owned() }),
221 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Err("createeditorfile: file already exists".to_string()),
222 Err(e) => Err(format!("createeditorfile: {e}")),
223 }
224}
225
226pub(super) fn create_dir(home: &Path, cmd: &CreateEditorDirReq) -> Result<CreateEditorDirResult, String> {
228 let expanded = expand_home_dir_safe(&cmd.parent_path);
229 let canonical_home = home.canonicalize().map_err(|e| format!("createeditordir: home: {e}"))?;
230 let canonical_parent = expanded.as_path().canonicalize().map_err(|e| format!("createeditordir: {e}"))?;
231 if !editor_may_change(&canonical_parent, &canonical_home) {
232 return Err("createeditordir: path outside home directory".to_string());
233 }
234 if !is_plain_name(&cmd.name) {
235 return Err("createeditordir: name must be a plain name".to_string());
236 }
237 let dir_path = canonical_parent.join(&cmd.name);
238 if dir_path.exists() {
239 return Err("createeditordir: already exists".to_string());
240 }
241 std::fs::create_dir(&dir_path).map_err(|e| format!("createeditordir: {e}"))?;
242 Ok(CreateEditorDirResult { dir_path: dir_path.to_string_lossy().into_owned() })
243}
244
245pub(super) fn delete_file(home: &Path, cmd: &DeleteEditorFileReq) -> Result<(), String> {
247 let expanded = expand_home_dir_safe(&cmd.path);
248 let path = expanded.as_path();
249 let canonical_home = home.canonicalize().map_err(|e| format!("deleteeditorfile: home: {e}"))?;
250 let canonical = path.canonicalize().map_err(|e| format!("deleteeditorfile: {e}"))?;
251 if !editor_may_change(&canonical, &canonical_home) || is_a_home(&canonical, &canonical_home) {
252 return Err("deleteeditorfile: path outside or is the home directory".to_string());
253 }
254 let meta = std::fs::symlink_metadata(path).map_err(|e| format!("deleteeditorfile: {e}"))?;
258 if meta.file_type().is_symlink() {
259 #[cfg(windows)]
262 if path.is_dir() {
263 std::fs::remove_dir(path).map_err(|e| format!("deleteeditorfile: {e}"))?;
264 } else {
265 std::fs::remove_file(path).map_err(|e| format!("deleteeditorfile: {e}"))?;
266 }
267 #[cfg(not(windows))]
268 std::fs::remove_file(path).map_err(|e| format!("deleteeditorfile: {e}"))?;
269 } else if canonical.is_dir() {
270 if cmd.recursive {
271 std::fs::remove_dir_all(&canonical).map_err(|e| format!("deleteeditorfile: {e}"))?;
272 } else {
273 std::fs::remove_dir(&canonical).map_err(|e| format!("deleteeditorfile: directory not empty: {e}"))?;
274 }
275 } else {
276 std::fs::remove_file(&canonical).map_err(|e| format!("deleteeditorfile: {e}"))?;
277 }
278 Ok(())
279}