v1.1
This commit is contained in:
@@ -2,15 +2,17 @@ use std::io;
|
||||
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::command::entity::{DeviceItem, RouteItem, Status};
|
||||
|
||||
pub struct CommandClient {
|
||||
udp: UdpSocket,
|
||||
}
|
||||
|
||||
impl CommandClient {
|
||||
pub fn new() -> io::Result<Self> {
|
||||
let port = crate::config::read_command_port().unwrap();
|
||||
let port = crate::config::read_command_port()?;
|
||||
let udp = UdpSocket::bind("127.0.0.1:0")?;
|
||||
udp.set_read_timeout(Some(Duration::from_secs(5)))?;
|
||||
udp.set_read_timeout(Some(Duration::from_secs(2)))?;
|
||||
udp.connect(SocketAddr::V4(SocketAddrV4::new(
|
||||
Ipv4Addr::new(127, 0, 0, 1),
|
||||
port,
|
||||
@@ -20,16 +22,52 @@ impl CommandClient {
|
||||
}
|
||||
|
||||
impl CommandClient {
|
||||
pub fn list(&self) -> io::Result<String> {
|
||||
pub fn list(&self) -> io::Result<Vec<DeviceItem>> {
|
||||
self.udp.send(b"list")?;
|
||||
let mut buf = [0; 10240];
|
||||
let len = self.udp.recv(&mut buf)?;
|
||||
Ok(String::from_utf8(buf[..len].to_vec()).unwrap())
|
||||
match serde_json::from_slice::<Vec<DeviceItem>>(&buf[..len]) {
|
||||
Ok(val) => {
|
||||
Ok(val)
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("{:?}",e);
|
||||
Err(io::Error::new(io::ErrorKind::Other, "data error"))
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn status(&self) -> io::Result<String> {
|
||||
pub fn route(&self) -> io::Result<Vec<RouteItem>> {
|
||||
self.udp.send(b"route")?;
|
||||
let mut buf = [0; 10240];
|
||||
let len = self.udp.recv(&mut buf)?;
|
||||
match serde_json::from_slice::<Vec<RouteItem>>(&buf[..len]) {
|
||||
Ok(val) => {
|
||||
Ok(val)
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("{:?}",e);
|
||||
Err(io::Error::new(io::ErrorKind::Other, "data error"))
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn status(&self) -> io::Result<Status> {
|
||||
self.udp.send(b"status")?;
|
||||
let mut buf = [0; 10240];
|
||||
let len = self.udp.recv(&mut buf)?;
|
||||
match serde_json::from_slice::<Status>(&buf[..len]) {
|
||||
Ok(val) => {
|
||||
Ok(val)
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("{:?},{:?}",&buf[..len],e);
|
||||
Err(io::Error::new(io::ErrorKind::Other, "data error"))
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn stop(&self) -> io::Result<String> {
|
||||
self.udp.send(b"stop")?;
|
||||
let mut buf = [0; 10240];
|
||||
let len = self.udp.recv(&mut buf)?;
|
||||
Ok(String::from_utf8(buf[..len].to_vec()).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct Status {
|
||||
pub name: String,
|
||||
pub virtual_ip: String,
|
||||
pub virtual_gateway: String,
|
||||
pub virtual_netmask: String,
|
||||
pub connect_status: String,
|
||||
pub relay_server: String,
|
||||
pub nat_type: String,
|
||||
pub public_ips: String,
|
||||
pub local_ip: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct RouteItem {
|
||||
pub destination: String,
|
||||
pub next_hop: String,
|
||||
pub metric: String,
|
||||
pub rt: String,
|
||||
pub interface: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct DeviceItem {
|
||||
pub name: String,
|
||||
pub virtual_ip: String,
|
||||
pub nat_type: String,
|
||||
pub public_ips: String,
|
||||
pub local_ip: String,
|
||||
pub nat_traversal_type: String,
|
||||
pub rt: String,
|
||||
pub status: String,
|
||||
}
|
||||
@@ -1,2 +1,3 @@
|
||||
pub mod client;
|
||||
pub mod server;
|
||||
pub mod entity;
|
||||
|
||||
@@ -3,9 +3,9 @@ use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
|
||||
use std::sync::Arc;
|
||||
|
||||
use console::style;
|
||||
use switch::core::Switch;
|
||||
use crate::command::entity::{DeviceItem, RouteItem, Status};
|
||||
|
||||
use switch::handle::{PeerDeviceStatus, RouteType};
|
||||
use switch::Switch;
|
||||
|
||||
pub struct CommandServer {}
|
||||
|
||||
@@ -54,111 +54,137 @@ impl CommandServer {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn command_route(switch: &Switch) -> Vec<RouteItem> {
|
||||
let route_table = switch.route_table();
|
||||
let mut route_list = Vec::with_capacity(route_table.len());
|
||||
for (destination, route) in route_table {
|
||||
let next_hop = switch.route_key(&route.route_key()).map_or(String::new(), |v| v.to_string());
|
||||
let metric = route.metric.to_string();
|
||||
let rt = if route.rt < 0 {
|
||||
"".to_string()
|
||||
} else {
|
||||
route.rt.to_string()
|
||||
};
|
||||
let interface = route.addr.to_string();
|
||||
let item = RouteItem {
|
||||
destination: destination.to_string(),
|
||||
next_hop,
|
||||
metric,
|
||||
rt,
|
||||
interface,
|
||||
};
|
||||
route_list.push(item);
|
||||
}
|
||||
route_list
|
||||
}
|
||||
|
||||
pub fn command_list(switch: &Switch) -> Vec<DeviceItem> {
|
||||
let device_list = switch.device_list();
|
||||
let mut list = Vec::new();
|
||||
for peer in device_list {
|
||||
let name = peer.name;
|
||||
let virtual_ip = peer.virtual_ip.to_string();
|
||||
let (nat_type, public_ips, local_ip) = if let Some(nat_info) = switch.peer_nat_info(&peer.virtual_ip) {
|
||||
let nat_type = format!("{:?}", nat_info.nat_type);
|
||||
let public_ips: Vec<String> = nat_info.public_ips.iter().map(|v| v.to_string()).collect();
|
||||
let public_ips = public_ips.join(",");
|
||||
let local_ip = nat_info.local_ip.to_string();
|
||||
(nat_type, public_ips, local_ip)
|
||||
} else {
|
||||
("".to_string(), "".to_string(), "".to_string())
|
||||
};
|
||||
let (nat_traversal_type, rt) = if let Some(route) = switch.route(&peer.virtual_ip) {
|
||||
let nat_traversal_type = if route.metric == 1 { "p2p" } else { "relay" }.to_string();
|
||||
let rt = if route.rt < 0 {
|
||||
"".to_string()
|
||||
} else {
|
||||
route.rt.to_string()
|
||||
};
|
||||
(nat_traversal_type, rt)
|
||||
} else {
|
||||
("relay".to_string(), "".to_string())
|
||||
};
|
||||
let status = format!("{:?}", peer.status);
|
||||
let item = DeviceItem {
|
||||
name,
|
||||
virtual_ip,
|
||||
nat_type,
|
||||
public_ips,
|
||||
local_ip,
|
||||
nat_traversal_type,
|
||||
rt,
|
||||
status,
|
||||
};
|
||||
list.push(item);
|
||||
}
|
||||
list
|
||||
}
|
||||
|
||||
pub fn command_status(switch: &Switch) -> Status {
|
||||
let current_device = switch.current_device();
|
||||
let nat_info = switch.nat_info();
|
||||
let name = switch.name().to_string();
|
||||
let virtual_ip = current_device.virtual_ip().to_string();
|
||||
let virtual_gateway = current_device.virtual_gateway().to_string();
|
||||
let virtual_netmask = current_device.virtual_netmask.to_string();
|
||||
let connect_status = format!("{:?}", switch.connection_status());
|
||||
let relay_server = current_device.connect_server.to_string();
|
||||
let nat_type = format!("{:?}", nat_info.nat_type);
|
||||
let public_ips: Vec<String> = nat_info.public_ips.iter().map(|v| v.to_string()).collect();
|
||||
let public_ips = public_ips.join(",");
|
||||
let local_ip = nat_info.local_ip.to_string();
|
||||
Status {
|
||||
name,
|
||||
virtual_ip,
|
||||
virtual_gateway,
|
||||
virtual_netmask,
|
||||
connect_status,
|
||||
relay_server,
|
||||
nat_type,
|
||||
public_ips,
|
||||
local_ip,
|
||||
}
|
||||
}
|
||||
|
||||
fn command(cmd: &str, switch: &Switch) -> io::Result<String> {
|
||||
let mut out_str = String::new();
|
||||
match cmd {
|
||||
"list" => {
|
||||
let server_rt = switch.server_rt();
|
||||
let device_list = switch.device_list();
|
||||
if device_list.is_empty() {
|
||||
return Ok("No other devices found\n".to_string());
|
||||
let out_str = match cmd {
|
||||
"route" => {
|
||||
match serde_json::to_string(&command_route(switch)) {
|
||||
Ok(str) => {
|
||||
str
|
||||
}
|
||||
Err(e) => {
|
||||
format!("{:?}", e)
|
||||
}
|
||||
}
|
||||
for peer_device_info in device_list {
|
||||
let route = switch.route(&peer_device_info.virtual_ip);
|
||||
let str = if peer_device_info.status == PeerDeviceStatus::Online {
|
||||
if route.route_type == RouteType::P2P {
|
||||
let str = if route.rt >= 0 {
|
||||
format!(
|
||||
"[{}] {}(p2p delay:{}ms)\n",
|
||||
peer_device_info.name, peer_device_info.virtual_ip, route.rt
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"[{}] {}(p2p)",
|
||||
peer_device_info.name, peer_device_info.virtual_ip
|
||||
)
|
||||
};
|
||||
style(str).green().to_string()
|
||||
} else {
|
||||
let str = if server_rt >= 0 {
|
||||
format!(
|
||||
"[{}] {}(relay delay:{}ms)\n",
|
||||
peer_device_info.name,
|
||||
peer_device_info.virtual_ip,
|
||||
server_rt * 2
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"[{}] {}(relay)\n",
|
||||
peer_device_info.name, peer_device_info.virtual_ip
|
||||
)
|
||||
};
|
||||
style(str).blue().to_string()
|
||||
}
|
||||
} else {
|
||||
let str = format!(
|
||||
"[{}] {}(Offline)\n",
|
||||
peer_device_info.name, peer_device_info.virtual_ip
|
||||
);
|
||||
style(str).red().to_string()
|
||||
};
|
||||
out_str.push_str(&str);
|
||||
}
|
||||
"list" => {
|
||||
match serde_json::to_string(&command_list(switch)) {
|
||||
Ok(str) => {
|
||||
str
|
||||
}
|
||||
Err(e) => {
|
||||
format!("{:?}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
"status" => {
|
||||
let server_rt = switch.server_rt();
|
||||
let current_device = switch.current_device();
|
||||
let str = format!("Virtual ip:{}\n", style(current_device.virtual_ip).green());
|
||||
out_str.push_str(&str);
|
||||
let str = format!(
|
||||
"Virtual gateway:{}\n",
|
||||
style(current_device.virtual_gateway).green()
|
||||
);
|
||||
out_str.push_str(&str);
|
||||
let str = format!(
|
||||
"Connection status :{}\n",
|
||||
style(format!("{:?}", switch.connection_status())).green()
|
||||
);
|
||||
out_str.push_str(&str);
|
||||
let str = format!(
|
||||
"Relay server :{}\n",
|
||||
style(current_device.connect_server).green()
|
||||
);
|
||||
out_str.push_str(&str);
|
||||
if server_rt >= 0 {
|
||||
let str = format!("Delay of relay server :{}ms\n", style(server_rt).green());
|
||||
out_str.push_str(&str);
|
||||
}
|
||||
if let Some(nat_info) = switch.nat_info() {
|
||||
let str = format!(
|
||||
"NAT type :{}",
|
||||
style(format!("{:?}", nat_info.nat_type)).green()
|
||||
);
|
||||
out_str.push_str(&str);
|
||||
match serde_json::to_string(&command_status(switch)) {
|
||||
Ok(str) => {
|
||||
str
|
||||
}
|
||||
Err(e) => {
|
||||
format!("{:?}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
"help" | "h" => {
|
||||
let str = format!("Options: \n");
|
||||
out_str.push_str(&str);
|
||||
let str = format!(
|
||||
"{} , Query the virtual IP of other devices\n",
|
||||
style("list").green()
|
||||
);
|
||||
out_str.push_str(&str);
|
||||
let str = format!("{} , View current device status\n", style("status").green());
|
||||
out_str.push_str(&str);
|
||||
let str = format!("{} , Exit the program\n", style("exit").green());
|
||||
out_str.push_str(&str);
|
||||
}
|
||||
"exit" => {
|
||||
switch.stop_async();
|
||||
"stop" => {
|
||||
switch.stop()?;
|
||||
"stopping".to_string()
|
||||
}
|
||||
_ => {
|
||||
let str = format!("command '{}' not fount. \n", style(cmd).red());
|
||||
out_str.push_str(&str);
|
||||
let str = format!("Try to enter: '{}'\n", style("help").green());
|
||||
out_str.push_str(&str);
|
||||
format!("command '{}' not fount. \n Try to enter: 'help'\n", cmd)
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(out_str)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
use std::io;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub fn log_init_service(home: PathBuf) -> io::Result<()> {
|
||||
if !home.exists() {
|
||||
std::fs::create_dir(&home)?;
|
||||
}
|
||||
let logfile = log4rs::append::file::FileAppender::builder()
|
||||
// Pattern: https://docs.rs/log4rs/*/log4rs/encode/pattern/index.html
|
||||
.encoder(Box::new(log4rs::encode::pattern::PatternEncoder::new(
|
||||
"{d(%+)(utc)} [{f}:{L}] {h({l})} {M}:{m}{n}\n",
|
||||
)))
|
||||
.build(home.join("switch-service.log"))?;
|
||||
match log4rs::Config::builder()
|
||||
.appender(log4rs::config::Appender::builder().build("logfile", Box::new(logfile)))
|
||||
.build(
|
||||
log4rs::config::Root::builder()
|
||||
.appender("logfile")
|
||||
.build(log::LevelFilter::Info),
|
||||
) {
|
||||
Ok(config) => {
|
||||
let _ = log4rs::init_config(config);
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn log_init() -> io::Result<()> {
|
||||
let home = dirs::home_dir().unwrap().join(".switch");
|
||||
if !home.exists() {
|
||||
std::fs::create_dir(&home)?;
|
||||
}
|
||||
let stderr = log4rs::append::console::ConsoleAppender::builder()
|
||||
.target(log4rs::append::console::Target::Stderr)
|
||||
.build();
|
||||
let logfile = log4rs::append::file::FileAppender::builder()
|
||||
// Pattern: https://docs.rs/log4rs/*/log4rs/encode/pattern/index.html
|
||||
.encoder(Box::new(log4rs::encode::pattern::PatternEncoder::new(
|
||||
"{d(%+)(utc)} [{f}:{L}] {h({l})} {M}:{m}{n}\n",
|
||||
)))
|
||||
.build(home.join("switch.log"))?;
|
||||
match log4rs::Config::builder()
|
||||
.appender(log4rs::config::Appender::builder().build("logfile", Box::new(logfile)))
|
||||
.appender(
|
||||
log4rs::config::Appender::builder()
|
||||
.filter(Box::new(log4rs::filter::threshold::ThresholdFilter::new(
|
||||
log::LevelFilter::Error,
|
||||
)))
|
||||
.build("stderr", Box::new(stderr)),
|
||||
)
|
||||
.build(
|
||||
log4rs::config::Root::builder()
|
||||
.appender("logfile")
|
||||
.appender("stderr")
|
||||
.build(log::LevelFilter::Info),
|
||||
) {
|
||||
Ok(config) => {
|
||||
let _ = log4rs::init_config(config);
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,11 +1,104 @@
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{SocketAddr, ToSocketAddrs};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use lazy_static::lazy_static;
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use crate::{BaseArgs, StartArgs};
|
||||
|
||||
pub mod log_config;
|
||||
|
||||
pub struct BaseConfig {
|
||||
pub name: String,
|
||||
pub token: String,
|
||||
pub server: SocketAddr,
|
||||
pub nat_test_server: Vec<SocketAddr>,
|
||||
pub device_id: String,
|
||||
}
|
||||
|
||||
pub fn default_config(start_args: StartArgs) -> Result<BaseConfig, String> {
|
||||
let args_config = read_config();
|
||||
if args_config.is_none() && start_args.token.is_none() {
|
||||
return Err("找不到token(Token not found)".to_string());
|
||||
}
|
||||
let token = start_args.token.unwrap_or_else(|| args_config.as_ref().unwrap().token.clone()).trim().to_string();
|
||||
if token.is_empty() {
|
||||
return Err("token不能为空(Token cannot be empty)".to_string());
|
||||
}
|
||||
if token.len() > 64 {
|
||||
return Err("token不能超过64字符(Token cannot exceed 64 characters)".to_string());
|
||||
}
|
||||
let name = start_args.name.unwrap_or_else(|| {
|
||||
if let Some(c) = &args_config {
|
||||
c.name.clone()
|
||||
} else {
|
||||
os_info::get().to_string()
|
||||
}
|
||||
});
|
||||
let name = name.trim();
|
||||
let name = if name.len() > 64 {
|
||||
name[..64].to_string()
|
||||
} else {
|
||||
name.to_string()
|
||||
};
|
||||
let device_id = start_args.device_id.unwrap_or_else(|| {
|
||||
if let Some(c) = &args_config {
|
||||
if !c.device_id.is_empty() {
|
||||
return c.device_id.clone();
|
||||
}
|
||||
}
|
||||
if let Ok(Some(mac_address)) = mac_address::get_mac_address() {
|
||||
mac_address.to_string()
|
||||
} else {
|
||||
"".to_string()
|
||||
}
|
||||
});
|
||||
if device_id.is_empty() || device_id.len() > 64 {
|
||||
return Err("设备id不能为空并且长度不能大于64字符(The device id cannot be empty and the length cannot be greater than 64 characters)".to_string());
|
||||
}
|
||||
let server = match start_args.server.unwrap_or_else(|| {
|
||||
if let Some(c) = &args_config {
|
||||
if !c.server.is_empty() {
|
||||
return c.server.clone();
|
||||
}
|
||||
}
|
||||
"nat1.wherewego.top:29875".to_string()
|
||||
}).to_socket_addrs() {
|
||||
Ok(mut server) => {
|
||||
if let Some(addr) = server.next() {
|
||||
addr
|
||||
} else {
|
||||
return Err("中继服务器地址错误( Relay server address error)".to_string());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(format!("中继服务器地址错误( Relay server address error) :{:?}", e));
|
||||
}
|
||||
};
|
||||
let nat_test_server = start_args.nat_test_server.unwrap_or_else(|| {
|
||||
if let Some(c) = &args_config {
|
||||
if !c.nat_test_server.is_empty() {
|
||||
return c.nat_test_server.join(",");
|
||||
}
|
||||
}
|
||||
"nat1.wherewego.top:35061,nat1.wherewego.top:35062,nat2.wherewego.top:35061,nat2.wherewego.top:35062".to_string()
|
||||
}).split(",").flat_map(|a| a.to_socket_addrs()).flatten()
|
||||
.collect::<Vec<_>>();
|
||||
if nat_test_server.is_empty() {
|
||||
return Err("NAT检测服务地址错误(NAT detection service address error)".to_string());
|
||||
}
|
||||
let base_config = BaseConfig {
|
||||
name,
|
||||
token,
|
||||
server,
|
||||
nat_test_server,
|
||||
device_id,
|
||||
};
|
||||
Ok(base_config)
|
||||
}
|
||||
|
||||
lazy_static! {
|
||||
static ref CONFIG: Mutex<Option<ArgsConfig>> = Mutex::new(None);
|
||||
@@ -14,17 +107,43 @@ lazy_static! {
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct ArgsConfig {
|
||||
#[serde(default = "default_version")]
|
||||
pub version: String,
|
||||
#[serde(default = "default_str")]
|
||||
pub token: String,
|
||||
pub name: Option<String>,
|
||||
#[serde(default = "default_str")]
|
||||
pub name: String,
|
||||
pub command_port: Option<u16>,
|
||||
#[serde(default = "default_str")]
|
||||
pub server: String,
|
||||
#[serde(default = "default_resource_vec")]
|
||||
pub nat_test_server: Vec<String>,
|
||||
#[serde(default = "default_str")]
|
||||
pub device_id: String,
|
||||
}
|
||||
|
||||
fn default_version() -> String {
|
||||
"1.0".to_string()
|
||||
}
|
||||
|
||||
fn default_str() -> String {
|
||||
"".to_string()
|
||||
}
|
||||
|
||||
fn default_resource_vec() -> Vec<String> {
|
||||
vec![]
|
||||
}
|
||||
|
||||
impl ArgsConfig {
|
||||
pub fn new(token: String, name: Option<String>) -> Self {
|
||||
pub fn new(token: String, name: String, server: String, nat_test_server: Vec<String>, device_id: String) -> Self {
|
||||
Self {
|
||||
version: "1.0".to_string(),
|
||||
token,
|
||||
name,
|
||||
command_port: None,
|
||||
server,
|
||||
nat_test_server,
|
||||
device_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -66,13 +185,13 @@ pub fn read_config() -> Option<ArgsConfig> {
|
||||
return c;
|
||||
}
|
||||
if let Some(home) = SWITCH_HOME_PATH.lock().clone() {
|
||||
match read_config_(home) {
|
||||
match read_config_(home.to_path_buf()) {
|
||||
Ok(config) => {
|
||||
lock.replace(config.clone());
|
||||
Some(config)
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("{:?}", e);
|
||||
log::error!("{:?},path:{:?}", e,home);
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
use std::net::Ipv4Addr;
|
||||
use console::style;
|
||||
|
||||
use switch::Route;
|
||||
|
||||
use crate::command::entity::{DeviceItem, RouteItem, Status};
|
||||
|
||||
pub mod table;
|
||||
|
||||
pub fn console_status(status: Status) {
|
||||
println!("Name: {}", style(status.name).green());
|
||||
println!("Virtual ip: {}", style(status.virtual_ip).green());
|
||||
println!("Virtual gateway: {}", style(status.virtual_gateway).green());
|
||||
println!("Virtual netmask: {}", style(status.virtual_netmask).green());
|
||||
println!("Connection status: {}", style(status.connect_status).green());
|
||||
println!("NAT type: {}", style(status.nat_type).green());
|
||||
println!("Relay server: {}", style(status.relay_server).green());
|
||||
println!("Public ips: {}", style(status.public_ips).green());
|
||||
println!("Local ip: {}", style(status.local_ip).green());
|
||||
}
|
||||
|
||||
pub fn console_route_table(list: Vec<RouteItem>) {
|
||||
if list.is_empty() {
|
||||
println!("No route found");
|
||||
return;
|
||||
}
|
||||
let mut out_list = Vec::with_capacity(list.len());
|
||||
//表头
|
||||
out_list.push(vec!["Destination".to_string(), "Next Hop".to_string(), "Metric".to_string(),
|
||||
"Rt".to_string(), "Interface".to_string()]);
|
||||
for item in list {
|
||||
out_list.push(vec![item.destination, item.next_hop, item.metric,
|
||||
item.rt, item.interface]);
|
||||
}
|
||||
table::println_table(out_list)
|
||||
}
|
||||
|
||||
pub fn console_device_list(list: Vec<DeviceItem>) {
|
||||
if list.is_empty() {
|
||||
println!("No other devices found");
|
||||
return;
|
||||
}
|
||||
let mut out_list = Vec::with_capacity(list.len());
|
||||
//表头
|
||||
out_list.push(vec!["Name".to_string(), "Virtual Ip".to_string(), "P2P/Relay".to_string(), "Rt".to_string(), "Status".to_string()]);
|
||||
for item in list {
|
||||
out_list.push(vec![item.name, item.virtual_ip, item.nat_traversal_type,
|
||||
item.rt, item.status]);
|
||||
}
|
||||
table::println_table(out_list)
|
||||
}
|
||||
|
||||
pub fn console_device_list_all(list: Vec<DeviceItem>) {
|
||||
if list.is_empty() {
|
||||
println!("No other devices found");
|
||||
return;
|
||||
}
|
||||
let mut out_list = Vec::with_capacity(list.len());
|
||||
//表头
|
||||
out_list.push(vec!["Name".to_string(), "Virtual Ip".to_string(), "NAT Type".to_string(),
|
||||
"Public Ips".to_string(), "Local Ip".to_string(), "P2P/Relay".to_string(),
|
||||
"Rt".to_string(), "Status".to_string()]);
|
||||
for item in list {
|
||||
out_list.push(vec![item.name, item.virtual_ip, item.nat_type,
|
||||
item.public_ips, item.local_ip, item.nat_traversal_type,
|
||||
item.rt, item.status]);
|
||||
}
|
||||
table::println_table(out_list)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
const NODE: &str = "+";
|
||||
const EDGE: &str = "-";
|
||||
const HIGH: &str = "|";
|
||||
const SPACE: &str = " ";
|
||||
const EMPTY: &str = "";
|
||||
|
||||
pub fn println_table(table: Vec<Vec<String>>) {
|
||||
if table.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut width_list = vec![0; table[0].len()];
|
||||
for in_list in table.iter() {
|
||||
for (index, item) in in_list.iter().enumerate() {
|
||||
let width = console::measure_text_width(item)+6;
|
||||
if width_list[index] < width {
|
||||
width_list[index] = width;
|
||||
}
|
||||
}
|
||||
}
|
||||
for in_list in table {
|
||||
for (index, item) in in_list.iter().enumerate() {
|
||||
print!("{item:width$}", item = item, width = width_list[index]);
|
||||
}
|
||||
println!()
|
||||
}
|
||||
}
|
||||
+179
-189
@@ -1,104 +1,183 @@
|
||||
use std::io;
|
||||
use std::net::ToSocketAddrs;
|
||||
use std::net::{SocketAddr, ToSocketAddrs};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::Parser;
|
||||
use clap::{Parser, Subcommand};
|
||||
use console::style;
|
||||
use switch::core::{Config, Switch};
|
||||
use switch::handle::PeerDeviceStatus;
|
||||
use crate::config::log_config::{log_init, log_init_service};
|
||||
|
||||
use switch::handle::{PeerDeviceStatus, RouteType};
|
||||
use switch::*;
|
||||
|
||||
#[cfg(windows)]
|
||||
mod command;
|
||||
#[cfg(windows)]
|
||||
mod config;
|
||||
#[cfg(windows)]
|
||||
mod windows;
|
||||
|
||||
mod unix;
|
||||
mod console_out;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(
|
||||
author = "Lu Beilin",
|
||||
version,
|
||||
about = "一个虚拟网络工具,启动后会获取一个ip,相同token下的设备之间可以用ip直接通信"
|
||||
author = "Lu Beilin",
|
||||
version,
|
||||
about = "一个虚拟网络工具,启动后会获取一个ip,相同token下的设备之间可以用ip直接通信"
|
||||
)]
|
||||
struct Args {
|
||||
/// 32位字符
|
||||
pub struct BaseArgs {
|
||||
// /// 不超过64个字符
|
||||
// /// 相同token的设备之间才能通信。
|
||||
// /// 建议使用uuid保证唯一性。
|
||||
// /// No more than 64 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>,
|
||||
// /// 设备唯一标识,为空时默认使用MAC地址,不超过64个字符
|
||||
// /// Unique identification of the device. If it is blank, the MAC address is used by default. No more than 64 characters
|
||||
// #[arg(long)]
|
||||
// device_id: Option<String>,
|
||||
// /// 注册和中继服务器地址
|
||||
// /// Register and relay server address
|
||||
// #[arg(long)]
|
||||
// server: Option<String>,
|
||||
// /// NAT检测服务地址,使用逗号分隔
|
||||
// /// NAT detection service address. Use comma to separate
|
||||
// #[arg(long)]
|
||||
// nat_test_server: Option<String>,
|
||||
// /// 开机自启动
|
||||
// /// Software automatically start up at boot.
|
||||
// #[cfg(windows)]
|
||||
// #[arg(long)]
|
||||
// auto: bool,
|
||||
// #[arg(long)]
|
||||
// start: 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(subcommand)]
|
||||
// // start111: Option<StartArgs>,
|
||||
// #[arg(long)]
|
||||
// /// 停止,启动服务后,使用 --stop停止服务
|
||||
// /// Stop. After starting 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,
|
||||
// /// 启动服务后,使用 --route 查看所有路由
|
||||
// /// After starting the service, use -- route to View all routes
|
||||
// #[arg(long)]
|
||||
// route: bool,
|
||||
//
|
||||
// /// 安装服务,安装后可以后台运行,需要指定安装路径
|
||||
// /// The installation service can run in the background after installation, and the installation path needs to be specified
|
||||
// #[cfg(windows)]
|
||||
// #[arg(long)]
|
||||
// install: Option<String>,
|
||||
// /// 卸载服务
|
||||
// /// Uninstall service
|
||||
// #[cfg(windows)]
|
||||
// #[arg(long)]
|
||||
// uninstall: bool,
|
||||
#[clap(subcommand)]
|
||||
command: Commands,
|
||||
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
enum Commands {
|
||||
/// 启动
|
||||
Start(StartArgs),
|
||||
/// 停止后台服务
|
||||
Stop,
|
||||
/// 安装服务
|
||||
/// Install service
|
||||
#[cfg(windows)]
|
||||
Install(InstallArgs),
|
||||
/// 卸载服务
|
||||
/// Uninstall service
|
||||
#[cfg(windows)]
|
||||
Uninstall,
|
||||
/// 配置
|
||||
#[cfg(windows)]
|
||||
Config(ConfigArgs),
|
||||
/// 查看路由
|
||||
/// View route
|
||||
Route,
|
||||
/// 查看设备列表
|
||||
/// View device list
|
||||
List {
|
||||
/// 查看所有
|
||||
#[arg(short, long)]
|
||||
all: bool
|
||||
},
|
||||
/// 查看设备当前状态
|
||||
/// View the current status of the device
|
||||
Status,
|
||||
}
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
pub struct StartArgs {
|
||||
/// 不超过64个字符
|
||||
/// 相同token的设备之间才能通信。
|
||||
/// 建议使用uuid保证唯一性。
|
||||
/// 32-bit characters.
|
||||
/// No more than 64 characters
|
||||
/// Only devices with the same token can communicate with each other.
|
||||
/// It is recommended to use uuid to ensure uniqueness
|
||||
#[arg(long)]
|
||||
token: String,
|
||||
token: Option<String>,
|
||||
/// 给设备一个名称,为空时默认用系统版本信息
|
||||
/// Give the device a name. If it is blank, the system version information will be used by default
|
||||
#[arg(long)]
|
||||
#[arg(long, action)]
|
||||
name: Option<String>,
|
||||
/// 设备唯一标识,为空时默认使用MAC地址,不超过64个字符
|
||||
/// Unique identification of the device. If it is blank, the MAC address is used by default. No more than 64 characters
|
||||
#[arg(long)]
|
||||
device_id: Option<String>,
|
||||
/// 注册和中继服务器地址
|
||||
/// Register and relay server address
|
||||
#[arg(long)]
|
||||
server: Option<String>,
|
||||
/// NAT检测服务地址,使用逗号分隔
|
||||
/// NAT detection service address. Use comma to separate
|
||||
#[arg(long)]
|
||||
nat_test_server: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn log_init_service(home: PathBuf) -> io::Result<()> {
|
||||
if !home.exists() {
|
||||
std::fs::create_dir(&home)?;
|
||||
}
|
||||
let logfile = log4rs::append::file::FileAppender::builder()
|
||||
// Pattern: https://docs.rs/log4rs/*/log4rs/encode/pattern/index.html
|
||||
.encoder(Box::new(log4rs::encode::pattern::PatternEncoder::new(
|
||||
"{d(%+)(utc)} [{f}:{L}] {h({l})} {M}:{m}{n}\n",
|
||||
)))
|
||||
.build(home.join("switch-service.log"))?;
|
||||
match log4rs::Config::builder()
|
||||
.appender(log4rs::config::Appender::builder().build("logfile", Box::new(logfile)))
|
||||
.build(
|
||||
log4rs::config::Root::builder()
|
||||
.appender("logfile")
|
||||
.build(log::LevelFilter::Info),
|
||||
) {
|
||||
Ok(config) => {
|
||||
let _ = log4rs::init_config(config);
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
#[derive(Parser, Debug)]
|
||||
pub struct InstallArgs {
|
||||
/// 安装路径
|
||||
/// Service installation path
|
||||
#[arg(long)]
|
||||
path: String,
|
||||
/// 服务开机自启动
|
||||
/// Autostart on system startup
|
||||
#[arg(long)]
|
||||
auto: bool,
|
||||
}
|
||||
|
||||
fn log_init() -> io::Result<()> {
|
||||
let home = dirs::home_dir().unwrap().join(".switch");
|
||||
if !home.exists() {
|
||||
std::fs::create_dir(&home)?;
|
||||
}
|
||||
let stderr = log4rs::append::console::ConsoleAppender::builder()
|
||||
.target(log4rs::append::console::Target::Stderr)
|
||||
.build();
|
||||
let logfile = log4rs::append::file::FileAppender::builder()
|
||||
// Pattern: https://docs.rs/log4rs/*/log4rs/encode/pattern/index.html
|
||||
.encoder(Box::new(log4rs::encode::pattern::PatternEncoder::new(
|
||||
"{d(%+)(utc)} [{f}:{L}] {h({l})} {M}:{m}{n}\n",
|
||||
)))
|
||||
.build(home.join("switch.log"))?;
|
||||
match log4rs::Config::builder()
|
||||
.appender(log4rs::config::Appender::builder().build("logfile", Box::new(logfile)))
|
||||
.appender(
|
||||
log4rs::config::Appender::builder()
|
||||
.filter(Box::new(log4rs::filter::threshold::ThresholdFilter::new(
|
||||
log::LevelFilter::Error,
|
||||
)))
|
||||
.build("stderr", Box::new(stderr)),
|
||||
)
|
||||
.build(
|
||||
log4rs::config::Root::builder()
|
||||
.appender("logfile")
|
||||
.appender("stderr")
|
||||
.build(log::LevelFilter::Info),
|
||||
) {
|
||||
Ok(config) => {
|
||||
let _ = log4rs::init_config(config);
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
#[derive(Parser, Debug)]
|
||||
pub struct ConfigArgs {
|
||||
/// 服务开机自启动
|
||||
/// Autostart on system startup
|
||||
#[arg(long)]
|
||||
auto: bool,
|
||||
/// 取消服务开机自启动
|
||||
/// started manually
|
||||
#[arg(long)]
|
||||
not_auto: bool,
|
||||
}
|
||||
|
||||
|
||||
#[cfg(windows)]
|
||||
fn main() {
|
||||
let args: Vec<_> = std::env::args().collect();
|
||||
@@ -111,10 +190,12 @@ fn main() {
|
||||
windows::service::start();
|
||||
return;
|
||||
} else {
|
||||
let home = dirs::home_dir().unwrap().join(".switch");
|
||||
config::set_home(home);
|
||||
let _ = log_init();
|
||||
windows::main0();
|
||||
let args = BaseArgs::parse();
|
||||
windows::main0(args);
|
||||
}
|
||||
// println!("{}", style("starting...").green());
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
@@ -132,50 +213,16 @@ fn main() {
|
||||
start(args.token, args.name);
|
||||
}
|
||||
|
||||
pub fn start(token: String, name: Option<String>) {
|
||||
let mac_address = mac_address::get_mac_address().unwrap().unwrap().to_string();
|
||||
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(),
|
||||
];
|
||||
let switch = match Config::new(
|
||||
pub fn start(token: String, name: String, server_address: SocketAddr, nat_test_server: Vec<SocketAddr>, device_id: String) {
|
||||
let config = Config::new(
|
||||
token,
|
||||
mac_address,
|
||||
device_id,
|
||||
name,
|
||||
server_address,
|
||||
nat_test_server,
|
||||
|| {},
|
||||
) {
|
||||
Ok(config) => match Switch::start(config) {
|
||||
Ok(switch) => switch,
|
||||
Err(e) => {
|
||||
log::error!("{:?}", e);
|
||||
return;
|
||||
}
|
||||
},
|
||||
);
|
||||
let switch = match Switch::start(config) {
|
||||
Ok(switch) => switch,
|
||||
Err(e) => {
|
||||
log::error!("{:?}", e);
|
||||
return;
|
||||
@@ -187,11 +234,11 @@ pub fn start(token: String, name: Option<String>) {
|
||||
let current_device = switch.current_device();
|
||||
println!(
|
||||
"当前虚拟ip(virtual ip): {:?}",
|
||||
style(current_device.virtual_ip).green()
|
||||
style(current_device.virtual_ip()).green()
|
||||
);
|
||||
println!(
|
||||
"虚拟网关(virtual gateway): {:?}",
|
||||
style(current_device.virtual_gateway).green()
|
||||
style(current_device.virtual_gateway()).green()
|
||||
);
|
||||
loop {
|
||||
println!(
|
||||
@@ -202,14 +249,18 @@ pub fn start(token: String, name: Option<String>) {
|
||||
Ok(cmd) => {
|
||||
if command(cmd.trim(), &switch).is_err() {
|
||||
println!("{}", style("stopping").red());
|
||||
switch.stop();
|
||||
if let Err(e) = switch.stop() {
|
||||
println!("stop:{:?}", e);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!("read_line:{:?}", e);
|
||||
println!("{}", style("stopping...").red());
|
||||
switch.stop();
|
||||
if let Err(e) = switch.stop() {
|
||||
println!("stop:{:?}", e);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -218,81 +269,20 @@ pub fn start(token: String, name: Option<String>) {
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
|
||||
fn command(cmd: &str, switch: &Switch) -> Result<(), ()> {
|
||||
match cmd {
|
||||
"route" => {
|
||||
let list = command::server::command_route(switch);
|
||||
console_out::console_route_table(list);
|
||||
}
|
||||
"list" => {
|
||||
let server_rt = switch.server_rt();
|
||||
let device_list = switch.device_list();
|
||||
if device_list.is_empty() {
|
||||
println!("No other devices found");
|
||||
return Ok(());
|
||||
}
|
||||
for peer_device_info in device_list {
|
||||
let route = switch.route(&peer_device_info.virtual_ip);
|
||||
if peer_device_info.status == PeerDeviceStatus::Online {
|
||||
if route.route_type == RouteType::P2P {
|
||||
let str = if route.rt >= 0 {
|
||||
format!(
|
||||
"[{}] {}(p2p delay:{}ms)",
|
||||
peer_device_info.name, peer_device_info.virtual_ip, route.rt
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"[{}] {}(p2p)",
|
||||
peer_device_info.name, peer_device_info.virtual_ip
|
||||
)
|
||||
};
|
||||
println!("{}", style(str).green());
|
||||
} else {
|
||||
let str = if server_rt >= 0 {
|
||||
format!(
|
||||
"[{}] {}(relay delay:{}ms)",
|
||||
peer_device_info.name,
|
||||
peer_device_info.virtual_ip,
|
||||
server_rt * 2
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"[{}] {}(relay)",
|
||||
peer_device_info.name, peer_device_info.virtual_ip
|
||||
)
|
||||
};
|
||||
println!("{}", style(str).blue());
|
||||
}
|
||||
} else {
|
||||
let str = format!(
|
||||
"[{}] {}(Offline)",
|
||||
peer_device_info.name, peer_device_info.virtual_ip
|
||||
);
|
||||
println!("{}", style(str).red());
|
||||
}
|
||||
}
|
||||
let list = command::server::command_list(switch);
|
||||
console_out::console_device_list(list);
|
||||
}
|
||||
"status" => {
|
||||
let server_rt = switch.server_rt();
|
||||
let current_device = switch.current_device();
|
||||
println!("Virtual ip:{}", style(current_device.virtual_ip).green());
|
||||
println!(
|
||||
"Virtual gateway:{}",
|
||||
style(current_device.virtual_gateway).green()
|
||||
);
|
||||
println!(
|
||||
"Connection status :{}",
|
||||
style(format!("{:?}", switch.connection_status())).green()
|
||||
);
|
||||
println!(
|
||||
"Relay server :{}",
|
||||
style(current_device.connect_server).green()
|
||||
);
|
||||
if server_rt >= 0 {
|
||||
println!("Delay of relay server :{}ms", style(server_rt).green());
|
||||
}
|
||||
if let Some(nat_info) = switch.nat_info() {
|
||||
println!(
|
||||
"NAT type :{}",
|
||||
style(format!("{:?}", nat_info.nat_type)).green()
|
||||
);
|
||||
}
|
||||
let status = command::server::command_status(switch);
|
||||
console_out::console_status(status);
|
||||
}
|
||||
"help" | "h" => {
|
||||
println!("Options: ");
|
||||
|
||||
+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