Compare commits

...

16 Commits

Author SHA1 Message Date
咸鱼而已
65e755269a
Merge 780bb6dcdb into 4fc3ff8ce8 2024-11-11 08:15:56 +08:00
chao wan
780bb6dcdb Merge remote-tracking branch 'upstream/main' 2024-11-09 00:27:46 +08:00
chao wan
6d332ff5bb Add a command line option work-dir to specify the working directory
Adjust the error handling logic
2024-11-08 23:45:34 +08:00
chao wan
eb502c9a49 Move the service-related features to be implemented in easytier-cli. 2024-11-07 22:52:37 +08:00
chao wan
1440406828 Resolved merge conflicts 2024-11-03 12:13:40 +08:00
chao wan
24bb475799 Resolved merge conflicts 2024-11-03 11:39:27 +08:00
chao wan
0ff6f758bc debug 2024-11-03 00:52:21 +08:00
chao wan
bbbdc84aa9 fix bug 2024-11-03 00:46:49 +08:00
chao wan
084f0deddd Support service manager 2024-11-02 23:37:21 +08:00
咸鱼而已
c68bc084e6
Merge branch 'EasyTier:main' into main 2024-10-31 02:42:49 +08:00
chao wan
ff5002b2a4 Remove the use of std::ffi::OsString at the top. 2024-10-26 00:45:49 +08:00
chao wan
a6f215dcdf When running in a Windows service environment, delegate the termination of the program to the win_service_event_loop function. 2024-10-25 23:34:33 +08:00
chao wan
68b8800900 Merge branch 'main' of https://github.com/hvvvvvvv/EasyTier 2024-10-25 12:07:37 +08:00
chao wan
d31c19b126 Optimize startup logic contro 2024-10-25 12:03:28 +08:00
咸鱼而已
21984fc3cf
Merge branch 'EasyTier:main' into main 2024-10-25 03:30:43 +08:00
chao wan
f1f3134058 Support running as a Windows service. 2024-10-25 03:26:05 +08:00
7 changed files with 540 additions and 143 deletions

41
Cargo.lock generated
View File

@ -1191,6 +1191,15 @@ dependencies = [
"objc", "objc",
] ]
[[package]]
name = "codepage"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48f68d061bc2828ae826206326e61251aca94c1e4a5305cf52d9138639c918b4"
dependencies = [
"encoding_rs",
]
[[package]] [[package]]
name = "color_quant" name = "color_quant"
version = "1.1.0" version = "1.1.0"
@ -1866,6 +1875,7 @@ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
"serial_test", "serial_test",
"service-manager",
"smoltcp", "smoltcp",
"socket2", "socket2",
"stun_codec", "stun_codec",
@ -2063,6 +2073,17 @@ dependencies = [
"encoding_index_tests", "encoding_index_tests",
] ]
[[package]]
name = "encoding-utils"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87b881ab2524b96a5ce932056c7482ba6152e2226fed3936b3e592adeb95ca6d"
dependencies = [
"codepage",
"encoding_rs",
"windows-sys 0.52.0",
]
[[package]] [[package]]
name = "encoding_index_tests" name = "encoding_index_tests"
version = "0.1.4" version = "0.1.4"
@ -6543,6 +6564,20 @@ dependencies = [
"syn 1.0.109", "syn 1.0.109",
] ]
[[package]]
name = "service-manager"
version = "0.7.1"
source = "git+https://github.com/chipsenkbeil/service-manager-rs.git?branch=main#13dae5e8160f91fdc9834d847165cc5ce0a72fb3"
dependencies = [
"cfg-if",
"dirs 4.0.0",
"encoding-utils",
"encoding_rs",
"plist",
"which",
"xml-rs",
]
[[package]] [[package]]
name = "servo_arc" name = "servo_arc"
version = "0.1.1" version = "0.1.1"
@ -9339,6 +9374,12 @@ dependencies = [
"windows-sys 0.59.0", "windows-sys 0.59.0",
] ]
[[package]]
name = "xml-rs"
version = "0.8.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af4e2e2f7cba5a093896c1e150fbfe177d1883e7448200efb81d40b9d339ef26"
[[package]] [[package]]
name = "yansi" name = "yansi"
version = "1.0.1" version = "1.0.1"

View File

@ -181,6 +181,8 @@ sys-locale = "0.3"
ringbuf = "0.4.5" ringbuf = "0.4.5"
async-ringbuf = "0.3.1" async-ringbuf = "0.3.1"
service-manager = {git = "https://github.com/chipsenkbeil/service-manager-rs.git", branch = "main"}
[target.'cfg(any(target_os = "linux", target_os = "macos", target_os = "windows", target_os = "freebsd"))'.dependencies] [target.'cfg(any(target_os = "linux", target_os = "macos", target_os = "windows", target_os = "freebsd"))'.dependencies]
machine-uid = "0.5.3" machine-uid = "0.5.3"

