mod decoder;
#[cfg(test)]
mod tests;
pub use decoder::FrameDecoder;
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use core::future::Future;
use crate::base::channel::{Channel, SelectResult};
use crate::base::decimal::format_u32;
use crate::base::destination::{self as dest, DestinationError};
use crate::base::protocol::features::Feature;
use crate::base::session::Session;
use crate::error::{Error, ProtocolError};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FrameId {
Stdin,
Stdout,
Stderr,
Exit,
CloseStdin,
WindowSizeChange,
}
impl TryFrom<u8> for FrameId {
type Error = u8;
fn try_from(id: u8) -> Result<Self, u8> {
Ok(match id {
0 => Self::Stdin,
1 => Self::Stdout,
2 => Self::Stderr,
3 => Self::Exit,
4 => Self::CloseStdin,
5 => Self::WindowSizeChange,
other => return Err(other),
})
}
}
impl From<FrameId> for u8 {
fn from(id: FrameId) -> Self {
match id {
FrameId::Stdin => 0,
FrameId::Stdout => 1,
FrameId::Stderr => 2,
FrameId::Exit => 3,
FrameId::CloseStdin => 4,
FrameId::WindowSizeChange => 5,
}
}
}
impl FrameId {
pub fn byte_of(id: Result<FrameId, u8>) -> u8 {
match id {
Ok(id) => id.into(),
Err(byte) => byte,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ShellMode<'a> {
Raw,
Pty {
term: Option<&'a str>,
},
}
pub fn destination(mode: ShellMode<'_>, command: &str) -> Result<String, ProtocolError> {
if command.contains('\0') {
return Err(ProtocolError::InvalidDestination);
}
Ok(match mode {
ShellMode::Raw => format!("shell,v2,raw:{command}\0"),
ShellMode::Pty {
term: None | Some(""),
} => format!("shell,v2,pty:{command}\0"),
ShellMode::Pty { term: Some(term) } => {
if term.contains([',', ':', '\0']) {
return Err(ProtocolError::InvalidDestination);
}
format!("shell,v2,pty,TERM={term}:{command}\0")
}
})
}
pub const HEADER_SIZE: usize = 5;
pub(crate) fn parse_header(buf: &[u8; HEADER_SIZE]) -> (Result<FrameId, u8>, u32) {
let length = u32::from_le_bytes([buf[1], buf[2], buf[3], buf[4]]);
(FrameId::try_from(buf[0]), length)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct WindowSize {
pub rows: u16,
pub cols: u16,
}
impl WindowSize {
pub fn encode(&self) -> EncodedWindowSize {
let mut out = EncodedWindowSize {
bytes: [0; EncodedWindowSize::MAX_LEN],
len: 0,
};
let mut digits = [0; 10];
out.push(format_u32(self.rows.into(), &mut digits));
out.push(b"x");
out.push(format_u32(self.cols.into(), &mut digits));
out.push(b",0x0\0");
out
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct EncodedWindowSize {
bytes: [u8; Self::MAX_LEN],
len: usize,
}
impl EncodedWindowSize {
pub const MAX_LEN: usize = "65535x65535,0x0\0".len();
pub fn as_bytes(&self) -> &[u8] {
&self.bytes[..self.len]
}
fn push(&mut self, part: &[u8]) {
let end = self.len + part.len();
self.bytes[self.len..end].copy_from_slice(part);
self.len = end;
}
}
impl AsRef<[u8]> for EncodedWindowSize {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl fmt::Debug for EncodedWindowSize {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let text = core::str::from_utf8(self.as_bytes()).unwrap_or("<not ASCII>");
f.debug_tuple("EncodedWindowSize").field(&text).finish()
}
}
#[derive(Debug, Clone)]
pub enum Frame {
Stdout(Vec<u8>),
Stderr(Vec<u8>),
Exit(u8),
Other {
id: u8,
payload: Vec<u8>,
},
}
#[derive(Debug, Clone, Default)]
pub struct CommandOutput {
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
pub exit_code: u8,
}
pub struct Shell<'a, 'b, S> {
channel: Channel<'a, S>,
rx: &'b mut [u8],
decoder: FrameDecoder,
}
impl<'a, 'b, S: Session> Shell<'a, 'b, S> {
pub fn new(channel: Channel<'a, S>, rx: &'b mut [u8]) -> Self {
assert!(
rx.len() >= HEADER_SIZE,
"Shell rx buffer must be at least HEADER_SIZE ({}) bytes",
HEADER_SIZE,
);
Self {
channel,
rx,
decoder: FrameDecoder::new(),
}
}
pub async fn send_frame(
&mut self,
id: FrameId,
payload: &[u8],
) -> Result<(), Error<S::IoError>> {
let len_u32 = u32::try_from(payload.len()).map_err(|_| ProtocolError::PayloadTooLarge)?;
let hdr: [u8; HEADER_SIZE] = {
let b = len_u32.to_le_bytes();
[id.into(), b[0], b[1], b[2], b[3]]
};
let total = HEADER_SIZE + payload.len();
self.decoder.compact(self.rx);
let free = self.rx.len() - self.decoder.tail;
if total <= free {
let start = self.decoder.tail;
self.rx[start..start + HEADER_SIZE].copy_from_slice(&hdr);
self.rx[start + HEADER_SIZE..start + total].copy_from_slice(payload);
self.channel.write(&self.rx[start..start + total]).await
} else {
self.channel.write(&hdr).await?;
if !payload.is_empty() {
self.channel.write(payload).await?;
}
Ok(())
}
}
pub async fn write_stdin(&mut self, data: &[u8]) -> Result<(), Error<S::IoError>> {
self.send_frame(FrameId::Stdin, data).await
}
pub async fn close_stdin(&mut self) -> Result<(), Error<S::IoError>> {
match self.send_frame(FrameId::CloseStdin, &[]).await {
Err(Error::ChannelClosed) => Ok(()),
sent => sent,
}
}
pub async fn set_window_size(&mut self, size: WindowSize) -> Result<(), Error<S::IoError>> {
self.send_frame(FrameId::WindowSizeChange, size.encode().as_bytes())
.await
}
pub async fn read_frame(&mut self) -> Result<Frame, Error<S::IoError>> {
loop {
if let Some(frame) = self.try_next_frame()? {
return Ok(frame);
}
self.ensure_writable()?;
let n = self.channel.read(&mut self.rx[self.decoder.tail..]).await?;
self.decoder.commit(n);
}
}
pub fn try_next_frame(&mut self) -> Result<Option<Frame>, Error<S::IoError>> {
self.decoder
.try_next_frame(self.rx)
.map_err(Error::Protocol)
}
#[allow(clippy::type_complexity)]
pub fn try_next_raw_ref(
&mut self,
) -> Result<Option<(Result<FrameId, u8>, &[u8])>, Error<S::IoError>> {
self.decoder
.try_next_raw_ref(self.rx)
.map_err(Error::Protocol)
}
pub async fn pump<F: Future>(
&mut self,
interrupt: F,
) -> Result<SelectResult<F::Output>, Error<S::IoError>> {
self.ensure_writable()?;
let result = self
.channel
.select(&mut self.rx[self.decoder.tail..], interrupt)
.await?;
if let SelectResult::Data(n) = &result {
self.decoder.commit(*n);
}
Ok(result)
}
fn ensure_writable(&mut self) -> Result<(), Error<S::IoError>> {
if self.decoder.tail < self.rx.len() {
return Ok(());
}
self.decoder.compact(self.rx);
if self.decoder.tail == self.rx.len() {
return Err(Error::ReceiveBufferFull);
}
Ok(())
}
pub async fn collect(mut self) -> Result<CommandOutput, Error<S::IoError>> {
let mut out = CommandOutput::default();
let read = loop {
match self.read_frame().await {
Ok(Frame::Stdout(b)) => out.stdout.extend_from_slice(&b),
Ok(Frame::Stderr(b)) => out.stderr.extend_from_slice(&b),
Ok(Frame::Exit(code)) => {
out.exit_code = code;
break Ok(out);
}
Ok(Frame::Other { .. }) => {}
Err(e) => break Err(e),
}
};
let _ = self.channel.close().await;
read
}
pub(crate) async fn run_to_exit(mut self) -> Result<CommandOutput, Error<S::IoError>> {
if let Err(e) = self.close_stdin().await {
let _ = self.close().await;
return Err(e);
}
self.collect().await
}
pub async fn close(self) -> Result<(), Error<S::IoError>> {
self.channel.close().await
}
}
pub async fn open<'a, 'b, S: Session>(
session: &'a mut S,
command: &str,
rx: &'b mut [u8],
) -> Result<Shell<'a, 'b, S>, Error<S::IoError>> {
session.require_feature(Feature::ShellV2)?;
let dest = destination(ShellMode::Raw, command)?;
let channel = session.open(dest.as_bytes()).await?;
Ok(Shell::new(channel, rx))
}
pub async fn open_interactive<'a, 'b, S: Session>(
session: &'a mut S,
command: &str,
term: Option<&str>,
window_size: Option<WindowSize>,
rx: &'b mut [u8],
) -> Result<Shell<'a, 'b, S>, Error<S::IoError>> {
session.require_feature(Feature::ShellV2)?;
let dest = destination(ShellMode::Pty { term }, command)?;
let channel = session.open(dest.as_bytes()).await?;
let mut shell = Shell::new(channel, rx);
if let Some(size) = window_size {
if let Err(e) = shell.set_window_size(size).await {
let _ = shell.close().await;
return Err(e);
}
}
Ok(shell)
}
pub async fn exec<S: Session>(
session: &mut S,
command: &str,
rx: &mut [u8],
) -> Result<CommandOutput, Error<S::IoError>> {
open(session, command, rx).await?.run_to_exit().await
}
pub(crate) fn write_argv_destination(
buf: &mut [u8],
prefix: &[u8],
args: &[&str],
) -> Result<usize, DestinationError> {
dest::write_destination(buf, &[b"shell,v2,raw:", prefix], args)
}
pub(crate) async fn open_argv<'a, S: Session>(
session: &'a mut S,
prefix: &[u8],
args: &[&str],
buf: &mut [u8],
) -> Result<Channel<'a, S>, Error<S::IoError>> {
session.require_feature(Feature::ShellV2)?;
let dest_len = write_argv_destination(buf, prefix, args)?;
session.open(&buf[..dest_len]).await
}