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
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165

use std::os::unix::io::{AsRawFd, RawFd, IntoRawFd};
use libc::{c_int, c_uint, c_char};
use std::ffi::{CString};
use std::io::{Read, Write, Result};



extern {
    fn create_macvtap(ifname: *const c_char, device: *mut c_char, mtu: c_uint) -> c_int;
    fn create_tap(ifname: *const c_char, device: *mut c_char, mtu: c_uint) -> c_int;
}


#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Mode {
    Tun,
    Tap,
    MacvTap
}


#[derive(Debug)]
pub struct Iface {
    fd: i32
}


impl Iface {
    /// Creates a new Iface.
    ///
    /// # Examples
    /// ```
    /// modprobe macvtap
    /// 
    /// ip link add link ens192 name tap0 type macvtap mode bridge
    /// 
    /// ```
    ///
    /// ```
    /// use macvtap::{Iface, Mode};
    /// use std::{io::{Read, Write, Result}, vec};
    /// 
    /// // sync read/write
    /// let mut iface = Iface::new("tap0", Mode::MacvTap, 1500)?;
    /// let mut buf = vec![0;1504];
    /// buf.read(&mut buf);
    ///
    /// // async read/write
    /// use smol::{Async};
    ///  
    /// let async_iface = Async::new(iface)?;
    /// async_iface.read(&mut buf).await;
    /// ```
    pub fn new(ifname: &str, mode: Mode, mtu: u32) -> Result<Self> {
        let fd = unsafe {
            let t = CString::new(ifname).unwrap();
            let iface_name = t.as_ptr();
            let mut device = vec![0i8; 256];
            match mode {
                Mode::Tap => { create_tap(iface_name, device.as_mut_ptr(), mtu) },
                Mode::MacvTap => { create_macvtap(iface_name, device.as_mut_ptr(), mtu) },
                _ => { -1 }
            }
        };

        if fd < 0 {
            use std::io::{Error, ErrorKind};
            return Err(Error::new(ErrorKind::Other, "unable to create tap"));
        }

        Ok(Self {
            fd
        })
    }

    pub fn close(&mut self) -> i32 {
        unsafe {
            libc::close(self.fd)
        }
    }
}


impl AsRawFd for Iface {
    fn as_raw_fd(&self) -> RawFd {
        self.fd
    }
}


impl IntoRawFd for Iface {
    fn into_raw_fd(self) -> RawFd {
        self.fd
    }
}


impl Read for &Iface {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        assert!(buf.len() <= isize::max_value() as usize);
        match unsafe { libc::read(self.fd, buf.as_mut_ptr() as _, buf.len()) } {
            x if x < 0 => Err(std::io::Error::last_os_error()),
            x => Ok(x as usize),
        }
    }
}


impl Read for Iface {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        assert!(buf.len() <= isize::max_value() as usize);
        match unsafe { libc::read(self.fd, buf.as_mut_ptr() as _, buf.len()) } {
            x if x < 0 => Err(std::io::Error::last_os_error()),
            x => Ok(x as usize),
        }
    }
}


impl Write for &Iface {
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        assert!(buf.len() <= isize::max_value() as usize);
        match unsafe { libc::write(self.fd, buf.as_ptr() as _, buf.len()) } {
            x if x < 0 => Err(std::io::Error::last_os_error()),
            x => Ok(x as usize),
        }
    }

    fn flush(&mut self) -> Result<()> {
        Ok(())
    }
}


impl Write for Iface {
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        assert!(buf.len() <= isize::max_value() as usize);
        match unsafe { libc::write(self.fd, buf.as_ptr() as _, buf.len()) } {
            x if x < 0 => Err(std::io::Error::last_os_error()),
            x => Ok(x as usize),
        }
    }

    fn flush(&mut self) -> Result<()> {
        Ok(())
    }
}


impl Drop for Iface {
    fn drop(&mut self) {
        let _ = self.close();
    }
}




#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
    }
}