rust-expect 0.1.0

Next-generation Expect-style terminal automation library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
//! SSH channel management.
//!
//! This module provides SSH channel handling with I/O support for
//! interactive sessions when the `ssh` feature is enabled.

#[cfg(feature = "ssh")]
use std::collections::VecDeque;
#[cfg(feature = "ssh")]
use std::io;
#[cfg(feature = "ssh")]
use std::pin::Pin;
#[cfg(feature = "ssh")]
use std::task::{Context, Poll};
use std::time::Duration;

#[cfg(feature = "ssh")]
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};

#[cfg(feature = "ssh")]
use crate::error::SshError;
use crate::types::Dimensions;

/// SSH channel type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChannelType {
    /// Session channel (for shell/exec).
    Session,
    /// Direct TCP/IP forwarding.
    DirectTcpIp,
    /// Forwarded TCP/IP.
    ForwardedTcpIp,
    /// X11 forwarding.
    X11,
}

/// SSH channel request type.
#[derive(Debug, Clone)]
pub enum ChannelRequest {
    /// Request a PTY.
    Pty {
        /// Terminal type.
        term: String,
        /// Terminal dimensions.
        dimensions: Dimensions,
        /// Terminal modes.
        modes: Vec<u8>,
    },
    /// Request shell.
    Shell,
    /// Execute a command.
    Exec {
        /// Command to execute.
        command: String,
    },
    /// Request subsystem.
    Subsystem {
        /// Subsystem name.
        name: String,
    },
    /// Window size change.
    WindowChange {
        /// New dimensions.
        dimensions: Dimensions,
    },
    /// Send signal.
    Signal {
        /// Signal name.
        signal: String,
    },
    /// Request environment variable.
    Env {
        /// Variable name.
        name: String,
        /// Variable value.
        value: String,
    },
}

/// SSH channel state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChannelState {
    /// Opening.
    Opening,
    /// Open and ready.
    Open,
    /// End of file received.
    Eof,
    /// Closed.
    Closed,
}

/// SSH channel configuration.
#[derive(Debug, Clone)]
pub struct ChannelConfig {
    /// Channel type.
    pub channel_type: ChannelType,
    /// Read timeout.
    pub read_timeout: Duration,
    /// Write timeout.
    pub write_timeout: Duration,
    /// Buffer size.
    pub buffer_size: usize,
    /// Request PTY.
    pub pty: bool,
    /// Terminal type.
    pub term: String,
    /// Terminal dimensions.
    pub dimensions: Dimensions,
}

impl Default for ChannelConfig {
    fn default() -> Self {
        Self {
            channel_type: ChannelType::Session,
            read_timeout: Duration::from_secs(30),
            write_timeout: Duration::from_secs(30),
            buffer_size: 32768,
            pty: true,
            term: "xterm-256color".to_string(),
            dimensions: Dimensions::default(),
        }
    }
}

impl ChannelConfig {
    /// Create new config.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set terminal type.
    #[must_use]
    pub fn term(mut self, term: impl Into<String>) -> Self {
        self.term = term.into();
        self
    }

    /// Set dimensions.
    #[must_use]
    pub const fn dimensions(mut self, cols: u16, rows: u16) -> Self {
        self.dimensions = Dimensions { cols, rows };
        self
    }

    /// Disable PTY.
    #[must_use]
    pub const fn no_pty(mut self) -> Self {
        self.pty = false;
        self
    }

    /// Set buffer size.
    #[must_use]
    pub const fn buffer_size(mut self, size: usize) -> Self {
        self.buffer_size = size;
        self
    }
}

// ============================================================================
// russh channel wrapper (when ssh feature is enabled)
// ============================================================================

/// SSH channel wrapper with AsyncRead/AsyncWrite support.
///
/// This wraps a russh `Channel` to provide a familiar async I/O interface
/// that can be used with the `Session` type.
#[cfg(feature = "ssh")]
pub struct SshChannelStream {
    /// The underlying russh channel.
    channel: russh::Channel<russh::client::Msg>,
    /// Configuration.
    config: ChannelConfig,
    /// Current state.
    state: ChannelState,
    /// Read buffer for data received from the channel.
    read_buffer: VecDeque<u8>,
    /// Exit status when received.
    exit_status: Option<u32>,
    /// Whether EOF has been received.
    eof_received: bool,
}

