Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions admin-web/src/view/node/NodeDetailPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ export function RelayConfigView({hide}: {hide:boolean}) {
const postUpTooltip =(
<>
<p>This command run after node up, it normally used for config os to allow ForNet redirect network packages. The command would be:</p>
<p style={{fontStyle:'italic'}}>iptables -A FORWARD -i for0 -j ACCEPT; iptables -A FORWARD -o for0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE</p>
<p style={{fontStyle:'italic'}} dangerouslySetInnerHTML={{__html:'iptables -A FORWARD -i {tun} -j ACCEPT; iptables -A FORWARD -o {tun} -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE'}}></p>
<p>(Please remember to change <span style={{fontWeight:'bold'}}>eth0</span> to correct ethernet interface)</p>
</>
)
const postDownToolTip = (
<>
<p>This command run after node down, it normally used for config OS to remove ForNet postUp command effects. The command would be:</p>
<p style={{fontStyle:'italic'}}>iptables -D FORWARD -i for0 -j ACCEPT; iptables -D FORWARD -o for0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE</p>
<p style={{fontStyle:'italic'}} dangerouslySetInnerHTML={{__html: 'iptables -D FORWARD -i {tun} -j ACCEPT; iptables -D FORWARD -o {tun} -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE'}}></p>
<p>(Please remember to change <span style={{fontWeight:'bold'}}>eth0</span> to correct ethernet interface)</p>

</>
Expand Down
11 changes: 11 additions & 0 deletions client/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions client/lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ serde = { version = "1.0.144", features = ["derive"] }
serde_derive = "1.0.144"
serde_json = "1.0.85"
reqwest = { version = "0.11", features = ["json", "blocking"]}
new_string_template = "1.4.0"

dirs = "4.0.0"

Expand Down
6 changes: 2 additions & 4 deletions client/lib/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,8 @@ pub async fn api_handler(server_manager: &mut ServerManager, command: String, st
}
}
"list" => {
if server_manager.wr_manager.is_alive() {
let data = server_manager.wr_manager.device_info();
let _ = stream.write(ApiResponse::boxed(data).to_json().as_bytes()).await;
}
let data = server_manager.wr_manager.device_info();
let _ = stream.write(ApiResponse::boxed(data).to_json().as_bytes()).await;
}
"autoLaunch" => {
cfg_if! {
Expand Down
6 changes: 4 additions & 2 deletions client/lib/src/device/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ use allowed_ips::AllowedIps;
use peer::{AllowedIP, Peer};
use script_run::Scripts;
use crate::device::peer::TcpConnection;
use crate::device::script_run::run_opt_script;
use crate::device::script_run::{run_opt_script, run_opt_script_with_param};
use crate::protobuf::config::NodeType;
use self::tun::WritePart;

Expand Down Expand Up @@ -232,7 +232,9 @@ impl DeviceData {

impl Drop for DeviceData {
fn drop(&mut self) {
let _ = run_opt_script(&self.scripts.post_down);
let mut script_param:HashMap<&str, String> = HashMap::new();
script_param.insert("tun", self.name.clone());
let _ = run_opt_script_with_param(&self.scripts.post_down , &script_param);
}
}

Expand Down
18 changes: 18 additions & 0 deletions client/lib/src/device/script_run.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::collections::HashMap;
use new_string_template::template::Template;
use shell_candy::{ShellTask, ShellTaskBehavior, ShellTaskLog};
use crate::protobuf::config::Interface;

Expand All @@ -19,6 +21,22 @@ impl Scripts {
}
}
}
pub fn run_opt_script_with_param(script:&Option<String>, params:&HashMap<&str,String>) -> shell_candy::Result<Option<()>> {
if let Some(ref script) = script {
let templ = Template::new(script);
match templ.render(params) {
Ok(rendered_script) => {
Ok(Some(run_script(&rendered_script)?))
}
Err(e) => {
tracing::warn!("script: {script} render err: {e}");
Ok(None)
}
}
} else {
Ok(None)
}
}
//TODO: add log and handle if this would block.
pub fn run_opt_script(script:&Option<String>) -> shell_candy::Result<Option<()>> {
if let Some(ref script) = script {
Expand Down
12 changes: 8 additions & 4 deletions client/lib/src/device/unix_device.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
use std::time::Duration;
Expand All @@ -10,7 +11,7 @@ use tokio::task::JoinHandle;
use crate::device;
use crate::device::{DeviceData, Peers, HANDSHAKE_RATE_LIMIT, MAX_UDP_SIZE};
use crate::device::peer::AllowedIP;
use crate::device::script_run::{run_opt_script, Scripts};
use crate::device::script_run::{run_opt_script, run_opt_script_with_param, Scripts};
use crate::device::tun::create_async_tun;
use crate::device::tunnel::{create_tcp_server, create_udp_socket};
use nix::unistd::Uid;
Expand Down Expand Up @@ -126,9 +127,10 @@ impl Device {
protocol,
};

//run_opt_script(&Some("iptables -A FORWARD -i for0 -j ACCEPT".to_owned()))?;

run_opt_script(&device.scripts.post_up)?;
let mut script_params:HashMap<&str, String> = HashMap::new();
script_params.insert("tun", device.name.clone());
run_opt_script_with_param(&device.scripts.post_up, &script_params)?;
Ok(device)
}

Expand Down Expand Up @@ -157,7 +159,9 @@ impl DerefMut for Device {

impl Drop for Device {
fn drop(&mut self) {
self.task.abort();
if !self.task.is_finished() {
self.task.abort();
}
tracing::debug!("device has been dropped");
}
}
Expand Down
2 changes: 1 addition & 1 deletion client/lib/src/sc_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ impl <'a> AsyncEventHandler for MqttWrapper<'a> {
if let Some(info) = network_message.info {
match info {
Peer(peer_change) => {
let _ = self.sender.send(ServerMessage::SyncPeers(peer_change)).await;
let _ = self.sender.send(ServerMessage::SyncPeers(network_message.network_id.clone(), peer_change)).await;
}
NStatus(status) => {
if let Some(NetworkStatus::NetworkDelete) = NetworkStatus::from_i32(status) {
Expand Down
11 changes: 7 additions & 4 deletions client/lib/src/server_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ impl ServerManager {
let _ = server_config.save_config(&config.config_path);
}
}
server_manager.wr_manager.close().await;
server_manager.wr_manager.close(&network_id).await;
}
ServerMessage::SyncConfig(network_token_id,wr_config) => {
if let Some(config) = &server_manager.config {
Expand All @@ -94,12 +94,13 @@ impl ServerManager {
.unwrap_or_else(|e| panic!("wr_manager start tun error,{:?}", e));
}
}
ServerMessage::SyncPeers(peer_change_message) => {
ServerMessage::SyncPeers(network_token_id, peer_change_message) => {

if let Some(public_key) = peer_change_message.remove_public_key {
if server_manager.config.as_ref().map(|x|x.identity.pk_base64 != public_key).unwrap_or(true) {
match Identity::get_pub_identity_from_base64(&public_key) {
Ok((x_pub_key, _)) => {
server_manager.wr_manager.remove_peer(&x_pub_key).await;
server_manager.wr_manager.remove_peer(&network_token_id, &x_pub_key).await;
}
Err(_) => {
tracing::warn!("peer identity parse error")
Expand All @@ -113,6 +114,7 @@ impl ServerManager {
let endpoint = peer.endpoint.map(|endpoint| endpoint.parse::<SocketAddr>().unwrap());
let (x_pub_key,_) = Identity::get_pub_identity_from_base64(&peer.public_key).unwrap();
server_manager.wr_manager.add_peer(
&network_token_id,
x_pub_key,
endpoint,
&allowed_ip,
Expand All @@ -127,6 +129,7 @@ impl ServerManager {
let endpoint = peer.endpoint.map(|endpoint| endpoint.parse::<SocketAddr>().unwrap());
let (x_pub_key,_) = Identity::get_pub_identity_from_base64(&peer.public_key).unwrap();
server_manager.wr_manager.add_peer(
&network_token_id,
x_pub_key,
endpoint,
&allowed_ip,
Expand All @@ -152,6 +155,6 @@ impl ServerManager {
pub enum ServerMessage {
// NodeStatus::Normal => start WireGuard, other => stop WireGuard
StopWR{network_id:String,reason:String, delete_tun:bool},
SyncPeers(crate::protobuf::config::PeerChange),
SyncPeers(String, crate::protobuf::config::PeerChange),
SyncConfig(String, WrConfig),
}
47 changes: 25 additions & 22 deletions client/lib/src/wr_manager.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
use std::str::FromStr;
use std::time::Duration;
Expand All @@ -12,31 +13,32 @@ use crate::device::script_run::Scripts;
//WireGuard Manager
// rewrite boring/Device, mainly change thread pool to tokio.
pub struct WRManager {
device: Option<Device>,
devices: HashMap<String, Device>,
}

impl WRManager {
pub fn new() -> Self {
WRManager {
device: None,
devices: HashMap::new(),
}
}

pub async fn remove_peer(&mut self, public_key: &x25519_dalek::PublicKey) {
if let Some(device) = &mut self.device {
pub async fn remove_peer(&mut self, network_token_id:&str ,public_key: &x25519_dalek::PublicKey) {
if let Some(device) = self.devices.get_mut(network_token_id) {
device.remove_peer(public_key).await;
} else {
tracing::warn!("there's no active device when remove peer")
tracing::warn!("there's no active device in {network_token_id} when remove peer")
}
}

pub async fn add_peer(&mut self,
network_token_id:&str,
pub_key: x25519_dalek::PublicKey,
endpoint: Option<SocketAddr>,
allowed_ips: &[AllowedIP],
ip:IpAddr,
keepalive: Option<u16>) {
if let Some(device) = &mut self.device {
if let Some(device) = &mut self.devices.get_mut(network_token_id) {
device.update_peer(
pub_key,
false,
Expand Down Expand Up @@ -64,12 +66,12 @@ impl WRManager {
//TODO: check if need restart
// if interface not equal, restart
// check peers, remove or add new ones.
let has_alive = self.is_alive();
let has_alive = self.is_alive(&network_token_id);
if has_alive {
let node_type = self.device.as_ref().map(|x|x.node_type).unwrap_or(NodeType::NodeClient);
tracing::info!("close device");
self.close().await;
let sleep_time = if node_type == NodeType::NodeRelay {10} else {20};
let node_type = self.devices.get(&network_token_id).map(|x|x.node_type).unwrap_or(NodeType::NodeClient);
tracing::info!("close {} device", network_token_id);
self.close(&network_token_id).await;
let sleep_time = if node_type == NodeType::NodeRelay {10} else {20};
tokio::time::sleep(Duration::from_secs(sleep_time)).await;
}

Expand Down Expand Up @@ -107,7 +109,7 @@ impl WRManager {
} else {
server_config.info.push(NetworkInfo {
tun_name: Some(wr_interface.name.clone()),
network_id: network_token_id
network_id: network_token_id.clone()
});
need_save = true;
}
Expand All @@ -117,13 +119,14 @@ impl WRManager {
}
}

self.device = Some(wr_interface);
self.devices.insert(network_token_id.clone(),wr_interface);
for peer in wr_config.peers {
let (x_pub_key,_) = Identity::get_pub_identity_from_base64(&peer.public_key)?;
let endpoint = peer.endpoint.map(|v| SocketAddr::from_str(&v).unwrap());
let allowed_ip:Vec<AllowedIP> = peer.allowed_ip.into_iter().map(|ip| AllowedIP::from_str(&ip).unwrap()).collect();
let ip:IpAddr = peer.address.first().unwrap().parse().unwrap();
self.add_peer(
&network_token_id,
x_pub_key,
endpoint,
allowed_ip.as_slice(),
Expand All @@ -135,20 +138,20 @@ impl WRManager {
Ok(())
}

pub fn is_alive(&self) -> bool { self.device.is_some() }
pub fn is_alive(&self, network_token_id:&str) -> bool { self.devices.contains_key(network_token_id) }

pub async fn close(&mut self) {
if let Some(ref mut device) = self.device.take() {
device.close().await
pub async fn close(&mut self, network_token_id:&str) {
if let Some(device) = self.devices.get_mut(network_token_id) {
device.close().await;
self.devices.remove(network_token_id);
}

}

pub fn device_info(&self) -> Vec<DeviceInfoResp> {
self.device.as_ref().map_or(vec![], |device| {
vec![DeviceInfoResp {
name: device.name.clone()
}]
})
self.devices.values().map(|device| DeviceInfoResp {
name: device.name.clone()
}).collect()
}
}

Expand Down