diff --git a/src/android.rs b/src/android.rs index cca174c..21dd5eb 100644 --- a/src/android.rs +++ b/src/android.rs @@ -52,7 +52,7 @@ pub unsafe extern "C" fn Java_com_github_shadowsocks_bg_Tun2proxy_run( .close_fd_on_drop(close_fd_on_drop) .dns(dns) .verbosity(verbosity); - crate::mobile_api::mobile_run(args, tun_mtu, false) + crate::general_api::general_run_for_api(args, tun_mtu, false) } /// # Safety @@ -60,7 +60,7 @@ pub unsafe extern "C" fn Java_com_github_shadowsocks_bg_Tun2proxy_run( /// Shutdown tun2proxy #[no_mangle] pub unsafe extern "C" fn Java_com_github_shadowsocks_bg_Tun2proxy_stop(_env: JNIEnv, _: JClass) -> jint { - crate::mobile_api::mobile_stop() + crate::general_api::tun2proxy_stop_internal() } fn get_java_string(env: &mut JNIEnv, string: &JString) -> Result { diff --git a/src/bin/main.rs b/src/bin/main.rs index d5b1ebe..e690f6c 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -50,7 +50,7 @@ async fn main_async(args: Args) -> Result<(), BoxError> { } unsafe { tun2proxy::tun2proxy_set_traffic_status_callback(1, Some(traffic_cb), std::ptr::null_mut()) }; - if let Err(err) = tun2proxy::desktop_run_async(args, MTU, false, shutdown_token).await { + if let Err(err) = tun2proxy::general_run_async(args, MTU, false, shutdown_token).await { log::error!("main loop error: {}", err); } } diff --git a/src/desktop_api.rs b/src/general_api.rs similarity index 84% rename from src/desktop_api.rs rename to src/general_api.rs index ed8dbb5..9385f48 100644 --- a/src/desktop_api.rs +++ b/src/general_api.rs @@ -1,11 +1,9 @@ -#![cfg(any(target_os = "windows", target_os = "macos", target_os = "linux"))] - use crate::{ args::{ArgDns, ArgProxy}, ArgVerbosity, Args, }; use std::os::raw::{c_char, c_int}; -use tun::{AbstractDevice, DEFAULT_MTU as MTU}; +use tun::DEFAULT_MTU as MTU; static TUN_QUIT: std::sync::Mutex> = std::sync::Mutex::new(None); @@ -41,7 +39,7 @@ pub unsafe extern "C" fn tun2proxy_with_name_run( #[cfg(target_os = "linux")] args.setup(_root_privilege); - desktop_run(args) + general_run_for_api(args, MTU, false) } /// # Safety @@ -55,45 +53,48 @@ pub unsafe extern "C" fn tun2proxy_run_with_cli_args(cli_args: *const c_char) -> return -5; }; let args = ::parse_from(cli_args.split_whitespace()); - desktop_run(args) + general_run_for_api(args, MTU, false) } -pub fn desktop_run(args: Args) -> c_int { +pub fn general_run_for_api(args: Args, tun_mtu: u16, packet_information: bool) -> c_int { log::set_max_level(args.verbosity.into()); if let Err(err) = log::set_boxed_logger(Box::::default()) { - log::warn!("set logger error: {}", err); + log::debug!("set logger error: {}", err); } let shutdown_token = tokio_util::sync::CancellationToken::new(); - { - if let Ok(mut lock) = TUN_QUIT.lock() { - if lock.is_some() { - return -1; - } - *lock = Some(shutdown_token.clone()); - } else { - return -2; + 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; } let Ok(rt) = tokio::runtime::Builder::new_multi_thread().enable_all().build() else { + log::error!("failed to create tokio runtime with"); return -3; }; - let res = rt.block_on(async move { - if let Err(err) = desktop_run_async(args, MTU, false, shutdown_token).await { + match rt.block_on(async move { + if let Err(err) = general_run_async(args, tun_mtu, packet_information, shutdown_token).await { log::error!("main loop error: {}", err); return Err(err); } Ok(()) - }); - match res { + }) { Ok(_) => 0, - Err(_) => -4, + Err(e) => { + log::error!("failed to run tun2proxy with error: {:?}", e); + -4 + } } } /// Run the tun2proxy component with some arguments. -pub async fn desktop_run_async( +pub async fn general_run_async( args: Args, tun_mtu: u16, _packet_information: bool, @@ -153,7 +154,8 @@ pub async fn desktop_run_async( let device = tun::create_as_async(&tun_config)?; #[cfg(any(target_os = "linux", target_os = "windows", target_os = "macos"))] - if let Ok(tun_name) = device.tun_name() { + if let Ok(tun_name) = tun::AbstractDevice::tun_name(&*device) { + // Above line is equivalent to: `use tun::AbstractDevice; if let Ok(tun_name) = device.tun_name() {` tproxy_args = tproxy_args.tun_name(&tun_name); } @@ -205,6 +207,10 @@ pub async fn desktop_run_async( /// Shutdown the tun2proxy component. #[no_mangle] pub unsafe extern "C" fn tun2proxy_with_name_stop() -> c_int { + tun2proxy_stop_internal() +} + +pub(crate) fn tun2proxy_stop_internal() -> c_int { if let Ok(mut lock) = TUN_QUIT.lock() { if let Some(shutdown_token) = lock.take() { shutdown_token.cancel(); diff --git a/src/lib.rs b/src/lib.rs index 1972b9c..f211110 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -40,25 +40,17 @@ pub use { #[global_allocator] static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc; -#[cfg(any(target_os = "windows", target_os = "macos", target_os = "linux"))] -pub use desktop_api::desktop_run_async; - -#[cfg(any(target_os = "ios", target_os = "android"))] -pub use mobile_api::{desktop_run_async, mobile_run, mobile_stop}; - -#[cfg(target_os = "macos")] -pub use mobile_api::{mobile_run, mobile_stop}; +pub use general_api::general_run_async; mod android; -mod apple; mod args; -mod desktop_api; mod directions; mod dns; mod dump_logger; mod error; +mod general_api; mod http; -mod mobile_api; +mod mobile; mod no_proxy; mod proxy_handler; mod session_info; diff --git a/src/apple.rs b/src/mobile.rs similarity index 82% rename from src/apple.rs rename to src/mobile.rs index 155b101..3747d67 100644 --- a/src/apple.rs +++ b/src/mobile.rs @@ -27,11 +27,6 @@ pub unsafe extern "C" fn tun2proxy_with_fd_run( dns_strategy: ArgDns, verbosity: ArgVerbosity, ) -> c_int { - log::set_max_level(verbosity.into()); - if let Err(err) = log::set_boxed_logger(Box::::default()) { - log::warn!("failed to set logger: {:?}", err); - } - let proxy_url = std::ffi::CStr::from_ptr(proxy_url).to_str().unwrap(); let proxy = ArgProxy::try_from(proxy_url).unwrap(); @@ -42,7 +37,7 @@ pub unsafe extern "C" fn tun2proxy_with_fd_run( .dns(dns_strategy) .verbosity(verbosity); - crate::mobile_api::mobile_run(args, tun_mtu, packet_information) + crate::general_api::general_run_for_api(args, tun_mtu, packet_information) } /// # Safety @@ -50,5 +45,5 @@ pub unsafe extern "C" fn tun2proxy_with_fd_run( /// Shutdown the tun2proxy component. #[no_mangle] pub unsafe extern "C" fn tun2proxy_with_fd_stop() -> c_int { - crate::mobile_api::mobile_stop() + crate::general_api::tun2proxy_stop_internal() } diff --git a/src/mobile_api.rs b/src/mobile_api.rs deleted file mode 100644 index 3f885d5..0000000 --- a/src/mobile_api.rs +++ /dev/null @@ -1,82 +0,0 @@ -#![cfg(any(target_os = "ios", target_os = "android", target_os = "macos"))] - -use crate::Args; -use std::os::raw::c_int; - -static TUN_QUIT: std::sync::Mutex> = std::sync::Mutex::new(None); - -/// Dummy function to make the build pass. -#[doc(hidden)] -#[cfg(not(target_os = "macos"))] -pub async fn desktop_run_async(_: Args, _: u16, _: bool, _: tokio_util::sync::CancellationToken) -> std::io::Result<()> { - Ok(()) -} - -pub async fn mobile_run_async( - args: Args, - tun_mtu: u16, - _packet_information: bool, - shutdown_token: tokio_util::sync::CancellationToken, -) -> std::io::Result<()> { - let mut config = tun::Configuration::default(); - - #[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); - }; - } else if let Some(ref tun) = args.tun { - config.tun_name(tun); - } - #[cfg(windows)] - if let Some(ref tun) = args.tun { - config.tun_name(tun); - } - - #[cfg(any(target_os = "ios", target_os = "macos"))] - config.platform_config(|config| { - config.packet_information(_packet_information); - }); - - let device = tun::create_as_async(&config).map_err(std::io::Error::from)?; - let join_handle = tokio::spawn(crate::run(device, tun_mtu, args, shutdown_token)); - - Ok(join_handle.await.map_err(std::io::Error::from)??) -} - -pub fn mobile_run(args: Args, tun_mtu: u16, _packet_information: bool) -> c_int { - let shutdown_token = tokio_util::sync::CancellationToken::new(); - 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; - } - - let Ok(rt) = tokio::runtime::Builder::new_multi_thread().enable_all().build() else { - log::error!("failed to create tokio runtime with"); - return -1; - }; - match rt.block_on(mobile_run_async(args, tun_mtu, _packet_information, shutdown_token)) { - Ok(_) => 0, - Err(e) => { - log::error!("failed to run tun2proxy with error: {:?}", e); - -2 - } - } -} - -pub fn mobile_stop() -> c_int { - if let Ok(mut lock) = TUN_QUIT.lock() { - if let Some(shutdown_token) = lock.take() { - shutdown_token.cancel(); - return 0; - } - } - -1 -} diff --git a/src/win_svc.rs b/src/win_svc.rs index e775049..ac87417 100644 --- a/src/win_svc.rs +++ b/src/win_svc.rs @@ -78,7 +78,7 @@ fn run_service(_arguments: Vec) -> Result<(), crate::BoxErro } unsafe { crate::tun2proxy_set_traffic_status_callback(1, Some(traffic_cb), std::ptr::null_mut()) }; - if let Err(err) = crate::desktop_run_async(args, tun::DEFAULT_MTU, false, shutdown_token).await { + if let Err(err) = crate::general_run_async(args, tun::DEFAULT_MTU, false, shutdown_token).await { log::error!("main loop error: {}", err); } Ok::<(), crate::Error>(())