Skip to content

Commit

Permalink
Merge pull request #99 from vnt-dev/1.2.x
Browse files Browse the repository at this point in the history
1.2.x
  • Loading branch information
vnt-dev authored Oct 20, 2024
2 parents 2979f2e + 8aa4736 commit 501a9e8
Show file tree
Hide file tree
Showing 14 changed files with 80 additions and 96 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ jobs:
OS: ${{ matrix.OS }}
FEATURES: ${{ matrix.FEATURES }}
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Init submodules
uses: snickerbockers/submodules-init@v4
- name: Cargo cache
Expand Down Expand Up @@ -221,7 +221,7 @@ jobs:
cd ./artifacts
tar -czf vnt-$TARGET-$TAG.tar.gz *
- name: Archive artifact
uses: actions/upload-artifact@v2
uses: actions/upload-artifact@v3
with:
name: vnt-cli
path: |
Expand All @@ -233,7 +233,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Download artifacts
uses: actions/download-artifact@v2
uses: actions/download-artifact@v3
with:
name: vnt-cli
path: ./artifacts
Expand Down
10 changes: 5 additions & 5 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion common/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "common"
version = "1.2.13"
version = "1.2.14"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand Down
21 changes: 7 additions & 14 deletions common/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ pub fn parse_args_config() -> anyhow::Result<Option<(Config, Vec<String>, bool)>
opts.optmulti("", "vnt-mapping", "vnt-mapping", "<mapping>");
opts.optopt("f", "", "配置文件", "<conf>");
opts.optopt("", "compressor", "压缩算法", "<lz4>");
opts.optopt("", "local-ipv4", "指定本地ipv4网卡IP", "<IP>");
opts.optopt("", "local-dev", "指定本地ipv4网卡名称", "<NAME>");
opts.optflag("", "disable-stats", "关闭流量统计");
opts.optflag("", "allow-wg", "允许接入WireGuard");
//"后台运行时,查看其他设备列表"
Expand Down Expand Up @@ -284,15 +284,8 @@ pub fn parse_args_config() -> anyhow::Result<Option<(Config, Vec<String>, bool)>
#[cfg(feature = "port_mapping")]
let port_mapping_list = matches.opt_strs("mapping");
let vnt_mapping_list = matches.opt_strs("vnt-mapping");
let local_ipv4: Option<String> = matches.opt_get("local-ipv4").unwrap();
let local_ipv4 = local_ipv4
.map(|v| Ipv4Addr::from_str(&v).expect(&format!("'--local-ipv4 {}' error", v)));
if let Some(local_ipv4) = local_ipv4 {
if local_ipv4.is_unspecified() || local_ipv4.is_broadcast() || local_ipv4.is_multicast()
{
return Err(anyhow::anyhow!("'--local-ipv4 {}' invalid", local_ipv4));
}
}
let local_dev: Option<String> = matches.opt_get("local-dev").unwrap();

