Skip to main content

fynx_proto/ssh/
connection.rs

1//! SSH connection protocol (RFC 4254).
2//!
3//! This module implements SSH channels and connection services:
4//! - Channel multiplexing (multiple channels over one connection)
5//! - Channel types: session, direct-tcpip, forwarded-tcpip
6//! - Channel flow control (window size management)
7//! - Channel requests: exec, shell, pty-req, env, exit-status, exit-signal
8//! - Global requests: tcpip-forward, cancel-tcpip-forward
9//!
10//! # Architecture
11//!
12//! The SSH Connection Protocol runs on top of the authenticated transport layer
13//! and provides channels for multiplexing different services over a single connection.
14//!
15//! # Security
16//!
17//! - **Window size limits** - Prevents memory exhaustion attacks
18//! - **Maximum packet size** - Prevents buffer overflow attacks
19//! - **Channel number validation** - Prevents channel confusion attacks
20//!
21//! # Example
22//!
23//! ```rust
24//! use fynx_proto::ssh::connection::{ChannelOpen, ChannelType};
25//!
26//! // Open a session channel
27//! let open = ChannelOpen::new(
28//!     ChannelType::Session,
29//!     0,           // sender channel
30//!     1048576,     // initial window size (1MB)
31//!     32768,       // maximum packet size (32KB)
32//! );
33//! ```
34
35use bytes::{BufMut, BytesMut};
36use fynx_platform::{FynxError, FynxResult};
37
38/// Maximum window size (16 MB).
39pub const MAX_WINDOW_SIZE: u32 = 16 * 1024 * 1024;
40
41/// Maximum packet size (256 KB).
42pub const MAX_PACKET_SIZE: u32 = 256 * 1024;
43
44/// Channel type.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub enum ChannelType {
47    /// Session channel (interactive shell, exec, subsystem).
48    Session,
49    /// Direct TCP/IP channel (port forwarding).
50    DirectTcpip {
51        /// Host to connect to
52        host: String,
53        /// Port to connect to
54        port: u32,
55        /// Originator IP address
56        originator_address: String,
57        /// Originator port
58        originator_port: u32,
59    },
60    /// Forwarded TCP/IP channel (reverse port forwarding).
61    ForwardedTcpip {
62        /// Connected address
63        connected_address: String,
64        /// Connected port
65        connected_port: u32,
66        /// Originator IP address
67        originator_address: String,
68        /// Originator port
69        originator_port: u32,
70    },
71}
72
73impl ChannelType {
74    /// Returns the channel type name.
75    pub fn name(&self) -> &str {
76        match self {
77            ChannelType::Session => "session",
78            ChannelType::DirectTcpip { .. } => "direct-tcpip",
79            ChannelType::ForwardedTcpip { .. } => "forwarded-tcpip",
80        }
81    }
82}
83
84/// SSH_MSG_CHANNEL_OPEN message (RFC 4254 Section 5.1).
85///
86/// Sent by either side to open a new channel.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct ChannelOpen {
89    /// Channel type
90    channel_type: ChannelType,
91    /// Sender channel number
92    sender_channel: u32,
93    /// Initial window size
94    initial_window_size: u32,
95    /// Maximum packet size
96    maximum_packet_size: u32,
97}
98
99impl ChannelOpen {
100    /// Creates a new channel open message.
101    ///
102    /// # Arguments
103    ///
104    /// * `channel_type` - Type of channel to open
105    /// * `sender_channel` - Sender's channel number
106    /// * `initial_window_size` - Initial window size (max 16 MB)
107    /// * `maximum_packet_size` - Maximum packet size (max 256 KB)
108    ///
109    /// # Example
110    ///
111    /// ```rust
112    /// use fynx_proto::ssh::connection::{ChannelOpen, ChannelType};
113    ///
114    /// let open = ChannelOpen::new(
115    ///     ChannelType::Session,
116    ///     0,
117    ///     1048576,  // 1 MB window
118    ///     32768,    // 32 KB max packet
119    /// );
120    /// ```
121    pub fn new(
122        channel_type: ChannelType,
123        sender_channel: u32,
124        initial_window_size: u32,
125        maximum_packet_size: u32,
126    ) -> Self {
127        Self {
128            channel_type,
129            sender_channel,
130            initial_window_size,
131            maximum_packet_size,
132        }
133    }
134
135    /// Returns the channel type.
136    pub fn channel_type(&self) -> &ChannelType {
137        &self.channel_type
138    }
139
140    /// Returns the sender channel number.
141    pub fn sender_channel(&self) -> u32 {
142        self.sender_channel
143    }
144
145    /// Returns the initial window size.
146    pub fn initial_window_size(&self) -> u32 {
147        self.initial_window_size
148    }
149
150    /// Returns the maximum packet size.
151    pub fn maximum_packet_size(&self) -> u32 {
152        self.maximum_packet_size
153    }
154
155    /// Serializes to bytes.
156    ///
157    /// Format (RFC 4254 Section 5.1):
158    /// ```text
159    /// byte      SSH_MSG_CHANNEL_OPEN (90)
160    /// string    channel type
161    /// uint32    sender channel
162    /// uint32    initial window size
163    /// uint32    maximum packet size
164    /// ....      channel type specific data
165    /// ```
166    pub fn to_bytes(&self) -> Vec<u8> {
167        let mut buf = BytesMut::new();
168
169        // byte SSH_MSG_CHANNEL_OPEN (90)
170        buf.put_u8(90);
171
172        // string channel type
173        write_string(&mut buf, self.channel_type.name());
174
175        // uint32 sender channel
176        buf.put_u32(self.sender_channel);
177
178        // uint32 initial window size
179        buf.put_u32(self.initial_window_size);
180
181        // uint32 maximum packet size
182        buf.put_u32(self.maximum_packet_size);
183
184        // Channel type specific data
185        match &self.channel_type {
186            ChannelType::Session => {
187                // No additional data
188            }
189            ChannelType::DirectTcpip {
190                host,
191                port,
192                originator_address,
193                originator_port,
194            } => {
195                write_string(&mut buf, host);
196                buf.put_u32(*port);
197                write_string(&mut buf, originator_address);
198                buf.put_u32(*originator_port);
199            }
200            ChannelType::ForwardedTcpip {
201                connected_address,
202                connected_port,
203                originator_address,
204                originator_port,
205            } => {
206                write_string(&mut buf, connected_address);
207                buf.put_u32(*connected_port);
208                write_string(&mut buf, originator_address);
209                buf.put_u32(*originator_port);
210            }
211        }
212
213        buf.to_vec()
214    }
215
216    /// Parses from bytes.
217    ///
218    /// # Errors
219    ///
220    /// Returns [`FynxError::Protocol`] if the data is invalid.
221    pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
222        if data.is_empty() {
223            return Err(FynxError::Protocol(
224                "CHANNEL_OPEN message is empty".to_string(),
225            ));
226        }
227
228        if data[0] != 90 {
229            return Err(FynxError::Protocol(format!(
230                "Invalid message type: expected 90 (SSH_MSG_CHANNEL_OPEN), got {}",
231                data[0]
232            )));
233        }
234
235        let mut offset = 1;
236
237        // string channel type
238        let type_name = read_string(data, &mut offset)?;
239
240        // uint32 sender channel
241        let sender_channel = read_u32(data, &mut offset)?;
242
243        // uint32 initial window size
244        let initial_window_size = read_u32(data, &mut offset)?;
245
246        // uint32 maximum packet size
247        let maximum_packet_size = read_u32(data, &mut offset)?;
248
249        // Validate window size and packet size
250        if initial_window_size > MAX_WINDOW_SIZE {
251            return Err(FynxError::Protocol(format!(
252                "Initial window size {} exceeds maximum {}",
253                initial_window_size, MAX_WINDOW_SIZE
254            )));
255        }
256
257        if maximum_packet_size > MAX_PACKET_SIZE {
258            return Err(FynxError::Protocol(format!(
259                "Maximum packet size {} exceeds maximum {}",
260                maximum_packet_size, MAX_PACKET_SIZE
261            )));
262        }
263
264        // Parse channel type specific data
265        let channel_type = match type_name.as_str() {
266            "session" => ChannelType::Session,
267            "direct-tcpip" => {
268                let host = read_string(data, &mut offset)?;
269                let port = read_u32(data, &mut offset)?;
270                let originator_address = read_string(data, &mut offset)?;
271                let originator_port = read_u32(data, &mut offset)?;
272                ChannelType::DirectTcpip {
273                    host,
274                    port,
275                    originator_address,
276                    originator_port,
277                }
278            }
279            "forwarded-tcpip" => {
280                let connected_address = read_string(data, &mut offset)?;
281                let connected_port = read_u32(data, &mut offset)?;
282                let originator_address = read_string(data, &mut offset)?;
283                let originator_port = read_u32(data, &mut offset)?;
284                ChannelType::ForwardedTcpip {
285                    connected_address,
286                    connected_port,
287                    originator_address,
288                    originator_port,
289                }
290            }
291            _ => {
292                return Err(FynxError::Protocol(format!(
293                    "Unsupported channel type: '{}'",
294                    type_name
295                )))
296            }
297        };
298
299        Ok(Self {
300            channel_type,
301            sender_channel,
302            initial_window_size,
303            maximum_packet_size,
304        })
305    }
306}
307
308/// SSH_MSG_CHANNEL_OPEN_CONFIRMATION message (RFC 4254 Section 5.1).
309///
310/// Sent in response to SSH_MSG_CHANNEL_OPEN to confirm the channel opening.
311#[derive(Debug, Clone, PartialEq, Eq)]
312pub struct ChannelOpenConfirmation {
313    /// Recipient channel number
314    recipient_channel: u32,
315    /// Sender channel number
316    sender_channel: u32,
317    /// Initial window size
318    initial_window_size: u32,
319    /// Maximum packet size
320    maximum_packet_size: u32,
321}
322
323impl ChannelOpenConfirmation {
324    /// Creates a new channel open confirmation message.
325    pub fn new(
326        recipient_channel: u32,
327        sender_channel: u32,
328        initial_window_size: u32,
329        maximum_packet_size: u32,
330    ) -> Self {
331        Self {
332            recipient_channel,
333            sender_channel,
334            initial_window_size,
335            maximum_packet_size,
336        }
337    }
338
339    /// Returns the recipient channel number.
340    pub fn recipient_channel(&self) -> u32 {
341        self.recipient_channel
342    }
343
344    /// Returns the sender channel number.
345    pub fn sender_channel(&self) -> u32 {
346        self.sender_channel
347    }
348
349    /// Returns the initial window size.
350    pub fn initial_window_size(&self) -> u32 {
351        self.initial_window_size
352    }
353
354    /// Returns the maximum packet size.
355    pub fn maximum_packet_size(&self) -> u32 {
356        self.maximum_packet_size
357    }
358
359    /// Serializes to bytes.
360    pub fn to_bytes(&self) -> Vec<u8> {
361        let mut buf = BytesMut::new();
362
363        // byte SSH_MSG_CHANNEL_OPEN_CONFIRMATION (91)
364        buf.put_u8(91);
365        buf.put_u32(self.recipient_channel);
366        buf.put_u32(self.sender_channel);
367        buf.put_u32(self.initial_window_size);
368        buf.put_u32(self.maximum_packet_size);
369
370        buf.to_vec()
371    }
372
373    /// Parses from bytes.
374    pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
375        if data.is_empty() {
376            return Err(FynxError::Protocol(
377                "CHANNEL_OPEN_CONFIRMATION message is empty".to_string(),
378            ));
379        }
380
381        if data[0] != 91 {
382            return Err(FynxError::Protocol(format!(
383                "Invalid message type: expected 91 (SSH_MSG_CHANNEL_OPEN_CONFIRMATION), got {}",
384                data[0]
385            )));
386        }
387
388        let mut offset = 1;
389
390        let recipient_channel = read_u32(data, &mut offset)?;
391        let sender_channel = read_u32(data, &mut offset)?;
392        let initial_window_size = read_u32(data, &mut offset)?;
393        let maximum_packet_size = read_u32(data, &mut offset)?;
394
395        Ok(Self {
396            recipient_channel,
397            sender_channel,
398            initial_window_size,
399            maximum_packet_size,
400        })
401    }
402}
403
404/// Channel open failure reason codes (RFC 4254 Section 5.1).
405#[derive(Debug, Clone, Copy, PartialEq, Eq)]
406#[repr(u32)]
407pub enum ChannelOpenFailureReason {
408    /// Administratively prohibited
409    AdministrativelyProhibited = 1,
410    /// Connect failed
411    ConnectFailed = 2,
412    /// Unknown channel type
413    UnknownChannelType = 3,
414    /// Resource shortage
415    ResourceShortage = 4,
416}
417
418impl ChannelOpenFailureReason {
419    /// Converts from u32.
420    pub fn from_u32(value: u32) -> Option<Self> {
421        match value {
422            1 => Some(Self::AdministrativelyProhibited),
423            2 => Some(Self::ConnectFailed),
424            3 => Some(Self::UnknownChannelType),
425            4 => Some(Self::ResourceShortage),
426            _ => None,
427        }
428    }
429
430    /// Returns the reason as a string.
431    pub fn as_str(&self) -> &'static str {
432        match self {
433            Self::AdministrativelyProhibited => "Administratively prohibited",
434            Self::ConnectFailed => "Connect failed",
435            Self::UnknownChannelType => "Unknown channel type",
436            Self::ResourceShortage => "Resource shortage",
437        }
438    }
439}
440
441/// SSH_MSG_CHANNEL_OPEN_FAILURE message (RFC 4254 Section 5.1).
442///
443/// Sent in response to SSH_MSG_CHANNEL_OPEN to indicate channel open failure.
444#[derive(Debug, Clone, PartialEq, Eq)]
445pub struct ChannelOpenFailure {
446    /// Recipient channel number
447    recipient_channel: u32,
448    /// Reason code
449    reason_code: ChannelOpenFailureReason,
450    /// Description
451    description: String,
452    /// Language tag
453    language_tag: String,
454}
455
456impl ChannelOpenFailure {
457    /// Creates a new channel open failure message.
458    pub fn new(recipient_channel: u32, reason_code: ChannelOpenFailureReason) -> Self {
459        Self {
460            recipient_channel,
461            reason_code,
462            description: reason_code.as_str().to_string(),
463            language_tag: String::new(),
464        }
465    }
466
467    /// Creates a new channel open failure with custom description.
468    pub fn with_description(
469        recipient_channel: u32,
470        reason_code: ChannelOpenFailureReason,
471        description: String,
472    ) -> Self {
473        Self {
474            recipient_channel,
475            reason_code,
476            description,
477            language_tag: String::new(),
478        }
479    }
480
481    /// Returns the recipient channel number.
482    pub fn recipient_channel(&self) -> u32 {
483        self.recipient_channel
484    }
485
486    /// Returns the reason code.
487    pub fn reason_code(&self) -> ChannelOpenFailureReason {
488        self.reason_code
489    }
490
491    /// Returns the description.
492    pub fn description(&self) -> &str {
493        &self.description
494    }
495
496    /// Serializes to bytes.
497    pub fn to_bytes(&self) -> Vec<u8> {
498        let mut buf = BytesMut::new();
499
500        // byte SSH_MSG_CHANNEL_OPEN_FAILURE (92)
501        buf.put_u8(92);
502        buf.put_u32(self.recipient_channel);
503        buf.put_u32(self.reason_code as u32);
504        write_string(&mut buf, &self.description);
505        write_string(&mut buf, &self.language_tag);
506
507        buf.to_vec()
508    }
509
510    /// Parses from bytes.
511    pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
512        if data.is_empty() {
513            return Err(FynxError::Protocol(
514                "CHANNEL_OPEN_FAILURE message is empty".to_string(),
515            ));
516        }
517
518        if data[0] != 92 {
519            return Err(FynxError::Protocol(format!(
520                "Invalid message type: expected 92 (SSH_MSG_CHANNEL_OPEN_FAILURE), got {}",
521                data[0]
522            )));
523        }
524
525        let mut offset = 1;
526
527        let recipient_channel = read_u32(data, &mut offset)?;
528        let reason_code_u32 = read_u32(data, &mut offset)?;
529        let description = read_string(data, &mut offset)?;
530        let language_tag = read_string(data, &mut offset)?;
531
532        let reason_code = ChannelOpenFailureReason::from_u32(reason_code_u32).ok_or_else(|| {
533            FynxError::Protocol(format!("Invalid failure reason code: {}", reason_code_u32))
534        })?;
535
536        Ok(Self {
537            recipient_channel,
538            reason_code,
539            description,
540            language_tag,
541        })
542    }
543}
544
545/// SSH_MSG_CHANNEL_WINDOW_ADJUST message (RFC 4254 Section 5.2).
546///
547/// Sent to increase the window size.
548#[derive(Debug, Clone, Copy, PartialEq, Eq)]
549pub struct ChannelWindowAdjust {
550    /// Recipient channel number
551    recipient_channel: u32,
552    /// Bytes to add to window
553    bytes_to_add: u32,
554}
555
556impl ChannelWindowAdjust {
557    /// Creates a new window adjust message.
558    pub fn new(recipient_channel: u32, bytes_to_add: u32) -> Self {
559        Self {
560            recipient_channel,
561            bytes_to_add,
562        }
563    }
564
565    /// Returns the recipient channel number.
566    pub fn recipient_channel(&self) -> u32 {
567        self.recipient_channel
568    }
569
570    /// Returns the bytes to add.
571    pub fn bytes_to_add(&self) -> u32 {
572        self.bytes_to_add
573    }
574
575    /// Serializes to bytes.
576    pub fn to_bytes(&self) -> Vec<u8> {
577        let mut buf = BytesMut::new();
578
579        // byte SSH_MSG_CHANNEL_WINDOW_ADJUST (93)
580        buf.put_u8(93);
581        buf.put_u32(self.recipient_channel);
582        buf.put_u32(self.bytes_to_add);
583
584        buf.to_vec()
585    }
586
587    /// Parses from bytes.
588    pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
589        if data.is_empty() {
590            return Err(FynxError::Protocol(
591                "CHANNEL_WINDOW_ADJUST message is empty".to_string(),
592            ));
593        }
594
595        if data[0] != 93 {
596            return Err(FynxError::Protocol(format!(
597                "Invalid message type: expected 93 (SSH_MSG_CHANNEL_WINDOW_ADJUST), got {}",
598                data[0]
599            )));
600        }
601
602        let mut offset = 1;
603
604        let recipient_channel = read_u32(data, &mut offset)?;
605        let bytes_to_add = read_u32(data, &mut offset)?;
606
607        Ok(Self {
608            recipient_channel,
609            bytes_to_add,
610        })
611    }
612}
613
614/// SSH_MSG_CHANNEL_DATA message (RFC 4254 Section 5.2).
615///
616/// Sent to transmit data on a channel.
617#[derive(Debug, Clone, PartialEq, Eq)]
618pub struct ChannelData {
619    /// Recipient channel number
620    recipient_channel: u32,
621    /// Data to send
622    data: Vec<u8>,
623}
624
625impl ChannelData {
626    /// Creates a new channel data message.
627    pub fn new(recipient_channel: u32, data: Vec<u8>) -> Self {
628        Self {
629            recipient_channel,
630            data,
631        }
632    }
633
634    /// Returns the recipient channel number.
635    pub fn recipient_channel(&self) -> u32 {
636        self.recipient_channel
637    }
638
639    /// Returns the data.
640    pub fn data(&self) -> &[u8] {
641        &self.data
642    }
643
644    /// Serializes to bytes.
645    pub fn to_bytes(&self) -> Vec<u8> {
646        let mut buf = BytesMut::new();
647
648        // byte SSH_MSG_CHANNEL_DATA (94)
649        buf.put_u8(94);
650        buf.put_u32(self.recipient_channel);
651        write_bytes(&mut buf, &self.data);
652
653        buf.to_vec()
654    }
655
656    /// Parses from bytes.
657    pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
658        if data.is_empty() {
659            return Err(FynxError::Protocol(
660                "CHANNEL_DATA message is empty".to_string(),
661            ));
662        }
663
664        if data[0] != 94 {
665            return Err(FynxError::Protocol(format!(
666                "Invalid message type: expected 94 (SSH_MSG_CHANNEL_DATA), got {}",
667                data[0]
668            )));
669        }
670
671        let mut offset = 1;
672
673        let recipient_channel = read_u32(data, &mut offset)?;
674        let channel_data = read_bytes(data, &mut offset)?;
675
676        Ok(Self {
677            recipient_channel,
678            data: channel_data,
679        })
680    }
681}
682
683/// Extended data type code (RFC 4254 Section 5.2).
684#[derive(Debug, Clone, Copy, PartialEq, Eq)]
685#[repr(u32)]
686pub enum ExtendedDataType {
687    /// Stderr data
688    Stderr = 1,
689}
690
691impl ExtendedDataType {
692    /// Converts from u32.
693    pub fn from_u32(value: u32) -> Option<Self> {
694        match value {
695            1 => Some(Self::Stderr),
696            _ => None,
697        }
698    }
699}
700
701/// SSH_MSG_CHANNEL_EXTENDED_DATA message (RFC 4254 Section 5.2).
702///
703/// Sent to transmit extended data (e.g., stderr) on a channel.
704#[derive(Debug, Clone, PartialEq, Eq)]
705pub struct ChannelExtendedData {
706    /// Recipient channel number
707    recipient_channel: u32,
708    /// Data type code
709    data_type_code: ExtendedDataType,
710    /// Data to send
711    data: Vec<u8>,
712}
713
714impl ChannelExtendedData {
715    /// Creates a new channel extended data message.
716    pub fn new(recipient_channel: u32, data_type_code: ExtendedDataType, data: Vec<u8>) -> Self {
717        Self {
718            recipient_channel,
719            data_type_code,
720            data,
721        }
722    }
723
724    /// Returns the recipient channel number.
725    pub fn recipient_channel(&self) -> u32 {
726        self.recipient_channel
727    }
728
729    /// Returns the data type code.
730    pub fn data_type_code(&self) -> ExtendedDataType {
731        self.data_type_code
732    }
733
734    /// Returns the data.
735    pub fn data(&self) -> &[u8] {
736        &self.data
737    }
738
739    /// Serializes to bytes.
740    pub fn to_bytes(&self) -> Vec<u8> {
741        let mut buf = BytesMut::new();
742
743        // byte SSH_MSG_CHANNEL_EXTENDED_DATA (95)
744        buf.put_u8(95);
745        buf.put_u32(self.recipient_channel);
746        buf.put_u32(self.data_type_code as u32);
747        write_bytes(&mut buf, &self.data);
748
749        buf.to_vec()
750    }
751
752    /// Parses from bytes.
753    pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
754        if data.is_empty() {
755            return Err(FynxError::Protocol(
756                "CHANNEL_EXTENDED_DATA message is empty".to_string(),
757            ));
758        }
759
760        if data[0] != 95 {
761            return Err(FynxError::Protocol(format!(
762                "Invalid message type: expected 95 (SSH_MSG_CHANNEL_EXTENDED_DATA), got {}",
763                data[0]
764            )));
765        }
766
767        let mut offset = 1;
768
769        let recipient_channel = read_u32(data, &mut offset)?;
770        let data_type_code_u32 = read_u32(data, &mut offset)?;
771        let channel_data = read_bytes(data, &mut offset)?;
772
773        let data_type_code = ExtendedDataType::from_u32(data_type_code_u32).ok_or_else(|| {
774            FynxError::Protocol(format!(
775                "Invalid extended data type: {}",
776                data_type_code_u32
777            ))
778        })?;
779
780        Ok(Self {
781            recipient_channel,
782            data_type_code,
783            data: channel_data,
784        })
785    }
786}
787
788/// SSH_MSG_CHANNEL_EOF message (RFC 4254 Section 5.3).
789///
790/// Sent when no more data will be sent on a channel.
791#[derive(Debug, Clone, Copy, PartialEq, Eq)]
792pub struct ChannelEof {
793    /// Recipient channel number
794    recipient_channel: u32,
795}
796
797impl ChannelEof {
798    /// Creates a new channel EOF message.
799    pub fn new(recipient_channel: u32) -> Self {
800        Self { recipient_channel }
801    }
802
803    /// Returns the recipient channel number.
804    pub fn recipient_channel(&self) -> u32 {
805        self.recipient_channel
806    }
807
808    /// Serializes to bytes.
809    pub fn to_bytes(&self) -> Vec<u8> {
810        let mut buf = BytesMut::new();
811
812        // byte SSH_MSG_CHANNEL_EOF (96)
813        buf.put_u8(96);
814        buf.put_u32(self.recipient_channel);
815
816        buf.to_vec()
817    }
818
819    /// Parses from bytes.
820    pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
821        if data.is_empty() {
822            return Err(FynxError::Protocol(
823                "CHANNEL_EOF message is empty".to_string(),
824            ));
825        }
826
827        if data[0] != 96 {
828            return Err(FynxError::Protocol(format!(
829                "Invalid message type: expected 96 (SSH_MSG_CHANNEL_EOF), got {}",
830                data[0]
831            )));
832        }
833
834        let mut offset = 1;
835        let recipient_channel = read_u32(data, &mut offset)?;
836
837        Ok(Self { recipient_channel })
838    }
839}
840
841/// SSH_MSG_CHANNEL_CLOSE message (RFC 4254 Section 5.3).
842///
843/// Sent to close a channel.
844#[derive(Debug, Clone, Copy, PartialEq, Eq)]
845pub struct ChannelClose {
846    /// Recipient channel number
847    recipient_channel: u32,
848}
849
850impl ChannelClose {
851    /// Creates a new channel close message.
852    pub fn new(recipient_channel: u32) -> Self {
853        Self { recipient_channel }
854    }
855
856    /// Returns the recipient channel number.
857    pub fn recipient_channel(&self) -> u32 {
858        self.recipient_channel
859    }
860
861    /// Serializes to bytes.
862    pub fn to_bytes(&self) -> Vec<u8> {
863        let mut buf = BytesMut::new();
864
865        // byte SSH_MSG_CHANNEL_CLOSE (97)
866        buf.put_u8(97);
867        buf.put_u32(self.recipient_channel);
868
869        buf.to_vec()
870    }
871
872    /// Parses from bytes.
873    pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
874        if data.is_empty() {
875            return Err(FynxError::Protocol(
876                "CHANNEL_CLOSE message is empty".to_string(),
877            ));
878        }
879
880        if data[0] != 97 {
881            return Err(FynxError::Protocol(format!(
882                "Invalid message type: expected 97 (SSH_MSG_CHANNEL_CLOSE), got {}",
883                data[0]
884            )));
885        }
886
887        let mut offset = 1;
888        let recipient_channel = read_u32(data, &mut offset)?;
889
890        Ok(Self { recipient_channel })
891    }
892}
893
894/// Channel request type (RFC 4254 Section 6).
895#[derive(Debug, Clone, PartialEq, Eq)]
896pub enum ChannelRequestType {
897    /// PTY request (pseudoterminal allocation)
898    PtyReq {
899        /// Terminal type (e.g., "xterm")
900        term: String,
901        /// Terminal width in characters
902        width_chars: u32,
903        /// Terminal height in rows
904        height_rows: u32,
905        /// Terminal width in pixels
906        width_pixels: u32,
907        /// Terminal height in pixels
908        height_pixels: u32,
909        /// Encoded terminal modes
910        modes: Vec<u8>,
911    },
912    /// Environment variable
913    Env {
914        /// Variable name
915        name: String,
916        /// Variable value
917        value: String,
918    },
919    /// Execute command
920    Exec {
921        /// Command to execute
922        command: String,
923    },
924    /// Start interactive shell
925    Shell,
926    /// Start subsystem (e.g., "sftp")
927    Subsystem {
928        /// Subsystem name
929        name: String,
930    },
931    /// Exit status
932    ExitStatus {
933        /// Exit status code
934        exit_status: u32,
935    },
936    /// Exit signal
937    ExitSignal {
938        /// Signal name
939        signal_name: String,
940        /// Core dumped flag
941        core_dumped: bool,
942        /// Error message
943        error_message: String,
944        /// Language tag
945        language_tag: String,
946    },
947}
948
949impl ChannelRequestType {
950    /// Returns the request type name.
951    pub fn name(&self) -> &str {
952        match self {
953            ChannelRequestType::PtyReq { .. } => "pty-req",
954            ChannelRequestType::Env { .. } => "env",
955            ChannelRequestType::Exec { .. } => "exec",
956            ChannelRequestType::Shell => "shell",
957            ChannelRequestType::Subsystem { .. } => "subsystem",
958            ChannelRequestType::ExitStatus { .. } => "exit-status",
959            ChannelRequestType::ExitSignal { .. } => "exit-signal",
960        }
961    }
962}
963
964/// SSH_MSG_CHANNEL_REQUEST message (RFC 4254 Section 6).
965///
966/// Sent to make a channel-specific request.
967#[derive(Debug, Clone, PartialEq, Eq)]
968pub struct ChannelRequest {
969    /// Recipient channel number
970    recipient_channel: u32,
971    /// Request type
972    request_type: ChannelRequestType,
973    /// Want reply flag
974    want_reply: bool,
975}
976
977impl ChannelRequest {
978    /// Creates a new channel request.
979    pub fn new(recipient_channel: u32, request_type: ChannelRequestType, want_reply: bool) -> Self {
980        Self {
981            recipient_channel,
982            request_type,
983            want_reply,
984        }
985    }
986
987    /// Returns the recipient channel number.
988    pub fn recipient_channel(&self) -> u32 {
989        self.recipient_channel
990    }
991
992    /// Returns the request type.
993    pub fn request_type(&self) -> &ChannelRequestType {
994        &self.request_type
995    }
996
997    /// Returns whether a reply is wanted.
998    pub fn want_reply(&self) -> bool {
999        self.want_reply
1000    }
1001
1002    /// Serializes to bytes.
1003    pub fn to_bytes(&self) -> Vec<u8> {
1004        let mut buf = BytesMut::new();
1005
1006        // byte SSH_MSG_CHANNEL_REQUEST (98)
1007        buf.put_u8(98);
1008        buf.put_u32(self.recipient_channel);
1009        write_string(&mut buf, self.request_type.name());
1010        buf.put_u8(if self.want_reply { 1 } else { 0 });
1011
1012        // Request type specific data
1013        match &self.request_type {
1014            ChannelRequestType::PtyReq {
1015                term,
1016                width_chars,
1017                height_rows,
1018                width_pixels,
1019                height_pixels,
1020                modes,
1021            } => {
1022                write_string(&mut buf, term);
1023                buf.put_u32(*width_chars);
1024                buf.put_u32(*height_rows);
1025                buf.put_u32(*width_pixels);
1026                buf.put_u32(*height_pixels);
1027                write_bytes(&mut buf, modes);
1028            }
1029            ChannelRequestType::Env { name, value } => {
1030                write_string(&mut buf, name);
1031                write_string(&mut buf, value);
1032            }
1033            ChannelRequestType::Exec { command } => {
1034                write_string(&mut buf, command);
1035            }
1036            ChannelRequestType::Shell => {
1037                // No additional data
1038            }
1039            ChannelRequestType::Subsystem { name } => {
1040                write_string(&mut buf, name);
1041            }
1042            ChannelRequestType::ExitStatus { exit_status } => {
1043                buf.put_u32(*exit_status);
1044            }
1045            ChannelRequestType::ExitSignal {
1046                signal_name,
1047                core_dumped,
1048                error_message,
1049                language_tag,
1050            } => {
1051                write_string(&mut buf, signal_name);
1052                buf.put_u8(if *core_dumped { 1 } else { 0 });
1053                write_string(&mut buf, error_message);
1054                write_string(&mut buf, language_tag);
1055            }
1056        }
1057
1058        buf.to_vec()
1059    }
1060
1061    /// Parses from bytes.
1062    pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
1063        if data.is_empty() {
1064            return Err(FynxError::Protocol(
1065                "CHANNEL_REQUEST message is empty".to_string(),
1066            ));
1067        }
1068
1069        if data[0] != 98 {
1070            return Err(FynxError::Protocol(format!(
1071                "Invalid message type: expected 98 (SSH_MSG_CHANNEL_REQUEST), got {}",
1072                data[0]
1073            )));
1074        }
1075
1076        let mut offset = 1;
1077
1078        let recipient_channel = read_u32(data, &mut offset)?;
1079        let request_name = read_string(data, &mut offset)?;
1080
1081        // boolean want reply
1082        if offset >= data.len() {
1083            return Err(FynxError::Protocol(
1084                "CHANNEL_REQUEST truncated (missing want_reply flag)".to_string(),
1085            ));
1086        }
1087        let want_reply = data[offset] != 0;
1088        offset += 1;
1089
1090        // Parse request type specific data
1091        let request_type = match request_name.as_str() {
1092            "pty-req" => {
1093                let term = read_string(data, &mut offset)?;
1094                let width_chars = read_u32(data, &mut offset)?;
1095                let height_rows = read_u32(data, &mut offset)?;
1096                let width_pixels = read_u32(data, &mut offset)?;
1097                let height_pixels = read_u32(data, &mut offset)?;
1098                let modes = read_bytes(data, &mut offset)?;
1099                ChannelRequestType::PtyReq {
1100                    term,
1101                    width_chars,
1102                    height_rows,
1103                    width_pixels,
1104                    height_pixels,
1105                    modes,
1106                }
1107            }
1108            "env" => {
1109                let name = read_string(data, &mut offset)?;
1110                let value = read_string(data, &mut offset)?;
1111                ChannelRequestType::Env { name, value }
1112            }
1113            "exec" => {
1114                let command = read_string(data, &mut offset)?;
1115                ChannelRequestType::Exec { command }
1116            }
1117            "shell" => ChannelRequestType::Shell,
1118            "subsystem" => {
1119                let name = read_string(data, &mut offset)?;
1120                ChannelRequestType::Subsystem { name }
1121            }
1122            "exit-status" => {
1123                let exit_status = read_u32(data, &mut offset)?;
1124                ChannelRequestType::ExitStatus { exit_status }
1125            }
1126            "exit-signal" => {
1127                let signal_name = read_string(data, &mut offset)?;
1128                let core_dumped = if offset < data.len() {
1129                    let val = data[offset] != 0;
1130                    offset += 1;
1131                    val
1132                } else {
1133                    return Err(FynxError::Protocol(
1134                        "CHANNEL_REQUEST exit-signal truncated".to_string(),
1135                    ));
1136                };
1137                let error_message = read_string(data, &mut offset)?;
1138                let language_tag = read_string(data, &mut offset)?;
1139                ChannelRequestType::ExitSignal {
1140                    signal_name,
1141                    core_dumped,
1142                    error_message,
1143                    language_tag,
1144                }
1145            }
1146            _ => {
1147                return Err(FynxError::Protocol(format!(
1148                    "Unsupported channel request type: '{}'",
1149                    request_name
1150                )))
1151            }
1152        };
1153
1154        Ok(Self {
1155            recipient_channel,
1156            request_type,
1157            want_reply,
1158        })
1159    }
1160}
1161
1162/// SSH_MSG_CHANNEL_SUCCESS message (RFC 4254 Section 6.4).
1163///
1164/// Sent in response to a channel request to indicate success.
1165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1166pub struct ChannelSuccess {
1167    /// Recipient channel number
1168    recipient_channel: u32,
1169}
1170
1171impl ChannelSuccess {
1172    /// Creates a new channel success message.
1173    pub fn new(recipient_channel: u32) -> Self {
1174        Self { recipient_channel }
1175    }
1176
1177    /// Returns the recipient channel number.
1178    pub fn recipient_channel(&self) -> u32 {
1179        self.recipient_channel
1180    }
1181
1182    /// Serializes to bytes.
1183    pub fn to_bytes(&self) -> Vec<u8> {
1184        let mut buf = BytesMut::new();
1185
1186        // byte SSH_MSG_CHANNEL_SUCCESS (99)
1187        buf.put_u8(99);
1188        buf.put_u32(self.recipient_channel);
1189
1190        buf.to_vec()
1191    }
1192
1193    /// Parses from bytes.
1194    pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
1195        if data.is_empty() {
1196            return Err(FynxError::Protocol(
1197                "CHANNEL_SUCCESS message is empty".to_string(),
1198            ));
1199        }
1200
1201        if data[0] != 99 {
1202            return Err(FynxError::Protocol(format!(
1203                "Invalid message type: expected 99 (SSH_MSG_CHANNEL_SUCCESS), got {}",
1204                data[0]
1205            )));
1206        }
1207
1208        let mut offset = 1;
1209        let recipient_channel = read_u32(data, &mut offset)?;
1210
1211        Ok(Self { recipient_channel })
1212    }
1213}
1214
1215/// SSH_MSG_CHANNEL_FAILURE message (RFC 4254 Section 6.4).
1216///
1217/// Sent in response to a channel request to indicate failure.
1218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1219pub struct ChannelFailure {
1220    /// Recipient channel number
1221    recipient_channel: u32,
1222}
1223
1224impl ChannelFailure {
1225    /// Creates a new channel failure message.
1226    pub fn new(recipient_channel: u32) -> Self {
1227        Self { recipient_channel }
1228    }
1229
1230    /// Returns the recipient channel number.
1231    pub fn recipient_channel(&self) -> u32 {
1232        self.recipient_channel
1233    }
1234
1235    /// Serializes to bytes.
1236    pub fn to_bytes(&self) -> Vec<u8> {
1237        let mut buf = BytesMut::new();
1238
1239        // byte SSH_MSG_CHANNEL_FAILURE (100)
1240        buf.put_u8(100);
1241        buf.put_u32(self.recipient_channel);
1242
1243        buf.to_vec()
1244    }
1245
1246    /// Parses from bytes.
1247    pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
1248        if data.is_empty() {
1249            return Err(FynxError::Protocol(
1250                "CHANNEL_FAILURE message is empty".to_string(),
1251            ));
1252        }
1253
1254        if data[0] != 100 {
1255            return Err(FynxError::Protocol(format!(
1256                "Invalid message type: expected 100 (SSH_MSG_CHANNEL_FAILURE), got {}",
1257                data[0]
1258            )));
1259        }
1260
1261        let mut offset = 1;
1262        let recipient_channel = read_u32(data, &mut offset)?;
1263
1264        Ok(Self { recipient_channel })
1265    }
1266}
1267
1268// Helper functions for encoding/decoding
1269
1270fn write_string(buf: &mut BytesMut, s: &str) {
1271    let bytes = s.as_bytes();
1272    buf.put_u32(bytes.len() as u32);
1273    buf.put_slice(bytes);
1274}
1275
1276fn write_bytes(buf: &mut BytesMut, bytes: &[u8]) {
1277    buf.put_u32(bytes.len() as u32);
1278    buf.put_slice(bytes);
1279}
1280
1281fn read_string(data: &[u8], offset: &mut usize) -> FynxResult<String> {
1282    let bytes = read_bytes(data, offset)?;
1283    String::from_utf8(bytes)
1284        .map_err(|_| FynxError::Protocol("String contains invalid UTF-8".to_string()))
1285}
1286
1287fn read_bytes(data: &[u8], offset: &mut usize) -> FynxResult<Vec<u8>> {
1288    if *offset + 4 > data.len() {
1289        return Err(FynxError::Protocol(format!(
1290            "Cannot read length at offset {}",
1291            offset
1292        )));
1293    }
1294
1295    let length = u32::from_be_bytes([
1296        data[*offset],
1297        data[*offset + 1],
1298        data[*offset + 2],
1299        data[*offset + 3],
1300    ]) as usize;
1301    *offset += 4;
1302
1303    if *offset + length > data.len() {
1304        return Err(FynxError::Protocol(format!(
1305            "Data truncated: expected {} bytes at offset {}",
1306            length, offset
1307        )));
1308    }
1309
1310    let bytes = data[*offset..*offset + length].to_vec();
1311    *offset += length;
1312
1313    Ok(bytes)
1314}
1315
1316fn read_u32(data: &[u8], offset: &mut usize) -> FynxResult<u32> {
1317    if *offset + 4 > data.len() {
1318        return Err(FynxError::Protocol(format!(
1319            "Cannot read u32 at offset {}",
1320            offset
1321        )));
1322    }
1323
1324    let value = u32::from_be_bytes([
1325        data[*offset],
1326        data[*offset + 1],
1327        data[*offset + 2],
1328        data[*offset + 3],
1329    ]);
1330    *offset += 4;
1331
1332    Ok(value)
1333}
1334
1335#[cfg(test)]
1336mod tests {
1337    use super::*;
1338
1339    #[test]
1340    fn test_channel_open_session() {
1341        let open = ChannelOpen::new(ChannelType::Session, 0, 1048576, 32768);
1342
1343        assert_eq!(open.sender_channel(), 0);
1344        assert_eq!(open.initial_window_size(), 1048576);
1345        assert_eq!(open.maximum_packet_size(), 32768);
1346
1347        let bytes = open.to_bytes();
1348        let parsed = ChannelOpen::from_bytes(&bytes).unwrap();
1349
1350        assert_eq!(parsed.channel_type(), &ChannelType::Session);
1351        assert_eq!(parsed.sender_channel(), 0);
1352    }
1353
1354    #[test]
1355    fn test_channel_open_direct_tcpip() {
1356        let open = ChannelOpen::new(
1357            ChannelType::DirectTcpip {
1358                host: "example.com".to_string(),
1359                port: 80,
1360                originator_address: "192.168.1.1".to_string(),
1361                originator_port: 12345,
1362            },
1363            1,
1364            1048576,
1365            32768,
1366        );
1367
1368        let bytes = open.to_bytes();
1369        let parsed = ChannelOpen::from_bytes(&bytes).unwrap();
1370
1371        if let ChannelType::DirectTcpip {
1372            host,
1373            port,
1374            originator_address,
1375            originator_port,
1376        } = parsed.channel_type()
1377        {
1378            assert_eq!(host, "example.com");
1379            assert_eq!(*port, 80);
1380            assert_eq!(originator_address, "192.168.1.1");
1381            assert_eq!(*originator_port, 12345);
1382        } else {
1383            panic!("Expected DirectTcpip channel type");
1384        }
1385    }
1386
1387    #[test]
1388    fn test_channel_open_confirmation() {
1389        let confirm = ChannelOpenConfirmation::new(0, 1, 1048576, 32768);
1390
1391        let bytes = confirm.to_bytes();
1392        let parsed = ChannelOpenConfirmation::from_bytes(&bytes).unwrap();
1393
1394        assert_eq!(parsed.recipient_channel(), 0);
1395        assert_eq!(parsed.sender_channel(), 1);
1396        assert_eq!(parsed.initial_window_size(), 1048576);
1397        assert_eq!(parsed.maximum_packet_size(), 32768);
1398    }
1399
1400    #[test]
1401    fn test_channel_open_failure() {
1402        let failure =
1403            ChannelOpenFailure::new(0, ChannelOpenFailureReason::AdministrativelyProhibited);
1404
1405        assert_eq!(
1406            failure.reason_code(),
1407            ChannelOpenFailureReason::AdministrativelyProhibited
1408        );
1409
1410        let bytes = failure.to_bytes();
1411        let parsed = ChannelOpenFailure::from_bytes(&bytes).unwrap();
1412
1413        assert_eq!(parsed.recipient_channel(), 0);
1414        assert_eq!(
1415            parsed.reason_code(),
1416            ChannelOpenFailureReason::AdministrativelyProhibited
1417        );
1418    }
1419
1420    #[test]
1421    fn test_channel_window_adjust() {
1422        let adjust = ChannelWindowAdjust::new(0, 32768);
1423
1424        let bytes = adjust.to_bytes();
1425        let parsed = ChannelWindowAdjust::from_bytes(&bytes).unwrap();
1426
1427        assert_eq!(parsed.recipient_channel(), 0);
1428        assert_eq!(parsed.bytes_to_add(), 32768);
1429    }
1430
1431    #[test]
1432    fn test_channel_data() {
1433        let data = ChannelData::new(0, b"Hello, SSH!".to_vec());
1434
1435        assert_eq!(data.data(), b"Hello, SSH!");
1436
1437        let bytes = data.to_bytes();
1438        let parsed = ChannelData::from_bytes(&bytes).unwrap();
1439
1440        assert_eq!(parsed.recipient_channel(), 0);
1441        assert_eq!(parsed.data(), b"Hello, SSH!");
1442    }
1443
1444    #[test]
1445    fn test_channel_extended_data() {
1446        let data = ChannelExtendedData::new(0, ExtendedDataType::Stderr, b"Error!".to_vec());
1447
1448        let bytes = data.to_bytes();
1449        let parsed = ChannelExtendedData::from_bytes(&bytes).unwrap();
1450
1451        assert_eq!(parsed.recipient_channel(), 0);
1452        assert_eq!(parsed.data_type_code(), ExtendedDataType::Stderr);
1453        assert_eq!(parsed.data(), b"Error!");
1454    }
1455
1456    #[test]
1457    fn test_channel_eof() {
1458        let eof = ChannelEof::new(0);
1459
1460        let bytes = eof.to_bytes();
1461        let parsed = ChannelEof::from_bytes(&bytes).unwrap();
1462
1463        assert_eq!(parsed.recipient_channel(), 0);
1464    }
1465
1466    #[test]
1467    fn test_channel_close() {
1468        let close = ChannelClose::new(0);
1469
1470        let bytes = close.to_bytes();
1471        let parsed = ChannelClose::from_bytes(&bytes).unwrap();
1472
1473        assert_eq!(parsed.recipient_channel(), 0);
1474    }
1475
1476    #[test]
1477    fn test_window_size_validation() {
1478        let mut data =
1479            ChannelOpen::new(ChannelType::Session, 0, MAX_WINDOW_SIZE + 1, 32768).to_bytes();
1480        // Manually set invalid window size
1481        data[13] = 0x01; // Set to MAX_WINDOW_SIZE + 1
1482
1483        let result = ChannelOpen::from_bytes(&data);
1484        assert!(result.is_err());
1485    }
1486
1487    #[test]
1488    fn test_packet_size_validation() {
1489        let mut data =
1490            ChannelOpen::new(ChannelType::Session, 0, 1048576, MAX_PACKET_SIZE + 1).to_bytes();
1491        // Manually set invalid packet size
1492        data[17] = 0x01; // Set to MAX_PACKET_SIZE + 1
1493
1494        let result = ChannelOpen::from_bytes(&data);
1495        assert!(result.is_err());
1496    }
1497
1498    #[test]
1499    fn test_channel_request_exec() {
1500        let request = ChannelRequest::new(
1501            0,
1502            ChannelRequestType::Exec {
1503                command: "ls -la".to_string(),
1504            },
1505            true,
1506        );
1507
1508        assert!(request.want_reply());
1509
1510        let bytes = request.to_bytes();
1511        let parsed = ChannelRequest::from_bytes(&bytes).unwrap();
1512
1513        assert_eq!(parsed.recipient_channel(), 0);
1514        assert!(parsed.want_reply());
1515
1516        if let ChannelRequestType::Exec { command } = parsed.request_type() {
1517            assert_eq!(command, "ls -la");
1518        } else {
1519            panic!("Expected Exec request type");
1520        }
1521    }
1522
1523    #[test]
1524    fn test_channel_request_shell() {
1525        let request = ChannelRequest::new(0, ChannelRequestType::Shell, true);
1526
1527        let bytes = request.to_bytes();
1528        let parsed = ChannelRequest::from_bytes(&bytes).unwrap();
1529
1530        assert_eq!(parsed.request_type(), &ChannelRequestType::Shell);
1531    }
1532
1533    #[test]
1534    fn test_channel_request_pty() {
1535        let request = ChannelRequest::new(
1536            0,
1537            ChannelRequestType::PtyReq {
1538                term: "xterm".to_string(),
1539                width_chars: 80,
1540                height_rows: 24,
1541                width_pixels: 640,
1542                height_pixels: 480,
1543                modes: vec![0],
1544            },
1545            true,
1546        );
1547
1548        let bytes = request.to_bytes();
1549        let parsed = ChannelRequest::from_bytes(&bytes).unwrap();
1550
1551        if let ChannelRequestType::PtyReq {
1552            term,
1553            width_chars,
1554            height_rows,
1555            ..
1556        } = parsed.request_type()
1557        {
1558            assert_eq!(term, "xterm");
1559            assert_eq!(*width_chars, 80);
1560            assert_eq!(*height_rows, 24);
1561        } else {
1562            panic!("Expected PtyReq request type");
1563        }
1564    }
1565
1566    #[test]
1567    fn test_channel_request_env() {
1568        let request = ChannelRequest::new(
1569            0,
1570            ChannelRequestType::Env {
1571                name: "PATH".to_string(),
1572                value: "/usr/bin".to_string(),
1573            },
1574            false,
1575        );
1576
1577        let bytes = request.to_bytes();
1578        let parsed = ChannelRequest::from_bytes(&bytes).unwrap();
1579
1580        if let ChannelRequestType::Env { name, value } = parsed.request_type() {
1581            assert_eq!(name, "PATH");
1582            assert_eq!(value, "/usr/bin");
1583        } else {
1584            panic!("Expected Env request type");
1585        }
1586    }
1587
1588    #[test]
1589    fn test_channel_request_subsystem() {
1590        let request = ChannelRequest::new(
1591            0,
1592            ChannelRequestType::Subsystem {
1593                name: "sftp".to_string(),
1594            },
1595            true,
1596        );
1597
1598        let bytes = request.to_bytes();
1599        let parsed = ChannelRequest::from_bytes(&bytes).unwrap();
1600
1601        if let ChannelRequestType::Subsystem { name } = parsed.request_type() {
1602            assert_eq!(name, "sftp");
1603        } else {
1604            panic!("Expected Subsystem request type");
1605        }
1606    }
1607
1608    #[test]
1609    fn test_channel_request_exit_status() {
1610        let request =
1611            ChannelRequest::new(0, ChannelRequestType::ExitStatus { exit_status: 0 }, false);
1612
1613        let bytes = request.to_bytes();
1614        let parsed = ChannelRequest::from_bytes(&bytes).unwrap();
1615
1616        if let ChannelRequestType::ExitStatus { exit_status } = parsed.request_type() {
1617            assert_eq!(*exit_status, 0);
1618        } else {
1619            panic!("Expected ExitStatus request type");
1620        }
1621    }
1622
1623    #[test]
1624    fn test_channel_success() {
1625        let success = ChannelSuccess::new(0);
1626
1627        let bytes = success.to_bytes();
1628        let parsed = ChannelSuccess::from_bytes(&bytes).unwrap();
1629
1630        assert_eq!(parsed.recipient_channel(), 0);
1631    }
1632
1633    #[test]
1634    fn test_channel_failure() {
1635        let failure = ChannelFailure::new(0);
1636
1637        let bytes = failure.to_bytes();
1638        let parsed = ChannelFailure::from_bytes(&bytes).unwrap();
1639
1640        assert_eq!(parsed.recipient_channel(), 0);
1641    }
1642}