Compare commits

..

No commits in common. "6537049e716f12630eea3d1110fefdfb7180b5b5" and "51c323008a0f70422bea7e884ad981188ba786a7" have entirely different histories.

38 changed files with 638 additions and 1550 deletions

13
.cargo/config.toml Executable file → Normal file
View File

@ -1,11 +1,2 @@
[target.aarch64-unknown-linux-gnu]
linker = "aarch64-linux-gnu-gcc"
ar = "aarch64-linux-gnu-gcc"
strip = { path = "aarch64-linux-gnu-strip" }
# ranlib = "aarch64-linux-gnu-ranlib"
[target.x86_64-pc-windows-gnu]
linker = "x86_64-w64-mingw32-gcc"
# [build]
# target = "x86_64-unknown-linux-gnu"
[target.x86_64-unknown-linux-musl]
linker = "x86_64-linux-musl-gcc"

1
.gitignore vendored Executable file → Normal file
View File

@ -11,4 +11,3 @@ sdlan.exe
*.tar
*.tar.gz
*.tgz
/punchnet

1519
Cargo.lock generated Executable file → Normal file

File diff suppressed because it is too large Load Diff

34
Cargo.toml Executable file → Normal file
View File

@ -1,6 +1,6 @@
[package]
name = "punchnet"
version = "1.0.0"
name = "sdlan-rs"
version = "0.1.0"
edition = "2021"
[dependencies]
@ -17,41 +17,15 @@ prost = "0.12.6"
prost-build = "0.12.6"
rand = "0.8.5"
rsa = "0.9.6"
sdlan-sn-rs = { git = "ssh://git@git2.asxalex.pw/sdlan-v2/sdlan-rs.git" }
# sdlan-sn-rs = {path = "../sdlan-rs"}
sdlan-sn-rs = { git = "ssh://git@git.asxalex.pw/sdlan-v2/sdlan-rs.git" }
# sdlan-sn-rs = { git = "https://git.asxalex.pw/sdlan-v2/sdlan-rs.git" }
structopt = "0.3.26"
tokio = { version = "1.38.0", features = ["full"] }
tokio-util = "0.7.11"
tracing = "0.1.40"
# rolling-file = { path = "../rolling-file" }
[target.'cfg(windows)'.dependencies]
wintun = "0.4.0"
[features]
tun = []
[build-dependencies]
cargo-deb = "3.6.2"
[package.metadata.deb]
maintainer = "alex <asxalex@163.com>"
copyright = "2025, alex"
# license-file = ["MIT"]
depends = "$auto"
## assets
assets = [
## libs and exxcutables
["target/release/punchnet", "usr/local/", "755"],
["assets/yolov5", "usr/bin/dump-rtsp-jpg", "755"],
["assets/libswscale.so.5.7.100", "usr/lib/libswscale.so.5.7.100", "755"],
# ["usr/lib/libswscale.so.5", "usr/lib/libswscale.so.5.7.100", "symlink"]
# ["usr/lib/libswscale.so", "usr/lib/libswscale.so.5.7.100", "symlink"]
]
maintainer-scripts = "debian"
systemd-units = [
{ unit-name = "sys-op-api", enable = true }
]
tap = []

27
Makefile Executable file → Normal file
View File

@ -1,18 +1,14 @@
self:
RUSTFLAGS="-L ." cargo build --release
RUSTFLAGS="-L ." cargo build --features "tap" --release
linux:
RUSTFLAGS="-L ." cargo build --release --target x86_64-unknown-linux-musl
aarch64:
RUSTFLAGS="-L ." cargo build --release --target aarch64-unknown-linux-gnu
RUSTFLAGS="-L ." cargo build --features "tap" --release --target x86_64-unknown-linux-musl
linux-tun:
RUSTFLAGS="-L ." cargo build --features "tun" --release
RUSTFLAGS="-L ." cargo build --release
win:
cargo build --release --target x86_64-pc-windows-gnu
cargo build --release
pb:
cargo run --bin build_pb
@ -22,16 +18,7 @@ libtun-so-clang:
cd src/network && clang -fPIC -shared -o libtuntap.so tuntap.c && cd -
libtun-so:
cd src/network && gcc -fPIC -shared -o libtuntap.so tuntap.c && cp libtuntap.so ../.. && cd -
cd src/network && gcc -fPIC -shared -o libtuntap.so tuntap.c && cd -
libtun-aarch64-so:
cd src/network && aarch64-linux-gnu-gcc -fPIC -shared -o libtuntap_aarch64.so tuntap.c && cp libtuntap_aarch64.so ../../libtuntap.so && cd -
pack:
tar -czvf punchnet.tar.gz punchnet punchnet.service libtuntap.so install.sh
deb-aarch64: libtun-aarch64-so
cargo deb --target aarch64-unknown-linux-gnu
deb: libtun-so
cargo deb
libtun-a:
cd src/network && gcc -c tuntap.c && ar rcs libtuntap.a tuntap.o && cd -

View File

@ -1,13 +0,0 @@
uid=`id -u`
if [ "$uid" != "0" ]; then
echo "need to be root"
exit -1
fi
mkdir -p /usr/local/punchnet
cp punchnet /usr/local/punchnet
cp libtuntap.so /usr/lib/
cp punchnet.service /etc/systemd/system
systemctl enable punchnet
systemctl start punchnet

View File