View File

@ -120,6 +120,9 @@ core_clap:
ipv6_listener: ipv6_listener:
en: "the url of the ipv6 listener, e.g.: tcp://[::]:11010, if not set, will listen on random udp port" en: "the url of the ipv6 listener, e.g.: tcp://[::]:11010, if not set, will listen on random udp port"
zh-CN: "IPv6 监听器的URL例如tcp://[::]:11010如果未设置将在随机UDP端口上监听" zh-CN: "IPv6 监听器的URL例如tcp://[::]:11010如果未设置将在随机UDP端口上监听"
work_dir:
en: "Specify the working directory for the program. If not specified, the current directory will be used."
zh-CN: "指定程序的工作目录。如果未指定,将使用当前目录。"
core_app: core_app:
panic_backtrace_save: panic_backtrace_save:

View File

@ -152,4 +152,4 @@ pub fn setup_socket_for_win<S: AsRawSocket>(
} }
Ok(()) Ok(())
} }

View File

@ -1,10 +1,18 @@
use std::{net::SocketAddr, sync::Mutex, time::Duration, vec}; use std::{
ffi::OsString,
net::SocketAddr,
path::PathBuf,
sync::Mutex,
time::Duration,
vec
};
use anyhow::{Context, Ok}; use anyhow::{Context, Ok};
use clap::{command, Args, Parser, Subcommand}; use clap::{command, Args, Parser, Subcommand};
use humansize::format_size; use humansize::format_size;
use tabled::settings::Style; use tabled::settings::Style;
use tokio::time::timeout; use tokio::time::timeout;
use service_manager::*;
use easytier::{ use easytier::{
common::{ common::{
@ -26,7 +34,7 @@ use easytier::{
rpc_types::controller::BaseController, rpc_types::controller::BaseController,
}, },
tunnel::tcp::TcpTunnelConnector, tunnel::tcp::TcpTunnelConnector,
utils::{cost_to_str, float_to_str, PeerRoutePair}, utils::{cost_to_str, float_to_str, PeerRoutePair},
}; };
rust_i18n::i18n!("locales", fallback = "en"); rust_i18n::i18n!("locales", fallback = "en");
@ -54,6 +62,7 @@ enum SubCommand {
PeerCenter, PeerCenter,
VpnPortal, VpnPortal,
Node(NodeArgs), Node(NodeArgs),
Service(ServiceArgs)
} }
#[derive(Args, Debug)] #[derive(Args, Debug)]
@ -74,7 +83,7 @@ enum PeerSubCommand {
Remove, Remove,
List(PeerListArgs), List(PeerListArgs),
ListForeign, ListForeign,
ListGlobalForeign, ListGlobalForeign,
} }
#[derive(Args, Debug)] #[derive(Args, Debug)]
@ -120,6 +129,29 @@ struct NodeArgs {
sub_command: Option<NodeSubCommand>, sub_command: Option<NodeSubCommand>,
} }
#[derive(Args, Debug)]
struct ServiceArgs{
#[command(subcommand)]
sub_command: ServiceSubCommand
}
#[derive(Subcommand, Debug)]
enum ServiceSubCommand {
Install(InstallArgs),
Uninstall,
Status,
Start,
Stop
}
#[derive(Args, Debug)]
struct InstallArgs {
#[arg(long)]
core_path: Option<PathBuf>,
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
core_args: Option<Vec<OsString>>
}
type Error = anyhow::Error; type Error = anyhow::Error;
struct CommandHandler { struct CommandHandler {
@ -476,6 +508,120 @@ impl CommandHandler {
} }
} }
pub struct Service{
lable: ServiceLabel,
service_manager: Box<dyn ServiceManager>
}
impl Service {
pub fn new() -> Result<Self, Error> {
#[cfg(target_os = "windows")]
let service_manager = Box::new(
crate::win_service_manager::WinServiceManager::new(
Some(OsString::from("EasyTier Service")),
Some(OsString::from(env!("CARGO_PKG_DESCRIPTION"))),
vec![OsString::from("dnscache"), OsString::from("rpcss")],
)?
);
#[cfg(not(target_os = "windows"))]
let service_manager = <dyn ServiceManager>::native()?;
Ok(Self {
lable: env!("CARGO_PKG_NAME").parse().unwrap(),
service_manager
})
}
pub fn install(&self, bin_path: std::path::PathBuf, bin_args: Vec<OsString>) -> Result<(), Error> {
let ctx = ServiceInstallCtx {
label: self.lable.clone(),
contents: None,
program: bin_path,
args: bin_args,
autostart: true,
username: None,
working_directory: None,
environment: None,
};
if self.status()? != ServiceStatus::NotInstalled {
return Err(anyhow::anyhow!("Service is already installed"));
}
self.service_manager.install(ctx).map_err(|e| anyhow::anyhow!("failed to install service: {}", e))
}
pub fn uninstall(&self) -> Result<(), Error> {
let ctx = ServiceUninstallCtx {
label: self.lable.clone(),
};
let status = self.status()?;
if status == ServiceStatus::NotInstalled {
return Err(anyhow::anyhow!("Service is not installed"));
}
if status == ServiceStatus::Running {
self.service_manager.stop(ServiceStopCtx {
label: self.lable.clone(),
})?;
}
self.service_manager.uninstall(ctx).map_err(|e| anyhow::anyhow!("failed to uninstall service: {}", e))
}
pub fn status(&self) -> Result<ServiceStatus, Error> {
let ctx = ServiceStatusCtx {
label: self.lable.clone(),
};
let status = self.service_manager.status(ctx)?;
Ok(status)
}
pub fn start(&self) -> Result<(), Error> {
let ctx = ServiceStartCtx {
label: self.lable.clone(),
};
let status = self.status()?;
match status {
ServiceStatus::Running => {
Err(anyhow::anyhow!("Service is already running"))
}
ServiceStatus::Stopped(_) => {
self.service_manager.start(ctx).map_err(|e| anyhow::anyhow!("failed to start service: {}", e))?;
Ok(())
}
ServiceStatus::NotInstalled => {
Err(anyhow::anyhow!("Service is not installed"))
}
}
}
pub fn stop(&self) -> Result<(), Error> {
let ctx = ServiceStopCtx {
label: self.lable.clone(),
};
let status = self.status()?;
match status {
ServiceStatus::Running => {
self.service_manager.stop(ctx).map_err(|e| anyhow::anyhow!("failed to stop service: {}", e))?;
Ok(())
}
ServiceStatus::Stopped(_) => {
Err(anyhow::anyhow!("Service is already stopped"))
}
ServiceStatus::NotInstalled => {
Err(anyhow::anyhow!("Service is not installed"))
}
}
}
}
#[tokio::main] #[tokio::main]
#[tracing::instrument] #[tracing::instrument]
async fn main() -> Result<(), Error> { async fn main() -> Result<(), Error> {
@ -638,7 +784,206 @@ async fn main() -> Result<(), Error> {
} }
} }
} }
SubCommand::Service(service_args) => {
let service = Service::new()?;
match service_args.sub_command {
ServiceSubCommand::Install(install_args) => {
let bin_path = install_args.core_path.unwrap_or_else(|| {
let mut ret = std::env::current_exe()
.unwrap()
.parent()
.unwrap()
.join("easytier-core");
if cfg!(target_os = "windows") {
ret.set_extension("exe");
}
ret
});
let bin_path = std::fs::canonicalize(bin_path).map_err(|e| {
anyhow::anyhow!("failed to get easytier core application: {}", e)
})?;
let bin_args = install_args.core_args.unwrap_or_default();
service.install(bin_path, bin_args)?;
}
ServiceSubCommand::Uninstall => {
service.uninstall()?;
}
ServiceSubCommand::Status => {
let status = service.status()?;
match status {
ServiceStatus::Running => println!("Service is running"),
ServiceStatus::Stopped(_) => println!("Service is stopped"),
ServiceStatus::NotInstalled => println!("Service is not installed"),
}
}
ServiceSubCommand::Start => {
service.start()?;
}
ServiceSubCommand::Stop => {
service.stop()?;
}
}
}
} }
Ok(()) Ok(())
} }
#[cfg(target_os = "windows")]
mod win_service_manager {
use windows_service::{
service::{
ServiceType,
ServiceErrorControl,
ServiceDependency,
ServiceInfo,
ServiceStartType,
ServiceAccess
},
service_manager::{
ServiceManagerAccess,
ServiceManager
}
};
use std::{
io,
ffi::OsString,
ffi::OsStr
};
use service_manager::{
ServiceInstallCtx,
ServiceLevel,
ServiceStartCtx,
ServiceStatus,
ServiceStatusCtx,
ServiceUninstallCtx,
ServiceStopCtx
};
pub struct WinServiceManager {
service_manager: ServiceManager,
display_name: Option<OsString>,
description: Option<OsString>,
dependencies: Vec<OsString>
}
impl WinServiceManager {
pub fn new(display_name: Option<OsString>, description: Option<OsString>, dependencies: Vec<OsString>,) -> Result<Self, crate::Error> {
let service_manager = ServiceManager::local_computer(
None::<&str>,
ServiceManagerAccess::ALL_ACCESS,
)?;
Ok(Self {
service_manager,
display_name,
description,
dependencies,
})
}
}
impl service_manager::ServiceManager for WinServiceManager {
fn available(&self) -> io::Result<bool> {
Ok(true)
}
fn install(&self, ctx: ServiceInstallCtx) -> io::Result<()> {
let start_type_ = if ctx.autostart { ServiceStartType::AutoStart } else { ServiceStartType::OnDemand };
let srv_name = OsString::from(ctx.label.to_qualified_name());
let dis_name = self.display_name.clone().unwrap_or_else(|| srv_name.clone());
let dependencies = self.dependencies.iter().map(|dep| ServiceDependency::Service(dep.clone())).collect::<Vec<_>>();
let service_info = ServiceInfo {
name: srv_name,
display_name: dis_name,
service_type: ServiceType::OWN_PROCESS,
start_type: start_type_,
error_control: ServiceErrorControl::Normal,
executable_path: ctx.program,
launch_arguments: ctx.args,
dependencies: dependencies.clone(),
account_name: None,
account_password: None
};
let service = self.service_manager.create_service(&service_info, ServiceAccess::ALL_ACCESS).map_err(|e| {
io::Error::new(io::ErrorKind::Other, e)
})?;
if let Some(s) = &self.description {
service.set_description(s.clone()).map_err(|e| {
io::Error::new(io::ErrorKind::Other, e)
})?;
}
Ok(())
}
fn uninstall(&self, ctx: ServiceUninstallCtx) -> io::Result<()> {
let service = self.service_manager.open_service(ctx.label.to_qualified_name(), ServiceAccess::ALL_ACCESS).map_err(|e|{
io::Error::new(io::ErrorKind::Other, e)
})?;
service.delete().map_err(|e|{
io::Error::new(io::ErrorKind::Other, e)
})
}
fn start(&self, ctx: ServiceStartCtx) -> io::Result<()> {
let service = self.service_manager.open_service(ctx.label.to_qualified_name(), ServiceAccess::ALL_ACCESS).map_err(|e|{
io::Error::new(io::ErrorKind::Other, e)
})?;
service.start(&[] as &[&OsStr]).map_err(|e|{
io::Error::new(io::ErrorKind::Other, e)
})
}
fn stop(&self, ctx: ServiceStopCtx) -> io::Result<()> {
let service = self.service_manager.open_service(ctx.label.to_qualified_name(), ServiceAccess::ALL_ACCESS).map_err(|e|{
io::Error::new(io::ErrorKind::Other, e)
})?;
_ = service.stop().map_err(|e|{
io::Error::new(io::ErrorKind::Other, e)
})?;
Ok(())
}
fn level(&self) -> ServiceLevel {
ServiceLevel::System
}
fn set_level(&mut self, level: ServiceLevel) -> io::Result<()> {
match level {
ServiceLevel::System => Ok(()),
_ => Err(io::Error::new(io::ErrorKind::Other, "Unsupported service level"))
}
}
fn status(&self, ctx: ServiceStatusCtx) -> io::Result<ServiceStatus> {
let service = match self.service_manager.open_service(ctx.label.to_qualified_name(), ServiceAccess::QUERY_STATUS) {
Ok(s) => s,
Err(e) => {
if let windows_service::Error::Winapi(ref win_err) = e {
if win_err.raw_os_error() == Some(0x424) {
return Ok(ServiceStatus::NotInstalled);
}
}
return Err(io::Error::new(io::ErrorKind::Other, e));
}
};
let status = service.query_status().map_err(|e|{
io::Error::new(io::ErrorKind::Other, e)
})?;
match status.current_state {
windows_service::service::ServiceState::Stopped => Ok(ServiceStatus::Stopped(None)),
_ => Ok(ServiceStatus::Running),
}
}
}
}

