Lines
95.45 %
Functions
100 %
Branches
//! Per-channel state for the `nomisync-eval` ssh subsystem.
//!
//! One channel is one [`Mux`] (ADR-0036). Channel bytes go through a
//! bounded queue to a reader task that frames them and feeds the mux; a
//! forwarder task writes the mux's replies back to the channel. The handler
//! never waits: when the client stops reading, the replies fill, the reader
//! stops, the input queue fills and the next chunk ends the channel. A full
//! stream queue stops the reader the same way, so piped input is answered in
//! full instead of refused with `busy`.
//! Constructed in `subsystem_request` once the requested subsystem name matches
//! `"nomisync-eval"` AND the session has authenticated. [`end_input`] (EOF or
//! close) drops the mux once the queued input is read, every stream answers what
//! is still queued, and the forwarder then finishes the SSH channel. The state
//! counts as live until that last reply is sent.
//! [`end_input`]: EvalChannelState::end_input
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Weak};
use russh::ChannelId;
use russh::server::Handle as RusshHandle;
use tokio::runtime::Handle;
use tokio::sync::mpsc::{self, error::TrySendError};
use rpc::ScriptCtx;
use rpc::mux::{AbortHandle, Mux, OpenSession};
use rpc::session::SessionError;
/// Eval channels one SSH connection may hold.
pub const MAX_EVAL_CHANNELS: usize = 2;
/// Unread input chunks a channel keeps. A frame is at most 1 MiB and a chunk at
/// most 32 KiB, so the queue holds a whole frame with room to spare.
const INPUT_CHUNKS: usize = 64;
/// Written when the client sends input faster than it reads replies.
pub const BACKLOG_REPLY: &str =
"(:id 0 :error (:code busy :message \"input backlog: replies are not being read\"))\n";
/// Trait for the worker's response back-channel. The russh-backed
/// impl writes to an SSH channel via the server's `Handle`; the
/// mpsc-backed impl drains into a tokio receiver for unit tests.
/// Either way, the worker emits one full response (newline-
/// terminated) per send call.
pub trait ResponseSink: Send + Sync + 'static {
fn send(&self, bytes: Vec<u8>) -> SinkFuture<'_>;
/// Ends the channel after the last queued response was sent.
fn finish(&self) -> SinkFuture<'_>;
}
pub type SinkFuture<'a> = Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
pub struct RusshSink {
handle: RusshHandle,
channel: ChannelId,
impl RusshSink {
pub fn new(handle: RusshHandle, channel: ChannelId) -> Self {
Self { handle, channel }
impl ResponseSink for RusshSink {
fn send(&self, bytes: Vec<u8>) -> SinkFuture<'_> {
Box::pin(async move {
if let Err(remaining) = self.handle.data(self.channel, bytes).await {
tracing::warn!(
"eval channel response write dropped {} bytes (channel closed?)",
remaining.len()
);
})
fn finish(&self) -> SinkFuture<'_> {
// OpenSSH exits 255 when a channel closes without an exit status.
let finished = self
.handle
.exit_status_request(self.channel, 0)
.await
.is_ok()
&& self.handle.eof(self.channel).await.is_ok()
&& self.handle.close(self.channel).await.is_ok();
if !finished {
tracing::debug!("eval channel session already gone at finish");
pub struct EvalChannelState {
input: Option<mpsc::Sender<Vec<u8>>>,
/// Outlives the reader: a close after EOF still aborts what is draining.
abort: AbortHandle,
/// Upgradable until the forwarder has finished the channel.
live: Weak<()>,
/// The client sent more than the channel could take while it was not reading replies.
#[derive(Debug, PartialEq, Eq)]
pub struct Backlog;
impl EvalChannelState {
/// Opens the channel's mux on stream 0. The daemon always passes
/// `Session::guarded`; tests an unguarded one for users with no row.
///
/// # Errors
/// Stream 0 could not be built.
pub fn open(
ctx: ScriptCtx,
open: OpenSession,
sink: Box<dyn ResponseSink>,
) -> Result<Self, SessionError> {
let (mux, replies) = Mux::new(&Handle::current(), ctx, open)?;
let (input, chunks) = mpsc::channel(INPUT_CHUNKS);
let alive = Arc::new(());
let live = Arc::downgrade(&alive);
tokio::spawn(forward(replies, sink, alive));
let abort = mux.abort_handle();
tokio::spawn(read_input(mux, chunks));
Ok(Self {
input: Some(input),
abort,
live,
/// False once the input ended and every reply was sent; the channel's
/// streams may run on after the client closed it.
pub fn is_live(&self) -> bool {
self.live.strong_count() > 0
/// Queues raw channel bytes without waiting.
/// [`Backlog`] when the queue is full. Bytes after the channel's input
/// ended, or after a framing error, are dropped.
pub fn feed(&mut self, bytes: &[u8]) -> Result<(), Backlog> {
let Some(input) = &self.input else {
return Ok(());
};
match input.try_send(bytes.to_vec()) {
Err(TrySendError::Full(_)) => Err(Backlog),
Ok(()) | Err(TrySendError::Closed(_)) => Ok(()),
/// The client half-closed: the mux answers what is queued, then the channel ends.
pub fn end_input(&mut self) {
self.input = None;
/// The client closed the channel or overran it: whatever runs is aborted,
/// what is queued is answered `interrupted`, and the channel ends.
pub fn close(&mut self) {
self.abort.abort();
async fn forward(mut replies: mpsc::Receiver<String>, sink: Box<dyn ResponseSink>, alive: Arc<()>) {
while let Some(mut line) = replies.recv().await {
line.push('\n');
sink.send(line.into_bytes()).await;
drop(alive);
sink.finish().await;
mod reader;
use reader::read_input;
#[cfg(test)]
mod tests;