git clone https://garage44.eu/jeroen/pinnacle.git.. /ui/src/remote.rs
//! A command run on another device: what goes over the reliable stream
//! the p2p service opens to a contact for it (`docs/terminal-and-agent.md`).
//! Each message is a frame: its kind, its body's length (u32), the body.
//!
//! The terminal hands the service the same five channels a local command
//! has (stdin, stdout, stderr, the exit code, and a control channel whose
//! message or closing stops it); the service on the other device starts the
//! command as the terminal would ([`crate::command`]), if that contact is
//! allowed to, and carries its output back. An image's pixels travel in
//! the frame and arrive as shared memory, as a local one does.
use alloc::vec::Vec;
/// The service tag its streams open with (`pinnacle_p2p::Node::open_stream`).
pub const SERVICE: &str = "exec";
/// To the device that runs it: the command line.
pub const RUN: u8 = 1;
/// To it: a message for the command's stdin (an answer).
pub const STDIN: u8 = 2;
/// To it: stop the command.
pub const STOP: u8 = 3;
/// Back: a message on stdout.
pub const OUT: u8 = 0x10;
/// Back: a message on stderr.
pub const ERR: u8 = 0x11;
/// Back: an image on stdout: width (u32), height (u32), its pixels.
pub const IMAGE: u8 = 0x12;
/// Back: the exit code (u64); the stream ends after it.
pub const EXIT: u8 = 0x13;
/// Back: why it was not run (text); the stream ends after it.
pub const REFUSED: u8 = 0x14;
/// The largest frame: an image of 1024 × 1024 and its header.
pub const MAX_FRAME: usize = 1024 * 1024 * 4 + 8;
pub fn frame(kind: u8, body: &[u8]) -> Vec<u8> {
let mut f = Vec::with_capacity(5 + body.len());
f.push(kind);
f.extend_from_slice(&(body.len() as u32).to_le_bytes());
f.extend_from_slice(body);
f
}
/// Frames out of a stream's bytes, as they come.
#[derive(Default)]
pub struct Frames {
buffer: Vec<u8>,
/// A frame said to be larger than [`MAX_FRAME`]: nothing more is read.
pub broken: bool,
}
impl Frames {
pub fn push(&mut self, data: &[u8]) {
self.buffer.extend_from_slice(data);
}
pub fn take(&mut self) -> Option<(u8, Vec<u8>)> {
if self.broken || self.buffer.len() < 5 {
return None;
}
let len = u32::from_le_bytes(self.buffer[1..5].try_into().unwrap()) as usize;
if len > MAX_FRAME {
self.broken = true;
return None;
}
if self.buffer.len() < 5 + len {
return None;
}
let kind = self.buffer[0];
let body = self.buffer[5..5 + len].to_vec();
self.buffer.drain(..5 + len);
Some((kind, body))
}
}