diff --git a/Cargo.lock b/Cargo.lock index 9c5c21420..3b98b5d8b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4569,9 +4569,19 @@ dependencies = [ name = "wezterm-ssh" version = "0.1.0" dependencies = [ + "anyhow", + "base64", "dirs-next", + "filedescriptor", "k9", + "log", + "portable-pty", "regex", + "shell-words", + "smol", + "ssh2", + "structopt", + "termwiz", ] [[package]] diff --git a/wezterm-ssh/Cargo.toml b/wezterm-ssh/Cargo.toml index cbc68b186..8542d115a 100644 --- a/wezterm-ssh/Cargo.toml +++ b/wezterm-ssh/Cargo.toml @@ -7,8 +7,18 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +anyhow = "1.0" +base64 = "0.13" dirs-next = "2.0" +filedescriptor = { version="0.7", path = "../filedescriptor" } +log = "0.4" +portable-pty = { path = "../pty" } regex = "1" +smol = "1.2" +ssh2 = "0.9" [dev-dependencies] k9 = "0.11.0" +shell-words = "1.0" +structopt = "0.3" +termwiz = { path = "../termwiz" } diff --git a/wezterm-ssh/examples/ssh.rs b/wezterm-ssh/examples/ssh.rs new file mode 100644 index 000000000..300f73bac --- /dev/null +++ b/wezterm-ssh/examples/ssh.rs @@ -0,0 +1,172 @@ +//! This is a really basic ssh client example intended +//! to test the guts of the ssh handling, rather than +//! to be a full fledged replacement for ssh. +use anyhow::Context; +use portable_pty::{Child, MasterPty, PtySize}; +use std::io::{Read, Write}; +use structopt::StructOpt; +use termwiz::cell::unicode_column_width; +use termwiz::lineedit::*; +use wezterm_ssh::{Config, Session, SessionEvent}; + +#[derive(Default)] +struct PasswordPromptHost { + history: BasicHistory, + echo: bool, +} +impl LineEditorHost for PasswordPromptHost { + fn history(&mut self) -> &mut dyn History { + &mut self.history + } + + fn highlight_line(&self, line: &str, cursor_position: usize) -> (Vec, usize) { + if self.echo { + (vec![OutputElement::Text(line.to_string())], cursor_position) + } else { + // Rewrite the input so that we can obscure the password + // characters when output to the terminal widget + let placeholder = "🔑"; + let grapheme_count = unicode_column_width(line); + let mut output = vec![]; + for _ in 0..grapheme_count { + output.push(OutputElement::Text(placeholder.to_string())); + } + (output, unicode_column_width(placeholder) * cursor_position) + } + } +} + +#[derive(Debug, StructOpt, Default, Clone)] +struct Opt { + #[structopt(long = "user", short = "l")] + pub user: Option, + pub destination: String, + pub cmd: Vec, +} + +fn main() { + let opts = Opt::from_args(); + + let mut config = Config::new(); + config.add_default_config_files(); + + let mut config = config.for_host(&opts.destination); + if let Some(user) = opts.user.as_ref() { + config.insert("user".to_string(), user.to_string()); + } + + let res = smol::block_on(async move { + let (session, events) = Session::connect(config.clone())?; + + while let Ok(event) = events.recv().await { + match event { + SessionEvent::Banner(banner) => { + if let Some(banner) = banner { + log::trace!("{}", banner); + } + } + SessionEvent::HostVerify(verify) => { + eprintln!("{}", verify.message); + let mut terminal = line_editor_terminal()?; + let mut editor = LineEditor::new(&mut terminal); + let mut host = PasswordPromptHost::default(); + host.echo = true; + editor.set_prompt("Enter [y/n]> "); + let ok = if let Some(line) = editor.read_line(&mut host)? { + match line.as_ref() { + "y" | "Y" | "yes" | "YES" => true, + "n" | "N" | "no" | "NO" | _ => false, + } + } else { + false + }; + verify.answer(ok).await.context("send verify response")?; + } + SessionEvent::Authenticate(auth) => { + if !auth.username.is_empty() { + eprintln!("Authentication for {}", auth.username); + } + if !auth.instructions.is_empty() { + eprintln!("{}", auth.instructions); + } + let mut terminal = line_editor_terminal()?; + let mut editor = LineEditor::new(&mut terminal); + let mut host = PasswordPromptHost::default(); + let mut answers = vec![]; + for prompt in &auth.prompts { + let mut prompt_lines = prompt.prompt.split('\n').collect::>(); + editor.set_prompt(prompt_lines.pop().unwrap()); + host.echo = prompt.echo; + for line in &prompt_lines { + eprintln!("{}", line); + } + if let Some(line) = editor.read_line(&mut host)? { + answers.push(line); + } else { + anyhow::bail!("Authentication was cancelled"); + } + } + auth.answer(answers).await?; + } + SessionEvent::Error(err) => { + anyhow::bail!("{}", err); + } + SessionEvent::Authenticated => break, + } + } + + let command_line = shell_words::join(&opts.cmd); + let command_line = if command_line.is_empty() { + None + } else { + Some(command_line.as_str()) + }; + + let (pty, mut child) = session + .request_pty("xterm-256color", PtySize::default(), command_line, None) + .await?; + + let mut reader = pty.try_clone_reader()?; + let stdout = std::thread::spawn(move || { + let mut buf = [0u8; 8192]; + let mut stdout = std::io::stdout(); + while let Ok(len) = reader.read(&mut buf) { + if len == 0 { + break; + } + if stdout.write_all(&buf[0..len]).is_err() { + break; + } + } + }); + + // Need to separate out the writer so that we can drop + // the pty which would otherwise keep the ssh session + // thread alive + let mut writer = pty.try_clone_writer()?; + std::thread::spawn(move || { + let mut buf = [0u8; 8192]; + let mut stdin = std::io::stdin(); + while let Ok(len) = stdin.read(&mut buf) { + if len == 0 { + break; + } + if writer.write_all(&buf[0..len]).is_err() { + break; + } + } + }); + + let status = child.wait()?; + let _ = stdout.join(); + if !status.success() { + std::process::exit(1); + } + Ok(()) + }); + + if let Err(err) = res { + eprintln!("{:#}", err); + std::process::exit(1); + } +} diff --git a/wezterm-ssh/src/auth.rs b/wezterm-ssh/src/auth.rs new file mode 100644 index 000000000..d2cf583b1 --- /dev/null +++ b/wezterm-ssh/src/auth.rs @@ -0,0 +1,136 @@ +use crate::session::SessionEvent; +use anyhow::Context; +use smol::channel::{bounded, Sender}; +use std::collections::HashSet; + +#[derive(Debug)] +pub struct AuthenticationPrompt { + pub prompt: String, + pub echo: bool, +} + +#[derive(Debug)] +pub struct AuthenticationEvent { + pub username: String, + pub instructions: String, + pub prompts: Vec, + pub(crate) reply: Sender>, +} + +impl AuthenticationEvent { + pub async fn answer(self, answers: Vec) -> anyhow::Result<()> { + Ok(self.reply.send(answers).await?) + } + + pub fn try_answer(self, answers: Vec) -> anyhow::Result<()> { + Ok(self.reply.try_send(answers)?) + } +} + +impl crate::session::SessionInner { + pub fn authenticate( + &mut self, + sess: &ssh2::Session, + user: &str, + host: &str, + ) -> anyhow::Result<()> { + loop { + if sess.authenticated() { + return Ok(()); + } + + // Re-query the auth methods on each loop as a successful method + // may unlock a new method on a subsequent iteration (eg: password + // auth may then unlock 2fac) + let methods: HashSet<&str> = sess.auth_methods(&user)?.split(',').collect(); + log::trace!("ssh auth methods: {:?}", methods); + + if !sess.authenticated() && methods.contains("publickey") { + if let Err(err) = sess.userauth_agent(&user) { + log::warn!("while attempting agent auth: {}", err); + } else { + continue; + } + } + + if !sess.authenticated() && methods.contains("password") { + let (reply, answers) = bounded(1); + self.tx_event + .try_send(SessionEvent::Authenticate(AuthenticationEvent { + username: user.to_string(), + instructions: "".to_string(), + prompts: vec![AuthenticationPrompt { + prompt: format!("Password for {}@{}: ", user, host), + echo: false, + }], + reply, + })) + .context("sending Authenticate request to user")?; + + let answers = smol::block_on(answers.recv()) + .context("waiting for authentication answers from user")?; + + if answers.is_empty() { + anyhow::bail!("user cancelled authentication"); + } + + if let Err(err) = sess.userauth_password(user, &answers[0]) { + log::error!("while attempting password auth: {}", err); + } + } + + if !sess.authenticated() && methods.contains("keyboard-interactive") { + struct Helper<'a> { + tx_event: &'a Sender, + } + + impl<'a> ssh2::KeyboardInteractivePrompt for Helper<'a> { + fn prompt<'b>( + &mut self, + username: &str, + instructions: &str, + prompts: &[ssh2::Prompt<'b>], + ) -> Vec { + let (reply, answers) = bounded(1); + if let Err(err) = self.tx_event.try_send(SessionEvent::Authenticate( + AuthenticationEvent { + username: username.to_string(), + instructions: instructions.to_string(), + prompts: prompts + .iter() + .map(|p| AuthenticationPrompt { + prompt: p.text.to_string(), + echo: p.echo, + }) + .collect(), + reply, + }, + )) { + log::error!("sending Authenticate request to user: {:#}", err); + return vec![]; + } + + match smol::block_on(answers.recv()) { + Err(err) => { + log::error!( + "waiting for authentication answers from user: {:#}", + err + ); + return vec![]; + } + Ok(answers) => answers, + } + } + } + + let mut helper = Helper { + tx_event: &self.tx_event, + }; + + if let Err(err) = sess.userauth_keyboard_interactive(user, &mut helper) { + log::error!("while attempting keyboard-interactive auth: {}", err); + } + } + } + } +} diff --git a/wezterm-ssh/src/host.rs b/wezterm-ssh/src/host.rs new file mode 100644 index 000000000..103c8f36b --- /dev/null +++ b/wezterm-ssh/src/host.rs @@ -0,0 +1,136 @@ +use crate::session::SessionEvent; +use anyhow::{anyhow, Context}; +use smol::channel::{bounded, Sender}; +use ssh2::CheckResult; +use std::io::Write; +use std::path::Path; + +#[derive(Debug)] +pub struct HostVerificationEvent { + pub message: String, + reply: Sender, +} + +impl HostVerificationEvent { + pub async fn answer(self, trust_host: bool) -> anyhow::Result<()> { + Ok(self.reply.send(trust_host).await?) + } + pub fn try_answer(self, trust_host: bool) -> anyhow::Result<()> { + Ok(self.reply.try_send(trust_host)?) + } +} + +impl crate::session::SessionInner { + pub fn host_verification( + &mut self, + sess: &ssh2::Session, + remote_host_name: &str, + port: u16, + remote_address: &str, + ) -> anyhow::Result<()> { + let mut known_hosts = sess.known_hosts().context("preparing known hosts")?; + + let known_hosts_files = self + .config + .get("userknownhostsfile") + .unwrap() + .split_whitespace() + .map(|s| s.to_string()); + + for file in known_hosts_files { + let file = Path::new(&file); + + if !file.exists() { + continue; + } + + known_hosts + .read_file(&file, ssh2::KnownHostFileKind::OpenSSH) + .with_context(|| format!("reading known_hosts file {}", file.display()))?; + + let (key, key_type) = sess + .host_key() + .ok_or_else(|| anyhow!("failed to get ssh host key"))?; + + let fingerprint = sess + .host_key_hash(ssh2::HashType::Sha256) + .map(|fingerprint| { + format!( + "SHA256:{}", + base64::encode_config( + fingerprint, + base64::Config::new(base64::CharacterSet::Standard, false) + ) + ) + }) + .or_else(|| { + // Querying for the Sha256 can fail if for example we were linked + // against libssh < 1.9, so let's fall back to Sha1 in that case. + sess.host_key_hash(ssh2::HashType::Sha1).map(|fingerprint| { + let mut res = vec![]; + write!(&mut res, "SHA1").ok(); + for b in fingerprint { + write!(&mut res, ":{:02x}", *b).ok(); + } + String::from_utf8(res).unwrap() + }) + }) + .ok_or_else(|| anyhow!("failed to get host fingerprint"))?; + + match known_hosts.check_port(&remote_host_name, port, key) { + CheckResult::Match => {} + CheckResult::NotFound => { + let (reply, confirm) = bounded(1); + self.tx_event + .try_send(SessionEvent::HostVerify(HostVerificationEvent { + message: format!( + "SSH host {} is not yet trusted.\n\ + {:?} Fingerprint: {}.\n\ + Trust and continue connecting?", + remote_address, key_type, fingerprint + ), + reply, + })) + .context("sending HostVerify request to user")?; + + let trusted = smol::block_on(confirm.recv()) + .context("waiting for host verification confirmation from user")?; + + if !trusted { + anyhow::bail!("user declined to trust host"); + } + + let host_and_port = if port != 22 { + format!("[{}]:{}", remote_host_name, port) + } else { + remote_host_name.to_string() + }; + + known_hosts + .add(&host_and_port, key, &remote_address, key_type.into()) + .context("adding known_hosts entry in memory")?; + + known_hosts + .write_file(&file, ssh2::KnownHostFileKind::OpenSSH) + .with_context(|| format!("writing known_hosts file {}", file.display()))?; + } + CheckResult::Mismatch => { + anyhow::bail!( + "host key mismatch for ssh server {}.\n\ + Got fingerprint {} instead of expected value from known_hosts\n\ + file {}.\n\ + Refusing to connect.", + remote_address, + fingerprint, + file.display() + ); + } + CheckResult::Failure => { + anyhow::bail!("failed to check the known hosts"); + } + } + } + + Ok(()) + } +} diff --git a/wezterm-ssh/src/lib.rs b/wezterm-ssh/src/lib.rs index ef68c3694..241315129 100644 --- a/wezterm-ssh/src/lib.rs +++ b/wezterm-ssh/src/lib.rs @@ -1 +1,11 @@ -pub mod config; +mod auth; +mod config; +mod host; +mod pty; +mod session; + +pub use auth::*; +pub use config::*; +pub use host::*; +pub use pty::*; +pub use session::*; diff --git a/wezterm-ssh/src/pty.rs b/wezterm-ssh/src/pty.rs new file mode 100644 index 000000000..a79bd2a48 --- /dev/null +++ b/wezterm-ssh/src/pty.rs @@ -0,0 +1,242 @@ +use crate::session::{ChannelId, ChannelInfo, DescriptorState, SessionRequest, SessionSender}; +use filedescriptor::{socketpair, FileDescriptor}; +use portable_pty::{ExitStatus, PtySize}; +use smol::channel::{bounded, Receiver, Sender, TryRecvError}; +use std::collections::HashMap; +use std::collections::VecDeque; +use std::io::{Read, Write}; +use std::sync::Mutex; + +#[derive(Debug)] +pub(crate) struct NewPty { + pub term: String, + pub size: PtySize, + pub command_line: Option, + pub env: Option>, + pub reply: Sender<(SshPty, SshChildProcess)>, +} + +#[derive(Debug)] +pub(crate) struct ResizePty { + pub channel: ChannelId, + pub size: PtySize, + pub reply: Sender<()>, +} + +#[derive(Debug)] +pub struct SshPty { + pub(crate) channel: ChannelId, + pub(crate) tx: Option, + pub(crate) reader: FileDescriptor, + pub(crate) writer: FileDescriptor, + pub(crate) size: Mutex, +} + +impl std::io::Write for SshPty { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.writer.write(buf) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.writer.flush() + } +} + +impl portable_pty::MasterPty for SshPty { + fn resize(&self, size: PtySize) -> anyhow::Result<()> { + let (tx, rx) = bounded(1); + self.tx + .as_ref() + .unwrap() + .try_send(SessionRequest::ResizePty(ResizePty { + channel: self.channel, + size, + reply: tx, + }))?; + + smol::block_on(rx.recv())?; + *self.size.lock().unwrap() = size; + Ok(()) + } + + fn get_size(&self) -> anyhow::Result { + Ok(*self.size.lock().unwrap()) + } + + fn try_clone_reader(&self) -> anyhow::Result> { + self.reader + .try_clone() + .map(|f| -> Box<(dyn Read + Send + 'static)> { Box::new(f) }) + } + + fn try_clone_writer(&self) -> anyhow::Result> { + self.writer + .try_clone() + .map(|f| -> Box<(dyn Write + Send + 'static)> { Box::new(f) }) + } + + fn process_group_leader(&self) -> Option { + // It's not local, so there's no meaningful leader + None + } +} + +#[derive(Debug)] +pub struct SshChildProcess { + pub(crate) channel: ChannelId, + pub(crate) tx: Option, + pub(crate) exit: Receiver, + pub(crate) exited: Option, +} + +impl portable_pty::Child for SshChildProcess { + fn try_wait(&mut self) -> std::io::Result> { + if let Some(status) = self.exited.as_ref() { + return Ok(Some(status.clone())); + } + match self.exit.try_recv() { + Ok(status) => { + self.exited.replace(status.clone()); + Ok(Some(status)) + } + Err(TryRecvError::Empty) => Ok(None), + Err(TryRecvError::Closed) => { + let status = ExitStatus::with_exit_code(1); + self.exited.replace(status.clone()); + Ok(Some(status)) + } + } + } + + fn kill(&mut self) -> std::io::Result<()> { + // There is no way to send a signal via libssh2. + // Just pretend that we did. :-/ + Ok(()) + } + + fn wait(&mut self) -> std::io::Result { + if let Some(status) = self.exited.as_ref() { + return Ok(status.clone()); + } + match smol::block_on(self.exit.recv()) { + Ok(status) => { + self.exited.replace(status.clone()); + Ok(status) + } + Err(_) => { + let status = ExitStatus::with_exit_code(1); + self.exited.replace(status.clone()); + Ok(status) + } + } + } + + fn process_id(&self) -> Option { + None + } +} + +impl crate::session::SessionInner { + pub fn new_pty(&mut self, sess: &ssh2::Session, newpty: &NewPty) -> anyhow::Result<()> { + sess.set_blocking(true); + + let mut channel = sess.channel_session()?; + + channel.handle_extended_data(ssh2::ExtendedData::Merge)?; + channel.request_pty( + &newpty.term, + None, + Some(( + newpty.size.cols.into(), + newpty.size.rows.into(), + newpty.size.pixel_width.into(), + newpty.size.pixel_height.into(), + )), + )?; + + if let Some(env) = &newpty.env { + for (key, val) in env { + if let Err(err) = channel.setenv(key, val) { + // Depending on the server configuration, a given + // setenv request may not succeed, but that doesn't + // prevent the connection from being set up. + log::error!("ssh: setenv {}={} failed: {}", key, val, err); + } + } + } + + if let Some(cmd) = &newpty.command_line { + channel.exec(cmd)?; + } else { + channel.shell()?; + } + + let channel_id = self.next_channel_id; + self.next_channel_id += 1; + + let (write_to_stdin, mut read_from_stdin) = socketpair()?; + let (mut write_to_stdout, read_from_stdout) = socketpair()?; + + read_from_stdin.set_non_blocking(true)?; + write_to_stdout.set_non_blocking(true)?; + + let ssh_pty = SshPty { + channel: channel_id, + tx: None, + reader: read_from_stdout, + writer: write_to_stdin, + size: Mutex::new(newpty.size), + }; + + let (exit_tx, exit_rx) = bounded(1); + + let child = SshChildProcess { + channel: channel_id, + tx: None, + exit: exit_rx, + exited: None, + }; + + let info = ChannelInfo { + channel_id, + channel, + exit: Some(exit_tx), + descriptors: [ + DescriptorState { + fd: Some(read_from_stdin), + buf: VecDeque::with_capacity(8192), + }, + DescriptorState { + fd: Some(write_to_stdout), + buf: VecDeque::with_capacity(8192), + }, + DescriptorState { + fd: None, + buf: VecDeque::new(), + }, + ], + }; + + newpty.reply.try_send((ssh_pty, child))?; + self.channels.insert(channel_id, info); + + Ok(()) + } + + pub fn resize_pty(&mut self, sess: &ssh2::Session, resize: &ResizePty) -> anyhow::Result<()> { + sess.set_blocking(true); + + let info = self + .channels + .get_mut(&resize.channel) + .ok_or_else(|| anyhow::anyhow!("invalid channel id {}", resize.channel))?; + info.channel.request_pty_size( + resize.size.cols.into(), + resize.size.rows.into(), + Some(resize.size.pixel_width.into()), + Some(resize.size.pixel_height.into()), + )?; + resize.reply.try_send(())?; + Ok(()) + } +} diff --git a/wezterm-ssh/src/session.rs b/wezterm-ssh/src/session.rs new file mode 100644 index 000000000..0eebbc905 --- /dev/null +++ b/wezterm-ssh/src/session.rs @@ -0,0 +1,425 @@ +use crate::auth::*; +use crate::config::ConfigMap; +use crate::host::*; +use crate::pty::*; +use anyhow::{anyhow, Context}; +use filedescriptor::{ + poll, pollfd, socketpair, AsRawSocketDescriptor, FileDescriptor, POLLIN, POLLOUT, +}; +use portable_pty::{ExitStatus, PtySize}; +use smol::channel::{bounded, Receiver, Sender, TryRecvError}; +use ssh2::BlockDirections; +use std::collections::{HashMap, VecDeque}; +use std::io::{Read, Write}; +use std::net::TcpStream; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +#[derive(Debug)] +pub enum SessionEvent { + Banner(Option), + HostVerify(HostVerificationEvent), + Authenticate(AuthenticationEvent), + Error(String), + Authenticated, +} + +#[derive(Debug, Clone)] +pub(crate) struct SessionSender { + pub tx: Sender, + pub pipe: Arc>, +} + +impl SessionSender { + fn post_send(&self) { + let mut pipe = self.pipe.lock().unwrap(); + let _ = pipe.write(b"x"); + } + + pub fn try_send(&self, event: SessionRequest) -> anyhow::Result<()> { + self.tx.try_send(event)?; + self.post_send(); + Ok(()) + } + + pub async fn send(&self, event: SessionRequest) -> anyhow::Result<()> { + self.tx.send(event).await?; + self.post_send(); + Ok(()) + } +} + +#[derive(Debug)] +pub(crate) enum SessionRequest { + NewPty(NewPty), + ResizePty(ResizePty), +} + +pub(crate) struct DescriptorState { + pub fd: Option, + pub buf: VecDeque, +} + +pub(crate) struct ChannelInfo { + pub channel_id: ChannelId, + pub channel: ssh2::Channel, + pub exit: Option>, + pub descriptors: [DescriptorState; 3], +} + +pub(crate) type ChannelId = usize; + +pub(crate) struct SessionInner { + pub config: ConfigMap, + pub tx_event: Sender, + pub rx_req: Receiver, + pub channels: HashMap, + pub next_channel_id: ChannelId, + pub sender_read: FileDescriptor, +} + +impl Drop for SessionInner { + fn drop(&mut self) { + log::trace!("Dropping SessionInner"); + } +} + +impl SessionInner { + fn run(&mut self) { + if let Err(err) = self.run_impl() { + self.tx_event + .try_send(SessionEvent::Error(format!("{:#}", err))) + .ok(); + } + } + + fn run_impl(&mut self) -> anyhow::Result<()> { + let hostname = self + .config + .get("hostname") + .ok_or_else(|| anyhow!("hostname not present in config"))? + .to_string(); + let user = self + .config + .get("user") + .ok_or_else(|| anyhow!("username not present in config"))? + .to_string(); + let port = self.config.get("port").unwrap().parse::()?; + + let remote_address = format!("{}:{}", hostname, port); + let tcp = TcpStream::connect((hostname.as_str(), port)) + .with_context(|| format!("connecting to {}", remote_address))?; + + tcp.set_nodelay(true) + .context("setting TCP NODELAY on ssh connection")?; + + let mut sess = ssh2::Session::new()?; + sess.set_tcp_stream(tcp); + sess.handshake() + .with_context(|| format!("ssh handshake with {}", remote_address))?; + + self.tx_event + .try_send(SessionEvent::Banner(sess.banner().map(|s| s.to_string()))) + .context("notifying user of banner")?; + + self.host_verification(&sess, &hostname, port, &remote_address) + .context("host verification")?; + + self.authenticate(&sess, &user, &hostname) + .context("authentication")?; + + self.tx_event + .try_send(SessionEvent::Authenticated) + .context("notifying user that session is authenticated")?; + + sess.set_blocking(false); + self.request_loop(sess) + } + + fn request_loop(&mut self, sess: ssh2::Session) -> anyhow::Result<()> { + loop { + self.tick_io()?; + self.drain_request_pipe(); + self.dispatch_pending_requests(&sess)?; + + let mut poll_array = vec![ + pollfd { + fd: self.sender_read.as_socket_descriptor(), + events: POLLIN, + revents: 0, + }, + pollfd { + fd: sess.as_socket_descriptor(), + events: match sess.block_directions() { + BlockDirections::None => 0, + BlockDirections::Inbound => POLLIN, + BlockDirections::Outbound => POLLOUT, + BlockDirections::Both => POLLIN | POLLOUT, + }, + revents: 0, + }, + ]; + let mut mapping = vec![]; + + for info in self.channels.values() { + for (fd_num, state) in info.descriptors.iter().enumerate() { + if let Some(fd) = state.fd.as_ref() { + poll_array.push(pollfd { + fd: fd.as_socket_descriptor(), + events: if fd_num == 0 { + POLLIN + } else if !state.buf.is_empty() { + POLLOUT + } else { + 0 + }, + revents: 0, + }); + mapping.push((info.channel_id, fd_num)); + } + } + } + + poll(&mut poll_array, Some(Duration::from_secs(1))).context("poll")?; + + for (idx, poll) in poll_array.iter().enumerate() { + if idx == 0 || idx == 1 { + // Dealt with at the top of the loop + } else if poll.revents != 0 { + let (channel_id, fd_num) = mapping[idx - 2]; + let info = self.channels.get_mut(&channel_id).unwrap(); + let state = &mut info.descriptors[fd_num]; + let fd = state.fd.as_mut().unwrap(); + + if fd_num == 0 { + // There's data we can read into the buffer + match read_into_buf(fd, &mut state.buf) { + Ok(_) => {} + Err(err) => { + log::debug!("error reading from stdin pipe: {:#}", err); + let _ = info.channel.close(); + state.fd.take(); + } + } + } else { + // We can write our buffered output + match write_from_buf(fd, &mut state.buf) { + Ok(_) => {} + Err(err) => { + log::debug!( + "error while writing to channel {} fd {}: {:#}", + channel_id, + fd_num, + err + ); + + // Close it out + state.fd.take(); + } + } + } + } + } + } + } + + /// Goal: if we have data to write to channels, try to send it. + /// If we have room in our channel fd write buffers, try to fill it + fn tick_io(&mut self) -> anyhow::Result<()> { + for chan in self.channels.values_mut() { + if chan.exit.is_some() { + if chan.channel.wait_close().is_ok() { + fn has_signal(chan: &ssh2::Channel) -> Option { + if let Ok(sig) = chan.exit_signal() { + if sig.exit_signal.is_some() { + return Some(sig); + } + } + None + } + + let status = if let Some(_sig) = has_signal(&chan.channel) { + Some(ExitStatus::with_exit_code(1)) + } else if let Ok(status) = chan.channel.exit_status() { + Some(ExitStatus::with_exit_code(status as _)) + } else { + None + }; + + if let Some(status) = status { + let exit = chan.exit.take().unwrap(); + smol::block_on(exit.send(status)).ok(); + } + } + } + + let stdin = &mut chan.descriptors[0]; + if stdin.fd.is_some() && !stdin.buf.is_empty() { + match write_from_buf(&mut chan.channel, &mut stdin.buf) { + Ok(_) => {} + Err(err) => { + log::error!("Failed to write data to channel: {:#}. Now what?", err); + } + } + } + + for out in chan.descriptors.get_mut(1..).unwrap() { + if out.fd.is_none() { + continue; + } + let current_len = out.buf.len(); + let room = out.buf.capacity() - current_len; + if room == 0 { + continue; + } + match read_into_buf(&mut chan.channel, &mut out.buf) { + Ok(_) => {} + Err(err) => { + if out.buf.is_empty() { + log::trace!( + "Failed to read data from channel: {:#}, closing pipe", + err + ); + out.fd.take(); + } else { + log::trace!("Failed to read data from channel: {:#}, but still have some buffer to drain", err); + } + } + } + } + } + Ok(()) + } + + fn drain_request_pipe(&mut self) { + let mut buf = [0u8; 16]; + let _ = self.sender_read.read(&mut buf); + } + + fn dispatch_pending_requests(&mut self, sess: &ssh2::Session) -> anyhow::Result<()> { + sess.set_blocking(true); + while self.dispatch_one_request(sess)? {} + sess.set_blocking(false); + Ok(()) + } + + fn dispatch_one_request(&mut self, sess: &ssh2::Session) -> anyhow::Result { + match self.rx_req.try_recv() { + Err(TryRecvError::Closed) => anyhow::bail!("all clients are closed"), + Err(TryRecvError::Empty) => Ok(false), + Ok(SessionRequest::NewPty(newpty)) => { + if let Err(err) = self.new_pty(&sess, &newpty) { + log::error!("{:?} -> error: {:#}", newpty, err); + } + Ok(true) + } + Ok(SessionRequest::ResizePty(resize)) => { + if let Err(err) = self.resize_pty(&sess, &resize) { + log::error!("{:?} -> error: {:#}", resize, err); + } + Ok(true) + } + } + } +} + +pub struct Session { + tx: SessionSender, +} + +impl Drop for Session { + fn drop(&mut self) { + log::trace!("Drop Session"); + } +} + +impl Session { + pub fn connect(config: ConfigMap) -> anyhow::Result<(Self, Receiver)> { + let (tx_event, rx_event) = bounded(8); + let (tx_req, rx_req) = bounded(8); + let (mut sender_write, mut sender_read) = socketpair()?; + sender_write.set_non_blocking(true)?; + sender_read.set_non_blocking(true)?; + + let session_sender = SessionSender { + tx: tx_req, + pipe: Arc::new(Mutex::new(sender_write)), + }; + + let mut inner = SessionInner { + config, + tx_event, + rx_req, + channels: HashMap::new(), + next_channel_id: 1, + sender_read, + }; + std::thread::spawn(move || inner.run()); + Ok((Self { tx: session_sender }, rx_event)) + } + + pub async fn request_pty( + &self, + term: &str, + size: PtySize, + command_line: Option<&str>, + env: Option>, + ) -> anyhow::Result<(SshPty, SshChildProcess)> { + let (reply, rx) = bounded(1); + self.tx + .send(SessionRequest::NewPty(NewPty { + term: term.to_string(), + size, + command_line: command_line.map(|s| s.to_string()), + env, + reply, + })) + .await?; + let (mut ssh_pty, mut child) = rx.recv().await?; + ssh_pty.tx.replace(self.tx.clone()); + child.tx.replace(self.tx.clone()); + Ok((ssh_pty, child)) + } +} + +fn write_from_buf(w: &mut W, buf: &mut VecDeque) -> std::io::Result<()> { + match w.write(buf.make_contiguous()) { + Ok(len) => { + buf.drain(0..len); + Ok(()) + } + Err(err) => { + if err.kind() == std::io::ErrorKind::WouldBlock { + return Ok(()); + } + Err(err) + } + } +} + +fn read_into_buf(r: &mut R, buf: &mut VecDeque) -> std::io::Result<()> { + let current_len = buf.len(); + buf.resize(buf.capacity(), 0); + let target_buf = &mut buf.make_contiguous()[current_len..]; + match r.read(target_buf) { + Ok(len) => { + buf.resize(current_len + len, 0); + if len == 0 { + Err(std::io::Error::new( + std::io::ErrorKind::UnexpectedEof, + "EOF", + )) + } else { + Ok(()) + } + } + Err(err) => { + buf.resize(current_len, 0); + + if err.kind() == std::io::ErrorKind::WouldBlock { + return Ok(()); + } + Err(err) + } + } +}