let disable_stats = matches.opt_present("disable-stats");
let allow_wire_guard = matches.opt_present("allow-wg");
let compressor = if let Some(compressor) = matches.opt_str("compressor").as_ref() {
Expand Down Expand Up @@ -336,7 +329,7 @@ pub fn parse_args_config() -> anyhow::Result<Option<(Config, Vec<String>, bool)>
compressor,
!disable_stats,
allow_wire_guard,
local_ipv4,
local_dev,
)?;
(config, vnt_mapping_list, cmd)
};
Expand Down Expand Up @@ -383,7 +376,7 @@ fn get_description(key: &str, language: &str) -> String {
("--compressor-lz4 <lz4>", ("启用压缩,可选值lz4,例如 --compressor lz4", "Enable compression, option lz4, e.g., --compressor lz4")),
("--compressor-zstd <zstd>", ("启用压缩,可选值zstd<,level>,level为压缩级别,例如 --compressor zstd,10", "Enable compression, options zstd<,level>, level is compression level, e.g., --compressor zstd,10")),
("--vnt-mapping <x>", ("vnt地址映射,例如 --vnt-mapping tcp:80-10.26.0.10:80 映射目标是vnt网络或其子网中的设备", "VNT address mapping, e.g., --vnt-mapping tcp:80-10.26.0.10:80 maps to a device in VNT network or its subnet")),
("--local-ipv4", ("本地出口网卡的ipv4地址", "IPv4 address of local export network card")),
("--local-dev", ("本地出口网卡的名称", "name of local export network card")),
("--disable-stats", ("关闭流量统计", "Disable traffic statistics")),
("--allow-wg", ("允许接入WireGuard客户端", "Allow access to WireGuard client")),
("--list", ("后台运行时,查看其他设备列表", "View list of other devices when running in background")),
Expand Down Expand Up @@ -572,8 +565,8 @@ fn print_usage(program: &str, _opts: Options) {
green(get_description("--vnt-mapping <x>", &language).to_string())
);
println!(
" --local-ipv4 <IP> {}",
get_description("--local-ipv4", &language)
" --local-dev <NAME> {}",
get_description("--local-dev", &language)
);
println!(
" --disable-stats {}",
Expand Down
6 changes: 3 additions & 3 deletions common/src/config/file_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ pub struct FileConfig {
pub disable_stats: bool,
// 允许传递wg流量
pub allow_wire_guard: bool,
pub local_ipv4: Option<Ipv4Addr>,
pub local_dev: Option<String>,
}

impl Default for FileConfig {
Expand Down Expand Up @@ -94,7 +94,7 @@ impl Default for FileConfig {
vnt_mapping: vec![],
disable_stats: false,
allow_wire_guard: false,
local_ipv4: None,
local_dev: None,
}
}
}
Expand Down Expand Up @@ -183,7 +183,7 @@ pub fn read_config(file_path: &str) -> anyhow::Result<(Config, Vec<String>, bool
compressor,
!file_conf.disable_stats,
file_conf.allow_wire_guard,
file_conf.local_ipv4,
file_conf.local_dev,
)?;

Ok((config, file_conf.vnt_mapping, file_conf.cmd))
Expand Down
2 changes: 1 addition & 1 deletion vn-link-cli/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "vn-link-cli"
version = "1.2.13"
version = "1.2.14"
edition = "2021"

[dependencies]
Expand Down
2 changes: 1 addition & 1 deletion vn-link/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "vn-link"
version = "1.2.13"
version = "1.2.14"
edition = "2021"

[dependencies]
Expand Down
2 changes: 1 addition & 1 deletion vnt-cli/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "vnt-cli"
version = "1.2.13"
version = "1.2.14"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand Down
2 changes: 1 addition & 1 deletion vnt/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "vnt"
version = "1.2.13"
version = "1.2.14"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand Down
11 changes: 4 additions & 7 deletions vnt/packet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,12 @@ unsigned short getChecksum(unsigned short * iphead, int count)
pub fn cal_checksum(buffer: &[u8]) -> u16 {
use std::io::Cursor;
let mut sum = 0;
let length = buffer.len();
let mut buffer = Cursor::new(buffer);
while let Ok(value) = buffer.read_u16::<BigEndian>() {
sum += u32::from(value);
}
if length & 1 == 1 {
//奇数,说明还有一位,不足的补0
sum += u32c(buffer.read_u8().unwrap(), 0);
if let Ok(l) = buffer.read_u8() {
sum += u32c(l, 0);
}
while sum >> 16 != 0 {
sum = (sum & 0xffff) + (sum >> 16);
Expand Down Expand Up @@ -119,9 +117,8 @@ pub fn ipv4_cal_checksum(
while let Ok(value) = buffer.read_u16::<BigEndian>() {
sum += u32::from(value);
}
if length & 1 == 1 {
//奇数,说明还有一位
sum += u32c(buffer.read_u8().unwrap(), 0);
if let Ok(l) = buffer.read_u8() {
sum += u32c(l, 0);
}
while sum >> 16 != 0 {
sum = (sum & 0xffff) + (sum >> 16);
Expand Down
27 changes: 13 additions & 14 deletions vnt/src/channel/socket/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,6 @@ use anyhow::{anyhow, Context};
use network_interface::{NetworkInterface, NetworkInterfaceConfig};
use socket2::Protocol;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
#[cfg(unix)]
pub use unix::*;
#[cfg(windows)]
pub use windows::*;

#[cfg(unix)]
mod unix;
Expand Down Expand Up @@ -120,20 +116,23 @@ pub fn bind_udp(
bind_udp_ops(addr, true, default_interface).with_context(|| format!("{}", addr))
}

pub fn get_interface(dest_ip: Ipv4Addr) -> anyhow::Result<LocalInterface> {
pub fn get_interface(dest_name: String) -> anyhow::Result<(LocalInterface, Ipv4Addr)> {
let network_interfaces = NetworkInterface::show()?;
for iface in network_interfaces {
for addr in iface.addr {
if let IpAddr::V4(ip) = addr.ip() {
if ip == dest_ip {
return Ok(LocalInterface {
index: iface.index,
#[cfg(unix)]
name: Some(iface.name),
});
if iface.name == dest_name {
for addr in iface.addr {
if let IpAddr::V4(ip) = addr.ip() {
return Ok((
LocalInterface {
index: iface.index,
#[cfg(unix)]
name: Some(iface.name),
},
ip,
));
}
}
}
}
Err(anyhow!("No network card with IP {} found", dest_ip))
Err(anyhow!("No network card with name {} found", dest_name))
}
33 changes: 15 additions & 18 deletions vnt/src/channel/socket/unix.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
#[cfg(any(target_os = "linux", target_os = "macos"))]
use crate::channel::socket::get_interface;
use crate::channel::socket::{LocalInterface, VntSocketTrait};
#[cfg(any(target_os = "linux", target_os = "macos"))]
use anyhow::Context;
use std::net::Ipv4Addr;

#[cfg(target_os = "linux")]
impl VntSocketTrait for socket2::Socket {
Expand Down Expand Up @@ -32,18 +29,18 @@ impl VntSocketTrait for socket2::Socket {
}
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
pub fn get_best_interface(dest_ip: Ipv4Addr) -> anyhow::Result<LocalInterface> {
match get_interface(dest_ip) {
Ok(iface) => return Ok(iface),
Err(e) => {
log::warn!("not find interface e={:?},ip={}", e, dest_ip);
}
}
// 应该再查路由表找到默认路由的
Ok(LocalInterface::default())
}
#[cfg(target_os = "android")]
pub fn get_best_interface(_dest_ip: Ipv4Addr) -> anyhow::Result<LocalInterface> {
Ok(LocalInterface::default())
}
// #[cfg(any(target_os = "linux", target_os = "macos"))]
// pub fn get_best_interface(dest_ip: Ipv4Addr) -> anyhow::Result<LocalInterface> {
// match get_interface(dest_ip) {
// Ok(iface) => return Ok(iface),
// Err(e) => {
// log::warn!("not find interface e={:?},ip={}", e, dest_ip);
// }
// }
// // 应该再查路由表找到默认路由的
// Ok(LocalInterface::default())
// }
// #[cfg(target_os = "android")]
// pub fn get_best_interface(_dest_ip: Ipv4Addr) -> anyhow::Result<LocalInterface> {
// Ok(LocalInterface::default())
// }
40 changes: 19 additions & 21 deletions vnt/src/channel/socket/windows.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
use std::mem;
use std::net::Ipv4Addr;
use std::os::windows::io::AsRawSocket;

use windows_sys::core::PCSTR;
use windows_sys::Win32::NetworkManagement::IpHelper::GetBestInterfaceEx;
use windows_sys::Win32::Networking::WinSock::{
htonl, setsockopt, AF_INET, IPPROTO_IP, IP_UNICAST_IF, SOCKADDR, SOCKADDR_IN, SOCKET_ERROR,
htonl, setsockopt, IPPROTO_IP, IP_UNICAST_IF, SOCKET_ERROR,
};

use crate::channel::socket::{LocalInterface, VntSocketTrait};
Expand Down Expand Up @@ -38,21 +36,21 @@ impl VntSocketTrait for socket2::Socket {
}
}

pub fn get_best_interface(dest_ip: Ipv4Addr) -> anyhow::Result<LocalInterface> {
// 获取最佳接口
let index = unsafe {
let mut dest: SOCKADDR_IN = mem::zeroed();
dest.sin_family = AF_INET as u16;
dest.sin_addr.S_un.S_addr = u32::from_ne_bytes(dest_ip.octets());

let mut index: u32 = 0;
if GetBestInterfaceEx(&dest as *const _ as *mut SOCKADDR, &mut index) != 0 {
Err(anyhow::anyhow!(
"Failed to GetBestInterfaceEx: {:?}",
std::io::Error::last_os_error()
))?;
}
index
};
Ok(LocalInterface { index })
}
// pub fn get_best_interface(dest_ip: Ipv4Addr) -> anyhow::Result<LocalInterface> {
// // 获取最佳接口
// let index = unsafe {
// let mut dest: SOCKADDR_IN = mem::zeroed();
// dest.sin_family = AF_INET as u16;
// dest.sin_addr.S_un.S_addr = u32::from_ne_bytes(dest_ip.octets());
//
// let mut index: u32 = 0;
// if GetBestInterfaceEx(&dest as *const _ as *mut SOCKADDR, &mut index) != 0 {
// Err(anyhow::anyhow!(
// "Failed to GetBestInterfaceEx: {:?}",
// std::io::Error::last_os_error()
// ))?;
// }
// index
// };
// Ok(LocalInterface { index })
// }
12 changes: 6 additions & 6 deletions vnt/src/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ impl Config {
enable_traffic: bool,
// 允许传递wg流量
allow_wire_guard: bool,
local_ipv4: Option<Ipv4Addr>,
local_dev: Option<String>,
) -> anyhow::Result<Self> {
#[cfg(windows)]
#[cfg(feature = "integrated_tun")]
Expand Down Expand Up @@ -163,12 +163,12 @@ impl Config {
*dest = *mask & *dest;
}
in_ips.sort_by(|(dest1, _, _), (dest2, _, _)| dest2.cmp(dest1));
let local_interface = if let Some(local_ip) = local_ipv4 {
let default_interface = crate::channel::socket::get_interface(local_ip)?;
log::info!("default_interface = {:?}", default_interface);
default_interface
let (local_interface, local_ipv4) = if let Some(local_dev) = local_dev {
let (default_interface, ip) = crate::channel::socket::get_interface(local_dev)?;
log::info!("default_interface = {:?} local_ip= {ip}", default_interface);
(default_interface, Some(ip))
} else {
LocalInterface::default()
(LocalInterface::default(), None)
};
Ok(Self {
#[cfg(feature = "integrated_tun")]
Expand Down

0 comments on commit 501a9e8

Please sign in to comment.