Compare commits

..

No commits in common. "36a62018e58c23ad21a8910a0e06ef3e44825d80" and "1f72560438e9488384966823309ba9341daba2a2" have entirely different histories.

3 changed files with 40 additions and 80 deletions

View file

@ -1,14 +1,7 @@
use std::{net::SocketAddr, sync::Arc}; use std::{net::SocketAddr, sync::{Arc, LazyLock, OnceLock}};
use clap::Parser as _;
use cli::Cli;
use color_eyre::{eyre::eyre, Result}; use color_eyre::{eyre::eyre, Result};
use lazy_static::lazy_static; use russh::{keys::PrivateKey, server::{Config, Server}, MethodSet};
use russh::{
keys::PrivateKey,
server::{Config, Server},
MethodSet,
};
use ssh::SshServer; use ssh::SshServer;
use tokio::net::TcpListener; use tokio::net::TcpListener;
@ -18,42 +11,39 @@ mod cli;
mod components; mod components;
mod config; mod config;
mod errors; mod errors;
mod keycode;
mod logging; mod logging;
mod ssh; mod ssh;
mod tui; mod tui;
mod keycode;
const SSH_KEYS: &[&[u8]] = &[ const SOCKET_ADDR: LazyLock<SocketAddr> = LazyLock::new(|| SocketAddr::from(([127, 0, 0, 1], 2222)));
include_bytes!("../rsa.pem"), pub static SSH_CONFIG: OnceLock<Arc<Config>> = OnceLock::new();
include_bytes!("../ed25519.pem"),
];
lazy_static! {
pub(crate) static ref OPTIONS: Cli = Cli::parse();
pub(crate) static ref SOCKET_ADDR: SocketAddr = SocketAddr::from(([127, 0, 0, 1], 2222));
}
#[tokio::main] #[tokio::main]
async fn main() -> Result<()> { async fn main() -> Result<()> {
crate::errors::init()?; crate::errors::init()?;
crate::logging::init()?; crate::logging::init()?;
let config = ssh_config(); SSH_CONFIG.get_or_init(|| {
tracing::info!("Attempting to listen on {}", *SOCKET_ADDR); tracing::debug!("setting up ssh config");
SshServer::default()
.run_on_socket(Arc::new(config), &TcpListener::bind(*SOCKET_ADDR).await?)
.await
.map_err(|err| eyre!(err))
}
fn ssh_config() -> Config { let mut conf = Config::default();
let mut conf = Config::default(); conf.methods = MethodSet::NONE;
conf.methods = MethodSet::NONE; conf.keys = vec![
conf.keys = SSH_KEYS PrivateKey::from_openssh(include_bytes!("../rsa.pem")).unwrap(),
.to_vec() // PrivateKey::from_openssh(include_bytes!("../ecdsa.pem")).unwrap(),
.iter() PrivateKey::from_openssh(include_bytes!("../ed25519.pem")).unwrap()
.filter_map(|pem| PrivateKey::from_openssh(pem).ok()) ];
.collect(); Arc::new(conf)
});
tracing::trace!("SSH config: {:#?}", conf); // let args = Cli::parse();
conf // let mut app = App::new(args.tick_rate, args.frame_rate)?;
// app.run().await?;
tracing::info!("attemping to listen on {}", *SOCKET_ADDR);
SshServer::default().run_on_socket(
Arc::clone(SSH_CONFIG.get().unwrap()),
&TcpListener::bind(*SOCKET_ADDR).await?,
).await.map_err(|err| eyre!(err))
} }

View file

