use std::collections::HashMap;
use std::io::{self, BufReader, BufWriter, Read, Write};
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
use std::sync::mpsc::{self, RecvTimeoutError};
use std::thread::{self, JoinHandle};
use std::time::Duration;
use winit::event_loop::EventLoopProxy;
use super::session::SshSession;
use crate::desktop::{Event, PaneId};
const SFTP_VERSION: u32 = 3;
const MAX_SFTP_VERSION: u32 = 6;
const MAX_PACKET_LEN: usize = 4 * 1024 * 1024;
const MAX_VERSION_PACKET_LEN: usize = 64 * 1024;
const MAX_HANDSHAKE_PREAMBLE: usize = 16 * 1024;
const MAX_DIR_ENTRIES: usize = 20_000;
const IDLE_CONNECTION_TIMEOUT: Duration = Duration::from_millis(500);
const SSH_FXP_INIT: u8 = 1;
const SSH_FXP_VERSION: u8 = 2;
const SSH_FXP_OPEN: u8 = 3;
const SSH_FXP_CLOSE: u8 = 4;
const SSH_FXP_READ: u8 = 5;
const SSH_FXP_WRITE: u8 = 6;
const SSH_FXP_LSTAT: u8 = 7;
const SSH_FXP_OPENDIR: u8 = 11;
const SSH_FXP_READDIR: u8 = 12;
const SSH_FXP_REMOVE: u8 = 13;
const SSH_FXP_MKDIR: u8 = 14;
const SSH_FXP_RMDIR: u8 = 15;
const SSH_FXP_REALPATH: u8 = 16;
const SSH_FXP_STAT: u8 = 17;
const SSH_FXP_RENAME: u8 = 18;
const SSH_FXP_STATUS: u8 = 101;
const SSH_FXP_HANDLE: u8 = 102;
const SSH_FXP_DATA: u8 = 103;
const SSH_FXP_NAME: u8 = 104;
const SSH_FXP_ATTRS: u8 = 105;
pub(super) const SSH_FXF_READ: u32 = 0x0000_0001;
pub(super) const SSH_FXF_WRITE: u32 = 0x0000_0002;
pub(super) const SSH_FXF_CREAT: u32 = 0x0000_0008;
pub(super) const SSH_FXF_TRUNC: u32 = 0x0000_0010;
const SSH_FX_OK: u32 = 0;
const SSH_FX_EOF: u32 = 1;
const SSH_FILEXFER_ATTR_SIZE: u32 = 0x0000_0001;
const SSH_FILEXFER_ATTR_UIDGID: u32 = 0x0000_0002;
const SSH_FILEXFER_ATTR_PERMISSIONS: u32 = 0x0000_0004;
const SSH_FILEXFER_ATTR_ACMODTIME: u32 = 0x0000_0008;
const SSH_FILEXFER_ATTR_EXTENDED: u32 = 0x8000_0000;
const S_IFMT: u32 = 0o170_000;
const S_IFDIR: u32 = 0o040_000;
const S_IFREG: u32 = 0o100_000;
const S_IFLNK: u32 = 0o120_000;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::desktop) enum EntryKind {
Directory,
File,
Symlink,
Other,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(in crate::desktop) struct RemoteEntry {
pub(in crate::desktop) name: String,
pub(in crate::desktop) kind: EntryKind,
pub(in crate::desktop) size: Option<u64>,
pub(in crate::desktop) modified: Option<u64>,
pub(in crate::desktop) permissions: Option<u32>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct FileAttrs {
pub(super) size: Option<u64>,
pub(super) permissions: Option<u32>,
pub(super) modified: Option<u64>,
}
impl FileAttrs {
pub(super) fn entry_kind(self) -> EntryKind {
match self.permissions.map(|mode| mode & S_IFMT) {
Some(S_IFDIR) => EntryKind::Directory,
Some(S_IFREG) => EntryKind::File,
Some(S_IFLNK) => EntryKind::Symlink,
_ => EntryKind::Other,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::desktop) enum SshOpKind {
Delete,
CreateDir,
Rename,
}
#[derive(Debug)]
pub(in crate::desktop) struct SshOpResult {
pub(in crate::desktop) pane_id: PaneId,
pub(in crate::desktop) session_key: String,
pub(in crate::desktop) kind: SshOpKind,
pub(in crate::desktop) label: String,
pub(in crate::desktop) result: Result<(), String>,
}
#[derive(Debug)]
pub(in crate::desktop) struct SshBrowserUpdate {
pub(in crate::desktop) pane_id: PaneId,
pub(in crate::desktop) generation: u64,
pub(in crate::desktop) session_key: String,
pub(in crate::desktop) result: Result<DirectoryListing, String>,
}
#[derive(Clone, Debug)]
pub(in crate::desktop) struct DirectoryListing {
pub(in crate::desktop) path: String,
pub(in crate::desktop) entries: Vec<RemoteEntry>,
}
pub(super) struct SftpClient<R, W> {
reader: R,
writer: W,
next_id: u32,
}
impl<R: Read, W: Write> SftpClient<R, W> {
pub(super) fn new(reader: R, writer: W) -> io::Result<Self> {
let mut client = Self {
reader,
writer,
next_id: 1,
};
client.handshake()?;
Ok(client)
}
fn alloc_id(&mut self) -> u32 {
let id = self.next_id;
self.next_id = self.next_id.wrapping_add(1).max(1);
id
}
fn handshake(&mut self) -> io::Result<()> {
let mut payload = Vec::with_capacity(4);
write_u32(&mut payload, SFTP_VERSION);
self.write_packet(SSH_FXP_INIT, &payload)?;
let mut preamble = Vec::with_capacity(64);
let mut byte = [0u8; 1];
loop {
match self.reader.read(&mut byte) {
Ok(0) => {
return Err(unexpected_handshake_error(&preamble));
}
Ok(_) => preamble.push(byte[0]),
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
Err(error) => return Err(error),
}
if preamble.len() >= 9 {
let start = preamble.len() - 9;
let candidate_len = u32::from_be_bytes([
preamble[start],
preamble[start + 1],
preamble[start + 2],
preamble[start + 3],
]) as usize;
let packet_type = preamble[start + 4];
let version = u32::from_be_bytes([
preamble[start + 5],
preamble[start + 6],
preamble[start + 7],
preamble[start + 8],
]);
if packet_type == SSH_FXP_VERSION
&& (5..=MAX_VERSION_PACKET_LEN).contains(&candidate_len)
&& (SFTP_VERSION..=MAX_SFTP_VERSION).contains(&version)
{
let ext_len = candidate_len - 5;
let mut ext_buf = vec![0u8; ext_len];
if ext_len > 0 {
self.reader.read_exact(&mut ext_buf)?;
}
if validate_version_extensions(&ext_buf) {
return Ok(());
}
preamble.extend_from_slice(&ext_buf);
}
}
if preamble.len() >= MAX_HANDSHAKE_PREAMBLE {
return Err(unexpected_handshake_error(&preamble));
}
}
}
pub(super) fn realpath(&mut self, path: &str) -> io::Result<String> {
let id = self.alloc_id();
let mut payload = Vec::with_capacity(8 + path.len());
write_u32(&mut payload, id);
write_bytes(&mut payload, path.as_bytes());
self.write_packet(SSH_FXP_REALPATH, &payload)?;
let (packet_type, body) = self.read_packet()?;
let mut cursor = CursorSlice::new(&body);
let reply_id = cursor.read_u32()?;
expect_id(id, reply_id)?;
match packet_type {
SSH_FXP_NAME => {
let count = cursor.read_u32()?;
if count == 0 {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"empty SFTP REALPATH response",
));
}
let filename = cursor.read_string_lossy()?;
Ok(filename)
}
SSH_FXP_STATUS => Err(parse_status_error(&mut cursor)?),
other => Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("unexpected SFTP packet type {other} for REALPATH"),
)),
}
}
pub(super) fn stat(&mut self, path: &str, follow_symlinks: bool) -> io::Result<FileAttrs> {
let id = self.alloc_id();
let mut payload = Vec::with_capacity(8 + path.len());
write_u32(&mut payload, id);
write_bytes(&mut payload, path.as_bytes());
let op = if follow_symlinks {
SSH_FXP_STAT
} else {
SSH_FXP_LSTAT
};
self.write_packet(op, &payload)?;
let (packet_type, body) = self.read_packet()?;
let mut cursor = CursorSlice::new(&body);
let reply_id = cursor.read_u32()?;
expect_id(id, reply_id)?;
match packet_type {
SSH_FXP_ATTRS => parse_attrs(&mut cursor),
SSH_FXP_STATUS => Err(parse_status_error(&mut cursor)?),
other => Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("unexpected SFTP packet type {other} for STAT"),
)),
}
}
pub(super) fn list_dir(&mut self, path: &str) -> io::Result<Vec<RemoteEntry>> {
let handle = self.opendir(path)?;
let result = self.read_all_entries(&handle);
let _ = self.close_handle(&handle);
result
}
fn opendir(&mut self, path: &str) -> io::Result<Vec<u8>> {
let id = self.alloc_id();
let mut payload = Vec::with_capacity(8 + path.len());
write_u32(&mut payload, id);
write_bytes(&mut payload, path.as_bytes());
self.write_packet(SSH_FXP_OPENDIR, &payload)?;
let (packet_type, body) = self.read_packet()?;
let mut cursor = CursorSlice::new(&body);
let reply_id = cursor.read_u32()?;
expect_id(id, reply_id)?;
match packet_type {
SSH_FXP_HANDLE => cursor.read_bytes().map(|slice| slice.to_vec()),
SSH_FXP_STATUS => Err(parse_status_error(&mut cursor)?),
other => Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("unexpected SFTP packet type {other} for OPENDIR"),
)),
}
}
fn read_all_entries(&mut self, handle: &[u8]) -> io::Result<Vec<RemoteEntry>> {
let mut entries = Vec::new();
loop {
let id = self.alloc_id();
let mut payload = Vec::with_capacity(8 + handle.len());
write_u32(&mut payload, id);
write_bytes(&mut payload, handle);
self.write_packet(SSH_FXP_READDIR, &payload)?;
let (packet_type, body) = self.read_packet()?;
let mut cursor = CursorSlice::new(&body);
let reply_id = cursor.read_u32()?;
expect_id(id, reply_id)?;
match packet_type {
SSH_FXP_NAME => {
let count = cursor.read_u32()? as usize;
if count == 0 {
break;
}
for _ in 0..count {
let name = cursor.read_string_lossy()?;
let _longname = cursor.read_bytes()?;
let attrs = parse_attrs(&mut cursor)?;
if name == "." || name == ".." {
continue;
}
if entries.len() < MAX_DIR_ENTRIES {
entries.push(RemoteEntry {
name,
kind: attrs.entry_kind(),
size: attrs.size,
modified: attrs.modified,
permissions: attrs.permissions,
});
}
}
}
SSH_FXP_STATUS => {
let code = cursor.read_u32()?;
if code == SSH_FX_EOF {
break;
}
let message = cursor.read_string_lossy().unwrap_or_default();
return Err(status_to_io_error(code, &message));
}
other => {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("unexpected SFTP packet type {other} for READDIR"),
));
}
}
}
sort_entries(&mut entries);
Ok(entries)
}
pub(super) fn close_handle(&mut self, handle: &[u8]) -> io::Result<()> {
let id = self.alloc_id();
let mut payload = Vec::with_capacity(8 + handle.len());
write_u32(&mut payload, id);
write_bytes(&mut payload, handle);
self.write_packet(SSH_FXP_CLOSE, &payload)?;
let (packet_type, body) = self.read_packet()?;
let mut cursor = CursorSlice::new(&body);
let reply_id = cursor.read_u32()?;
expect_id(id, reply_id)?;
match packet_type {
SSH_FXP_STATUS => {
let code = cursor.read_u32()?;
if code == SSH_FX_OK {
Ok(())
} else {
let message = cursor.read_string_lossy().unwrap_or_default();
Err(status_to_io_error(code, &message))
}
}
_ => Ok(()),
}
}
pub(super) fn open_file(&mut self, path: &str, pflags: u32) -> io::Result<Vec<u8>> {
let id = self.alloc_id();
let mut payload = Vec::with_capacity(16 + path.len());
write_u32(&mut payload, id);
write_bytes(&mut payload, path.as_bytes());
write_u32(&mut payload, pflags);
write_u32(&mut payload, 0); self.write_packet(SSH_FXP_OPEN, &payload)?;
let (packet_type, body) = self.read_packet()?;
let mut cursor = CursorSlice::new(&body);
let reply_id = cursor.read_u32()?;
expect_id(id, reply_id)?;
match packet_type {
SSH_FXP_HANDLE => cursor.read_bytes().map(|slice| slice.to_vec()),
SSH_FXP_STATUS => Err(parse_status_error(&mut cursor)?),
other => Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("unexpected SFTP packet type {other} for OPEN"),
)),
}
}
pub(super) fn send_read(&mut self, handle: &[u8], offset: u64, len: u32) -> io::Result<u32> {
let id = self.alloc_id();
let mut payload = Vec::with_capacity(20 + handle.len());
write_u32(&mut payload, id);
write_bytes(&mut payload, handle);
payload.extend_from_slice(&offset.to_be_bytes());
write_u32(&mut payload, len);
self.write_packet_buffered(SSH_FXP_READ, &payload)?;
Ok(id)
}
pub(super) fn send_write(
&mut self,
handle: &[u8],
offset: u64,
data: &[u8],
) -> io::Result<u32> {
let id = self.alloc_id();
let mut payload = Vec::with_capacity(20 + handle.len() + data.len());
write_u32(&mut payload, id);
write_bytes(&mut payload, handle);
payload.extend_from_slice(&offset.to_be_bytes());
write_bytes(&mut payload, data);
self.write_packet_buffered(SSH_FXP_WRITE, &payload)?;
Ok(id)
}
pub(super) fn flush(&mut self) -> io::Result<()> {
self.writer.flush()
}
pub(super) fn read_data_reply(&mut self) -> io::Result<(u32, Option<Vec<u8>>)> {
let (packet_type, body) = self.read_packet()?;
let mut cursor = CursorSlice::new(&body);
let reply_id = cursor.read_u32()?;
match packet_type {
SSH_FXP_DATA => {
let data = cursor.read_bytes()?.to_vec();
Ok((reply_id, Some(data)))
}
SSH_FXP_STATUS => {
let code = cursor.read_u32()?;
if code == SSH_FX_EOF {
Ok((reply_id, None))
} else {
let message = cursor.read_string_lossy().unwrap_or_default();
Err(status_to_io_error(code, &message))
}
}
other => Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("unexpected SFTP packet type {other} for READ"),
)),
}
}
pub(super) fn read_status_reply(&mut self) -> io::Result<u32> {
let (packet_type, body) = self.read_packet()?;
let mut cursor = CursorSlice::new(&body);
let reply_id = cursor.read_u32()?;
match packet_type {
SSH_FXP_STATUS => {
let code = cursor.read_u32()?;
if code == SSH_FX_OK {
Ok(reply_id)
} else {
let message = cursor.read_string_lossy().unwrap_or_default();
Err(status_to_io_error(code, &message))
}
}
other => Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("unexpected SFTP packet type {other} for STATUS"),
)),
}
}
pub(super) fn mkdir(&mut self, path: &str) -> io::Result<()> {
let id = self.alloc_id();
let mut payload = Vec::with_capacity(12 + path.len());
write_u32(&mut payload, id);
write_bytes(&mut payload, path.as_bytes());
write_u32(&mut payload, 0); self.write_packet(SSH_FXP_MKDIR, &payload)?;
let reply_id = self.read_status_reply()?;
expect_id(id, reply_id)
}
pub(super) fn remove_file(&mut self, path: &str) -> io::Result<()> {
let id = self.alloc_id();
let mut payload = Vec::with_capacity(8 + path.len());
write_u32(&mut payload, id);
write_bytes(&mut payload, path.as_bytes());
self.write_packet(SSH_FXP_REMOVE, &payload)?;
let reply_id = self.read_status_reply()?;
expect_id(id, reply_id)
}
pub(super) fn remove_dir(&mut self, path: &str) -> io::Result<()> {
let id = self.alloc_id();
let mut payload = Vec::with_capacity(8 + path.len());
write_u32(&mut payload, id);
write_bytes(&mut payload, path.as_bytes());
self.write_packet(SSH_FXP_RMDIR, &payload)?;
let reply_id = self.read_status_reply()?;
expect_id(id, reply_id)
}
pub(super) fn rename(&mut self, old_path: &str, new_path: &str) -> io::Result<()> {
let id = self.alloc_id();
let mut payload = Vec::with_capacity(12 + old_path.len() + new_path.len());
write_u32(&mut payload, id);
write_bytes(&mut payload, old_path.as_bytes());
write_bytes(&mut payload, new_path.as_bytes());
self.write_packet(SSH_FXP_RENAME, &payload)?;
let reply_id = self.read_status_reply()?;
expect_id(id, reply_id)
}
fn write_packet_buffered(&mut self, packet_type: u8, payload: &[u8]) -> io::Result<()> {
let len = payload.len().checked_add(1).ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidInput, "SFTP packet length overflow")
})?;
if len > MAX_PACKET_LEN {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"SFTP packet exceeds maximum length",
));
}
self.writer.write_all(&(len as u32).to_be_bytes())?;
self.writer.write_all(&[packet_type])?;
self.writer.write_all(payload)
}
fn write_packet(&mut self, packet_type: u8, payload: &[u8]) -> io::Result<()> {
self.write_packet_buffered(packet_type, payload)?;
self.writer.flush()
}
fn read_packet(&mut self) -> io::Result<(u8, Vec<u8>)> {
let mut header = [0u8; 4];
self.reader.read_exact(&mut header)?;
let len = u32::from_be_bytes(header) as usize;
if len == 0 || len > MAX_PACKET_LEN {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("invalid SFTP packet length {len}"),
));
}
let mut type_byte = [0u8; 1];
self.reader.read_exact(&mut type_byte)?;
let mut body = vec![0u8; len - 1];
self.reader.read_exact(&mut body)?;
Ok((type_byte[0], body))
}
}
fn validate_version_extensions(bytes: &[u8]) -> bool {
let mut cursor = CursorSlice::new(bytes);
while cursor.offset < bytes.len() {
let Ok(name) = cursor.read_bytes() else {
return false;
};
if name.is_empty() || name.iter().any(|&b| b < 0x20 || b == 0x7f) {
return false;
}
if cursor.read_bytes().is_err() {
return false;
}
}
true
}
fn unexpected_handshake_error(preamble: &[u8]) -> io::Error {
if preamble.is_empty() {
return io::Error::new(
io::ErrorKind::UnexpectedEof,
"SFTP subsystem closed before handshake",
);
}
let preview: String = String::from_utf8_lossy(preamble)
.chars()
.map(|ch| if ch.is_control() { ' ' } else { ch })
.collect::<String>()
.split_whitespace()
.collect::<Vec<_>>()
.join(" ");
let clipped: String = preview.chars().take(120).collect();
if clipped.is_empty() {
io::Error::new(
io::ErrorKind::InvalidData,
"Invalid SFTP handshake response from server",
)
} else {
io::Error::new(
io::ErrorKind::InvalidData,
format!("Non-SFTP output during handshake: {clipped}"),
)
}
}
fn sort_entries(entries: &mut [RemoteEntry]) {
entries.sort_by(|a, b| {
let a_dir = matches!(a.kind, EntryKind::Directory);
let b_dir = matches!(b.kind, EntryKind::Directory);
b_dir
.cmp(&a_dir)
.then_with(|| {
let a_lower = a.name.to_ascii_lowercase();
let b_lower = b.name.to_ascii_lowercase();
a_lower.cmp(&b_lower)
})
.then_with(|| a.name.cmp(&b.name))
});
}
fn expect_id(expected: u32, actual: u32) -> io::Result<()> {
if expected != actual {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("SFTP request id mismatch: expected {expected}, got {actual}"),
));
}
Ok(())
}
fn parse_status_error(cursor: &mut CursorSlice<'_>) -> io::Result<io::Error> {
let code = cursor.read_u32()?;
let message = cursor.read_string_lossy().unwrap_or_default();
Ok(status_to_io_error(code, &message))
}
fn status_to_io_error(code: u32, message: &str) -> io::Error {
let kind = match code {
2 => io::ErrorKind::NotFound,
3 => io::ErrorKind::PermissionDenied,
_ => io::ErrorKind::Other,
};
let text = if message.trim().is_empty() {
match code {
2 => "No such file or directory".to_owned(),
3 => "Permission denied".to_owned(),
4 => "SFTP operation failed".to_owned(),
_ => format!("SFTP error (code {code})"),
}
} else {
message.trim().to_owned()
};
io::Error::new(kind, text)
}
fn parse_attrs(cursor: &mut CursorSlice<'_>) -> io::Result<FileAttrs> {
let flags = cursor.read_u32()?;
let mut attrs = FileAttrs::default();
if flags & SSH_FILEXFER_ATTR_SIZE != 0 {
attrs.size = Some(cursor.read_u64()?);
}
if flags & SSH_FILEXFER_ATTR_UIDGID != 0 {
let _uid = cursor.read_u32()?;
let _gid = cursor.read_u32()?;
}
if flags & SSH_FILEXFER_ATTR_PERMISSIONS != 0 {
attrs.permissions = Some(cursor.read_u32()?);
}
if flags & SSH_FILEXFER_ATTR_ACMODTIME != 0 {
let _atime = cursor.read_u32()?;
attrs.modified = Some(u64::from(cursor.read_u32()?));
}
if flags & SSH_FILEXFER_ATTR_EXTENDED != 0 {
let ext_count = cursor.read_u32()?;
for _ in 0..ext_count {
let _key = cursor.read_bytes()?;
let _value = cursor.read_bytes()?;
}
}
Ok(attrs)
}
fn write_u32(buf: &mut Vec<u8>, value: u32) {
buf.extend_from_slice(&value.to_be_bytes());
}
fn write_bytes(buf: &mut Vec<u8>, data: &[u8]) {
write_u32(buf, data.len() as u32);
buf.extend_from_slice(data);
}
struct CursorSlice<'a> {
data: &'a [u8],
offset: usize,
}
impl<'a> CursorSlice<'a> {
fn new(data: &'a [u8]) -> Self {
Self { data, offset: 0 }
}
fn take(&mut self, len: usize) -> io::Result<&'a [u8]> {
let end = self
.offset
.checked_add(len)
.ok_or_else(|| io::Error::new(io::ErrorKind::UnexpectedEof, "truncated SFTP packet"))?;
if end > self.data.len() {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"truncated SFTP packet",
));
}
let slice = &self.data[self.offset..end];
self.offset = end;
Ok(slice)
}
fn read_u32(&mut self) -> io::Result<u32> {
let bytes = self.take(4)?;
Ok(u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
}
fn read_u64(&mut self) -> io::Result<u64> {
let bytes = self.take(8)?;
Ok(u64::from_be_bytes([
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
]))
}
fn read_bytes(&mut self) -> io::Result<&'a [u8]> {
let len = self.read_u32()? as usize;
self.take(len)
}
fn read_string_lossy(&mut self) -> io::Result<String> {
let bytes = self.read_bytes()?;
Ok(String::from_utf8_lossy(bytes).into_owned())
}
}
enum WorkerCommand {
ListDir {
pane_id: PaneId,
generation: u64,
session: SshSession,
path: Option<String>,
verify_directory: bool,
},
Delete {
pane_id: PaneId,
session: SshSession,
path: String,
is_dir: bool,
},
CreateDir {
pane_id: PaneId,
session: SshSession,
path: String,
},
Rename {
pane_id: PaneId,
session: SshSession,
old_path: String,
new_path: String,
},
Disconnect(String),
Shutdown,
}
pub(super) struct LiveConnection {
child: Child,
pub(super) client: SftpClient<BufReader<ChildStdout>, BufWriter<ChildStdin>>,
}
impl LiveConnection {
pub(super) fn open(session: &SshSession) -> io::Result<Self> {
let mut command = Command::new("ssh");
command
.arg("-S")
.arg(&session.control_socket)
.arg("-o")
.arg("ControlMaster=no")
.arg("-o")
.arg("BatchMode=yes")
.arg("-o")
.arg("ConnectTimeout=5")
.arg("-o")
.arg("RemoteCommand=none")
.arg("-o")
.arg("RequestTTY=no")
.arg("-o")
.arg("PermitLocalCommand=no")
.arg("-o")
.arg("ClearAllForwardings=yes")
.arg("-o")
.arg("ForwardX11=no")
.arg("-o")
.arg("LogLevel=ERROR")
.arg("-T")
.arg("-s");
if let Some(config) = &session.config_file {
command.arg("-F").arg(config);
}
if let Some(port) = &session.port {
command.arg("-p").arg(port);
}
if let Some(user) = &session.user {
command.arg("-l").arg(user);
}
command
.arg("--")
.arg(&session.destination)
.arg("sftp")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = command.spawn()?;
let stdout = child
.stdout
.take()
.ok_or_else(|| io::Error::other("failed to capture sftp stdout"))?;
let stdin = child
.stdin
.take()
.ok_or_else(|| io::Error::other("failed to capture sftp stdin"))?;
match SftpClient::new(BufReader::new(stdout), BufWriter::new(stdin)) {
Ok(client) => Ok(Self { child, client }),
Err(error) => {
let detail = collect_child_stderr(&mut child);
let message = if detail.is_empty() {
format!("SFTP connection failed: {error}")
} else {
detail
};
Err(io::Error::other(message))
}
}
}
pub(super) fn close(mut self) {
drop(self.client);
let _ = self.child.kill();
let _ = self.child.wait();
}
}
fn collect_child_stderr(child: &mut Child) -> String {
let mut stderr_text = String::new();
if let Some(mut stderr) = child.stderr.take() {
let mut buf = [0u8; 512];
if let Ok(n) = stderr.read(&mut buf) {
stderr_text.push_str(&String::from_utf8_lossy(&buf[..n]));
}
}
let _ = child.kill();
let _ = child.wait();
stderr_text
.lines()
.map(str::trim)
.find(|line| !line.is_empty())
.unwrap_or("")
.to_owned()
}
pub(in crate::desktop) struct SftpWorker {
tx: mpsc::Sender<WorkerCommand>,
thread: Option<JoinHandle<()>>,
}
impl SftpWorker {
pub(in crate::desktop) fn spawn(proxy: EventLoopProxy<Event>) -> io::Result<Self> {
let (tx, rx) = mpsc::channel::<WorkerCommand>();
let thread = thread::Builder::new()
.name("lune-sftp".into())
.spawn(move || run_worker(rx, proxy))?;
Ok(Self {
tx,
thread: Some(thread),
})
}
pub(in crate::desktop) fn list_dir(
&self,
pane_id: PaneId,
generation: u64,
session: SshSession,
path: Option<String>,
verify_directory: bool,
) {
let _ = self.tx.send(WorkerCommand::ListDir {
pane_id,
generation,
session,
path,
verify_directory,
});
}
pub(in crate::desktop) fn delete(
&self,
pane_id: PaneId,
session: SshSession,
path: String,
is_dir: bool,
) {
let _ = self.tx.send(WorkerCommand::Delete {
pane_id,
session,
path,
is_dir,
});
}
pub(in crate::desktop) fn create_dir(
&self,
pane_id: PaneId,
session: SshSession,
path: String,
) {
let _ = self.tx.send(WorkerCommand::CreateDir {
pane_id,
session,
path,
});
}
pub(in crate::desktop) fn rename(
&self,
pane_id: PaneId,
session: SshSession,
old_path: String,
new_path: String,
) {
let _ = self.tx.send(WorkerCommand::Rename {
pane_id,
session,
old_path,
new_path,
});
}
pub(in crate::desktop) fn disconnect(&self, session_key: String) {
let _ = self.tx.send(WorkerCommand::Disconnect(session_key));
}
}
impl Drop for SftpWorker {
fn drop(&mut self) {
let _ = self.tx.send(WorkerCommand::Shutdown);
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
fn run_worker(rx: mpsc::Receiver<WorkerCommand>, proxy: EventLoopProxy<Event>) {
let mut connections: HashMap<String, LiveConnection> = HashMap::new();
loop {
let command = if connections.is_empty() {
match rx.recv() {
Ok(cmd) => cmd,
Err(_) => break,
}
} else {
match rx.recv_timeout(IDLE_CONNECTION_TIMEOUT) {
Ok(cmd) => cmd,
Err(RecvTimeoutError::Timeout) => {
for (_, conn) in connections.drain() {
conn.close();
}
continue;
}
Err(RecvTimeoutError::Disconnected) => break,
}
};
match command {
WorkerCommand::Shutdown => break,
WorkerCommand::Disconnect(key) => {
if let Some(conn) = connections.remove(&key) {
conn.close();
}
}
WorkerCommand::Delete {
pane_id,
session,
path,
is_dir,
} => {
let key = session.key();
let label = remote_basename(&path).to_owned();
let result = execute_mutation(&mut connections, &key, &session, |client| {
if is_dir {
client.remove_dir(&path)
} else {
client.remove_file(&path)
}
})
.map_err(|err| err.to_string());
let _ = proxy.send_event(Event::SshOpReady(SshOpResult {
pane_id,
session_key: key,
kind: SshOpKind::Delete,
label,
result,
}));
}
WorkerCommand::CreateDir {
pane_id,
session,
path,
} => {
let key = session.key();
let label = remote_basename(&path).to_owned();
let result = execute_mutation(&mut connections, &key, &session, |client| {
client.mkdir(&path)
})
.map_err(|err| err.to_string());
let _ = proxy.send_event(Event::SshOpReady(SshOpResult {
pane_id,
session_key: key,
kind: SshOpKind::CreateDir,
label,
result,
}));
}
WorkerCommand::Rename {
pane_id,
session,
old_path,
new_path,
} => {
let key = session.key();
let label = remote_basename(&new_path).to_owned();
let result = execute_mutation(&mut connections, &key, &session, |client| {
client.rename(&old_path, &new_path)
})
.map_err(|err| err.to_string());
let _ = proxy.send_event(Event::SshOpReady(SshOpResult {
pane_id,
session_key: key,
kind: SshOpKind::Rename,
label,
result,
}));
}
WorkerCommand::ListDir {
pane_id,
generation,
session,
path,
verify_directory,
} => {
let key = session.key();
let result = execute_list_dir(
&mut connections,
&key,
&session,
path.as_deref(),
verify_directory,
)
.map_err(|err| err.to_string());
let _ = proxy.send_event(Event::SshBrowserReady(SshBrowserUpdate {
pane_id,
generation,
session_key: key,
result,
}));
}
}
}
for (_, conn) in connections.drain() {
conn.close();
}
}
fn remote_basename(path: &str) -> &str {
path.trim_end_matches('/')
.rsplit('/')
.next()
.filter(|s| !s.is_empty())
.unwrap_or(path)
}
fn execute_mutation<F>(
connections: &mut HashMap<String, LiveConnection>,
key: &str,
session: &SshSession,
mut op: F,
) -> io::Result<()>
where
F: FnMut(&mut SftpClient<BufReader<ChildStdout>, BufWriter<ChildStdin>>) -> io::Result<()>,
{
for attempt in 0..2 {
if !connections.contains_key(key) {
if !session.is_socket_live() {
return Err(io::Error::new(
io::ErrorKind::NotConnected,
"SSH ControlMaster socket is not ready",
));
}
let conn = LiveConnection::open(session)?;
connections.insert(key.to_owned(), conn);
}
let conn = connections.get_mut(key).expect("connection inserted");
match op(&mut conn.client) {
Ok(()) => return Ok(()),
Err(error) if attempt == 0 && is_transport_error(&error) => {
if let Some(dead) = connections.remove(key) {
dead.close();
}
}
Err(error) => return Err(error),
}
}
unreachable!("loop returns on second attempt")
}
fn execute_list_dir(
connections: &mut HashMap<String, LiveConnection>,
key: &str,
session: &SshSession,
path: Option<&str>,
verify_directory: bool,
) -> io::Result<DirectoryListing> {
for attempt in 0..2 {
if !connections.contains_key(key) {
if !session.is_socket_live() {
return Err(io::Error::new(
io::ErrorKind::NotConnected,
"SSH ControlMaster socket is not ready",
));
}
let conn = LiveConnection::open(session)?;
connections.insert(key.to_owned(), conn);
}
let conn = connections.get_mut(key).expect("connection inserted");
match fetch_listing(&mut conn.client, path, verify_directory) {
Ok(listing) => return Ok(listing),
Err(error) if attempt == 0 && is_transport_error(&error) => {
if let Some(dead) = connections.remove(key) {
dead.close();
}
}
Err(error) => return Err(error),
}
}
unreachable!("loop returns on second attempt")
}
fn fetch_listing<R: Read, W: Write>(
client: &mut SftpClient<R, W>,
requested_path: Option<&str>,
verify_directory: bool,
) -> io::Result<DirectoryListing> {
let target = match requested_path {
Some(path) if !path.is_empty() => {
if verify_directory {
let attrs = client.stat(path, true)?;
if attrs.entry_kind() != EntryKind::Directory {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Selected target is not a directory",
));
}
}
client.realpath(path)?
}
_ => client.realpath(".")?,
};
let entries = client.list_dir(&target)?;
Ok(DirectoryListing {
path: target,
entries,
})
}
fn is_transport_error(error: &io::Error) -> bool {
matches!(
error.kind(),
io::ErrorKind::BrokenPipe
| io::ErrorKind::UnexpectedEof
| io::ErrorKind::ConnectionReset
| io::ErrorKind::ConnectionAborted
)
}
#[cfg(test)]
mod tests {
use std::io::Cursor;
use super::*;
fn packet(packet_type: u8, payload: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(5 + payload.len());
out.extend_from_slice(&((payload.len() + 1) as u32).to_be_bytes());
out.push(packet_type);
out.extend_from_slice(payload);
out
}
fn name_entry(buf: &mut Vec<u8>, name: &str, mode: u32, size: u64, mtime: u32) {
write_bytes(buf, name.as_bytes());
write_bytes(buf, name.as_bytes());
write_u32(
buf,
SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_PERMISSIONS | SSH_FILEXFER_ATTR_ACMODTIME,
);
buf.extend_from_slice(&size.to_be_bytes());
write_u32(buf, mode);
write_u32(buf, mtime);
write_u32(buf, mtime);
}
#[test]
fn sftp_v3_client_performs_handshake_realpath_readdir_and_sorting() {
let mut server_replies = Vec::new();
let mut ver = Vec::new();
write_u32(&mut ver, 3);
server_replies.extend_from_slice(&packet(SSH_FXP_VERSION, &ver));
let mut rp = Vec::new();
write_u32(&mut rp, 1);
write_u32(&mut rp, 1);
name_entry(&mut rp, "/srv/work", S_IFDIR | 0o755, 4096, 1700000000);
server_replies.extend_from_slice(&packet(SSH_FXP_NAME, &rp));
let mut od = Vec::new();
write_u32(&mut od, 2);
write_bytes(&mut od, b"h1");
server_replies.extend_from_slice(&packet(SSH_FXP_HANDLE, &od));
let mut rd1 = Vec::new();
write_u32(&mut rd1, 3);
write_u32(&mut rd1, 5);
name_entry(&mut rd1, ".", S_IFDIR | 0o755, 4096, 10);
name_entry(&mut rd1, "..", S_IFDIR | 0o755, 4096, 10);
name_entry(&mut rd1, "zeta.txt", S_IFREG | 0o644, 128, 20);
name_entry(&mut rd1, "Alpha", S_IFDIR | 0o755, 4096, 30);
name_entry(&mut rd1, "link.so", S_IFLNK | 0o777, 16, 40);
server_replies.extend_from_slice(&packet(SSH_FXP_NAME, &rd1));
let mut eof = Vec::new();
write_u32(&mut eof, 4);
write_u32(&mut eof, SSH_FX_EOF);
write_bytes(&mut eof, b"End of file");
write_bytes(&mut eof, b"");
server_replies.extend_from_slice(&packet(SSH_FXP_STATUS, &eof));
let mut ok = Vec::new();
write_u32(&mut ok, 5);
write_u32(&mut ok, SSH_FX_OK);
write_bytes(&mut ok, b"Success");
write_bytes(&mut ok, b"");
server_replies.extend_from_slice(&packet(SSH_FXP_STATUS, &ok));
let mut sent = Vec::new();
let mut client = SftpClient::new(Cursor::new(server_replies), &mut sent).unwrap();
let listing = fetch_listing(&mut client, None, false).unwrap();
assert_eq!(listing.path, "/srv/work");
assert_eq!(listing.entries.len(), 3);
assert_eq!(listing.entries[0].name, "Alpha");
assert_eq!(listing.entries[0].kind, EntryKind::Directory);
assert_eq!(listing.entries[1].name, "link.so");
assert_eq!(listing.entries[1].kind, EntryKind::Symlink);
assert_eq!(listing.entries[2].name, "zeta.txt");
assert_eq!(listing.entries[2].kind, EntryKind::File);
assert_eq!(listing.entries[2].size, Some(128));
}
#[test]
fn sftp_v3_client_skips_remote_shell_preamble_before_version_frame() {
let mut server_replies = Vec::new();
server_replies.extend_from_slice(b"Welcome to host!\r\n\x1b[32mready\x1b[0m\n");
let mut ver = Vec::new();
write_u32(&mut ver, 3);
write_bytes(&mut ver, b"posix-rename@openssh.com");
write_bytes(&mut ver, b"1");
server_replies.extend_from_slice(&packet(SSH_FXP_VERSION, &ver));
let mut rp = Vec::new();
write_u32(&mut rp, 1);
write_u32(&mut rp, 1);
name_entry(&mut rp, "/srv/home", S_IFDIR | 0o755, 4096, 1700000000);
server_replies.extend_from_slice(&packet(SSH_FXP_NAME, &rp));
let mut sent = Vec::new();
let mut client = SftpClient::new(Cursor::new(server_replies), &mut sent).unwrap();
assert_eq!(client.realpath(".").unwrap(), "/srv/home");
}
#[test]
fn sftp_v3_client_rejects_oversized_packet_and_maps_permission_denied() {
let garbage = b"bash: sftp-server: command not found\n".to_vec();
let mut sent = Vec::new();
let err = SftpClient::new(Cursor::new(garbage), &mut sent)
.err()
.unwrap();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
assert!(err.to_string().contains("sftp-server"));
let mut replies = Vec::new();
let mut ver = Vec::new();
write_u32(&mut ver, 3);
replies.extend_from_slice(&packet(SSH_FXP_VERSION, &ver));
replies.extend_from_slice(&((MAX_PACKET_LEN as u32) + 1).to_be_bytes());
let mut sent = Vec::new();
let mut client = SftpClient::new(Cursor::new(replies), &mut sent).unwrap();
let err = client.realpath(".").unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
let mut replies = Vec::new();
let mut ver = Vec::new();
write_u32(&mut ver, 3);
replies.extend_from_slice(&packet(SSH_FXP_VERSION, &ver));
let mut denied = Vec::new();
write_u32(&mut denied, 1);
write_u32(&mut denied, 3);
write_bytes(&mut denied, b"Permission denied");
write_bytes(&mut denied, b"");
replies.extend_from_slice(&packet(SSH_FXP_STATUS, &denied));
let mut sent = Vec::new();
let mut client = SftpClient::new(Cursor::new(replies), &mut sent).unwrap();
let err = client.list_dir("/root").unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::PermissionDenied);
}
}