#[cfg(feature = "ssh")]
impl std::fmt::Debug for SshChannelStream {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SshChannelStream")
            .field("config", &self.config)
            .field("state", &self.state)
            .field("read_buffer_len", &self.read_buffer.len())
            .field("exit_status", &self.exit_status)
            .field("eof_received", &self.eof_received)
            .finish()
    }
}

#[cfg(feature = "ssh")]
impl SshChannelStream {
    /// Create a new channel stream from a russh channel.
    #[must_use]
    pub fn new(channel: russh::Channel<russh::client::Msg>, config: ChannelConfig) -> Self {
        Self {
            channel,
            config,
            state: ChannelState::Open,
            read_buffer: VecDeque::with_capacity(32768),
            exit_status: None,
            eof_received: false,
        }
    }

    /// Get the configuration.
    #[must_use]
    pub const fn config(&self) -> &ChannelConfig {
        &self.config
    }

    /// Get the current state.
    #[must_use]
    pub const fn state(&self) -> ChannelState {
        self.state
    }

    /// Check if the channel is open.
    #[must_use]
    pub fn is_open(&self) -> bool {
        self.state == ChannelState::Open
    }

    /// Check if EOF has been received.
    #[must_use]
    pub const fn is_eof(&self) -> bool {
        self.eof_received
    }

    /// Get the exit status if the command has completed.
    #[must_use]
    pub const fn exit_status(&self) -> Option<u32> {
        self.exit_status
    }

    /// Request a PTY on this channel.
    ///
    /// # Errors
    ///
    /// Returns an error if the PTY request fails.
    pub async fn request_pty(&mut self) -> crate::error::Result<()> {
        self.channel
            .request_pty(
                false, // want_reply
                &self.config.term,
                self.config.dimensions.cols.into(),
                self.config.dimensions.rows.into(),
                0,   // pixel width
                0,   // pixel height
                &[], // terminal modes
            )
            .await
            .map_err(|e| {
                crate::error::ExpectError::Ssh(SshError::Channel {
                    reason: format!("PTY request failed: {e}"),
                })
            })
    }

    /// Request a shell on this channel.
    ///
    /// # Errors
    ///
    /// Returns an error if the shell request fails.
    pub async fn request_shell(&mut self) -> crate::error::Result<()> {
        self.channel.request_shell(false).await.map_err(|e| {
            crate::error::ExpectError::Ssh(SshError::Channel {
                reason: format!("Shell request failed: {e}"),
            })
        })
    }

    /// Execute a command on this channel.
    ///
    /// # Errors
    ///
    /// Returns an error if the exec request fails.
    pub async fn exec(&mut self, command: &str) -> crate::error::Result<()> {
        self.channel.exec(false, command).await.map_err(|e| {
            crate::error::ExpectError::Ssh(SshError::Channel {
                reason: format!("Exec request failed: {e}"),
            })
        })
    }

    /// Change the window size.
    ///
    /// # Errors
    ///
    /// Returns an error if the window change request fails.
    pub async fn window_change(&mut self, cols: u16, rows: u16) -> crate::error::Result<()> {
        self.channel
            .window_change(cols.into(), rows.into(), 0, 0)
            .await
            .map_err(|e| {
                crate::error::ExpectError::Ssh(SshError::Channel {
                    reason: format!("Window change failed: {e}"),
                })
            })
    }

    /// Send data to the channel.
    ///
    /// # Errors
    ///
    /// Returns an error if the data send fails.
    pub async fn send_data(&mut self, data: &[u8]) -> crate::error::Result<()> {
        self.channel.data(data).await.map_err(|e| {
            crate::error::ExpectError::Ssh(SshError::Channel {
                reason: format!("Data send failed: {e}"),
            })
        })
    }

    /// Send EOF to the channel.
    ///
    /// # Errors
    ///
    /// Returns an error if the EOF send fails.
    pub async fn send_eof(&mut self) -> crate::error::Result<()> {
        self.channel.eof().await.map_err(|e| {
            crate::error::ExpectError::Ssh(SshError::Channel {
                reason: format!("EOF send failed: {e}"),
            })
        })
    }

