Skip to main content

fynx_proto/ssh/forwarding/
remote.rs

1//! Remote port forwarding (tcpip-forward).
2//!
3//! Asks the SSH server to forward connections from a remote address to a local target.
4//!
5//! # How it works
6//!
7//! 1. Send global request "tcpip-forward" to server
8//! 2. Server listens on the specified remote address
9//! 3. When a connection arrives, server opens channel (`forwarded-tcpip`)
10//! 4. Client connects to local target and relays data bidirectionally
11//!
12//! # Example
13//!
14//! ```rust,no_run
15//! use fynx_proto::ssh::client::SshClient;
16//!
17//! # #[tokio::main]
18//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
19//! let mut client = SshClient::connect("server:22").await?;
20//! client.authenticate_password("user", "pass").await?;
21//!
22//! // Forward remote:8080 to localhost:3000
23//! let mut forward = client.remote_forward(
24//!     "0.0.0.0:8080",
25//!     "localhost:3000"
26//! ).await?;
27//!
28//! // Handle incoming connections
29//! forward.run().await?;
30//! # Ok(())
31//! # }
32//! ```
33
34use super::types::ForwardAddr;
35use crate::ssh::connection_mgr::SshConnection;
36use crate::ssh::dispatcher::MessageDispatcher;
37use fynx_platform::FynxResult;
38use std::sync::Arc;
39use tokio::sync::Mutex;
40use tracing::{debug, info, warn};
41
42/// Remote port forwarding handle.
43///
44/// Created by [`SshClient::remote_forward()`](crate::ssh::client::SshClient::remote_forward).
45pub struct RemoteForward {
46    /// Address the server is listening on
47    bind_addr: ForwardAddr,
48    /// Local target address to forward to
49    local_target: ForwardAddr,
50    /// SSH connection (for channel operations)
51    connection: Arc<Mutex<SshConnection>>,
52    /// Message dispatcher (for channel communication)
53    dispatcher: Arc<Mutex<MessageDispatcher>>,
54}
55
56impl RemoteForward {
57    /// Creates a new remote forward.
58    ///
59    /// This is called by `SshClient::remote_forward()` after sending
60    /// the tcpip-forward global request.
61    ///
62    /// # Arguments
63    ///
64    /// * `bind_addr` - Address the server is listening on
65    /// * `local_target` - Local address to forward connections to
66    /// * `connection` - SSH connection for channel operations
67    /// * `dispatcher` - Message dispatcher for channel communication
68    pub(crate) fn new(
69        bind_addr: ForwardAddr,
70        local_target: ForwardAddr,
71        connection: Arc<Mutex<SshConnection>>,
72        dispatcher: Arc<Mutex<MessageDispatcher>>,
73    ) -> Self {
74        Self {
75            bind_addr,
76            local_target,
77            connection,
78            dispatcher,
79        }
80    }
81
82    /// Returns the remote bind address.
83    pub fn bind_addr(&self) -> &ForwardAddr {
84        &self.bind_addr
85    }
86
87    /// Returns the local target address.
88    pub fn local_target(&self) -> &ForwardAddr {
89        &self.local_target
90    }
91
92    /// Runs the remote forwarder.
93    ///
94    /// This method handles incoming `forwarded-tcpip` channels from the server.
95    ///
96    /// When the SSH server receives a connection on the remote address, it will
97    /// send a CHANNEL_OPEN message with type "forwarded-tcpip". This method waits
98    /// for those messages and handles each incoming connection.
99    pub async fn run(self) -> FynxResult<()> {
100        info!(
101            "Remote forward active: {} -> {}",
102            self.bind_addr.to_string(),
103            self.local_target.to_string()
104        );
105
106        // TODO: Implement forwarded-tcpip channel handling
107        //
108        // This requires:
109        // 1. Listen for global messages from dispatcher
110        // 2. Parse CHANNEL_OPEN (forwarded-tcpip) messages
111        // 3. For each channel:
112        //    - Send CHANNEL_OPEN_CONFIRMATION
113        //    - Connect to local target (TcpStream::connect)
114        //    - Relay data bidirectionally (similar to LocalForward)
115        //
116        // The challenge is that CHANNEL_OPEN messages arrive via the dispatcher's
117        // global message channel, which we need to access.
118
119        loop {
120            // Wait for forwarded-tcpip CHANNEL_OPEN from server
121            let global_msg = match self.dispatcher.lock().await.receive_global().await {
122                Some(msg) => msg,
123                None => {
124                    warn!("Global message channel closed");
125                    break;
126                }
127            };
128
129            if global_msg.is_empty() {
130                continue;
131            }
132
133            // Check if this is a CHANNEL_OPEN message
134            use crate::ssh::message::MessageType;
135            if global_msg[0] != MessageType::ChannelOpen as u8 {
136                // Not a CHANNEL_OPEN, ignore
137                debug!(
138                    "Received non-CHANNEL_OPEN global message: {}",
139                    global_msg[0]
140                );
141                continue;
142            }
143
144            // Parse CHANNEL_OPEN message
145            // TODO: Proper parsing of forwarded-tcpip CHANNEL_OPEN
146            // For now, log that we received it
147
148            info!(
149                "Received CHANNEL_OPEN message, forwarded-tcpip handling not yet fully implemented"
150            );
151
152            // TODO:
153            // 1. Parse channel parameters (sender_channel, window_size, etc.)
154            // 2. Connect to local target
155            // 3. Send CHANNEL_OPEN_CONFIRMATION
156            // 4. Spawn task to handle bidirectional relay
157        }
158
159        Ok(())
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166
167    #[test]
168    fn test_forward_addr_remote() {
169        // Test ForwardAddr methods since we can't easily test RemoteForward
170        // without mocking connection and dispatcher
171        let bind = ForwardAddr::new("0.0.0.0".to_string(), 8080);
172        let target = ForwardAddr::new("localhost".to_string(), 3000);
173
174        assert_eq!(bind.host, "0.0.0.0");
175        assert_eq!(bind.port, 8080);
176        assert_eq!(target.host, "localhost");
177        assert_eq!(target.port, 3000);
178    }
179
180    // TODO: Add integration tests when full forwarded-tcpip support is complete
181    // Full tests require:
182    // 1. Mock or real SSH server that supports tcpip-forward
183    // 2. Connection and dispatcher setup
184    // 3. End-to-end remote forwarding validation
185}