1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use crate::interface::new_interface;
use crate::interface::Interface;
#[cfg(target_os = "linux")]
use crate::linux::ifreq::{ifreq, tunsetiff};
use crate::params::Params;
use crate::result::Result;
use async_std::fs::File;
#[cfg(target_os = "linux")]
use async_std::fs::OpenOptions;
#[cfg(target_os = "linux")]
use async_std::os::unix::io::{AsRawFd, FromRawFd};
#[cfg(target_os = "linux")]
use nix::errno::Errno;
use std::ops::{Deref, DerefMut};

/// Represents a Tun/Tap device. Use [TunBuilder](struct.TunBuilder.html) to create a new instance of [Tun](struct.Tun.html).
pub struct Tun {
    file: File,
    name: String,
}

impl Tun {
    #[cfg(target_os = "linux")]
    async fn alloc(params: Params) -> Result<(File, String)> {
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .open("/dev/net/tun")
            .await?;
        let iface = new_interface::<ifreq>(params)?;
        unsafe { tunsetiff(file.as_raw_fd(), &iface as *const _ as _) }.and_then(|ret| {
            if ret < 0 {
                Err(Errno::from_i32(ret).into())
            } else {
                Ok(())
            }
        })?;
        Ok((file, iface.name()))
    }

    #[cfg(not(any(target_os = "linux")))]
    async fn alloc(params: Params) -> Result<Self> {
        unimplemented!()
    }

    /// Creates a new instance of Tun/Tap device.
    pub(super) async fn new(params: Params) -> Result<Self> {
        let (file, name) = Self::alloc(params).await?;
        Ok(Self { file, name })
    }

    /// Returns the name of Tun/Tap device.
    pub fn name(&self) -> &str {
        self.name.as_str()
    }
}

impl Clone for Tun {
    #[cfg(target_os = "linux")]
    fn clone(&self) -> Self {
        Self {
            file: unsafe { File::from_raw_fd(self.file.as_raw_fd()) },
            name: self.name.clone(),
        }
    }

    #[cfg(not(any(target_os = "linux")))]
    fn clone(&self) -> Self {
        unimplemented!()
    }
}

impl Deref for Tun {
    type Target = File;

    fn deref(&self) -> &Self::Target {
        &self.file
    }
}

impl DerefMut for Tun {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.file
    }
}