    /// Close the channel.
    pub async fn close(&mut self) -> crate::error::Result<()> {
        self.state = ChannelState::Closed;
        self.channel.close().await.map_err(|e| {
            crate::error::ExpectError::Ssh(SshError::Channel {
                reason: format!("Channel close failed: {e}"),
            })
        })
    }

    /// Wait for and process the next message from the channel.
    ///
    /// This should be called in a loop to receive data from the remote.
    /// Returns `None` when the channel is closed.
    pub async fn wait(&mut self) -> Option<russh::ChannelMsg> {
        let msg = self.channel.wait().await?;

        match &msg {
            russh::ChannelMsg::Data { data } => {
                self.read_buffer.extend(data.as_ref());
            }
            russh::ChannelMsg::ExtendedData { data, ext } => {
                // ext 1 is typically stderr
                if *ext == 1 {
                    // For now, treat stderr the same as stdout
                    self.read_buffer.extend(data.as_ref());
                }
            }
            russh::ChannelMsg::ExitStatus { exit_status } => {
                self.exit_status = Some(*exit_status);
            }
            russh::ChannelMsg::Eof => {
                self.eof_received = true;
                self.state = ChannelState::Eof;
            }
            russh::ChannelMsg::Close => {
                self.state = ChannelState::Closed;
            }
            _ => {}
        }

        Some(msg)
    }

    /// Read available data from the internal buffer.
    ///
    /// Returns the number of bytes read.
    pub fn read_buffered(&mut self, buf: &mut [u8]) -> usize {
        let len = std::cmp::min(buf.len(), self.read_buffer.len());
        for (i, byte) in self.read_buffer.drain(..len).enumerate() {
            buf[i] = byte;
        }
        len
    }

    /// Check if there's data available in the read buffer.
    #[must_use]
    pub fn has_data(&self) -> bool {
        !self.read_buffer.is_empty()
    }

    /// Get the number of bytes available in the read buffer.
    #[must_use]
    pub fn available(&self) -> usize {
        self.read_buffer.len()
    }
}

#[cfg(feature = "ssh")]
impl AsyncRead for SshChannelStream {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        // First, try to read from the internal buffer
        if !self.read_buffer.is_empty() {
            let len = std::cmp::min(buf.remaining(), self.read_buffer.len());
            let data: Vec<u8> = self.read_buffer.drain(..len).collect();
            buf.put_slice(&data);
            return Poll::Ready(Ok(()));
        }

        // If EOF, return 0 bytes (signals EOF to caller)
        if self.eof_received || self.state == ChannelState::Closed {
            return Poll::Ready(Ok(()));
        }

        // We need to poll for more data from the channel.
        // Use a boxed future to avoid borrow issues with self.
        let this = self.get_mut();

        // Create and poll the wait future
        let wait_future = this.channel.wait();
        tokio::pin!(wait_future);

