tun2proxy/src/mobile_api.rs

84 lines
2.5 KiB
Rust
Raw Normal View History

2024-02-29 07:08:44 +03:30
#![cfg(any(target_os = "ios", target_os = "android", target_os = "macos"))]
2024-02-01 19:15:32 +08:00
use crate::Args;
2024-02-13 10:46:13 +08:00
use std::os::raw::c_int;
2024-02-01 19:15:32 +08:00
2024-02-13 10:46:13 +08:00
static TUN_QUIT: std::sync::Mutex<Option<tokio_util::sync::CancellationToken>> = std::sync::Mutex::new(None);
2024-02-01 19:15:32 +08:00
2024-02-13 10:46:13 +08:00
/// Dummy function to make the build pass.
#[doc(hidden)]
2024-02-29 07:08:44 +03:30
#[cfg(not(target_os = "macos"))]
2024-02-13 10:46:13 +08:00
pub async fn desktop_run_async(_: Args, _: tokio_util::sync::CancellationToken) -> std::io::Result<()> {
Ok(())
}
2024-03-28 17:03:36 +08:00
pub fn mobile_run(args: Args, tun_mtu: u16, _packet_information: bool) -> c_int {
2024-02-13 10:46:13 +08:00
let shutdown_token = tokio_util::sync::CancellationToken::new();
2024-02-11 01:53:20 +08:00
{
2024-03-06 18:01:02 +08:00
if let Ok(mut lock) = TUN_QUIT.lock() {
if lock.is_some() {
log::error!("tun2proxy already started");
return -1;
}
*lock = Some(shutdown_token.clone());
} else {
log::error!("failed to lock tun2proxy quit token");
return -2;
2024-02-11 01:53:20 +08:00
}
}
2024-02-01 19:15:32 +08:00
let block = async move {
let mut config = tun2::Configuration::default();
2024-02-12 21:36:18 +08:00
#[cfg(unix)]
if let Some(fd) = args.tun_fd {
config.raw_fd(fd);
if let Some(v) = args.close_fd_on_drop {
config.close_fd_on_drop(v);
};
2024-02-29 07:08:44 +03:30
} else if let Some(ref tun) = args.tun {
config.tun_name(tun);
2024-02-12 21:36:18 +08:00
}
#[cfg(windows)]
2024-02-29 07:08:44 +03:30
if let Some(ref tun) = args.tun {
config.tun_name(tun);
}
2024-02-01 19:15:32 +08:00
2024-03-30 12:30:01 +08:00
#[cfg(any(target_os = "ios", target_os = "macos"))]
2024-03-28 17:03:36 +08:00
config.platform_config(|config| {
config.packet_information(_packet_information);
});
2024-02-01 19:15:32 +08:00
let device = tun2::create_as_async(&config).map_err(std::io::Error::from)?;
let join_handle = tokio::spawn(crate::run(device, tun_mtu, args, shutdown_token));
2024-02-01 19:15:32 +08:00
join_handle.await.map_err(std::io::Error::from)?
2024-02-01 19:15:32 +08:00
};
let exit_code = match tokio::runtime::Builder::new_multi_thread().enable_all().build() {
Err(e) => {
log::error!("failed to create tokio runtime with error: {:?}", e);
2024-02-01 19:15:32 +08:00
-1
}
Ok(rt) => match rt.block_on(block) {
Ok(_) => 0,
Err(e) => {
log::error!("failed to run tun2proxy with error: {:?}", e);
2024-02-01 19:15:32 +08:00
-2
}
},
};
exit_code
2024-02-01 19:15:32 +08:00
}
2024-02-13 10:46:13 +08:00
pub fn mobile_stop() -> c_int {
2024-03-06 18:01:02 +08:00
if let Ok(mut lock) = TUN_QUIT.lock() {
if let Some(shutdown_token) = lock.take() {
2024-02-13 10:46:13 +08:00
shutdown_token.cancel();
return 0;
}
}
2024-02-13 10:46:13 +08:00
-1
2024-02-01 19:15:32 +08:00
}