1#[cfg(any(test, target_os = "windows"))]
4use std::ffi::OsString;
5#[cfg(any(test, target_os = "windows"))]
6use std::path::PathBuf;
7use std::sync::Arc;
8use std::time::Duration;
9
10#[cfg(any(target_os = "linux", target_os = "macos"))]
11use rings_gateway::bindings::unix::UnixTunnelControl;
12#[cfg(any(target_os = "linux", target_os = "macos"))]
13use rings_gateway::bindings::unix::UnixTunnelOptions;
14use rings_gateway::bindings::EstablishedTunnel;
15#[cfg(target_os = "windows")]
16use rings_gateway::bindings::NativeTunnelControl;
17#[cfg(target_os = "windows")]
18use rings_gateway::bindings::NativeTunnelOptions;
19use rings_gateway::bindings::TeardownFailure;
20use rings_gateway::bindings::TunnelControl;
21#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
22use rings_gateway::bindings::UnsupportedTunnelControl;
23use rings_gateway::ExitObservation;
24use rings_gateway::GatewayControlHandle;
25use rings_gateway::GatewayError;
26use rings_gateway::GatewayRuntime;
27use rings_gateway::GatewayStatusHandle;
28use tokio::sync::oneshot;
29
30use super::config::NativeGatewayConfig;
31use crate::onion::native::NativeOnionCircuitHandle;
32use crate::onion::NativeOnionGatewayConnector;
33use crate::onion::OnionServiceName;
34use crate::prelude::StopSource;
35use crate::prelude::StopToken;
36use crate::processor::Processor;
37#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
38use crate::util::expand_home;
39
40#[cfg(target_os = "windows")]
41type PlatformTunnelControl = NativeTunnelControl;
42#[cfg(any(target_os = "linux", target_os = "macos"))]
43type PlatformTunnelControl = UnixTunnelControl;
44#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
45type PlatformTunnelControl = UnsupportedTunnelControl;
46
47const MAX_STATUS_REFRESH_SECS: u64 = 30;
48
49pub struct NativeGatewayRunner {
51 processor: Arc<Processor>,
52 runtime: GatewayRuntime,
53 config: NativeGatewayConfig,
54}
55
56impl NativeGatewayRunner {
57 pub fn new(
59 processor: Arc<Processor>,
60 onion: NativeOnionCircuitHandle,
61 config: NativeGatewayConfig,
62 ) -> anyhow::Result<Self> {
63 validate_status_refresh_secs(config.status_refresh_secs)?;
64 let connector = Arc::new(NativeOnionGatewayConnector::new(processor.clone(), onion));
65 let runtime = GatewayRuntime::new(config.runtime.clone(), connector, rand::random())?;
66 Ok(Self {
67 processor,
68 runtime,
69 config,
70 })
71 }
72
73 pub fn status_handle(&self) -> GatewayStatusHandle {
75 self.runtime.status_handle()
76 }
77
78 pub async fn run_with_startup_barrier(
80 self,
81 stop: StopToken,
82 started: oneshot::Sender<()>,
83 ) -> anyhow::Result<()> {
84 self.run_inner(stop, Some(started)).await
85 }
86
87 async fn run_inner(
88 mut self,
89 stop: StopToken,
90 started: Option<oneshot::Sender<()>>,
91 ) -> anyhow::Result<()> {
92 let mut control = self.platform_control()?;
93 let EstablishedTunnel {
94 mut device,
95 lease,
96 interface_name,
97 } = control.establish(&self.config.runtime.plan).await?;
98
99 if let Err(error) = self.runtime.activate(interface_name) {
100 let cleanup = control
101 .teardown(lease)
102 .await
103 .map_err(TeardownFailure::into_error);
104 let cleanup = finish_gateway_cleanup(&mut self.runtime, device, cleanup);
105 return combine_gateway_results(Err(error), Ok(()), cleanup);
106 }
107 if let Some(started) = started {
108 let _ = started.send(());
109 }
110
111 let runtime_done = StopSource::new();
112 let updater_failed = StopSource::new();
113 let update = refresh_exit_availability(GatewayRefresh {
114 processor: self.processor.clone(),
115 gateway: self.runtime.control_handle(),
116 interval: Duration::from_secs(self.config.status_refresh_secs),
117 stop: stop.clone(),
118 runtime_done: runtime_done.token(),
119 updater_failed: updater_failed.clone(),
120 });
121 let updater_failed_token = updater_failed.token();
122 let runtime_done_after_run = runtime_done.clone();
123 let run = async {
124 let result = self.runtime.run(&mut device, || {
125 stop.should_stop() || updater_failed_token.should_stop()
126 });
127 let result = result.await;
128 runtime_done_after_run.request_stop();
129 result
130 };
131 let (runtime_result, updater_result) = tokio::join!(run, update);
132
133 let cleanup_result = control
134 .teardown(lease)
135 .await
136 .map_err(TeardownFailure::into_error);
137 let cleanup_result = finish_gateway_cleanup(&mut self.runtime, device, cleanup_result);
138 combine_gateway_results(runtime_result, updater_result, cleanup_result)
139 }
140
141 #[cfg(target_os = "windows")]
142 fn platform_control(&self) -> anyhow::Result<PlatformTunnelControl> {
143 let ledger = expand_home(&self.config.route_ledger_path)?;
144 let mut options = NativeTunnelOptions::new(ledger);
145 if let Some(interface_name) = self.config.interface_name.clone() {
146 options = options.with_interface_name(interface_name);
147 }
148 let environment = std::env::var_os("RINGS_GATEWAY_WINTUN_DLL");
149 if let Some(path) =
150 select_wintun_dll_path(self.config.wintun_dll_path.as_deref(), environment)?
151 {
152 options = options.with_wintun_dll(path);
153 }
154 NativeTunnelControl::new(options).map_err(Into::into)
155 }
156
157 #[cfg(any(target_os = "linux", target_os = "macos"))]
158 fn platform_control(&self) -> anyhow::Result<PlatformTunnelControl> {
159 let socket_path = expand_home(&self.config.unix_helper_socket)?;
160 Ok(UnixTunnelControl::new(UnixTunnelOptions::new(socket_path)))
161 }
162
163 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
164 fn platform_control(&self) -> anyhow::Result<PlatformTunnelControl> {
165 Ok(UnsupportedTunnelControl::new())
166 }
167}
168
169fn validate_status_refresh_secs(seconds: u64) -> Result<(), GatewayError> {
170 if seconds == 0 || seconds > MAX_STATUS_REFRESH_SECS {
171 return Err(GatewayError::Platform {
172 operation: "validate-gateway-status-refresh",
173 message: format!(
174 "gateway status_refresh_secs must be in 1..={MAX_STATUS_REFRESH_SECS}, got {seconds}"
175 ),
176 });
177 }
178 Ok(())
179}
180
181fn finish_gateway_cleanup<D: rings_gateway::PacketIo>(
182 runtime: &mut GatewayRuntime,
183 device: D,
184 cleanup: Result<(), GatewayError>,
185) -> Result<(), GatewayError> {
186 match cleanup {
187 Ok(()) => {
188 drop(device);
189 Ok(())
190 }
191 Err(error) => {
192 let reason = format!(
196 "gateway route cleanup failed; the packet device remains open for selected routes \
197 until privileged cleanup succeeds: {error}"
198 );
199 runtime.set_exit_availability(ExitObservation::Unknown(reason.clone()));
200 tracing::error!("{reason}");
201 std::mem::forget(device);
202 Err(error)
203 }
204 }
205}
206
207#[cfg(any(test, target_os = "windows"))]
208fn select_wintun_dll_path(
209 configured: Option<&str>,
210 environment: Option<OsString>,
211) -> Result<Option<PathBuf>, crate::error::Error> {
212 let selected = configured.map(PathBuf::from).or_else(|| {
213 environment
214 .filter(|path| !path.is_empty())
215 .map(PathBuf::from)
216 });
217 selected.map(expand_home).transpose()
218}
219
220struct GatewayRefresh {
221 processor: Arc<Processor>,
222 gateway: GatewayControlHandle,
223 interval: Duration,
224 stop: StopToken,
225 runtime_done: StopToken,
226 updater_failed: StopSource,
227}
228
229enum RefreshWake {
230 Tick,
231 Stop,
232}
233
234async fn wait_for_refresh(
235 ticker: &mut tokio::time::Interval,
236 stop: &StopToken,
237 runtime_done: &StopToken,
238) -> RefreshWake {
239 tokio::select! {
240 _ = stop.stopped() => RefreshWake::Stop,
241 _ = runtime_done.stopped() => RefreshWake::Stop,
242 _ = ticker.tick() => RefreshWake::Tick,
243 }
244}
245
246async fn refresh_exit_availability(refresh: GatewayRefresh) -> Result<(), GatewayError> {
247 let mut ticker = tokio::time::interval(refresh.interval);
248 loop {
249 if matches!(
250 wait_for_refresh(&mut ticker, &refresh.stop, &refresh.runtime_done).await,
251 RefreshWake::Stop
252 ) {
253 return Ok(());
254 }
255 let exit = match refresh
256 .processor
257 .lookup_onion_exits(OnionServiceName::tcp().as_str(), false)
258 .await
259 {
260 Ok(exits) if exits.is_empty() => ExitObservation::Unavailable(format!(
261 "no live Onion TCP exit advertises {}",
262 OnionServiceName::tcp().as_str()
263 )),
264 Ok(_) => ExitObservation::Available,
265 Err(error) => ExitObservation::Unknown(format!("Onion exit discovery failed: {error}")),
266 };
267 if refresh.gateway.set_exit_availability(exit).await.is_err() {
268 if refresh.runtime_done.should_stop() {
269 return Ok(());
270 }
271 refresh.updater_failed.request_stop();
272 return Err(GatewayError::Platform {
273 operation: "update-gateway-exit-availability",
274 message: "gateway runtime control channel closed".to_string(),
275 });
276 }
277 }
278}
279
280fn combine_gateway_results(
281 runtime: Result<(), GatewayError>,
282 updater: Result<(), GatewayError>,
283 cleanup: Result<(), GatewayError>,
284) -> anyhow::Result<()> {
285 match (runtime, updater, cleanup) {
286 (Ok(()), Ok(()), Ok(())) => Ok(()),
287 (runtime, updater, cleanup) => {
288 let failures = [
289 runtime.err().map(|error| format!("data plane: {error}")),
290 updater
291 .err()
292 .map(|error| format!("status updater: {error}")),
293 cleanup.err().map(|error| format!("cleanup: {error}")),
294 ]
295 .into_iter()
296 .flatten()
297 .collect::<Vec<_>>()
298 .join("; ");
299 Err(anyhow::anyhow!(failures))
300 }
301 }
302}
303
304#[cfg(test)]
305mod tests {
306 use super::*;
307
308 #[test]
309 fn configured_wintun_path_precedes_environment_fallback() {
310 let configured = select_wintun_dll_path(
311 Some("/configured/wintun.dll"),
312 Some(OsString::from("/environment/wintun.dll")),
313 )
314 .expect("select configured path");
315 assert_eq!(configured, Some(PathBuf::from("/configured/wintun.dll")));
316
317 let fallback =
318 select_wintun_dll_path(None, Some(OsString::from("/environment/wintun.dll")))
319 .expect("select environment path");
320 assert_eq!(fallback, Some(PathBuf::from("/environment/wintun.dll")));
321 }
322
323 #[test]
324 fn status_refresh_interval_is_bounded() {
325 assert!(validate_status_refresh_secs(0).is_err());
326 assert!(validate_status_refresh_secs(1).is_ok());
327 assert!(validate_status_refresh_secs(MAX_STATUS_REFRESH_SECS).is_ok());
328 assert!(validate_status_refresh_secs(MAX_STATUS_REFRESH_SECS + 1).is_err());
329 }
330
331 #[tokio::test]
332 async fn refresh_wait_wakes_immediately_when_stopped() {
333 let stop = StopSource::new();
334 let runtime_done = StopSource::new();
335 let mut ticker = tokio::time::interval(Duration::from_secs(3_600));
336 ticker.tick().await;
337 let stop_token = stop.token();
338 let runtime_done_token = runtime_done.token();
339 let wait = wait_for_refresh(&mut ticker, &stop_token, &runtime_done_token);
340 stop.request_stop();
341
342 let wake = tokio::time::timeout(Duration::from_secs(1), wait)
343 .await
344 .expect("stop wakes long refresh interval");
345 assert!(matches!(wake, RefreshWake::Stop));
346 }
347
348 #[test]
349 fn result_aggregation_preserves_all_failure_boundaries() {
350 let error = |operation| GatewayError::Platform {
351 operation,
352 message: "failed".to_string(),
353 };
354 let combined = combine_gateway_results(
355 Err(error("runtime")),
356 Err(error("status")),
357 Err(error("cleanup")),
358 )
359 .expect_err("three failures must remain visible")
360 .to_string();
361
362 assert!(combined.contains("data plane"));
363 assert!(combined.contains("status updater"));
364 assert!(combined.contains("cleanup"));
365 }
366}