v1.1
This commit is contained in:
+178
-140
@@ -2,8 +2,8 @@ use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use std::{io, thread};
|
||||
use std::net::ToSocketAddrs;
|
||||
|
||||
use clap::Parser;
|
||||
use console::style;
|
||||
|
||||
use windows_service::service::{
|
||||
@@ -12,173 +12,206 @@ use windows_service::service::{
|
||||
use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};
|
||||
use windows_service::Error;
|
||||
|
||||
use crate::config;
|
||||
use crate::{BaseArgs, Commands, config, console_out};
|
||||
use crate::config::BaseConfig;
|
||||
|
||||
pub mod service;
|
||||
mod windows_admin_check;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(
|
||||
author = "Lu Beilin",
|
||||
version,
|
||||
about = "一个虚拟网络工具,启动后会获取一个ip,相同token下的设备之间可以用ip直接通信"
|
||||
)]
|
||||
struct Args {
|
||||
/// 32位字符
|
||||
/// 相同token的设备之间才能通信。
|
||||
/// 建议使用uuid保证唯一性。
|
||||
/// 32-bit characters.
|
||||
/// Only devices with the same token can communicate with each other.
|
||||
/// It is recommended to use uuid to ensure uniqueness
|
||||
#[arg(long)]
|
||||
token: Option<String>,
|
||||
/// 给设备一个名称,为空时默认用系统版本信息
|
||||
/// Give the device a name. If it is blank, the system version information will be used by default
|
||||
#[arg(long)]
|
||||
name: Option<String>,
|
||||
/// 安装服务,安装后可以后台运行,需要指定安装路径
|
||||
/// The installation service can run in the background after installation, and the installation path needs to be specified
|
||||
#[arg(long)]
|
||||
install: Option<String>,
|
||||
/// 卸载服务
|
||||
/// Uninstall service
|
||||
#[arg(long)]
|
||||
uninstall: bool,
|
||||
/// 启动,启动时可以附加参数 --token,如果没有token,则会读取配置文件中上一次使用的token
|
||||
/// 安装服务后,会以服务的方式在后台启动,此时可以关闭命令行窗口
|
||||
/// When starting, you can attach the parameter -- token. If there is no token, the last token used in the configuration file will be read. After installing the service, it will be started in the background as a service. At this time, you can close the command line window
|
||||
#[arg(long)]
|
||||
start: bool,
|
||||
#[arg(long)]
|
||||
/// 停止,安装服务后,使用 --stop停止服务
|
||||
/// Stop. After installing the service, use -- stop to stop the service
|
||||
stop: bool,
|
||||
/// 启动服务后,使用 --list 查看设备列表
|
||||
/// After starting the service, use -- list to view the device list
|
||||
#[arg(long)]
|
||||
list: bool,
|
||||
/// 启动服务后,使用 --status 查看设备状态
|
||||
/// After starting the service, use -- status to view the device status
|
||||
#[arg(long)]
|
||||
status: bool,
|
||||
}
|
||||
|
||||
pub const SERVICE_FLAG: &'static str = "start_switch_service_";
|
||||
pub const SERVICE_NAME: &'static str = "switch-service";
|
||||
pub const SERVICE_FLAG: &'static str = "start_switch_service_v1_";
|
||||
pub const SERVICE_NAME: &'static str = "switch-service-v1";
|
||||
pub const SERVICE_TYPE: ServiceType = ServiceType::OWN_PROCESS;
|
||||
|
||||
pub fn main0() {
|
||||
let args = Args::parse();
|
||||
if args.list || args.status {
|
||||
match service_state() {
|
||||
Ok(state) => {
|
||||
if state == ServiceState::Running {
|
||||
let command_client = crate::command::client::CommandClient::new().unwrap();
|
||||
let out = if args.list {
|
||||
command_client.list().unwrap()
|
||||
} else if args.status {
|
||||
command_client.status().unwrap()
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
println!("{}", out);
|
||||
} else {
|
||||
println!("服务未启动")
|
||||
fn command(cmd: &str) {
|
||||
if let Err(e) = command_(cmd) {
|
||||
println!("{}:{:?}", style("连接服务错误(Connection service error)").red(), e);
|
||||
}
|
||||
}
|
||||
|
||||
fn command_(cmd: &str) -> io::Result<()> {
|
||||
match crate::command::client::CommandClient::new() {
|
||||
Ok(command_client) => {
|
||||
match cmd {
|
||||
"route" => {
|
||||
let list = command_client.route()?;
|
||||
console_out::console_route_table(list);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{:?}", e);
|
||||
"list" => {
|
||||
let list = command_client.list()?;
|
||||
console_out::console_device_list(list);
|
||||
}
|
||||
"list-all" => {
|
||||
let list = command_client.list()?;
|
||||
console_out::console_device_list_all(list);
|
||||
}
|
||||
"status" => {
|
||||
let status = command_client.status()?;
|
||||
console_out::console_status(status);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("{:?}",e);
|
||||
println!(
|
||||
"{}:{:?}",
|
||||
style("连接服务错误(Connection service error)").red(), e
|
||||
);
|
||||
}
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn admin_check() -> bool {
|
||||
if !windows_admin_check::is_app_elevated() {
|
||||
println!(
|
||||
"{}",
|
||||
style("请使用管理员权限运行(Please run with administrator privileges)").red()
|
||||
);
|
||||
return;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
if let Some(path) = args.install {
|
||||
let path: PathBuf = path.into();
|
||||
if !path.exists() {
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
}
|
||||
if !path.is_dir() {
|
||||
println!("参数必须为文件目录(Parameter must be a file directory)");
|
||||
} else {
|
||||
if let Err(e) = install(path) {
|
||||
log::error!("{:?}", e);
|
||||
}
|
||||
|
||||
fn not_started() -> bool {
|
||||
match service_state() {
|
||||
Ok(state) => {
|
||||
if state == ServiceState::Running {
|
||||
return false;
|
||||
} else {
|
||||
println!("{}", style("安装成功(Installation succeeded)").green())
|
||||
println!("服务未启动")
|
||||
}
|
||||
}
|
||||
} else if args.uninstall {
|
||||
if let Err(e) = uninstall() {
|
||||
log::error!("{:?}", e);
|
||||
} else {
|
||||
println!("{}", style("卸载成功(Uninstall succeeded)").green())
|
||||
Err(e) => {
|
||||
println!("{:?}", e);
|
||||
}
|
||||
} else if args.start {
|
||||
if args.token.is_none() {
|
||||
println!("{}", style("需要参数(require parameters) --token").red());
|
||||
} else {
|
||||
let token = args.token.clone().unwrap();
|
||||
match service_state() {
|
||||
Ok(state) => {
|
||||
if state == ServiceState::Stopped {
|
||||
config::save_config(config::ArgsConfig::new(
|
||||
token.clone(),
|
||||
args.name.clone(),
|
||||
))
|
||||
.unwrap();
|
||||
match start() {
|
||||
Ok(_) => {
|
||||
//需要检查启动状态
|
||||
println!("{}", style("启动成功(Start successfully)").green())
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("{:?}", e);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
pub fn main0(base_args: BaseArgs) {
|
||||
match base_args.command {
|
||||
Commands::Start(args) => {
|
||||
if admin_check() {
|
||||
return;
|
||||
}
|
||||
match config::default_config(args) {
|
||||
Ok(base_config) => {
|
||||
match service_state() {
|
||||
Ok(state) => {
|
||||
if state == ServiceState::Stopped {
|
||||
config::save_config(config::ArgsConfig::new(
|
||||
base_config.token.clone(),
|
||||
base_config.name.clone(),
|
||||
base_config.server.to_string(),
|
||||
base_config.nat_test_server.iter().map(|v| v.to_string()).collect::<Vec<String>>(),
|
||||
base_config.device_id.clone(),
|
||||
))
|
||||
.unwrap();
|
||||
match start() {
|
||||
Ok(_) => {
|
||||
//需要检查启动状态
|
||||
std::thread::sleep(std::time::Duration::from_secs(2));
|
||||
println!("{}", style("启动成功(Start successfully)").green())
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("{:?}", e);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
println!("服务未停止(Service not stopped)");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
println!("服务未停止(Service not stopped)");
|
||||
Err(e) => {
|
||||
match e {
|
||||
Error::Winapi(ref e) => {
|
||||
if let Some(code) = e.raw_os_error() {
|
||||
if code == 1060 {
|
||||
//指定的服务未安装。
|
||||
println!(
|
||||
"{}",
|
||||
style("服务未安装,在当前进程启动(The service is not installed and started in the current process)").red()
|
||||
);
|
||||
crate::start(base_config.token, base_config.name, base_config.server, base_config.nat_test_server, base_config.device_id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
println!("{:?}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
match e {
|
||||
Error::Winapi(ref e) => {
|
||||
if let Some(code) = e.raw_os_error() {
|
||||
if code == 1060 {
|
||||
//指定的服务未安装。
|
||||
println!(
|
||||
"{}",
|
||||
style("服务未安装,在当前进程启动(The service is not installed and started in the current process)").red()
|
||||
);
|
||||
crate::start(token, args.name);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
println!("{:?}", e);
|
||||
println!("{}", style(e).red());
|
||||
}
|
||||
};
|
||||
pause();
|
||||
}
|
||||
Commands::Stop => {
|
||||
if not_started() {
|
||||
return;
|
||||
}
|
||||
match stop() {
|
||||
Ok(_) => {
|
||||
println!("{}", style("停止成功(Stopped successfully)").green())
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("{:?}", e);
|
||||
}
|
||||
}
|
||||
pause();
|
||||
}
|
||||
} else if args.stop {
|
||||
match stop() {
|
||||
Ok(_) => {
|
||||
println!("{}", style("停止成功(Stopped successfully)").green())
|
||||
Commands::Install(args) => {
|
||||
let path: PathBuf = args.path.into();
|
||||
if !path.exists() {
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
}
|
||||
Err(e) => {
|
||||
if !path.is_dir() {
|
||||
println!("参数必须为文件目录(Parameter must be a file directory)");
|
||||
} else {
|
||||
if let Err(e) = install(path, args.auto) {
|
||||
log::error!("{:?}", e);
|
||||
} else {
|
||||
println!("{}", style("安装成功(Installation succeeded)").green())
|
||||
}
|
||||
}
|
||||
pause();
|
||||
}
|
||||
Commands::Uninstall => {
|
||||
if let Err(e) = uninstall() {
|
||||
log::error!("{:?}", e);
|
||||
} else {
|
||||
println!("{}", style("卸载成功(Uninstall succeeded)").green())
|
||||
}
|
||||
pause();
|
||||
}
|
||||
Commands::Config(args) => {}
|
||||
Commands::Route => {
|
||||
if not_started() {
|
||||
return;
|
||||
}
|
||||
command("route");
|
||||
}
|
||||
Commands::List { all } => {
|
||||
if not_started() {
|
||||
return;
|
||||
}
|
||||
if all {
|
||||
command("list-all");
|
||||
} else {
|
||||
command("list");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
println!("使用参数 -h 查看帮助(Use the parameter - h to view help)")
|
||||
Commands::Status => {
|
||||
if not_started() {
|
||||
return;
|
||||
}
|
||||
command("status");
|
||||
}
|
||||
}
|
||||
pause();
|
||||
}
|
||||
|
||||
fn pause() {
|
||||
@@ -191,11 +224,11 @@ fn pause() {
|
||||
let _ = term.read_char().unwrap();
|
||||
}
|
||||
|
||||
fn install(path: PathBuf) -> Result<(), Error> {
|
||||
fn install(path: PathBuf, auto: bool) -> Result<(), Error> {
|
||||
let manager_access = ServiceManagerAccess::CONNECT | ServiceManagerAccess::CREATE_SERVICE;
|
||||
let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;
|
||||
let current_exe_path = std::env::current_exe().unwrap();
|
||||
let service_path = path.join("switch-service.exe");
|
||||
let service_path = path.join("switch-service-v1.exe");
|
||||
std::fs::copy(current_exe_path, service_path.as_path()).unwrap();
|
||||
if let Err(e) = std::fs::copy("wintun.dll", path.join("wintun.dll").as_path()) {
|
||||
if e.kind() == io::ErrorKind::NotFound {
|
||||
@@ -210,11 +243,16 @@ fn install(path: PathBuf) -> Result<(), Error> {
|
||||
launch_arguments.push(OsString::from(
|
||||
dirs::home_dir().unwrap().join(".switch").to_str().unwrap(),
|
||||
));
|
||||
let start_type = if auto {
|
||||
ServiceStartType::AutoStart
|
||||
} else {
|
||||
ServiceStartType::OnDemand
|
||||
};
|
||||
let service_info = ServiceInfo {
|
||||
name: OsString::from(SERVICE_NAME),
|
||||
display_name: OsString::from("switch service"),
|
||||
display_name: OsString::from("switch service v1"),
|
||||
service_type: ServiceType::OWN_PROCESS,
|
||||
start_type: ServiceStartType::OnDemand,
|
||||
start_type,
|
||||
error_control: ServiceErrorControl::Normal,
|
||||
executable_path: service_path.into(),
|
||||
launch_arguments,
|
||||
|
||||
@@ -6,13 +6,12 @@ use std::sync::Arc;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
use std::net::ToSocketAddrs;
|
||||
use switch::{Config, Switch};
|
||||
use windows_service::service::{
|
||||
ServiceControl, ServiceControlAccept, ServiceExitCode, ServiceState, ServiceStatus,
|
||||
};
|
||||
use windows_service::service_control_handler::ServiceControlHandlerResult;
|
||||
use windows_service::{define_windows_service, service_control_handler, service_dispatcher};
|
||||
|
||||
use switch::core::{Config, Switch};
|
||||
use crate::windows::config::read_config;
|
||||
|
||||
define_windows_service!(ffi_service_main, switch_service_main);
|
||||
@@ -36,8 +35,8 @@ fn service_main() -> windows_service::Result<()> {
|
||||
|
||||
// Handle stop
|
||||
ServiceControl::Stop => {
|
||||
log::info!("handler 服务停止");
|
||||
un_parker.unpark();
|
||||
log::info!("handler 服务停止");
|
||||
ServiceControlHandlerResult::NoError
|
||||
}
|
||||
_ => ServiceControlHandlerResult::NotImplemented,
|
||||
@@ -59,72 +58,11 @@ fn service_main() -> windows_service::Result<()> {
|
||||
wait_hint: Duration::default(),
|
||||
process_id: None,
|
||||
})?;
|
||||
if let Some(config) = read_config() {
|
||||
let mac_address = mac_address::get_mac_address().unwrap().unwrap().to_string();
|
||||
let un_parker = parker.unparker().clone();
|
||||
let server_address = "nat1.wherewego.top:29875"
|
||||
.to_socket_addrs()
|
||||
.unwrap()
|
||||
.next()
|
||||
.unwrap();
|
||||
let nat_test_server = vec![
|
||||
"nat1.wherewego.top:35061"
|
||||
.to_socket_addrs()
|
||||
.unwrap()
|
||||
.next()
|
||||
.unwrap(),
|
||||
"nat1.wherewego.top:35062"
|
||||
.to_socket_addrs()
|
||||
.unwrap()
|
||||
.next()
|
||||
.unwrap(),
|
||||
"nat2.wherewego.top:35061"
|
||||
.to_socket_addrs()
|
||||
.unwrap()
|
||||
.next()
|
||||
.unwrap(),
|
||||
"nat2.wherewego.top:35062"
|
||||
.to_socket_addrs()
|
||||
.unwrap()
|
||||
.next()
|
||||
.unwrap(),
|
||||
];
|
||||
match Config::new(
|
||||
config.token,
|
||||
mac_address,
|
||||
config.name,
|
||||
server_address,
|
||||
nat_test_server,
|
||||
move || {
|
||||
un_parker.unpark();
|
||||
},
|
||||
) {
|
||||
Ok(config) => match Switch::start(config) {
|
||||
Ok(switch) => {
|
||||
log::info!("switch-service服务启动");
|
||||
let switch = Arc::new(switch);
|
||||
let command_server = crate::command::server::CommandServer::new();
|
||||
let switch1 = switch.clone();
|
||||
thread::spawn(move || {
|
||||
if let Err(e) = command_server.start(switch1) {
|
||||
log::warn!("{:?}", e);
|
||||
}
|
||||
});
|
||||
parker.park();
|
||||
switch.stop_async();
|
||||
thread::sleep(Duration::from_secs(1));
|
||||
log::info!("switch-service服务停止");
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("{:?}", e);
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
log::error!("{:?}", e);
|
||||
}
|
||||
};
|
||||
} else {
|
||||
log::info!("配置文件为空");
|
||||
if let Ok(switch) = start_switch() {
|
||||
parker.park();
|
||||
if let Err(e) = switch.stop() {
|
||||
log::warn!("switch stop:{:?}",e)
|
||||
}
|
||||
}
|
||||
status_handle.set_service_status(ServiceStatus {
|
||||
service_type: crate::windows::SERVICE_TYPE,
|
||||
@@ -137,6 +75,49 @@ fn service_main() -> windows_service::Result<()> {
|
||||
})
|
||||
}
|
||||
|
||||
fn start_switch() -> switch::Result<Arc<Switch>> {
|
||||
if let Some(config) = read_config() {
|
||||
let device_id = config.device_id;
|
||||
if device_id.trim().is_empty() {
|
||||
return Err(switch::error::Error::Stop("MAC address error".to_string()));
|
||||
}
|
||||
let server_address = if let Some(server_address) = config.server
|
||||
.to_socket_addrs()?
|
||||
.next() {
|
||||
server_address
|
||||
} else {
|
||||
return Err(switch::error::Error::Stop("server address error".to_string()));
|
||||
};
|
||||
let mut nat_test_server = config.nat_test_server.iter()
|
||||
.flat_map(|a| a.to_socket_addrs())
|
||||
.flatten()
|
||||
.collect::<Vec<_>>();
|
||||
;
|
||||
if nat_test_server.is_empty() {
|
||||
return Err(switch::error::Error::Stop("nat test server address error".to_string()));
|
||||
}
|
||||
let config = Config::new(
|
||||
config.token,
|
||||
device_id,
|
||||
config.name,
|
||||
server_address,
|
||||
nat_test_server);
|
||||
let switch = Switch::start(config)?;
|
||||
log::info!("switch-service服务启动");
|
||||
let switch = Arc::new(switch);
|
||||
let command_server = crate::command::server::CommandServer::new();
|
||||
let switch1 = switch.clone();
|
||||
thread::spawn(move || {
|
||||
if let Err(e) = command_server.start(switch1) {
|
||||
log::warn!("{:?}", e);
|
||||
}
|
||||
});
|
||||
Ok(switch)
|
||||
} else {
|
||||
Err(switch::error::Error::Stop("配置文件为空".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start() {
|
||||
log::info!("以服务的方式启动");
|
||||
service_dispatcher::start("switch-service", ffi_service_main).unwrap();
|
||||
|
||||
Reference in New Issue
Block a user