Debian Codegraph @

src/bin/sftp.rs

raw
1 use rustyline::error::ReadlineError;
2 use rustyline::DefaultEditor;
3 use sftp::{Attributes, Error as SftpError, OpenOptions, SftpClient};
4 use std::io::{Read, Write};
5 use std::path::{Path, PathBuf};
6 use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
7
8 /// A bidirectional channel backed by the stdin/stdout of an `ssh` subprocess.
9 struct SshChannel {
10 child: Child,
11 stdin: Option<ChildStdin>,
12 stdout: Option<ChildStdout>,
13 }
14
15 impl SshChannel {
16 fn spawn(destination: &str) -> std::io::Result<Self> {
17 let mut child = Command::new("ssh")
18 .arg("-s")
19 .arg(destination)
20 .arg("sftp")
21 .stdin(Stdio::piped())
22 .stdout(Stdio::piped())
23 .stderr(Stdio::inherit())
24 .spawn()?;
25 let stdin = child
26 .stdin
27 .take()
28 .ok_or_else(|| std::io::Error::other("failed to capture ssh stdin"))?;
29 let stdout = child
30 .stdout
31 .take()
32 .ok_or_else(|| std::io::Error::other("failed to capture ssh stdout"))?;
33 Ok(Self {
34 child,
35 stdin: Some(stdin),
36 stdout: Some(stdout),
37 })
38 }
39 }
40
41 impl Read for SshChannel {
42 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
43 match self.stdout.as_mut() {
44 Some(s) => s.read(buf),
45 None => Ok(0),
46 }
47 }
48 }
49
50 impl Write for SshChannel {
51 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
52 match self.stdin.as_mut() {
53 Some(s) => s.write(buf),
54 None => Err(std::io::Error::from(std::io::ErrorKind::BrokenPipe)),
55 }
56 }
57
58 fn flush(&mut self) -> std::io::Result<()> {
59 match self.stdin.as_mut() {
60 Some(s) => s.flush(),
61 None => Ok(()),
62 }
63 }
64 }
65
66 impl Drop for SshChannel {
67 fn drop(&mut self) {
68 // Close stdin first so the ssh subsystem sees EOF and exits;
69 // otherwise wait() blocks forever.
70 drop(self.stdin.take());
71 drop(self.stdout.take());
72 let _ = self.child.wait();
73 }
74 }
75
76 struct Shell {
77 client: SftpClient<SshChannel>,
78 remote_cwd: String,
79 }
80
81 impl Shell {
82 fn new(client: SftpClient<SshChannel>) -> Result<Self, SftpError> {
83 let remote_cwd = client.realpath(".", None, None)?;
84 Ok(Self { client, remote_cwd })
85 }
86
87 fn resolve_remote(&self, path: &str) -> String {
88 if path.starts_with('/') {
89 path.to_string()
90 } else if self.remote_cwd.ends_with('/') {
91 format!("{}{}", self.remote_cwd, path)
92 } else {
93 format!("{}/{}", self.remote_cwd, path)
94 }
95 }
96
97 fn cmd_pwd(&self) {
98 println!("Remote working directory: {}", self.remote_cwd);
99 }
100
101 fn cmd_cd(&mut self, path: Option<&str>) -> Result<(), SftpError> {
102 let target = match path {
103 Some(p) => self.resolve_remote(p),
104 None => "/".to_string(),
105 };
106 let canonical = self.client.realpath(&target, None, None)?;
107 let attrs = self.client.stat(&canonical, None)?;
108 if !is_dir(&attrs) {
109 return Err(SftpError::NotADirectory(String::new(), canonical));
110 }
111 self.remote_cwd = canonical;
112 Ok(())
113 }
114
115 fn cmd_ls(&self, args: &[String]) -> Result<(), SftpError> {
116 let (long, target) = parse_ls_args(args);
117 let path = match target {
118 Some(p) => self.resolve_remote(&p),
119 None => self.remote_cwd.clone(),
120 };
121 let attrs = self.client.stat(&path, None)?;
122 let entries: Vec<(String, String, Attributes)> = if is_dir(&attrs) {
123 let dir = self.client.opendir(&path)?;
124 let mut all = Vec::new();
125 loop {
126 match self.client.readdir(&dir) {
127 Ok(batch) => all.extend(batch),
128 Err(SftpError::Eof(_, _)) => break,
129 Err(e) => {
130 let _ = self.client.closedir(&dir);
131 return Err(e);
132 }
133 }
134 }
135 self.client.closedir(&dir)?;
136 all.sort_by(|a, b| a.0.cmp(&b.0));
137 all
138 } else {
139 let name = Path::new(&path)
140 .file_name()
141 .map(|s| s.to_string_lossy().into_owned())
142 .unwrap_or_else(|| path.clone());
143 vec![(name, format_long(&path, &attrs), attrs)]
144 };
145
146 if long {
147 for (_, longname, _) in &entries {
148 if longname.is_empty() {
149 continue;
150 }
151 println!("{}", longname);
152 }
153 } else {
154 for (name, _, _) in &entries {
155 println!("{}", name);
156 }
157 }
158 Ok(())
159 }
160
161 fn cmd_mkdir(&self, path: &str) -> Result<(), SftpError> {
162 let target = self.resolve_remote(path);
163 self.client.mkdir(&target, &Attributes::new())
164 }
165
166 fn cmd_rmdir(&self, path: &str) -> Result<(), SftpError> {
167 let target = self.resolve_remote(path);
168 self.client.rmdir(&target)
169 }
170
171 fn cmd_rm(&self, path: &str) -> Result<(), SftpError> {
172 let target = self.resolve_remote(path);
173 self.client.remove(&target)
174 }
175
176 fn cmd_rename(&self, old: &str, new: &str) -> Result<(), SftpError> {
177 let from = self.resolve_remote(old);
178 let to = self.resolve_remote(new);
179 self.client.rename(&from, &to, None)
180 }
181
182 fn cmd_symlink(&self, target: &str, link: &str) -> Result<(), SftpError> {
183 let link_path = self.resolve_remote(link);
184 self.client.symlink(&link_path, target)
185 }
186
187 fn cmd_ln(&self, target: &str, link: &str, symbolic: bool) -> Result<(), SftpError> {
188 let link_path = self.resolve_remote(link);
189 if symbolic {
190 self.client.symlink(&link_path, target)
191 } else {
192 let target_path = self.resolve_remote(target);
193 self.client.hardlink(&link_path, &target_path)
194 }
195 }
196
197 fn cmd_chmod(&self, mode_str: &str, path: &str) -> Result<(), SftpError> {
198 let mode = u32::from_str_radix(mode_str, 8).map_err(|e| {
199 SftpError::Io(std::io::Error::new(
200 std::io::ErrorKind::InvalidInput,
201 format!("invalid mode '{}': {}", mode_str, e),
202 ))
203 })?;
204 let target = self.resolve_remote(path);
205 let mut attrs = Attributes::new();
206 attrs.permissions = Some(mode);
207 self.client.setstat(&target, &attrs)
208 }
209
210 fn cmd_stat(&self, path: &str) -> Result<(), SftpError> {
211 let target = self.resolve_remote(path);
212 let attrs = self.client.stat(&target, None)?;
213 print_attrs(&target, &attrs);
214 Ok(())
215 }
216
217 fn cmd_get(&self, remote: &str, local: Option<&str>) -> Result<(), SftpError> {
218 let remote_path = self.resolve_remote(remote);
219 let local_path = match local {
220 Some(p) => PathBuf::from(p),
221 None => PathBuf::from(
222 Path::new(&remote_path)
223 .file_name()
224 .map(|s| s.to_string_lossy().into_owned())
225 .unwrap_or_else(|| remote_path.clone()),
226 ),
227 };
228
229 let file = self.client.open(
230 &remote_path,
231 OpenOptions::new().read(true),
232 &Attributes::new(),
233 )?;
234 let result = (|| -> Result<u64, SftpError> {
235 let mut out = std::fs::File::create(&local_path)?;
236 let mut offset: u64 = 0;
237 const CHUNK: u32 = 32 * 1024;
238 loop {
239 match self.client.pread(&file, offset, CHUNK) {
240 Ok(data) if data.is_empty() => break,
241 Ok(data) => {
242 out.write_all(&data)?;
243 offset += data.len() as u64;
244 }
245 Err(SftpError::Eof(_, _)) => break,
246 Err(e) => return Err(e),
247 }
248 }
249 Ok(offset)
250 })();
251 let _ = self.client.fclose(&file);
252 let bytes = result?;
253 println!("Fetched {} ({} bytes)", local_path.display(), bytes);
254 Ok(())
255 }
256
257 fn cmd_put(&self, local: &str, remote: Option<&str>) -> Result<(), SftpError> {
258 let local_path = PathBuf::from(local);
259 let remote_name = match remote {
260 Some(p) => p.to_string(),
261 None => local_path
262 .file_name()
263 .map(|s| s.to_string_lossy().into_owned())
264 .ok_or_else(|| {
265 SftpError::Io(std::io::Error::new(
266 std::io::ErrorKind::InvalidInput,
267 "cannot derive remote name from local path",
268 ))
269 })?,
270 };
271 let remote_path = self.resolve_remote(&remote_name);
272
273 let mut input = std::fs::File::open(&local_path)?;
274 let file = self.client.open(
275 &remote_path,
276 OpenOptions::new().write(true).create(true).truncate(true),
277 &Attributes::new(),
278 )?;
279 let result = (|| -> Result<u64, SftpError> {
280 let mut offset: u64 = 0;
281 let mut buf = vec![0u8; 32 * 1024];
282 loop {
283 let n = input.read(&mut buf)?;
284 if n == 0 {
285 break;
286 }
287 self.client.pwrite(&file, offset, &buf[..n])?;
288 offset += n as u64;
289 }
290 Ok(offset)
291 })();
292 let _ = self.client.fclose(&file);
293 let bytes = result?;
294 println!("Uploaded {} ({} bytes)", remote_path, bytes);
295 Ok(())
296 }
297
298 fn cmd_lpwd() -> std::io::Result<()> {
299 println!(
300 "Local working directory: {}",
301 std::env::current_dir()?.display()
302 );
303 Ok(())
304 }
305
306 fn cmd_lcd(path: Option<&str>) -> std::io::Result<()> {
307 let target = match path {
308 Some(p) => PathBuf::from(p),
309 None => dirs_home().ok_or_else(|| {
310 std::io::Error::new(std::io::ErrorKind::NotFound, "no home directory")
311 })?,
312 };
313 std::env::set_current_dir(&target)?;
314 Ok(())
315 }
316
317 fn cmd_lls(args: &[String]) -> std::io::Result<()> {
318 let dir = args
319 .first()
320 .map(PathBuf::from)
321 .unwrap_or_else(|| PathBuf::from("."));
322 for entry in std::fs::read_dir(&dir)? {
323 let entry = entry?;
324 println!("{}", entry.file_name().to_string_lossy());
325 }
326 Ok(())
327 }
328 }
329
330 fn dirs_home() -> Option<PathBuf> {
331 std::env::var_os("HOME").map(PathBuf::from)
332 }
333
334 fn is_dir(attrs: &Attributes) -> bool {
335 attrs
336 .permissions
337 .is_some_and(|p| (p & 0o170000) == 0o040000)
338 }
339
340 fn parse_ls_args(args: &[String]) -> (bool, Option<String>) {
341 let mut long = false;
342 let mut target = None;
343 for arg in args {
344 if arg == "-l" || arg == "-la" || arg == "-al" {
345 long = true;
346 } else if arg.starts_with('-') {
347 // ignore other flags for now
348 } else {
349 target = Some(arg.clone());
350 }
351 }
352 (long, target)
353 }
354
355 fn format_long(path: &str, attrs: &Attributes) -> String {
356 let perms = attrs
357 .permissions
358 .map(|p| format!("{:o}", p))
359 .unwrap_or_else(|| "?".to_string());
360 let size = attrs
361 .size
362 .map(|s| s.to_string())
363 .unwrap_or_else(|| "-".to_string());
364 format!("{} {} {}", perms, size, path)
365 }
366
367 fn print_attrs(path: &str, attrs: &Attributes) {
368 println!("{}:", path);
369 if let Some(s) = attrs.size {
370 println!(" size: {}", s);
371 }
372 if let Some(p) = attrs.permissions {
373 println!(" permissions: {:o}", p);
374 }
375 if let (Some(uid), Some(gid)) = (attrs.uid, attrs.gid) {
376 println!(" uid/gid: {}/{}", uid, gid);
377 }
378 if let (Some(owner), Some(group)) = (attrs.owner.as_deref(), attrs.group.as_deref()) {
379 println!(" owner/group: {}/{}", owner, group);
380 }
381 if let Some((secs, _)) = attrs.modify_time {
382 println!(" mtime: {}", secs);
383 }
384 }
385
386 fn print_help() {
387 println!("Available commands:");
388 println!(" cd [path] change remote directory");
389 println!(" pwd print remote working directory");
390 println!(" ls [-l] [path] list remote directory");
391 println!(" get remote [local] download file");
392 println!(" put local [remote] upload file");
393 println!(" mkdir path create remote directory");
394 println!(" rmdir path remove remote directory");
395 println!(" rm path remove remote file");
396 println!(" rename old new rename remote file");
397 println!(" ln [-s] target link create hard or symbolic link");
398 println!(" symlink target link create symbolic link");
399 println!(" chmod mode path change permissions (octal)");
400 println!(" stat path show file attributes");
401 println!(" lpwd print local working directory");
402 println!(" lcd [path] change local directory");
403 println!(" lls [path] list local directory");
404 println!(" help, ? show this help");
405 println!(" quit, exit, bye disconnect");
406 }
407
408 fn dispatch(shell: &mut Shell, line: &str) -> bool {
409 let tokens = match shell_words::split(line) {
410 Ok(t) => t,
411 Err(e) => {
412 eprintln!("parse error: {}", e);
413 return true;
414 }
415 };
416 if tokens.is_empty() {
417 return true;
418 }
419 let cmd = tokens[0].as_str();
420 let args = &tokens[1..];
421
422 let result: Result<(), SftpError> =
423 match cmd {
424 "quit" | "exit" | "bye" => return false,
425 "help" | "?" => {
426 print_help();
427 Ok(())
428 }
429 "pwd" => {
430 shell.cmd_pwd();
431 Ok(())
432 }
433 "cd" => shell.cmd_cd(args.first().map(String::as_str)),
434 "ls" | "dir" => shell.cmd_ls(args),
435 "mkdir" => need_arg(args, 1, "mkdir path").and_then(|_| shell.cmd_mkdir(&args[0])),
436 "rmdir" => need_arg(args, 1, "rmdir path").and_then(|_| shell.cmd_rmdir(&args[0])),
437 "rm" => need_arg(args, 1, "rm path").and_then(|_| shell.cmd_rm(&args[0])),
438 "rename" => need_arg(args, 2, "rename old new")
439 .and_then(|_| shell.cmd_rename(&args[0], &args[1])),
440 "symlink" => need_arg(args, 2, "symlink target link")
441 .and_then(|_| shell.cmd_symlink(&args[0], &args[1])),
442 "ln" => {
443 let symbolic = args.first().map(|s| s == "-s").unwrap_or(false);
444 let rest: Vec<&String> = args.iter().filter(|a| a.as_str() != "-s").collect();
445 if rest.len() != 2 {
446 Err(usage("ln [-s] target link"))
447 } else {
448 shell.cmd_ln(rest[0], rest[1], symbolic)
449 }
450 }
451 "chmod" => need_arg(args, 2, "chmod mode path")
452 .and_then(|_| shell.cmd_chmod(&args[0], &args[1])),
453 "stat" => need_arg(args, 1, "stat path").and_then(|_| shell.cmd_stat(&args[0])),
454 "get" => need_arg(args, 1, "get remote [local]")
455 .and_then(|_| shell.cmd_get(&args[0], args.get(1).map(String::as_str))),
456 "put" => need_arg(args, 1, "put local [remote]")
457 .and_then(|_| shell.cmd_put(&args[0], args.get(1).map(String::as_str))),
458 "lpwd" => Shell::cmd_lpwd().map_err(SftpError::Io),
459 "lcd" => Shell::cmd_lcd(args.first().map(String::as_str)).map_err(SftpError::Io),
460 "lls" => Shell::cmd_lls(args).map_err(SftpError::Io),
461 other => {
462 eprintln!("unknown command: {} (try 'help')", other);
463 Ok(())
464 }
465 };
466 if let Err(e) = result {
467 eprintln!("error: {:?}", e);
468 }
469 true
470 }
471
472 fn need_arg(args: &[String], n: usize, usage_str: &str) -> Result<(), SftpError> {
473 if args.len() < n {
474 Err(usage(usage_str))
475 } else {
476 Ok(())
477 }
478 }
479
480 fn usage(msg: &str) -> SftpError {
481 SftpError::Io(std::io::Error::new(
482 std::io::ErrorKind::InvalidInput,
483 format!("usage: {}", msg),
484 ))
485 }
486
487 fn history_path() -> Option<PathBuf> {
488 dirs_home().map(|h| h.join(".sftp_history"))
489 }
490
491 fn main() -> std::io::Result<()> {
492 let destination = std::env::args().nth(1).unwrap_or_else(|| {
493 eprintln!("Usage: sftp <user@host>");
494 std::process::exit(1);
495 });
496
497 let channel = SshChannel::spawn(&destination)?;
498 let client = SftpClient::new(channel)?;
499 println!("Connected. SFTP protocol version: {}", client.version());
500
501 let mut shell = Shell::new(client).map_err(|e| std::io::Error::other(format!("{:?}", e)))?;
502
503 let mut rl =
504 DefaultEditor::new().map_err(|e| std::io::Error::other(format!("readline init: {}", e)))?;
505 let history = history_path();
506 if let Some(h) = &history {
507 let _ = rl.load_history(h);
508 }
509
510 loop {
511 match rl.readline("sftp> ") {
512 Ok(line) => {
513 let trimmed = line.trim();
514 if trimmed.is_empty() {
515 continue;
516 }
517 let _ = rl.add_history_entry(trimmed);
518 if !dispatch(&mut shell, trimmed) {
519 break;
520 }
521 }
522 Err(ReadlineError::Interrupted) => continue,
523 Err(ReadlineError::Eof) => break,
524 Err(e) => {
525 eprintln!("readline error: {}", e);
526 break;
527 }
528 }
529 }
530
531 if let Some(h) = &history {
532 let _ = rl.save_history(h);
533 }
534 Ok(())
535 }