[mio] 创建tun/tap设备

This commit is contained in:
lubeilin
2024-02-29 22:22:25 +08:00
parent 27a6c686a7
commit 9e1bd28e2d
+55 -45
View File
@@ -1,52 +1,62 @@
#[cfg(target_os = "android")] use std::io;
mod android; use std::sync::Arc;
#[cfg(any(target_os = "linux"))]
mod linux; use tun::device::IFace;
#[cfg(any(target_os = "linux", target_os = "macos"))] use tun::Device;
mod linux_mac;
use crate::core::Config;
const DEFAULT_NAME: &str = "vnt0";
pub fn create_device(config: &Config) -> io::Result<Arc<Device>> {
#[cfg(target_os = "linux")]
let device = {
let device_name = config
.device_name
.clone()
.unwrap_or(DEFAULT_NAME.to_string());
if &device_name == DEFAULT_NAME {
delete_device();
}
Arc::new(Device::new(Some(&device_name), config.tap)?)
};
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
mod mac; let device = Arc::new(Device::new(Some(&config.device_name.clone()))?);
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
mod windows; let device = Arc::new(Device::new(
&config
.device_name
.as_ref()
.unwrap_or(&DEFAULT_NAME.to_string()),
config.tap,
)?);
#[cfg(target_os = "android")] #[cfg(target_os = "android")]
pub use android::create; let device = Arc::new(Device::new(config.device_fd as _)?);
#[cfg(target_os = "android")] #[cfg(not(target_os = "android"))]
pub use android::{DeviceReader, DeviceWriter}; {
#[cfg(any(target_os = "linux"))] let mtu = config.mtu.unwrap_or_else(|| {
pub use linux::create_device; if config.password.is_none() {
#[cfg(any(target_os = "linux"))] 1450
pub use linux::delete_device; } else {
#[cfg(any(target_os = "linux", target_os = "macos"))] 1410
pub use linux_mac::{DeviceReader, DeviceWriter}; }
#[cfg(target_os = "macos")] });
pub use mac::create_device; device.set_mtu(mtu)?;
#[cfg(target_os = "macos")] }
pub use mac::delete_device; Ok(device)
#[cfg(target_os = "windows")]
pub use windows::create_device;
#[cfg(target_os = "windows")]
pub use windows::delete_device;
#[cfg(target_os = "windows")]
pub use windows::{DeviceReader, DeviceWriter};
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum DeviceType {
Tun,
Tap,
} }
impl DeviceType { #[cfg(target_os = "linux")]
pub fn is_tun(&self) -> bool { fn delete_device() {
*self == DeviceType::Tun // 删除默认网卡,此操作有风险,后续可能去除
use std::process::Command;
let cmd = format!("ip link delete {}", DEFAULT_NAME);
let delete_tun = Command::new("sh")
.arg("-c")
.arg(&cmd)
.output()
.expect("sh exec error!");
if !delete_tun.status.success() {
log::warn!("删除网卡失败:{:?}", delete_tun);
} }
} }
#[derive(Clone)]
pub struct DriverInfo {
pub device_type: DeviceType,
pub name: String,
pub version: String,
pub mac: Option<String>,
}