1
//! Per-channel state for the `nomisync-eval` ssh subsystem.
2
//!
3
//! One channel is one [`Mux`] (ADR-0036). Channel bytes go through a
4
//! bounded queue to a reader task that frames them and feeds the mux; a
5
//! forwarder task writes the mux's replies back to the channel. The handler
6
//! never waits: when the client stops reading, the replies fill, the reader
7
//! stops, the input queue fills and the next chunk ends the channel. A full
8
//! stream queue stops the reader the same way, so piped input is answered in
9
//! full instead of refused with `busy`.
10
//!
11
//! Constructed in `subsystem_request` once the requested subsystem name matches
12
//! `"nomisync-eval"` AND the session has authenticated. [`end_input`] (EOF or
13
//! close) drops the mux once the queued input is read, every stream answers what
14
//! is still queued, and the forwarder then finishes the SSH channel. The state
15
//! counts as live until that last reply is sent.
16
//!
17
//! [`end_input`]: EvalChannelState::end_input
18

            
19
use std::future::Future;
20
use std::pin::Pin;
21
use std::sync::{Arc, Weak};
22

            
23
use russh::ChannelId;
24
use russh::server::Handle as RusshHandle;
25
use tokio::runtime::Handle;
26
use tokio::sync::mpsc::{self, error::TrySendError};
27

            
28
use rpc::ScriptCtx;
29
use rpc::mux::{AbortHandle, Mux, OpenSession};
30
use rpc::session::SessionError;
31

            
32
/// Eval channels one SSH connection may hold.
33
pub const MAX_EVAL_CHANNELS: usize = 2;
34
/// Unread input chunks a channel keeps. A frame is at most 1 MiB and a chunk at
35
/// most 32 KiB, so the queue holds a whole frame with room to spare.
36
const INPUT_CHUNKS: usize = 64;
37

            
38
/// Written when the client sends input faster than it reads replies.
39
pub const BACKLOG_REPLY: &str =
40
    "(:id 0 :error (:code busy :message \"input backlog: replies are not being read\"))\n";
41

            
42
/// Trait for the worker's response back-channel. The russh-backed
43
/// impl writes to an SSH channel via the server's `Handle`; the
44
/// mpsc-backed impl drains into a tokio receiver for unit tests.
45
/// Either way, the worker emits one full response (newline-
46
/// terminated) per send call.
47
pub trait ResponseSink: Send + Sync + 'static {
48
    fn send(&self, bytes: Vec<u8>) -> SinkFuture<'_>;
49
    /// Ends the channel after the last queued response was sent.
50
    fn finish(&self) -> SinkFuture<'_>;
51
}
52

            
53
pub type SinkFuture<'a> = Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
54

            
55
pub struct RusshSink {
56
    handle: RusshHandle,
57
    channel: ChannelId,
58
}
59

            
60
impl RusshSink {
61
11
    pub fn new(handle: RusshHandle, channel: ChannelId) -> Self {
62
11
        Self { handle, channel }
63
11
    }
64
}
65

            
66
impl ResponseSink for RusshSink {
67
20048
    fn send(&self, bytes: Vec<u8>) -> SinkFuture<'_> {
68
20048
        Box::pin(async move {
69
20048
            if let Err(remaining) = self.handle.data(self.channel, bytes).await {
70
                tracing::warn!(
71
                    "eval channel response write dropped {} bytes (channel closed?)",
72
                    remaining.len()
73
                );
74
20048
            }
75
20048
        })
76
20048
    }
77

            
78
11
    fn finish(&self) -> SinkFuture<'_> {
79
11
        Box::pin(async move {
80
            // OpenSSH exits 255 when a channel closes without an exit status.
81
11
            let finished = self
82
11
                .handle
83
11
                .exit_status_request(self.channel, 0)
84
11
                .await
85
                .is_ok()
86
9
                && self.handle.eof(self.channel).await.is_ok()
87
9
                && self.handle.close(self.channel).await.is_ok();
88
11
            if !finished {
89
2
                tracing::debug!("eval channel session already gone at finish");
90
9
            }
91
11
        })
92
11
    }
93
}
94

            
95
pub struct EvalChannelState {
96
    input: Option<mpsc::Sender<Vec<u8>>>,
97
    /// Outlives the reader: a close after EOF still aborts what is draining.
98
    abort: AbortHandle,
99
    /// Upgradable until the forwarder has finished the channel.
100
    live: Weak<()>,
101
}
102

            
103
/// The client sent more than the channel could take while it was not reading replies.
104
#[derive(Debug, PartialEq, Eq)]
105
pub struct Backlog;
106

            
107
impl EvalChannelState {
108
    /// Opens the channel's mux on stream 0. The daemon always passes
109
    /// `Session::guarded`; tests an unguarded one for users with no row.
110
    ///
111
    /// # Errors
112
    /// Stream 0 could not be built.
113
30
    pub fn open(
114
30
        ctx: ScriptCtx,
115
30
        open: OpenSession,
116
30
        sink: Box<dyn ResponseSink>,
117
30
    ) -> Result<Self, SessionError> {
118
30
        let (mux, replies) = Mux::new(&Handle::current(), ctx, open)?;
119
30
        let (input, chunks) = mpsc::channel(INPUT_CHUNKS);
120
30
        let alive = Arc::new(());
121
30
        let live = Arc::downgrade(&alive);
122
30
        tokio::spawn(forward(replies, sink, alive));
123
30
        let abort = mux.abort_handle();
124
30
        tokio::spawn(read_input(mux, chunks));
125
30
        Ok(Self {
126
30
            input: Some(input),
127
30
            abort,
128
30
            live,
129
30
        })
130
30
    }
131

            
132
    /// False once the input ended and every reply was sent; the channel's
133
    /// streams may run on after the client closed it.
134
38
    pub fn is_live(&self) -> bool {
135
38
        self.live.strong_count() > 0
136
38
    }
137

            
138
    /// Queues raw channel bytes without waiting.
139
    ///
140
    /// # Errors
141
    /// [`Backlog`] when the queue is full. Bytes after the channel's input
142
    /// ended, or after a framing error, are dropped.
143
358
    pub fn feed(&mut self, bytes: &[u8]) -> Result<(), Backlog> {
144
358
        let Some(input) = &self.input else {
145
            return Ok(());
146
        };
147
358
        match input.try_send(bytes.to_vec()) {
148
1
            Err(TrySendError::Full(_)) => Err(Backlog),
149
357
            Ok(()) | Err(TrySendError::Closed(_)) => Ok(()),
150
        }
151
358
    }
152

            
153
    /// The client half-closed: the mux answers what is queued, then the channel ends.
154
12
    pub fn end_input(&mut self) {
155
12
        self.input = None;
156
12
    }
157

            
158
    /// The client closed the channel or overran it: whatever runs is aborted,
159
    /// what is queued is answered `interrupted`, and the channel ends.
160
3
    pub fn close(&mut self) {
161
3
        self.input = None;
162
3
        self.abort.abort();
163
3
    }
164
}
165

            
166
30
async fn forward(mut replies: mpsc::Receiver<String>, sink: Box<dyn ResponseSink>, alive: Arc<()>) {
167
20448
    while let Some(mut line) = replies.recv().await {
168
20418
        line.push('\n');
169
20418
        sink.send(line.into_bytes()).await;
170
    }
171
19
    drop(alive);
172
19
    sink.finish().await;
173
18
}
174

            
175
mod reader;
176

            
177
use reader::read_input;
178

            
179
#[cfg(test)]
180
mod tests;