@ -1,7 +1,7 @@
use std::{io::Write, net::SocketAddr, sync::Arc}; use std::{io::Write, net::SocketAddr, sync::Arc};
use async_trait::async_trait; use async_trait::async_trait;
use color_eyre::eyre::{self, eyre}; use color_eyre::eyre::eyre;
use ratatui::prelude::CrosstermBackend; use ratatui::prelude::CrosstermBackend;
use russh::{ use russh::{
server::{Auth, Handle, Handler, Msg, Server, Session}, server::{Auth, Handle, Handler, Msg, Server, Session},
@ -16,7 +16,6 @@ use tracing::instrument;
use crate::{ use crate::{
app::App, app::App,
tui::{Terminal, Tui}, tui::{Terminal, Tui},
OPTIONS,
}; };
#[derive(Debug)] #[derive(Debug)]
@ -28,9 +27,7 @@ pub struct TermWriter {
} }
impl TermWriter { impl TermWriter {
#[instrument(skip(session, channel), level = "trace", fields(channel_id = %channel.id()))]
fn new(session: &mut Session, channel: Channel<Msg>) -> Self { fn new(session: &mut Session, channel: Channel<Msg>) -> Self {
tracing::trace!("Acquiring new SSH writer");
Self { Self {
session: session.handle(), session: session.handle(),
channel, channel,
@ -55,17 +52,12 @@ impl TermWriter {
impl Write for TermWriter { impl Write for TermWriter {
#[instrument(skip(self, buf), level = "debug")] #[instrument(skip(self, buf), level = "debug")]
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
tracing::trace!(
"Writing {} bytes into SSH terminal writer buffer",
buf.len()
);
self.inner.extend(buf); self.inner.extend(buf);
Ok(buf.len()) Ok(buf.len())
} }
#[instrument(skip(self), level = "trace")] #[instrument(skip(self), level = "trace")]
fn flush(&mut self) -> std::io::Result<()> { fn flush(&mut self) -> std::io::Result<()> {
tracing::trace!("Flushing SSH terminal writer buffer");
tokio::task::block_in_place(|| self.flush_inner()) tokio::task::block_in_place(|| self.flush_inner())
} }
} }
@ -76,48 +68,32 @@ pub struct SshSession {
tui: Arc<RwLock<Option<Tui>>>, tui: Arc<RwLock<Option<Tui>>>,
} }
unsafe impl Send for SshSession {}
impl SshSession { impl SshSession {
pub fn new() -> Self { pub fn new() -> Self {
let (ssh_tx, ssh_rx) = mpsc::unbounded_channel(); let (ssh_tx, ssh_rx) = mpsc::unbounded_channel();
Self { Self {
app: App::new(OPTIONS.tick_rate, OPTIONS.frame_rate, ssh_rx) app: App::new(10f64, 60f64, ssh_rx)
.ok() .ok()
.map(|app| Arc::new(Mutex::new(app))), .map(|app| Arc::new(Mutex::new(app))),
tui: Arc::new(RwLock::new(None)), tui: Arc::new(RwLock::new(None)),
ssh_tx, ssh_tx,
} }
} }
async fn run_app(
app: Arc<Mutex<App>>,
writer: Arc<Mutex<Terminal>>,
tui: Arc<RwLock<Option<Tui>>>,
session: &Handle,
channel_id: ChannelId,
) -> eyre::Result<()> {
app.lock_owned().await.run(writer, tui).await?;
session
.close(channel_id)
.await
.map_err(|_| eyre!("failed to close session"))?;
session
.exit_status_request(channel_id, 0)
.await
.map_err(|_| eyre!("failed to send session exit status"))
}
} }
#[async_trait] #[async_trait]
impl Handler for SshSession { impl Handler for SshSession {
type Error = eyre::Error; type Error = color_eyre::eyre::Error;
#[instrument(skip(self), span = "user_login", fields(method = "none"))] #[instrument(skip(self), span = "user_login", fields(method = "none"))]
async fn auth_none(&mut self, user: &str) -> Result<Auth, Self::Error> { async fn auth_none(&mut self, user: &str) -> Result<Auth, Self::Error> {
Ok(Auth::Accept) Ok(Auth::Accept)
} }
#[instrument(skip(self, session, channel), span = "channel_establish", fields(channel_id = %channel.id()))] #[instrument(skip(self), span = "channel_establish", level = "trace")]
async fn channel_open_session( async fn channel_open_session(
&mut self, &mut self,
channel: Channel<Msg>, channel: Channel<Msg>,
@ -132,16 +108,10 @@ impl Handler for SshSession {
let writer = Arc::new(Mutex::new(term)); let writer = Arc::new(Mutex::new(term));
let tui = Arc::clone(&self.tui); let tui = Arc::clone(&self.tui);
tracing::info!("Serving app to open session");
tokio::task::spawn(async move { tokio::task::spawn(async move {
let res = Self::run_app(inner_app, writer, tui, &session_handle, channel_id).await; inner_app.lock_owned().await.run(writer, tui).await.unwrap();
match res { session_handle.close(channel_id).await.unwrap();
Ok(()) => tracing::info!("session exited"), session_handle.exit_status_request(channel_id, 0).await.unwrap();
Err(err) => {
tracing::error!("Session exited with error: {err}");
let _ = session_handle.channel_failure(channel_id).await;
}
}
}); });
return Ok(true); return Ok(true);
@ -149,7 +119,7 @@ impl Handler for SshSession {
Err(eyre!("Failed to initialize App for session")) Err(eyre!("Failed to initialize App for session"))
} }
#[instrument(skip_all, fields(channel_id = %channel_id))] #[instrument(skip(self, session), level = "trace")]
async fn pty_request( async fn pty_request(
&mut self, &mut self,
channel_id: ChannelId, channel_id: ChannelId,
@ -158,10 +128,10 @@ impl Handler for SshSession {
row_height: u32, row_height: u32,
pix_width: u32, pix_width: u32,
pix_height: u32, pix_height: u32,
_modes: &[(Pty, u32)], modes: &[(Pty, u32)],
session: &mut Session, session: &mut Session,
) -> Result<(), Self::Error> { ) -> Result<(), Self::Error> {
tracing::info!("PTY requested by terminal: {term}"); tracing::info!("Received pty request from channel {channel_id}; terminal: {term}");
tracing::debug!("dims: {col_width} * {row_height}, pixel: {pix_width} * {pix_height}"); tracing::debug!("dims: {col_width} * {row_height}, pixel: {pix_width} * {pix_height}");
if !term.contains("xterm") { if !term.contains("xterm") {

View file

@ -243,6 +243,6 @@ impl Tui {
impl Drop for Tui { impl Drop for Tui {
fn drop(&mut self) { fn drop(&mut self) {
let _ = self.exit().inspect_err(|err| error!("Failed to exit Tui: {err}")); self.exit().unwrap();
} }
} }