@ -15,7 +15,7 @@ message SDLV6Info {
//
message SDLDevAddr {
string network_id = 1;
uint32 network_id = 1;
bytes mac = 2;
uint32 net_addr = 3;
uint32 net_bit_len = 4;
@ -33,7 +33,6 @@ message SDLRegisterSuper {
SDLDevAddr dev_addr = 4;
string pub_key = 5;
string token = 6;
string network_id = 7;
}
message SDLRegisterSuperAck {
@ -107,7 +106,7 @@ message SDLFlows {
message SDLStunRequest {
uint32 cookie = 1;
string client_id = 2;
string network_id = 3;
uint32 network_id = 3;
bytes mac = 4;
uint32 ip = 5;
uint32 nat_type = 6;
@ -119,7 +118,7 @@ message SDLStunReply {
}
message SDLData {
string network_id = 1;
uint32 network_id = 1;
bytes src_mac = 2;
bytes dst_mac = 3;
bool is_p2p = 4;
@ -128,13 +127,13 @@ message SDLData {
}
message SDLRegister {
string network_id = 1;
uint32 network_id = 1;
bytes src_mac = 2;
bytes dst_mac = 3;
}
message SDLRegisterAck {
string network_id = 1;
uint32 network_id = 1;
bytes src_mac = 2;
bytes dst_mac = 3;
}

0
nat-simulator.sh Executable file → Normal file
View File

View File

@ -1,12 +0,0 @@
[Unit]
Description=punchnet client
Before=network.target network.service
Wants=network.target
[Service]
Type=simple
WorkingDirectory=/usr/local/punchnet
ExecStart=/usr/local/punchnet/punchnet
[Install]
WantedBy=multi-user.target

View File

@ -1,4 +0,0 @@
origin git@git.asxalex.pw:rust/sdlan-lib-rs.git (fetch)
origin git@git.asxalex.pw:rust/sdlan-lib-rs.git (push)
origin2 http://101.43.184.190:3000/xlf/sdlan-lib-rs.git (fetch)
origin2 http://101.43.184.190:3000/xlf/sdlan-lib-rs.git (push)

0
run.sh Executable file → Normal file
View File

0
src/bin/build_pb/main.rs Executable file → Normal file
View File

37
src/bin/punchnet/main.rs → src/bin/sdlan/main.rs Executable file → Normal file
View File

@ -1,58 +1,41 @@
use punchnet::get_edge;
use punchnet::run_sdlan;
use punchnet::CommandLine;
use punchnet::CommandLineInput;
use sdlan_rs::get_edge;
use sdlan_rs::run_sdlan;
use sdlan_rs::CommandLine;
use sdlan_rs::CommandLineInput;
use sdlan_sn_rs::log;
use tracing::error;
use std::process::exit;
use std::time::Duration;
use structopt::StructOpt;
#[tokio::main]
async fn main() {
// let _guard = rolling_file::new_log(
// "./.output",
// 7,
// rolling_file::PeriodGap::Daily,
// tracing::Level::DEBUG,
// true,
// true,
// );
let _guard = log::init_log();
let cmd = CommandLineInput::from_args();
if cmd.token.is_empty() && cmd.user_network_id.is_empty() {
eprintln!("[ERROR] no token or network_id is specifed. \n\ttry \"punchnet --help\" for detailed usage");
exit(-1);
// error!("no token or network_id is specified");
// exit(-1);
}
// println!("port is {}", cmd.port);
println!("port is {}", cmd.port);
let (tx, rx) = std::sync::mpsc::channel();
let server = "punchnet.aioe.tech".to_owned();
let _ = run_sdlan(
CommandLine {
sn: server.clone()+":1265",
tcp: server.clone()+":18083",
nat_server1: server.clone() +":1265",
sn: "39.98.184.67:1265".to_owned(),
tcp: "39.98.184.67:18083".to_owned(),
nat_server1: "39.98.184.67:1265".to_owned(),
nat_server2: "47.98.178.3:1265".to_owned(),
_allow_routing: true,
_drop_multicast: true,
register_ttl: 1,
mtu: 1400,
mtu: 1290,
name: "tau".to_owned(),
tos: 0,
local_port: cmd.port,
token: "test-token".to_owned(),
user_network_id: cmd.user_network_id,
allow_p2p: true,
},
tx,
&punchnet::get_install_channel(),
&sdlan_rs::get_install_channel(),
None,
)
.await;

0
src/config/mod.rs Executable file → Normal file
View File

11
src/lib.rs Executable file → Normal file
View File

@ -43,16 +43,7 @@ pub async fn run_sdlan(
init_arp();
if let Err(e) = init_edge(
&args.token,
&args.user_network_id,
node_conf,
args.tos,
start_stop_sender,
args.mtu,
)
.await
{
if let Err(e) = init_edge(&args.token, node_conf, args.tos, start_stop_sender).await {
panic!("failed to init edge: {:?}", e);
}
let _ = sender.send(true);

0
src/network/arp.rs Executable file → Normal file
View File

33
src/network/async_main.rs Executable file → Normal file
View File

@ -18,7 +18,7 @@ use crate::ConnectionState;
use sdlan_sn_rs::config::AF_INET;
use sdlan_sn_rs::peer::{SdlanSock, V6Info};
use sdlan_sn_rs::utils::{get_current_timestamp, ip_to_string, is_multi_broadcast, rsa_decrypt};
use sdlan_sn_rs::utils::{Mac, Result, gen_rsa_keys};
use sdlan_sn_rs::utils::{Mac, Result};
use tokio::io::AsyncWriteExt;
use tokio::sync::mpsc::{channel, Receiver, Sender};
use tokio_util::sync::CancellationToken;
@ -61,7 +61,7 @@ async fn handle_tcp_message(msg: SdlanTcp) {
};
let ip = ip_to_string(&dev.net_addr);
// debug!("aes key is {:?}, ip is {}/{}", aes, ip, dev.net_bit_len,);
debug!("aes key is {:?}, ip is {}/{}", aes, ip, dev.net_bit_len,);
println!("assigned ip: {}", ip);
edge.device_config
.ip
@ -79,14 +79,13 @@ async fn handle_tcp_message(msg: SdlanTcp) {
.net_bit_len
.store(dev.net_bit_len as u8, Ordering::Relaxed);
edge.device.reload_config(&edge.device_config);
*edge.network_id.lock().unwrap() = dev.network_id;
// edge.network_id.store(dev.network_id, Ordering::Relaxed);
edge.network_id.store(dev.network_id, Ordering::Relaxed);
edge.set_authorized(true, aes);
send_stun_request(edge).await;
tokio::spawn(async {
let nattype = edge.probe_nat_type().await;
// println!("nat type is: {:?}", nattype);
println!("nat type is: {:?}", nattype);
});
}
PacketType::RegisterSuperNAK => {
@ -252,7 +251,7 @@ pub async fn async_main(
// let _ = PidRecorder::new(".pid");
// // gen public key
gen_rsa_keys(".client");
// gen_rsa_keys(".client");
// let mut pubkey = String::new();
// File::open(".client/id_rsa.pub")?.read_to_string(&mut pubkey)?;
// let privatekey = load_private_key_file(".client/id_rsa")?;
@ -291,7 +290,6 @@ pub async fn async_main(
let installed_channel = install_channel.to_owned();
Box::pin(async move {
let token = edge._token.lock().unwrap().clone();
let networkid = edge.network_id.lock().unwrap().clone();
// let edge = get_edge();
// let edge = get_edge();
// let token = args.token.clone();
@ -312,12 +310,11 @@ pub async fn async_main(
dev_addr: Some(SdlDevAddr {
mac: Vec::from(edge.device_config.get_mac()),
net_addr: 0,
network_id: "".to_owned(),
network_id: 0,
net_bit_len: 0,
}),
pub_key: edge.rsa_pubkey.clone(),
token,
network_id: networkid,
};
// debug!("send register super: {:?}", register_super);
let packet_id = match pkt_id {
@ -451,8 +448,7 @@ async fn send_stun_request(eee: &Node) {
let req = SdlStunRequest {
cookie: 0,
client_id: eee.config.node_uuid.clone(),
network_id: eee.network_id.lock().unwrap().clone(),
// network_id: eee.network_id.load(Ordering::Relaxed),
network_id: eee.network_id.load(Ordering::Relaxed),
ip: eee.device_config.get_ip(),
mac: Vec::from(eee.device_config.get_mac()),
nat_type: eee.get_nat_type() as u32,
@ -559,7 +555,7 @@ async fn loop_tap(eee: &'static Node, cancel: CancellationToken) {
async fn get_tun_flow(eee: &'static Node, tx: Sender<Vec<u8>>) {
loop {
let buf = tokio::task::spawn_blocking(|| {
let mut buf = vec![0; 1500];
let mut buf = vec![0; 1800];
let Ok(size) = eee.device.recv(&mut buf) else {
return vec![];
};
@ -640,32 +636,25 @@ async fn find_peer_destination(eee: &'static Node, dst_mac: Mac) -> (SdlanSock,
}
let mut is_p2p = false;
let result: SdlanSock;
let mut need_delete_from_known_peers = false;
if let Some(dst) = eee.known_peers.peers.get_mut(&dst_mac) {
if let Some(dst) = eee.known_peers.get_peer(&dst_mac) {
let now = get_current_timestamp();
if now - dst.last_p2p.load(Ordering::Relaxed) >= ((dst.timeout / 2) as u64) {
// too much time elapsed since we saw the peer, need to register again
error!("last p2p is too old, deleting from known_peers");
need_delete_from_known_peers = true;
// eee.known_peers.delete_peer_with_mac(&dst_mac);
debug!("deleted from known");
eee.known_peers.delete_peer_with_mac(&dst_mac);
result = eee.config.super_nodes
[eee.config.super_node_index.load(Ordering::Relaxed) as usize]
.deepcopy();
} else {
// dst.last_seen.store(now, Ordering::Relaxed);
is_p2p = true;
result = dst.sock.deepcopy();
result = dst.sock.read().unwrap().deepcopy();
}
} else {
result = eee.config.super_nodes
[eee.config.super_node_index.load(Ordering::Relaxed) as usize]
.deepcopy();
}
if need_delete_from_known_peers {
eee.known_peers.delete_peer_with_mac(&dst_mac);
}
// println!("find peer_destination: {}", is_p2p);
if !is_p2p {
debug!("check_query_peer_info");

4
src/network/device.rs Executable file → Normal file
View File

@ -7,18 +7,16 @@ use tracing::debug;
use crate::utils::generate_mac_address;
pub struct DeviceConfig {
pub mtu: u32,
pub mac: RwLock<Mac>,
pub ip: IpSubnet,
}
impl DeviceConfig {
pub fn new(mtu: u32) -> Self {
pub fn new() -> Self {
let mac = generate_mac_address();
println!("self mac: {}", mac_to_string(&mac));
debug!("self mac: {}", mac_to_string(&mac));
DeviceConfig {
mtu,
mac: RwLock::new(mac),
ip: IpSubnet::new(0, 0),
}

2
src/network/ipv6.rs Executable file → Normal file
View File

@ -76,7 +76,7 @@ pub fn get_current_ipv6() -> Option<Ipv6Addr> {
}
IpAddr::V6(ipv6) => {
if ipv6.octets()[0] & 0x70 == 0x20 {
// println!("got global ip: {}", ipv6);
println!("got global ip: {}", ipv6);
return Some(ipv6);
}
}

0
src/network/mod.rs Executable file → Normal file
View File

87
src/network/node.rs Executable file → Normal file
View File

@ -8,6 +8,7 @@ use std::time::Duration;
use tokio::io::AsyncReadExt;
use tokio::sync::mpsc::Sender;
use tokio::sync::oneshot;
use tokio::time::error::Elapsed;
use tracing::{debug, error};
use crate::pb::{
@ -16,7 +17,7 @@ use crate::pb::{
use crate::tcp::{get_tcp_conn, NatType, PacketType, StunProbeAttr};
use crate::utils::{PidRecorder, Socket};
use sdlan_sn_rs::peer::{IpSubnet, V6Info};
use sdlan_sn_rs::peer::{is_sdlan_sock_equal, IpSubnet, V6Info};
use once_cell::sync::OnceCell;
@ -31,11 +32,9 @@ static EDGE: OnceCell<Node> = OnceCell::new();
pub async fn init_edge(
token: &str,
user_network_id: &str,
node_conf: NodeConfig,
tos: u32,
start_stop: Sender<StartStopInfo>,
mtu: u32,
) -> Result<()> {
let _ = PidRecorder::new(".pid");
@ -73,11 +72,9 @@ pub async fn init_edge(
sock_v4,
sock_multicast,
token,
user_network_id,
privatekey,
tcp_pong.clone(),
start_stop,
mtu,
);
do_init_edge(edge)?;
@ -114,7 +111,7 @@ pub struct StartStopInfo {
pub struct Node {
packet_id: AtomicU32,
pub network_id: Mutex<String>,
pub network_id: AtomicU32,
pub tcp_pong: Arc<AtomicU64>,
@ -122,7 +119,6 @@ pub struct Node {
// user token info
pub _token: Mutex<String>,
pub _user_network_id: String,
pub device_config: DeviceConfig,
pub device: Iface,
@ -248,14 +244,11 @@ impl Node {
multicast_sock: Option<Socket>,
// tcpsock: TCPSocket,
token: &str,
user_network_id: &str,
// network: &str,
private: RsaPrivateKey,
tcp_pong: Arc<AtomicU64>,
start_stop: Sender<StartStopInfo>,
mtu: u32,
) -> Self {
let mode = if cfg!(not(feature = "tun")) {
let mode = if cfg!(feature = "tap") {
Mode::Tap
} else {
Mode::Tun
@ -263,10 +256,8 @@ impl Node {
Self {
packet_id: AtomicU32::new(1),
network_id: Mutex::new("".to_owned()),
// network_id: AtomicU32::new(0),
network_id: AtomicU32::new(0),
_token: Mutex::new(token.to_owned()),
_user_network_id: user_network_id.to_owned(),
start_stop_sender: start_stop,
@ -274,7 +265,7 @@ impl Node {
nat_type: Mutex::new(NatType::Blocked),
device_config: DeviceConfig::new(mtu),
device_config: DeviceConfig::new(),
device: new_iface("dev", mode),
authorized: AtomicBool::new(false),
@ -409,36 +400,28 @@ impl Node {
};
if reply1.ip == self.outer_ip_v4.load(Ordering::Relaxed) {
let Ok(_reply2) = self
.send_and_wait_for_probe_reply(StunProbeAttr::Peer, &self.config.nat_server1)
.await
else {
*self.nat_type.lock().unwrap() = NatType::Symmetric;
return NatType::Symmetric;
};
*self.nat_type.lock().unwrap() = NatType::NoNat;
return NatType::NoNat;
}
if let Ok(_reply2_2) = self
.send_and_wait_for_probe_reply(StunProbeAttr::Peer, &self.config.nat_server1)
.await
{
*self.nat_type.lock().unwrap() = NatType::FullCone;
return NatType::FullCone;
}
let Ok(reply3) = self
let Ok(reply2) = self
.send_and_wait_for_probe_reply(StunProbeAttr::None, &self.config.nat_server2)
.await
else {
*self.nat_type.lock().unwrap() = NatType::Blocked;
return NatType::Blocked;
};
if reply3.ip != reply1.ip || reply3.port != reply1.port {
if reply1.ip != reply2.ip || reply1.port != reply2.port {
*self.nat_type.lock().unwrap() = NatType::Symmetric;
return NatType::Symmetric;
}
*self.nat_type.lock().unwrap() = NatType::NoNat;
return NatType::NoNat;
}
if let Ok(_reply3) = self
.send_and_wait_for_probe_reply(StunProbeAttr::Peer, &self.config.nat_server1)
.await
{
*self.nat_type.lock().unwrap() = NatType::FullCone;
return NatType::FullCone;
}
if let Ok(_reply4) = self
.send_and_wait_for_probe_reply(StunProbeAttr::Port, &self.config.nat_server1)
@ -472,7 +455,7 @@ impl Node {
attr: msgattr as u32,
cookie,
};
// println!("==> sending probe request: {:?}", probe);
println!("==> sending probe request: {:?}", probe);
let (tx, rx) = oneshot::channel();
self.cookie_match.insert(cookie, tx);
@ -503,7 +486,7 @@ impl Node {
}
pub struct PeerMap {
pub peers: DashMap<Mac, EdgePeer>,
pub peers: DashMap<Mac, Arc<EdgePeer>>,
}
#[allow(unused)]
@ -514,37 +497,33 @@ impl PeerMap {
}
}
/*
pub fn get_peer(&self, mac: &Mac) -> Option<Arc<EdgePeer>> {
if let Some(v) = self.peers.get(mac) {
pub fn get_peer(&self, ip: &Mac) -> Option<Arc<EdgePeer>> {
if let Some(v) = self.peers.get(ip) {
Some(v.clone())
} else {
None
}
}
*/
pub fn clear(&self) {
self.peers.clear();
}
pub fn get_peer_by_sock(&self, sock: &SdlanSock) -> Option<Arc<EdgePeer>> {
/*
for s in self.peers.iter() {
let m = s.sock.read().unwrap();
if is_sdlan_sock_equal(&m, sock) {
return Some(s.value().clone());
}
}
*/
None
}
pub fn delete_peer_with_mac(&self, mac: &Mac) -> Option<(Mac, EdgePeer)> {
pub fn delete_peer_with_mac(&self, mac: &Mac) -> Option<(Mac, Arc<EdgePeer>)> {
self.peers.remove(mac)
}
pub fn insert_peer(&self, mac: Mac, p: EdgePeer) {
pub fn insert_peer(&self, mac: Mac, p: Arc<EdgePeer>) {
self.peers.insert(mac, p);
}
}
@ -579,7 +558,7 @@ impl NodeStats {
use sdlan_sn_rs::peer::SdlanSock;
use crate::config::{self, MULTICAST_PORT, REGISTER_SUPER_INTERVAL};
use crate::config::{self, MULTICAST_PORT, REGISTER_INTERVAL, REGISTER_SUPER_INTERVAL};
pub struct NodeConfig {
// node name
pub name: String,
@ -622,12 +601,12 @@ pub struct EdgePeer {
// pub mac: Mac,
pub dev_addr: IpSubnet,
pub nat_type: NatType,
pub nat_type: RwLock<NatType>,
// 对端对外开放的ip和端口信息
pub sock: SdlanSock,
pub sock: RwLock<SdlanSock>,
// peer's ipv6 info
pub _v6_info: Option<SdlanSock>,
pub _v6_info: RwLock<Option<SdlanSock>>,
pub timeout: u8,
@ -666,18 +645,18 @@ impl EdgePeer {
Self {
// mac,
dev_addr: IpSubnet::new(net_addr, net_bit_len),
sock: sock.deepcopy(),
_v6_info: v6_info,
sock: RwLock::new(sock.deepcopy()),
_v6_info: RwLock::new(v6_info),
timeout: REGISTER_SUPER_INTERVAL as u8,
last_p2p: AtomicU64::new(0),
last_seen: AtomicU64::new(0),
_last_valid_timestamp: AtomicU64::new(now),
last_sent_query: AtomicU64::new(0),
nat_type: NatType::Invalid,
nat_type: RwLock::new(NatType::Invalid),
}
}
pub fn get_nat_type(&self) -> NatType {
self.nat_type
*self.nat_type.read().unwrap()
}
}

214
src/network/packet.rs Executable file → Normal file
View File

@ -13,8 +13,9 @@ use crate::{
utils::{send_to_sock, Socket},
};
use etherparse::Ethernet2Header;
use num_enum::TryFromPrimitive;
use prost::Message;
use sdlan_sn_rs::utils::{aes_encrypt, BROADCAST_MAC};
use sdlan_sn_rs::utils::BROADCAST_MAC;
use sdlan_sn_rs::{
config::{AF_INET, AF_INET6},
peer::{is_sdlan_sock_equal, SdlanSock, V6Info},
@ -23,6 +24,7 @@ use sdlan_sn_rs::{
Mac, Result, SDLanError,
},
};
use std::sync::Arc;
use tracing::{debug, error, info};
@ -122,8 +124,6 @@ pub async fn handle_packet(eee: &'static Node, addr: SocketAddr, buf: &[u8]) ->
);
}
if data.is_p2p {
let from_sock = from_sock.deepcopy();
tokio::spawn(async move {
check_peer_registration_needed(
eee,
!data.is_p2p,
@ -133,7 +133,6 @@ pub async fn handle_packet(eee: &'static Node, addr: SocketAddr, buf: &[u8]) ->
&from_sock,
)
.await;
});
}
handle_tun_packet(eee, &from_sock, !data.is_p2p, data).await;
}
@ -143,7 +142,7 @@ pub async fn handle_packet(eee: &'static Node, addr: SocketAddr, buf: &[u8]) ->
error!("failed to decode SdlStunReply");
return Ok(());
};
// println!("got stun probe reply: {:?}", reply);
println!("got stun probe reply: {:?}", reply);
eee.send_nat_probe_reply(reply.cookie, reply).await;
}
PacketType::StunReply => {
@ -285,19 +284,16 @@ pub async fn handle_packet_peer_info(
if dst_mac == NULL_MAC {
// pong from sn
} else {
let pending = eee.pending_peers.peers.get_mut(&dst_mac);
match pending {
Some(mut v) => {
match eee.pending_peers.get_peer(&dst_mac) {
Some(edgeinfo) => {
let sock = SdlanSock {
family: AF_INET,
port: v4.port as u16,
v4: v4_u32,
v6: [0; 16],
};
v.nat_type = remote_nat;
v.sock = sock.deepcopy();
// v.sock = sock.deepcopy();
*(edgeinfo.nat_type.write().unwrap()) = remote_nat;
*(edgeinfo.sock.write().unwrap()) = sock.deepcopy();
info!(
"Rx PEERINFO for {}: is at {}",
mac_to_string(&dst_mac),
@ -308,6 +304,8 @@ pub async fn handle_packet_peer_info(
v6_info = Some(V6Info { port: v6_port, v6 })
}
send_register(eee, remote_nat, &sock, dst_mac, &v6_info).await;
// register_with_local_peers(eee).await;
}
None => {
debug!("Rx PEERINFO unknown peer: {}", mac_to_string(&dst_mac));
@ -546,28 +544,26 @@ pub async fn check_peer_registration_needed(
_v6_info: &Option<V6Info>,
peer_sock: &SdlanSock,
) {
let p = eee.known_peers.peers.get(&src_mac);
let last_seen;
let now;
let mut p = eee.known_peers.get_peer(&src_mac);
if let None = p {
p = eee.known_peers.get_peer_by_sock(peer_sock);
if let Some(ref k) = p {
eee.known_peers.insert_peer(src_mac, k.clone());
}
}
match p {
None => {
debug!("check peer registration needed, not found in known peers");
let _ = register_with_new_peer(eee, from_sn, src_mac, _v6_info, remote_nat, peer_sock)
.await;
return;
// unimplemented!();
}
Some(k) => {
// let mut ipv4_to_ipv6 = false;
now = get_current_timestamp();
let mut ipv4_to_ipv6 = false;
let now = get_current_timestamp();
if !from_sn {
k.last_p2p.store(now, Ordering::Relaxed);
}
let origin_family = k.sock.family;
if origin_family != peer_sock.family {
return;
}
/*
if peer_sock.family == AF_INET6 && k.sock.read().unwrap().family == AF_INET {
println!("changing to ipv6");
*k.sock.write().unwrap() = peer_sock.deepcopy();
@ -575,14 +571,13 @@ pub async fn check_peer_registration_needed(
} else {
println!("already is ipv6");
}
*/
last_seen = k.last_seen.load(Ordering::Relaxed);
let last_seen = k.last_seen.load(Ordering::Relaxed);
// more than 3 seconds
}
}
if now - last_seen > 3 {
check_known_peer_sock_change(eee, from_sn, src_mac, peer_sock, now, false).await;
check_known_peer_sock_change(eee, from_sn, src_mac, peer_sock, now, ipv4_to_ipv6)
.await;
}
}
}
}
@ -599,38 +594,30 @@ async fn check_known_peer_sock_change(
if is_multi_broadcast(&mac) {
return;
}
let delete_from_known_peers;
let remote_nat;
match eee.known_peers.peers.get_mut(&mac) {
match eee.known_peers.get_peer(&mac) {
Some(p) => {
if !ipv4_to_ipv6 && !is_sdlan_sock_equal(&p.sock, peersock) {
if !ipv4_to_ipv6 && !is_sdlan_sock_equal(&p.sock.read().unwrap(), peersock) {
if !from_sn {
info!(
"peer changed: {}: {} -> {}",
mac_to_string(&mac),
&p.sock.to_string(),
&p.sock.read().unwrap().to_string(),
peersock.to_string()
);
delete_from_known_peers = true;
remote_nat = p.get_nat_type();
eee.known_peers.delete_peer_with_mac(&mac);
error!("known peers is deleted");
let remote_nat = p.get_nat_type();
register_with_new_peer(eee, from_sn, mac, &None, remote_nat, peersock).await;
} else {
// from sn, sn could see a different sock with us, just ignore it
return;
}
} else {
p.last_seen.store(when, Ordering::Relaxed);
return;
// from sn, sn could see a different sock with us, just ignore it
}
}
None => return,
}
if delete_from_known_peers {
eee.known_peers.delete_peer_with_mac(&mac);
error!("known peers is deleted");
register_with_new_peer(eee, from_sn, mac, &None, remote_nat, peersock).await;
}
}
async fn register_with_new_peer(
@ -643,21 +630,25 @@ async fn register_with_new_peer(
peersock: &SdlanSock,
) {
let now = get_current_timestamp();
let entry = eee.pending_peers.peers.entry(mac);
let mut new_created = false;
let mut scan = entry.or_insert_with(|| {
new_created = true;
let temp = EdgePeer::new(0, eee.device_config.get_net_bit(), peersock, &None, now);
temp
});
if new_created {
let mut scan = eee.pending_peers.get_peer(&mac);
if let None = scan {
// such ip not found in pending
let temp = Arc::new(EdgePeer::new(
// mac,
0,
eee.device_config.get_net_bit(),
peersock,
&None,
now,
));
debug!(
"===> new pending {} => {}",
mac_to_string(&mac),
peersock.to_string(),
);
eee.pending_peers.insert_peer(mac, temp.clone());
scan = Some(temp);
debug!("Pending size: {}", eee.pending_peers.peers.len());
if from_sn {
// should send register to peer
@ -699,11 +690,14 @@ async fn register_with_new_peer(
}
register_with_local_peers(eee).await;
} else {
scan.sock = peersock.deepcopy();
if let Some(ref s) = scan {
*(s.sock.write().unwrap()) = peersock.deepcopy();
}
scan.last_seen
}
if let Some(s) = scan {
s.last_seen
.store(get_current_timestamp(), Ordering::Relaxed);
}
}
async fn register_with_local_peers(eee: &'static Node) {
@ -730,10 +724,8 @@ async fn send_register(
debug!("skipping register as p2p is disabled");
return;
}
let network_id = eee.network_id.lock().unwrap().clone();
// let network_id = eee.network_id.load(Ordering::Relaxed);
if network_id.is_empty() {
let network_id = eee.network_id.load(Ordering::Relaxed);
if network_id == 0 {
error!("not authed");
return;
}
@ -781,7 +773,7 @@ async fn send_register(
}
if need_guess_port {
// println!("need guess port");
println!("need guess port");
}
/*
@ -811,14 +803,6 @@ async fn send_register(
*/
}
pub fn printHex(key: &[u8]) {
let mut value = vec![];
for item in key {
value.push(format!("0x{:02x}", item))
}
println!("[{}]", value.join(" "))
}
async fn handle_tun_packet(
eee: &Node,
_from_sock: &SdlanSock,
@ -833,7 +817,6 @@ async fn handle_tun_packet(
return;
}
// test_aes(key.as_slice());
let origin = aes_decrypt(key.as_slice(), &payload);
if let Err(_e) = origin {
error!("failed to decrypt original data");
@ -1022,13 +1005,11 @@ async fn send_register_ack(eee: &Node, orig_sender: &SdlanSock, reg: &SdlRegiste
debug!("Skipping REGISTER ACK as P2P is disallowed");
return;
}
let network_id = eee.network_id.lock().unwrap().clone();
// let network_id = eee.network_id.load(Ordering::Relaxed);
if network_id.is_empty() {
let network_id = eee.network_id.load(Ordering::Relaxed);
if network_id == 0 {
error!("not authed");
return;
}
let src_mac = reg.src_mac.clone();
let ack = SdlRegisterAck {
network_id,
@ -1043,9 +1024,10 @@ async fn send_register_ack(eee: &Node, orig_sender: &SdlanSock, reg: &SdlRegiste
}
fn peer_set_p2p_confirmed(eee: &Node, src_mac: Mac, sender_sock: &SdlanSock) {
// let mut scan = eee.pending_peers.get_peer(&src_mac);
let scan = eee.pending_peers.peers.remove(&src_mac);
let mut scan = eee.pending_peers.get_peer(&src_mac);
if let None = scan {
scan = eee.pending_peers.get_peer_by_sock(sender_sock);
}
if let None = scan {
error!(
"failed to find sender in pending peer: {}",
@ -1053,17 +1035,30 @@ fn peer_set_p2p_confirmed(eee: &Node, src_mac: Mac, sender_sock: &SdlanSock) {
);
return;
}
let (_, scan) = scan.unwrap();
{
let entry = eee.known_peers.peers.entry(src_mac);
let mut scan2 = entry.or_insert(scan);
scan2.sock = sender_sock.deepcopy();
let now = get_current_timestamp();
scan2.last_p2p.store(now, Ordering::Relaxed);
scan2.last_seen.store(now, Ordering::Relaxed);
let mut scan = scan.unwrap();
eee.pending_peers.delete_peer_with_mac(&src_mac);
match eee.known_peers.get_peer(&src_mac) {
Some(scantmp) => {
eee.known_peers.delete_peer_with_mac(&src_mac);
scan = scantmp;
// set the remote peer sock
*scan.sock.write().unwrap() = sender_sock.deepcopy();
// scan.mac = src_mac;
/*
scan.dev_addr.net_addr.store(&src_mac, Ordering::Relaxed);
scan.dev_addr
.net_bit_len
.store(eee.device_config.get_net_bit(), Ordering::Relaxed);
*/
}
None => {
*(scan.sock.write().unwrap()) = sender_sock.deepcopy();
}
}
let now = get_current_timestamp();
scan.last_p2p.store(now, Ordering::Relaxed);
scan.last_seen.store(now, Ordering::Relaxed);
let mac_string = mac_to_string(&src_mac);
let sock_string = sender_sock.to_string();
@ -1071,47 +1066,45 @@ fn peer_set_p2p_confirmed(eee: &Node, src_mac: Mac, sender_sock: &SdlanSock) {
"P2P connection established: {} [{}]",
&mac_string, &sock_string,
);
// eee.known_peers.insert_peer(src_mac, scan);
eee.known_peers.insert_peer(src_mac, scan);
debug!("==> new peer: {} -> {}", &mac_string, &sock_string,);
}
pub async fn check_query_peer_info(eee: &'static Node, mac: Mac) {
// let scan: Arc<EdgePeer>;
let scan: Arc<EdgePeer>;
let now = get_current_timestamp();
let last_sent_query;
let mut need_send_query = false;
{
let entry = eee.pending_peers.peers.entry(mac);
match eee.pending_peers.get_peer(&mac) {
None => {
let sock = SdlanSock {
family: AF_INET,
port: 0,
v4: [0; 4],
v6: [0; 16],
};
let peer = EdgePeer::new(
let peer = Arc::new(EdgePeer::new(
// mac,
0,
eee.device_config.get_net_bit(),
&sock,
&None,
now,
);
));
debug!("insert peer {} to pending", mac_to_string(&mac));
let val = entry.or_insert(peer);
last_sent_query = val.last_sent_query.load(Ordering::Relaxed);
if now - last_sent_query > (REGISTER_INTERVAL as u64) {
need_send_query = true;
val.last_sent_query.store(now, Ordering::Relaxed);
eee.pending_peers.insert_peer(mac, peer.clone());
scan = peer;
}
Some(s) => {
scan = s;
}
}
debug!(
"now={}, last_sent_query={}, REGISTER_INTERVAL={}",
now, last_sent_query, REGISTER_INTERVAL,
"now={}, last_sent_query={}, REGISTER_INTERVAL={}, scan={:?}",
now,
scan.last_sent_query.load(Ordering::Relaxed),
REGISTER_INTERVAL,
scan,
);
if need_send_query {
if now - scan.last_sent_query.load(Ordering::Relaxed) > (REGISTER_INTERVAL as u64) {
/*
send_register(
eee,
@ -1122,16 +1115,19 @@ pub async fn check_query_peer_info(eee: &'static Node, mac: Mac) {
*/
debug!("sending query for {}", mac_to_string(&mac));
register_with_local_peers(eee).await;
let _ = send_query_peer(eee, mac).await;
if let Ok(()) = send_query_peer(eee, mac).await {
scan.last_sent_query.store(now, Ordering::Relaxed);
}
}
}
async fn send_query_peer(eee: &Node, dst_mac: Mac) -> Result<()> {
if !eee.is_authorized() {
let network_id = eee.network_id.load(Ordering::Relaxed);
if network_id == 0 {
error!("not authed");
return Err(SDLanError::NormalError("not connected"));
}
let query = SdlQueryInfo {
dst_mac: Vec::from(dst_mac),
};

11
src/network/route.rs Executable file → Normal file
View File

@ -3,8 +3,6 @@ use std::{net::Ipv4Addr, sync::RwLock};
use once_cell::sync::OnceCell;
use sdlan_sn_rs::utils::net_bit_len_to_mask;
use tracing::{debug, error};
#[derive(Debug)]
pub struct RouteTable {
content: RwLock<Vec<RouteInfo>>,
@ -31,7 +29,7 @@ impl RouteTable {
pub fn get_gateway_ip(&self, net_ip: u32) -> Option<u32> {
let routes = self.content.read().unwrap();
for route in &*routes {
debug!("route: {:?}", route.to_string());
println!("route: {:?}", route.to_string());
if (route.net_ip & route.net_mask) == (net_ip & route.net_mask) {
// found
return Some(route.gateway_ip);
@ -102,17 +100,16 @@ pub fn parse_route(route: String) -> Vec<(u32, u32, u32)> {
let routes: Vec<_> = route.split(",").collect();
for route in routes {
let route_info: Vec<_> = route.split(";").collect();
debug!("got route info: {:?}", route_info);
println!("got route info: {:?}", route_info);
if route_info.len() != 2 {
error!("route info format error");
println!("route info format error");
continue;
}
let cidr = route_info[0];
let gateway = route_info[1].parse::<Ipv4Addr>().unwrap();
let ip_and_mask: Vec<_> = cidr.split("/").collect();
if ip_and_mask.len() != 2 {
error!("route info ip/bit error");
println!("route info ip/bit error");
continue;
}
let ip = ip_and_mask[0].parse::<Ipv4Addr>().unwrap();

29
src/network/tun_linux.rs Executable file → Normal file
View File

@ -30,7 +30,6 @@ use crate::utils::{caculate_crc, mac_to_string};
use super::device::{DeviceConfig, Mode};
use super::TunTapPacketHandler;
// #[link(name = "tuntap", kind="static")]
#[link(name = "tuntap")]
extern "C" {
fn tuntap_setup(fd: c_int, name: *mut u8, mode: c_int, packet_info: c_int) -> c_int;
@ -117,8 +116,8 @@ impl Iface {
let ip = ip_to_string(&ip);
let netbit = ip_to_string(&net_bit_len_to_mask(netbit));
if cfg!(not(feature = "tun")) {
info!("set tap device");
if cfg!(feature = "tap") {
println!("set tap device");
let mac = device_config.get_mac();
let res = Command::new("ifconfig")
.arg(&self.name)
@ -131,8 +130,6 @@ impl Iface {
"{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]
))
.arg("mtu")
.arg(format!("{}", device_config.mtu))
.arg("up")
.output();
match res {
@ -144,14 +141,12 @@ impl Iface {
}
}
} else {
info!("set tun device");
println!("set tun device");
let res = Command::new("ifconfig")
.arg(&self.name)
.arg(ip)
.arg("netmask")
.arg(&netbit)
.arg("mtu")
.arg(format!("{}", device_config.mtu))
.arg("up")
.output();
match res {
@ -174,7 +169,7 @@ impl Iface {
}
}
#[cfg(not(feature = "tun"))]
#[cfg(feature = "tap")]
impl TunTapPacketHandler for Iface {
async fn handle_packet_from_net(&self, data: &[u8], _: &[u8]) -> std::io::Result<()> {
// debug!("in tap mode, got data: {:?}", data);
@ -206,10 +201,9 @@ impl TunTapPacketHandler for Iface {
error!("failed to encrypt packet request");
return Ok(());
};
let network_id = edge.network_id.lock().unwrap().clone();
let data = SdlData {
is_p2p: true,
network_id,
network_id: edge.network_id.load(Ordering::Relaxed),
ttl: SDLAN_DEFAULT_TTL as u32,
src_mac: Vec::from(edge.device_config.get_mac()),
dst_mac: Vec::from(target),
@ -227,7 +221,7 @@ impl TunTapPacketHandler for Iface {
}
}
#[cfg(feature = "tun")]
#[cfg(not(feature = "tap"))]
impl TunTapPacketHandler for Iface {
async fn handle_packet_from_net(&self, data: &[u8], key: &[u8]) -> std::io::Result<()> {
debug!("in tun mode");
@ -273,7 +267,7 @@ impl TunTapPacketHandler for Iface {
// handle ARP REQUEST
debug!("got ARP REQUEST");
if arp.ethhdr.dest != [0xff; 6] {
debug!("ARP REQUEST not broadcast");
println!("ARP REQUEST not broadcast");
return Ok(());
}
if dest_ip == self_ip {
@ -312,7 +306,7 @@ impl TunTapPacketHandler for Iface {
let v = encode_to_udp_message(Some(data), PacketType::Data as u8)
.unwrap();
debug!(
println!(
"xxxx send arp reply to [{}], selfmac=[{}]",
mac_to_string(&arp.dhwaddr),
mac_to_string(&self_mac)
@ -323,8 +317,9 @@ impl TunTapPacketHandler for Iface {
}
}
ARP_REPLY => {
println!("got arp reply",);
debug!("mac {:?} is at {:?}", arp.shwaddr, from_ip.to_be_bytes());
println!("mac {:?} is at {:?}", arp.shwaddr, from_ip.to_be_bytes());
if dest_ip == self_ip {
send_arp_request(ArpRequestInfo::Set {
ip: from_ip,
@ -335,7 +330,7 @@ impl TunTapPacketHandler for Iface {
}
}
_other => {
error!("unknown arp type info");
println!("unknown arp type info");
}
}
} else {
@ -416,7 +411,7 @@ impl TunTapPacketHandler for Iface {
} => {
if do_arp_request {
add_to_arp_wait_list(dstip, data);
debug!(
println!(
"find ip: {:?} => {:?}",
src.to_be_bytes(),
dstip.to_be_bytes()

39
src/network/tun_win.rs Executable file → Normal file
View File

@ -91,28 +91,6 @@ impl Iface {
error!("failed to run netsh: {}", e.to_string());
}
}
let mut cmd = Command::new("netsh");
let command = cmd
.creation_flags(0x08000000)
.arg("interface")
.arg("ipv4")
.arg("set")
.arg("subinterface")
.arg(&format!("\"{}\"", self.name))
.arg(format!("mtu={}", device_config.mtu))
.arg("store=persistent");
let res = command.output();
match res {
Ok(r) => {
debug!("netsh2 ok: [{:?}]", String::from_utf8_lossy(&r.stdout));
}
Err(e) => {
error!("failed to run netsh2: {}", e.to_string());
}
}
}
}
@ -152,18 +130,18 @@ impl TunTapPacketHandler for Iface {
let mut arp = ArpHdr::from_slice(&data);
let self_ip = edge.device_config.get_ip();
debug!("self_ip: {:?}", self_ip.to_be_bytes());
println!("self_ip: {:?}", self_ip.to_be_bytes());
let from_ip = ((arp.sipaddr[0] as u32) << 16) + arp.sipaddr[1] as u32;
debug!("from_ip: {:?}", from_ip.to_be_bytes());
println!("from_ip: {:?}", from_ip.to_be_bytes());
let dest_ip = ((arp.dipaddr[0] as u32) << 16) + arp.dipaddr[1] as u32;
debug!("dest_ip: {:?}", dest_ip.to_be_bytes());
println!("dest_ip: {:?}", dest_ip.to_be_bytes());
match arp.opcode {
ARP_REQUEST => {
// handle ARP REQUEST
debug!("got ARP REQUEST");
if arp.ethhdr.dest != [0xff; 6] {
debug!("ARP REQUEST not broadcast");
println!("ARP REQUEST not broadcast");
return Ok(());
}
if dest_ip == self_ip {
@ -201,7 +179,7 @@ impl TunTapPacketHandler for Iface {
let v = encode_to_udp_message(Some(data), PacketType::Data as u8)
.unwrap();
debug!(
println!(
"xxxx send arp reply to [{}], selfmac=[{}]",
mac_to_string(&arp.dhwaddr),
mac_to_string(&self_mac)
@ -212,8 +190,9 @@ impl TunTapPacketHandler for Iface {
}
}
ARP_REPLY => {
println!("got arp reply",);
debug!("mac {:?} is at {:?}", arp.shwaddr, from_ip.to_be_bytes());
println!("mac {:?} is at {:?}", arp.shwaddr, from_ip.to_be_bytes());
if dest_ip == self_ip {
send_arp_request(ArpRequestInfo::Set {
ip: from_ip,
@ -224,7 +203,7 @@ impl TunTapPacketHandler for Iface {
}
}
_other => {
error!("unknown arp type info");
println!("unknown arp type info");
}
}
} else {
@ -304,7 +283,7 @@ impl TunTapPacketHandler for Iface {
if do_arp_request {
add_to_arp_wait_list(dstip, data);
info!(
println!(
"find ip: {:?} => {:?}",
src.to_be_bytes(),
dstip.to_be_bytes()

0
src/network/tuntap.c Executable file → Normal file
View File

8
src/network/tuntap.rs Executable file → Normal file
View File

@ -8,8 +8,6 @@ use sdlan_sn_rs::{
utils::{aes_encrypt, get_current_timestamp, ip_to_string, Mac},
};
use tracing::debug;
use tracing::error;
use crate::{
@ -61,7 +59,7 @@ impl ArpWaitList {
}
async fn arp_arrived(&self, ip: u32, mac: Mac) {
debug!(
println!(
"arp for {} arrived: {}",
ip_to_string(&ip),
mac_to_string(&mac)
@ -76,7 +74,7 @@ impl ArpWaitList {
}
let encrypt_key = edge.get_encrypt_key();
let network_id = edge.network_id.lock().unwrap().clone();
let network_id = edge.network_id.load(Ordering::Relaxed);
let src_mac = edge.device_config.get_mac();
let now = get_current_timestamp();
@ -94,7 +92,7 @@ impl ArpWaitList {
};
let data = SdlData {
is_p2p: true,
network_id: network_id.clone(),
network_id,
ttl: SDLAN_DEFAULT_TTL as u32,
src_mac: Vec::from(src_mac),
dst_mac: Vec::from(mac),

View File

@ -21,8 +21,8 @@ pub struct Sdlv6Info {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SdlDevAddr {
#[prost(string, tag = "1")]
pub network_id: ::prost::alloc::string::String,
#[prost(uint32, tag = "1")]
pub network_id: u32,
#[prost(bytes = "vec", tag = "2")]
pub mac: ::prost::alloc::vec::Vec<u8>,
#[prost(uint32, tag = "3")]
@ -49,8 +49,6 @@ pub struct SdlRegisterSuper {
pub pub_key: ::prost::alloc::string::String,
#[prost(string, tag = "6")]
pub token: ::prost::alloc::string::String,
#[prost(string, tag = "7")]
pub network_id: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
@ -155,8 +153,8 @@ pub struct SdlStunRequest {
pub cookie: u32,
#[prost(string, tag = "2")]
pub client_id: ::prost::alloc::string::String,
#[prost(string, tag = "3")]
pub network_id: ::prost::alloc::string::String,
#[prost(uint32, tag = "3")]
pub network_id: u32,
#[prost(bytes = "vec", tag = "4")]
pub mac: ::prost::alloc::vec::Vec<u8>,
#[prost(uint32, tag = "5")]
@ -175,8 +173,8 @@ pub struct SdlStunReply {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SdlData {
#[prost(string, tag = "1")]
pub network_id: ::prost::alloc::string::String,
#[prost(uint32, tag = "1")]
pub network_id: u32,
#[prost(bytes = "vec", tag = "2")]
pub src_mac: ::prost::alloc::vec::Vec<u8>,
#[prost(bytes = "vec", tag = "3")]
@ -191,8 +189,8 @@ pub struct SdlData {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SdlRegister {
#[prost(string, tag = "1")]
pub network_id: ::prost::alloc::string::String,
#[prost(uint32, tag = "1")]
pub network_id: u32,
#[prost(bytes = "vec", tag = "2")]
pub src_mac: ::prost::alloc::vec::Vec<u8>,
#[prost(bytes = "vec", tag = "3")]
@ -201,8 +199,8 @@ pub struct SdlRegister {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SdlRegisterAck {
#[prost(string, tag = "1")]
pub network_id: ::prost::alloc::string::String,
#[prost(uint32, tag = "1")]
pub network_id: u32,
#[prost(bytes = "vec", tag = "2")]
pub src_mac: ::prost::alloc::vec::Vec<u8>,
#[prost(bytes = "vec", tag = "3")]

0
src/pb/mod.rs Executable file → Normal file
View File

0
src/tcp/mod.rs Executable file → Normal file
View File

0
src/tcp/tcp_codec.rs Executable file → Normal file
View File

3
src/tcp/tcp_conn.rs Executable file → Normal file
View File

@ -297,8 +297,7 @@ impl ReadWriterHandle {
if let Some(msg) = data_from_tcp.recv().await {
on_message(msg).await;
} else {
error!("data from tcp exited");
// eprintln!("data from tcp exited");
eprintln!("data from tcp exited");
return;
}
}

11
src/utils/command.rs Executable file → Normal file
View File

@ -2,14 +2,11 @@ use structopt::StructOpt;
#[derive(StructOpt, Debug)]
pub struct CommandLineInput {
#[structopt(long = "token", default_value = "", help="specify a token")]
#[structopt(long = "token", default_value = "")]
pub token: String,
#[structopt(short = "p", long = "port", default_value = "0", help="which port to use")]
#[structopt(short = "p", long = "port", default_value = "0")]
pub port: u16,
#[structopt(long = "network_id", short = "n", default_value = "", help="specify a networkid")]
pub user_network_id: String,
}
#[derive(StructOpt, Debug)]
@ -53,9 +50,6 @@ pub struct CommandLine {
#[structopt(long = "token", default_value = "0")]
pub token: String,
#[structopt(long = "network_id", default_value = "")]
pub user_network_id: String,
#[structopt(short = "p")]
pub allow_p2p: bool,
@ -76,7 +70,6 @@ impl Clone for CommandLine {
name: self.name.clone(),
tos: self.tos,
token: self.token.clone(),
user_network_id: self.user_network_id.clone(),
allow_p2p: self.allow_p2p,
nat_server1: self.nat_server1.clone(),
nat_server2: self.nat_server2.clone(),

0
src/utils/mod.rs Executable file → Normal file
View File

7
src/utils/pid_recorder.rs Executable file → Normal file
View File

@ -2,7 +2,6 @@ use std::{
fs::{self, OpenOptions},
io::Write,
};
use tracing::{debug, error};
pub struct PidRecorder(String);
@ -20,8 +19,7 @@ impl PidRecorder {
.expect("failed to write");
}
Err(e) => {
error!("failed to open pid file: {}", e);
// eprintln!("failed to open pid file: {}", e);
eprintln!("failed to open pid file: {}", e);
}
}
@ -32,8 +30,7 @@ impl PidRecorder {
impl Drop for PidRecorder {
fn drop(&mut self) {
if let Err(e) = fs::remove_file(&self.0) {
error!("failed to remove pid file: {}", e);
// eprintln!("failed to remove pid file: {}", e);
eprintln!("failed to remove pid file: {}", e);
}
}
}

0
src/utils/socks.rs Executable file → Normal file
View File

0
start_docker.sh Executable file → Normal file
View File

0
wintun.dll Executable file → Normal file
View File