View File

@ -289,16 +289,22 @@ struct Cli {
help = t!("core_clap.ipv6_listener").to_string() help = t!("core_clap.ipv6_listener").to_string()
)] )]
ipv6_listener: Option<String>, ipv6_listener: Option<String>,
#[arg(
long,
help = t!("core_clap.work_dir").to_string()
)]
work_dir: Option<String>,
} }
rust_i18n::i18n!("locales", fallback = "en"); rust_i18n::i18n!("locales", fallback = "en");
impl Cli { impl Cli {
fn parse_listeners(no_listener: bool, listeners: Vec<String>) -> Vec<String> { fn parse_listeners(no_listener: bool, listeners: Vec<String>) -> anyhow::Result<Vec<String>> {
let proto_port_offset = vec![("tcp", 0), ("udp", 0), ("wg", 1), ("ws", 1), ("wss", 2)]; let proto_port_offset = vec![("tcp", 0), ("udp", 0), ("wg", 1), ("ws", 1), ("wss", 2)];
if no_listener || listeners.is_empty() { if no_listener || listeners.is_empty() {
return vec![]; return Ok(vec![]);
} }
let origin_listners = listeners; let origin_listners = listeners;
@ -308,7 +314,7 @@ impl Cli {
for (proto, offset) in proto_port_offset { for (proto, offset) in proto_port_offset {
listeners.push(format!("{}://0.0.0.0:{}", proto, port + offset)); listeners.push(format!("{}://0.0.0.0:{}", proto, port + offset));
} }
return listeners; return Ok(listeners);
} }
} }
@ -325,7 +331,7 @@ impl Cli {
.iter() .iter()
.find(|(proto, _)| *proto == proto_port[0]) .find(|(proto, _)| *proto == proto_port[0])
else { else {
panic!("unknown protocol: {}", proto_port[0]); return Err(anyhow::anyhow!("unknown protocol: {}", proto_port[0]));
}; };
let port = if proto_port.len() == 2 { let port = if proto_port.len() == 2 {
@ -338,7 +344,7 @@ impl Cli {
} }
} }
listeners Ok(listeners)
} }
fn check_tcp_available(port: u16) -> Option<SocketAddr> { fn check_tcp_available(port: u16) -> Option<SocketAddr> {
@ -346,66 +352,62 @@ impl Cli {
TcpSocket::new_v4().unwrap().bind(s).map(|_| s).ok() TcpSocket::new_v4().unwrap().bind(s).map(|_| s).ok()
} }
fn parse_rpc_portal(rpc_portal: String) -> SocketAddr { fn parse_rpc_portal(rpc_portal: String) -> anyhow::Result<SocketAddr> {
if let Ok(port) = rpc_portal.parse::<u16>() { if let Ok(port) = rpc_portal.parse::<u16>() {
if port == 0 { if port == 0 {
// check tcp 15888 first // check tcp 15888 first
for i in 15888..15900 { for i in 15888..15900 {
if let Some(s) = Cli::check_tcp_available(i) { if let Some(s) = Cli::check_tcp_available(i) {
return s; return Ok(s);
} }
} }
return "0.0.0.0:0".parse().unwrap(); return Ok("0.0.0.0:0".parse().unwrap());
} }
return format!("0.0.0.0:{}", port).parse().unwrap(); return Ok("0.0.0.0:0".parse().unwrap());
} }
rpc_portal.parse().unwrap() Ok(rpc_portal.parse()?)
} }
} }
impl From<Cli> for TomlConfigLoader { impl TryFrom<&Cli> for TomlConfigLoader {
fn from(cli: Cli) -> Self { type Error = anyhow::Error;
fn try_from(cli: &Cli) -> Result<Self, Self::Error> {
if let Some(config_file) = &cli.config_file { if let Some(config_file) = &cli.config_file {
println!( println!(
"NOTICE: loading config file: {:?}, will ignore all command line flags\n", "NOTICE: loading config file: {:?}, will ignore all command line flags\n",
config_file config_file
); );
return TomlConfigLoader::new(config_file) return Ok(TomlConfigLoader::new(config_file)
.with_context(|| format!("failed to load config file: {:?}", cli.config_file)) .with_context(|| format!("failed to load config file: {:?}", cli.config_file))?)
.unwrap();
} }
let cfg = TomlConfigLoader::default(); let cfg = TomlConfigLoader::default();
cfg.set_hostname(cli.hostname); cfg.set_hostname(cli.hostname.clone());
cfg.set_network_identity(NetworkIdentity::new(cli.network_name, cli.network_secret)); cfg.set_network_identity(NetworkIdentity::new(cli.network_name.clone(), cli.network_secret.clone()));
cfg.set_dhcp(cli.dhcp); cfg.set_dhcp(cli.dhcp);
if let Some(ipv4) = &cli.ipv4 { if let Some(ipv4) = &cli.ipv4 {
cfg.set_ipv4(Some( cfg.set_ipv4(Some(
ipv4.parse() ipv4.parse()
.with_context(|| format!("failed to parse ipv4 address: {}", ipv4)) .with_context(|| format!("failed to parse ipv4 address: {}", ipv4))?
.unwrap(),
)) ))
} }
cfg.set_peers( let mut peers = Vec::<PeerConfig>::with_capacity(cli.peers.len());
cli.peers for p in &cli.peers {
.iter() peers.push(PeerConfig {
.map(|s| PeerConfig { uri: p.parse().with_context(|| format!("failed to parse peer uri: {}", p))?,
uri: s });
.parse() }
.with_context(|| format!("failed to parse peer uri: {}", s)) cfg.set_peers(peers);
.unwrap(),
})
.collect(),
);
cfg.set_listeners( cfg.set_listeners(
Cli::parse_listeners(cli.no_listener, cli.listeners) Cli::parse_listeners(cli.no_listener, cli.listeners.clone())?
.into_iter() .into_iter()
.map(|s| s.parse().unwrap()) .map(|s| s.parse().unwrap())
.collect(), .collect(),
@ -414,29 +416,29 @@ impl From<Cli> for TomlConfigLoader {
for n in cli.proxy_networks.iter() { for n in cli.proxy_networks.iter() {
cfg.add_proxy_cidr( cfg.add_proxy_cidr(
n.parse() n.parse()
.with_context(|| format!("failed to parse proxy network: {}", n)) .with_context(|| format!("failed to parse proxy network: {}", n))?
.unwrap(),
); );
} }
cfg.set_rpc_portal(Cli::parse_rpc_portal(cli.rpc_portal)); cfg.set_rpc_portal(Cli::parse_rpc_portal(cli.rpc_portal.clone()).with_context(|| {
format!("failed to parse rpc portal: {}", cli.rpc_portal)
})?);
if let Some(external_nodes) = cli.external_node { if let Some(external_nodes) = cli.external_node.as_ref() {
let mut old_peers = cfg.get_peers(); let mut old_peers = cfg.get_peers();
old_peers.push(PeerConfig { old_peers.push(PeerConfig {
uri: external_nodes uri: external_nodes
.parse() .parse()
.with_context(|| { .with_context(|| {
format!("failed to parse external node uri: {}", external_nodes) format!("failed to parse external node uri: {}", external_nodes)
}) })?
.unwrap(),
}); });
cfg.set_peers(old_peers); cfg.set_peers(old_peers);
} }
if cli.console_log_level.is_some() { if cli.console_log_level.is_some() {
cfg.set_console_logger_config(ConsoleLoggerConfig { cfg.set_console_logger_config(ConsoleLoggerConfig {
level: cli.console_log_level, level: cli.console_log_level.clone(),
}); });
} }
@ -448,43 +450,30 @@ impl From<Cli> for TomlConfigLoader {
}); });
} }
cfg.set_inst_name(cli.instance_name); cfg.set_inst_name(cli.instance_name.clone());
if let Some(vpn_portal) = cli.vpn_portal { if let Some(vpn_portal) = cli.vpn_portal.as_ref() {
let url: url::Url = vpn_portal let url: url::Url = vpn_portal
.parse() .parse()
.with_context(|| format!("failed to parse vpn portal url: {}", vpn_portal)) .with_context(|| format!("failed to parse vpn portal url: {}", vpn_portal))?;
.unwrap(); let host = url.host_str().ok_or_else(|| anyhow::anyhow!("vpn portal url missing host"))?;
let port = url.port().ok_or_else(|| anyhow::anyhow!("vpn portal url missing port"))?;
let client_cidr = url.path()[1..]
.parse()
.with_context(|| format!("failed to parse vpn portal client cidr: {}", url.path()))?;
let wireguard_listen: SocketAddr = format!("{}:{}", host, port).parse().unwrap();
cfg.set_vpn_portal_config(VpnPortalConfig { cfg.set_vpn_portal_config(VpnPortalConfig {
client_cidr: url.path()[1..] wireguard_listen,
.parse() client_cidr,
.with_context(|| {
format!("failed to parse vpn portal client cidr: {}", url.path())
})
.unwrap(),
wireguard_listen: format!("{}:{}", url.host_str().unwrap(), url.port().unwrap())
.parse()
.with_context(|| {
format!(
"failed to parse vpn portal wireguard listen address: {}",
url.host_str().unwrap()
)
})
.unwrap(),
}); });
} }
if let Some(manual_routes) = cli.manual_routes { if let Some(manual_routes) = cli.manual_routes.as_ref() {
cfg.set_routes(Some( let mut routes = Vec::<cidr::Ipv4Cidr>::with_capacity(manual_routes.len());
manual_routes for r in manual_routes{
.iter() routes.push(r.parse().with_context(|| format!("failed to parse route: {}", r))?);
.map(|s| { }
s.parse() cfg.set_routes(Some(routes));
.with_context(|| format!("failed to parse route: {}", s))
.unwrap()
})
.collect(),
));
} }
#[cfg(feature = "socks5")] #[cfg(feature = "socks5")]
@ -503,30 +492,29 @@ impl From<Cli> for TomlConfigLoader {
f.enable_encryption = !cli.disable_encryption; f.enable_encryption = !cli.disable_encryption;
f.enable_ipv6 = !cli.disable_ipv6; f.enable_ipv6 = !cli.disable_ipv6;
f.latency_first = cli.latency_first; f.latency_first = cli.latency_first;
f.dev_name = cli.dev_name.unwrap_or_default(); f.dev_name = cli.dev_name.clone().unwrap_or_default();
if let Some(mtu) = cli.mtu { if let Some(mtu) = cli.mtu {
f.mtu = mtu as u32; f.mtu = mtu as u32;
} }
f.enable_exit_node = cli.enable_exit_node; f.enable_exit_node = cli.enable_exit_node;
f.no_tun = cli.no_tun || cfg!(not(feature = "tun")); f.no_tun = cli.no_tun || cfg!(not(feature = "tun"));
f.use_smoltcp = cli.use_smoltcp; f.use_smoltcp = cli.use_smoltcp;
if let Some(wl) = cli.relay_network_whitelist { if let Some(wl) = cli.relay_network_whitelist.as_ref() {
f.foreign_network_whitelist = wl.join(" "); f.foreign_network_whitelist = wl.join(" ");
} }
f.disable_p2p = cli.disable_p2p; f.disable_p2p = cli.disable_p2p;
f.relay_all_peer_rpc = cli.relay_all_peer_rpc; f.relay_all_peer_rpc = cli.relay_all_peer_rpc;
if let Some(ipv6_listener) = cli.ipv6_listener { if let Some(ipv6_listener) = cli.ipv6_listener.as_ref() {
f.ipv6_listener = ipv6_listener f.ipv6_listener = ipv6_listener
.parse() .parse()
.with_context(|| format!("failed to parse ipv6 listener: {}", ipv6_listener)) .with_context(|| format!("failed to parse ipv6 listener: {}", ipv6_listener))?
.unwrap();
} }
f.multi_thread = cli.multi_thread; f.multi_thread = cli.multi_thread;
cfg.set_flags(f); cfg.set_flags(f);
cfg.set_exit_nodes(cli.exit_nodes.clone()); cfg.set_exit_nodes(cli.exit_nodes.clone());
cfg Ok(cfg)
} }
} }
@ -655,41 +643,56 @@ pub fn handle_event(mut events: EventBusSubscriber) -> tokio::task::JoinHandle<(
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
fn win_service_event_loop( fn win_service_event_loop(
stop_notify: std::sync::Arc<tokio::sync::Notify>, stop_notify: std::sync::Arc<tokio::sync::Notify>,
inst: launcher::NetworkInstance, cli: Cli,
status_handle: windows_service::service_control_handler::ServiceStatusHandle, status_handle: windows_service::service_control_handler::ServiceStatusHandle,
) { ) {
use std::time::Duration;
use tokio::runtime::Runtime; use tokio::runtime::Runtime;
use std::time::Duration;
use windows_service::service::*; use windows_service::service::*;
let normal_status = ServiceStatus {
service_type: ServiceType::OWN_PROCESS,
current_state: ServiceState::Running,
controls_accepted: ServiceControlAccept::STOP,
exit_code: ServiceExitCode::Win32(0),
checkpoint: 0,
wait_hint: Duration::default(),
process_id: None,
};
let error_status = ServiceStatus {
service_type: ServiceType::OWN_PROCESS,
current_state: ServiceState::Stopped,
controls_accepted: ServiceControlAccept::empty(),
exit_code: ServiceExitCode::ServiceSpecific(1u32),
checkpoint: 0,
wait_hint: Duration::default(),
process_id: None,
};
if cli.work_dir == None {
let mut path = std::env::current_exe().unwrap();
path.pop();
std::env::set_current_dir(path).unwrap();
}
std::thread::spawn(move || { std::thread::spawn(move || {
let rt = Runtime::new().unwrap(); let rt = Runtime::new().unwrap();
rt.block_on(async move { rt.block_on(async move {
tokio::select! { tokio::select! {
res = inst.wait() => { res = run_main(cli) => {
if let Some(e) = res { match res {
status_handle.set_service_status(ServiceStatus { Ok(_) => {
service_type: ServiceType::OWN_PROCESS, status_handle.set_service_status(normal_status).unwrap();
current_state: ServiceState::Stopped, std::process::exit(0);
controls_accepted: ServiceControlAccept::empty(), }
checkpoint: 0, Err(e) => {
wait_hint: Duration::default(), status_handle.set_service_status(error_status).unwrap();
exit_code: ServiceExitCode::ServiceSpecific(1u32), eprintln!("error: {}", e);
process_id: None }
}).unwrap();
panic!("launcher error: {:?}", e);
} }
}, },
_ = stop_notify.notified() => { _ = stop_notify.notified() => {
status_handle.set_service_status(ServiceStatus { _ = status_handle.set_service_status(normal_status);
service_type: ServiceType::OWN_PROCESS,
current_state: ServiceState::Stopped,
controls_accepted: ServiceControlAccept::empty(),
checkpoint: 0,
wait_hint: Duration::default(),
exit_code: ServiceExitCode::Win32(0),
process_id: None
}).unwrap();
std::process::exit(0); std::process::exit(0);
} }
} }
@ -706,9 +709,6 @@ fn win_service_main(_: Vec<std::ffi::OsString>) {
use windows_service::service_control_handler::*; use windows_service::service_control_handler::*;
let cli = Cli::parse(); let cli = Cli::parse();
let cfg = TomlConfigLoader::from(cli);
init_logger(&cfg, false).unwrap();
let stop_notify_send = Arc::new(Notify::new()); let stop_notify_send = Arc::new(Notify::new());
let stop_notify_recv = Arc::clone(&stop_notify_send); let stop_notify_recv = Arc::clone(&stop_notify_send);
@ -731,40 +731,16 @@ fn win_service_main(_: Vec<std::ffi::OsString>) {
checkpoint: 0, checkpoint: 0,
wait_hint: Duration::default(), wait_hint: Duration::default(),
process_id: None, process_id: None,
}; };
let mut inst = launcher::NetworkInstance::new(cfg).set_fetch_node_info(false); status_handle.set_service_status(next_status).expect("set service status fail");
inst.start().unwrap(); win_service_event_loop(stop_notify_recv, cli, status_handle);
status_handle
.set_service_status(next_status)
.expect("set service status fail");
win_service_event_loop(stop_notify_recv, inst, status_handle);
} }
#[tokio::main] async fn run_main(cli: Cli) -> anyhow::Result<()> {
async fn main() { if let Some(dir) = cli.work_dir.as_ref() {
let locale = sys_locale::get_locale().unwrap_or_else(|| String::from("en-US")); std::env::set_current_dir(dir).map_err(|e| anyhow::anyhow!("failed to set work dir: {}", e))?;
rust_i18n::set_locale(&locale); }
#[cfg(target_os = "windows")]
match windows_service::service_dispatcher::start(String::new(), ffi_service_main) {
Ok(_) => std::thread::park(),
Err(e) => {
let should_panic = if let windows_service::Error::Winapi(ref io_error) = e {
io_error.raw_os_error() != Some(0x427) // ERROR_FAILED_SERVICE_CONTROLLER_CONNECT
} else {
true
};
if should_panic {
panic!("SCM start an error: {}", e);
}
}
};
let cli = Cli::parse();
setup_panic_handler();
if cli.config_server.is_some() { if cli.config_server.is_some() {
let config_server_url_s = cli.config_server.clone().unwrap(); let config_server_url_s = cli.config_server.clone().unwrap();
@ -797,11 +773,11 @@ async fn main() {
let _wc = web_client::WebClient::new(UdpTunnelConnector::new(c_url), token.to_string()); let _wc = web_client::WebClient::new(UdpTunnelConnector::new(c_url), token.to_string());
tokio::signal::ctrl_c().await.unwrap(); tokio::signal::ctrl_c().await.unwrap();
return; return Ok(());
} }
let cfg = TomlConfigLoader::from(cli); let cfg = TomlConfigLoader::try_from(&cli)?;
init_logger(&cfg, false).unwrap(); init_logger(&cfg, false)?;
println!("Starting easytier with config:"); println!("Starting easytier with config:");
println!("############### TOML ###############\n"); println!("############### TOML ###############\n");
@ -810,7 +786,37 @@ async fn main() {
let mut l = launcher::NetworkInstance::new(cfg).set_fetch_node_info(false); let mut l = launcher::NetworkInstance::new(cfg).set_fetch_node_info(false);
let _t = ScopedTask::from(handle_event(l.start().unwrap())); let _t = ScopedTask::from(handle_event(l.start().unwrap()));
if let Some(e) = l.wait().await { if let Some(e) = l.wait().await{
panic!("launcher error: {:?}", e); return Err(anyhow::anyhow!("launcher error: {}", e));
} }
Ok(())
} }
#[tokio::main]
async fn main() {
let locale = sys_locale::get_locale().unwrap_or_else(|| String::from("en-US"));
rust_i18n::set_locale(&locale);
setup_panic_handler();
#[cfg(target_os = "windows")]
match windows_service::service_dispatcher::start(String::new(), ffi_service_main) {
Ok(_) => std::thread::park(),
Err(e) =>
{
let should_panic = if let windows_service::Error::Winapi(ref io_error) = e {
io_error.raw_os_error() != Some(0x427) // ERROR_FAILED_SERVICE_CONTROLLER_CONNECT
} else { true };
if should_panic {
panic!("SCM start an error: {}", e);
}
}
};
let cli = Cli::parse();
if let Err(e) = run_main(cli).await {
eprintln!("error: {:?}", e);
std::process::exit(1);
}
}

View File

@ -168,4 +168,4 @@ mod tests {
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
tracing::debug!("test display debug"); tracing::debug!("test display debug");
} }
} }