        match wait_future.poll(cx) {
            Poll::Ready(Some(msg)) => {
                // Future is done, safe to modify self now
                match msg {
                    russh::ChannelMsg::Data { data } => {
                        let len = std::cmp::min(buf.remaining(), data.len());
                        buf.put_slice(&data[..len]);
                        // Store remaining data in buffer
                        if len < data.len() {
                            this.read_buffer.extend(&data[len..]);
                        }
                        Poll::Ready(Ok(()))
                    }
                    russh::ChannelMsg::ExtendedData { data, ext } => {
                        if ext == 1 {
                            let len = std::cmp::min(buf.remaining(), data.len());
                            buf.put_slice(&data[..len]);
                            if len < data.len() {
                                this.read_buffer.extend(&data[len..]);
                            }
                        }
                        Poll::Ready(Ok(()))
                    }
                    russh::ChannelMsg::Eof => {
                        this.eof_received = true;
                        this.state = ChannelState::Eof;
                        Poll::Ready(Ok(()))
                    }
                    russh::ChannelMsg::Close => {
                        this.state = ChannelState::Closed;
                        Poll::Ready(Ok(()))
                    }
                    russh::ChannelMsg::ExitStatus { exit_status } => {
                        this.exit_status = Some(exit_status);
                        // Continue waiting for more data
                        cx.waker().wake_by_ref();
                        Poll::Pending
                    }
                    _ => {
                        // Other messages, continue waiting
                        cx.waker().wake_by_ref();
                        Poll::Pending
                    }
                }
            }
            Poll::Ready(None) => {
                // Channel closed
                this.state = ChannelState::Closed;
                Poll::Ready(Ok(()))
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

#[cfg(feature = "ssh")]
impl AsyncWrite for SshChannelStream {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        let this = self.get_mut();

        if this.state == ChannelState::Closed {
            return Poll::Ready(Err(io::Error::new(
                io::ErrorKind::BrokenPipe,
                "Channel is closed",
            )));
        }

        // Create and poll the data future
        let data_future = this.channel.data(buf);
        tokio::pin!(data_future);

        match data_future.poll(cx) {
            Poll::Ready(Ok(())) => Poll::Ready(Ok(buf.len())),
            Poll::Ready(Err(e)) => {
                Poll::Ready(Err(io::Error::other(format!("SSH write error: {e}"))))
            }
            Poll::Pending => Poll::Pending,
        }
    }

    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        // SSH channels don't have an explicit flush
        Poll::Ready(Ok(()))
    }

    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        let this = self.get_mut();

        let eof_future = this.channel.eof();
        tokio::pin!(eof_future);

        match eof_future.poll(cx) {
            Poll::Ready(Ok(())) => {
                this.state = ChannelState::Eof;
                Poll::Ready(Ok(()))
            }
            Poll::Ready(Err(e)) => {
                Poll::Ready(Err(io::Error::other(format!("SSH shutdown error: {e}"))))
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

// ============================================================================
// Stub implementation (when ssh feature is disabled)
// ============================================================================

/// SSH channel stub for when the `ssh` feature is disabled.
#[cfg(not(feature = "ssh"))]
#[derive(Debug)]
pub struct SshChannel {
    /// Configuration.
    config: ChannelConfig,
    /// Current state.
    state: ChannelState,
    /// Exit status (if command completed).
    exit_status: Option<i32>,
}

#[cfg(not(feature = "ssh"))]
impl SshChannel {
    /// Create a new channel.
    #[must_use]
    pub const fn new(config: ChannelConfig) -> Self {
        Self {
            config,
            state: ChannelState::Opening,
            exit_status: None,
        }
    }

    /// Get configuration.
    #[must_use]
    pub const fn config(&self) -> &ChannelConfig {
        &self.config
    }

    /// Get current state.
    #[must_use]
    pub const fn state(&self) -> ChannelState {
        self.state
    }

    /// Check if open.
    #[must_use]
    pub fn is_open(&self) -> bool {
        self.state == ChannelState::Open
    }

    /// Check if closed.
    #[must_use]
    pub fn is_closed(&self) -> bool {
        self.state == ChannelState::Closed
    }

    /// Get exit status.
    #[must_use]
    pub const fn exit_status(&self) -> Option<i32> {
        self.exit_status
    }

    /// Open the channel (stub).
    pub fn open(&mut self) -> crate::error::Result<()> {
        self.state = ChannelState::Open;
        Ok(())
    }

    /// Close the channel.
    pub fn close(&mut self) {
        self.state = ChannelState::Closed;
    }

    /// Set exit status.
    pub fn set_exit_status(&mut self, status: i32) {
        self.exit_status = Some(status);
    }
}

/// Alias for backward compatibility when ssh feature is enabled.
#[cfg(feature = "ssh")]
pub type SshChannel = SshChannelStream;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn channel_config() {
        let config = ChannelConfig::new()
            .term("vt100")
            .dimensions(120, 40)
            .buffer_size(65536);

        assert_eq!(config.term, "vt100");
        assert_eq!(config.dimensions.cols, 120);
        assert_eq!(config.buffer_size, 65536);
    }

    #[cfg(not(feature = "ssh"))]
    #[test]
    fn channel_state() {
        let mut channel = SshChannel::new(ChannelConfig::default());
        assert_eq!(channel.state(), ChannelState::Opening);

        channel.open().unwrap();
        assert!(channel.is_open());

        channel.close();
        assert!(channel.is_closed());
    }
}