-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathforwarder.rs
More file actions
280 lines (247 loc) · 8.9 KB
/
forwarder.rs
File metadata and controls
280 lines (247 loc) · 8.9 KB
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
//! Main dynamic forwarder implementation
use super::{connection::ConnectionHandler, stats::DynamicForwarderStats};
use crate::{
forwarding::{
ForwardingConfig, ForwardingMessage, ForwardingStats, ForwardingStatus, ForwardingType,
SocksVersion,
},
ssh::tokio_client::Client,
};
use anyhow::{Context, Result};
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use tokio::net::TcpListener;
use tokio::sync::{Semaphore, mpsc};
use tokio_util::sync::CancellationToken;
use tracing::{error, info, warn};
use uuid::Uuid;
/// Dynamic port forwarder implementation (SOCKS proxy)
#[derive(Debug)]
#[allow(dead_code)] // Future implementation
pub struct DynamicForwarder {
pub(crate) session_id: Uuid,
pub(crate) bind_addr: SocketAddr,
pub(crate) socks_version: SocksVersion,
config: ForwardingConfig,
ssh_client: Arc<Client>,
cancel_token: CancellationToken,
message_tx: mpsc::UnboundedSender<ForwardingMessage>,
stats: Arc<DynamicForwarderStats>,
}
impl DynamicForwarder {
/// Create a new dynamic forwarder instance
pub fn new(
session_id: Uuid,
spec: ForwardingType,
ssh_client: Arc<Client>,
config: ForwardingConfig,
cancel_token: CancellationToken,
message_tx: mpsc::UnboundedSender<ForwardingMessage>,
) -> Result<Self> {
let (bind_addr, socks_version) = match spec {
ForwardingType::Dynamic {
bind_addr,
bind_port,
socks_version,
} => {
let addr = SocketAddr::new(bind_addr, bind_port);
(addr, socks_version)
}
_ => {
return Err(anyhow::anyhow!(
"Invalid forwarding type for DynamicForwarder"
));
}
};
Ok(Self {
session_id,
bind_addr,
socks_version,
config,
ssh_client,
cancel_token,
message_tx,
stats: Arc::new(DynamicForwarderStats::default()),
})
}
/// Main entry point for running dynamic port forwarding
///
/// **Implementation Note:**
/// This is currently a placeholder implementation. The full implementation
/// will include:
/// 1. SOCKS v4/v5 protocol parser
/// 2. SOCKS server with authentication support
/// 3. DNS resolution through remote connection
/// 4. Dynamic SSH channel creation per request
pub async fn run(
session_id: Uuid,
spec: ForwardingType,
ssh_client: Arc<Client>,
config: ForwardingConfig,
cancel_token: CancellationToken,
message_tx: mpsc::UnboundedSender<ForwardingMessage>,
) -> Result<()> {
let mut forwarder = Self::new(
session_id,
spec,
ssh_client,
config,
cancel_token.clone(),
message_tx.clone(),
)?;
// Send initial status update
forwarder
.send_status_update(ForwardingStatus::Initializing)
.await;
info!(
"Starting dynamic forwarding: SOCKS{:?} proxy on {}",
forwarder.socks_version, forwarder.bind_addr
);
// Run the complete SOCKS proxy implementation
match forwarder.run_with_retry().await {
Ok(_) => {
forwarder
.send_status_update(ForwardingStatus::Stopped)
.await;
Ok(())
}
Err(e) => {
let error_msg = format!("Dynamic forwarding failed: {e}");
forwarder
.send_status_update(ForwardingStatus::Failed(error_msg.clone()))
.await;
Err(anyhow::anyhow!(error_msg))
}
}
}
/// Run SOCKS proxy with automatic retry on failures
async fn run_with_retry(&mut self) -> Result<()> {
let mut retry_count = 0u32;
let mut retry_delay = Duration::from_millis(self.config.reconnect_delay_ms);
loop {
// Check if we should stop
if self.cancel_token.is_cancelled() {
info!("SOCKS proxy cancelled");
break;
}
// Check retry limits
if self.config.max_reconnect_attempts > 0
&& retry_count >= self.config.max_reconnect_attempts
{
return Err(anyhow::anyhow!(
"Maximum retry attempts ({}) exceeded",
self.config.max_reconnect_attempts
));
}
// Update status based on retry state
if retry_count == 0 {
self.send_status_update(ForwardingStatus::Initializing)
.await;
} else {
self.send_status_update(ForwardingStatus::Reconnecting)
.await;
// Wait before retrying
tokio::select! {
_ = tokio::time::sleep(retry_delay) => {}
_ = self.cancel_token.cancelled() => {
info!("SOCKS proxy cancelled during retry delay");
break;
}
}
}
info!(
"Starting SOCKS{:?} proxy on {} (attempt {})",
self.socks_version,
self.bind_addr,
retry_count + 1
);
// Attempt to start SOCKS proxy
match self.run_socks_proxy_loop().await {
Ok(_) => {
// Successful completion (probably cancelled)
break;
}
Err(e) => {
error!("SOCKS proxy attempt {} failed: {}", retry_count + 1, e);
retry_count += 1;
if !self.config.auto_reconnect {
return Err(e);
}
// Exponential backoff with jitter
retry_delay = std::cmp::min(
retry_delay.mul_f64(1.5),
Duration::from_millis(self.config.max_reconnect_delay_ms),
);
// Add jitter to avoid thundering herd
let jitter = Duration::from_millis(rand::random_range(
0..=retry_delay.as_millis() as u64 / 4,
));
retry_delay += jitter;
}
}
}
Ok(())
}
/// Main SOCKS proxy loop - create listener and handle connections
async fn run_socks_proxy_loop(&mut self) -> Result<()> {
// Create TCP listener for SOCKS proxy
let listener = TcpListener::bind(self.bind_addr)
.await
.with_context(|| format!("Failed to bind SOCKS proxy to {}", self.bind_addr))?;
let local_addr = listener
.local_addr()
.with_context(|| "Failed to get local address for SOCKS proxy")?;
info!(
"SOCKS{:?} proxy listening on {}",
self.socks_version, local_addr
);
self.send_status_update(ForwardingStatus::Active).await;
// Create semaphore to limit concurrent connections
let connection_semaphore = Arc::new(Semaphore::new(self.config.max_connections));
// Create connection handler
let handler = ConnectionHandler::new(
self.session_id,
self.socks_version,
Arc::clone(&self.ssh_client),
Arc::clone(&self.stats),
self.cancel_token.clone(),
&self.config,
);
// Run the accept loop
handler.accept_loop(listener, connection_semaphore).await?;
info!("SOCKS proxy stopped");
Ok(())
}
/// Send status update to ForwardingManager
async fn send_status_update(&self, status: ForwardingStatus) {
let message = ForwardingMessage::StatusUpdate {
id: self.session_id,
status,
};
if let Err(e) = self.message_tx.send(message) {
warn!("Failed to send status update: {}", e);
}
}
/// Send statistics update to ForwardingManager
#[allow(dead_code)] // Used in future implementation
async fn send_stats_update(&self) {
let stats = ForwardingStats {
active_connections: self.stats.active_connections() as usize,
total_connections: self.stats.total_accepted(),
bytes_transferred: self.stats.bytes_transferred(),
failed_connections: self
.stats
.socks_connections_failed
.load(std::sync::atomic::Ordering::Relaxed),
last_error: None,
};
let message = ForwardingMessage::StatsUpdate {
id: self.session_id,
stats,
};
if let Err(e) = self.message_tx.send(message) {
warn!("Failed to send stats update: {}", e);
}
}
}