use alloc::vec::Vec;
use core::future::Future;
use embedded_io::ErrorType;
use embedded_io_async::{Read, Write};
use crate::base::channel::{Channel, SelectResult};
use crate::base::connection::{
Connection, DEFAULT_MAX_CHANNELS, DEFAULT_MAX_FEATURES, DEFAULT_MAX_PROPERTIES,
};
use crate::base::destination::build_shell_v2_destination;
use crate::base::error::{Error, ProtocolError};
use crate::base::protocol::features::Feature;
pub const STDIN: u8 = 0;
pub const STDOUT: u8 = 1;
pub const STDERR: u8 = 2;
pub const EXIT: u8 = 3;
pub const CLOSE_STDIN: u8 = 4;
pub const WINDOW_SIZE_CHANGE: u8 = 5;
pub const HEADER_SIZE: usize = 5;
pub(crate) fn parse_header(buf: &[u8; HEADER_SIZE]) -> (u8, u32) {
let id = buf[0];
let length = u32::from_le_bytes([buf[1], buf[2], buf[3], buf[4]]);
(id, length)
}
pub(crate) fn encode_window_size(rows: u16, cols: u16) -> [u8; 8] {
let mut buf = [0u8; 8];
buf[0..2].copy_from_slice(&rows.to_le_bytes());
buf[2..4].copy_from_slice(&cols.to_le_bytes());
buf
}
#[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,
T,
const MAX_CHANNELS: usize = DEFAULT_MAX_CHANNELS,
const MAX_PROPERTIES: usize = DEFAULT_MAX_PROPERTIES,
const MAX_FEATURES: usize = DEFAULT_MAX_FEATURES,
> where
T: Read + Write,
{
channel: Channel<'a, T, MAX_CHANNELS, MAX_PROPERTIES, MAX_FEATURES>,
rx: &'b mut [u8],
decoder: FrameDecoder,
}
impl<
'a,
'b,
T,
const MAX_CHANNELS: usize,
const MAX_PROPERTIES: usize,
const MAX_FEATURES: usize,
> Shell<'a, 'b, T, MAX_CHANNELS, MAX_PROPERTIES, MAX_FEATURES>
where
T: Read + Write,
{
pub fn new(
channel: Channel<'a, T, MAX_CHANNELS, MAX_PROPERTIES, MAX_FEATURES>,
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: u8,
payload: &[u8],
) -> Result<(), Error<<T as ErrorType>::Error>> {
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, 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<<T as ErrorType>::Error>> {
self.send_frame(STDIN, data).await
}
pub async fn close_stdin(&mut self) -> Result<(), Error<<T as ErrorType>::Error>> {
self.send_frame(CLOSE_STDIN, &[]).await
}
pub async fn set_window_size(
&mut self,
rows: u16,
cols: u16,
) -> Result<(), Error<<T as ErrorType>::Error>> {
let payload = encode_window_size(rows, cols);
self.send_frame(WINDOW_SIZE_CHANGE, &payload).await
}
pub async fn read_frame(&mut self) -> Result<Frame, Error<<T as ErrorType>::Error>> {
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<<T as ErrorType>::Error>> {
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<(u8, &[u8])>, Error<<T as ErrorType>::Error>> {
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<<T as ErrorType>::Error>>
where
T: crate::transport::ReadCancelSafety,
{
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<<T as ErrorType>::Error>> {
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<<T as ErrorType>::Error>> {
let mut out = CommandOutput::default();
loop {
match self.read_frame().await? {
Frame::Stdout(b) => out.stdout.extend_from_slice(&b),
Frame::Stderr(b) => out.stderr.extend_from_slice(&b),
Frame::Exit(code) => {
out.exit_code = code;
self.channel.close().await?;
return Ok(out);
}
Frame::Other { .. } => {}
}
}
}
pub async fn close(self) -> Result<(), Error<<T as ErrorType>::Error>> {
self.channel.close().await
}
}
pub async fn open<'a, 'b, T, const MC: usize, const MP: usize, const MF: usize>(
conn: &'a mut Connection<T, MC, MP, MF>,
command: &str,
rx: &'b mut [u8],
) -> Result<Shell<'a, 'b, T, MC, MP, MF>, Error<<T as ErrorType>::Error>>
where
T: Read + Write,
{
conn.require_feature(Feature::ShellV2)?;
let dest = build_shell_v2_destination(false, "", command)?;
let channel = conn.open(dest.as_bytes()).await?;
Ok(Shell::new(channel, rx))
}
pub async fn open_interactive<'a, 'b, T, const MC: usize, const MP: usize, const MF: usize>(
conn: &'a mut Connection<T, MC, MP, MF>,
command: &str,
term: &str,
window_size: Option<(u16, u16)>,
rx: &'b mut [u8],
) -> Result<Shell<'a, 'b, T, MC, MP, MF>, Error<<T as ErrorType>::Error>>
where
T: Read + Write,
{
conn.require_feature(Feature::ShellV2)?;
let dest = build_shell_v2_destination(true, term, command)?;
let channel = conn.open(dest.as_bytes()).await?;
let mut shell = Shell::new(channel, rx);
if let Some((rows, cols)) = window_size {
shell.set_window_size(rows, cols).await?;
}
Ok(shell)
}
pub async fn exec<T, const MC: usize, const MP: usize, const MF: usize>(
conn: &mut Connection<T, MC, MP, MF>,
command: &str,
rx: &mut [u8],
) -> Result<CommandOutput, Error<<T as ErrorType>::Error>>
where
T: Read + Write,
{
let mut shell = open(conn, command, rx).await?;
shell.close_stdin().await?;
shell.collect().await
}
mod decoder;
pub use decoder::FrameDecoder;
#[cfg(test)]
mod tests;