Skip to main content

ios_core/tunnel/tun/
kernel.rs

1//! Kernel TUN device via tun-rs.
2//!
3//! Creates a TUN interface using the OS kernel networking stack.
4//! Requires administrator/root privileges.
5
6use tun_rs::{AsyncDevice, DeviceBuilder};
7
8use crate::tunnel::tun::TunDevice;
9use crate::tunnel::TunnelError;
10
11pub struct KernelTunDevice {
12    device: AsyncDevice,
13    packet_buf: Vec<u8>,
14}
15
16impl KernelTunDevice {
17    /// Create a kernel TUN device with the given IPv6 address and MTU.
18    pub async fn create(client_address: &str, mtu: u32) -> Result<Self, TunnelError> {
19        let device = DeviceBuilder::new()
20            .ipv6(client_address, 64)
21            .mtu(mtu as u16)
22            .build_async()
23            .map_err(TunnelError::Io)?;
24
25        Ok(Self {
26            device,
27            packet_buf: vec![0u8; mtu as usize + 64],
28        })
29    }
30}
31
32impl TunDevice for KernelTunDevice {
33    async fn read_packet(&mut self) -> Result<Vec<u8>, TunnelError> {
34        let n = self.device.recv(&mut self.packet_buf).await?;
35        Ok(self.packet_buf[..n].to_vec())
36    }
37
38    async fn write_packet(&mut self, packet: &[u8]) -> Result<(), TunnelError> {
39        self.device.send(packet).await?;
40        Ok(())
41    }
42}