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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
//! # tap-windows
//! Library to interface with the tap-windows driver
//! created by OpenVPN to manage tap interfaces.
//! Look at the documentation for `Device` for a
//! pretty simple example on how to use this library.
#![cfg(windows)]

/// Encode a string as a utf16 buffer
fn encode_utf16(string: &str) -> Vec<u16> {
    use std::iter::once;
    string.encode_utf16().chain(once(0)).collect()
}

/// Decode a string from a utf16 buffer
fn decode_utf16(string: &[u16]) -> String {
    let end = string.iter().position(|b| *b == 0).unwrap_or(string.len());
    String::from_utf16_lossy(&string[..end])
}

mod ffi;
mod iface;
mod netsh;

use std::{io, net, time};
use winapi::shared::ifdef::NET_LUID;
use winapi::um::winioctl::*;
use winapi::um::winnt::HANDLE;

/// A tap-windows device handle, it offers facilities to:
/// - create, open and delete interfaces
/// - write and read the current configuration
/// - write and read packets from the device
/// Example
/// ```no_run
/// use tap_windows::Device;
/// use std::io::Read;
///
/// const MY_INTERFACE: &str = "My Interface";
///
/// // Try to open the device
/// let mut dev = Device::open(MY_INTERFACE)
///     .or_else(|_| -> std::io::Result<_> {
///         // The device does not exists...
///         // try creating a new one
///         
///         let dev = Device::create()?;
///         dev.set_name(MY_INTERFACE)?;
///     
///         Ok(dev)
///     })
///     // Everything failed, just panic
///     .expect("Failed to open device");
///
/// // Set the device ip
/// dev.set_ip([192, 168, 60, 1], [255, 255, 255, 0])
///     .expect("Failed to set device ip");
///
/// // Setup read buffer
/// let mtu = dev.get_mtu().unwrap_or(1500);
/// let mut buf = vec![0; mtu as usize];
///
/// // Read a single packet from the device
/// let amt = dev.read(&mut buf)
///     .expect("Failed to read packet");
///
/// // Print it
/// println!("{:#?}", &buf[..amt]);
/// ```
pub struct Device {
    luid: NET_LUID,
    handle: HANDLE,
}

impl Device {
    /// Creates a new tap-windows device
    /// Example
    /// ```no_run
    /// use tap_windows::Device;
    ///
    /// let dev = Device::create()
    ///     .expect("Failed to create device");
    ///
    /// println!("{:?}", dev.get_name());
    /// ```
    pub fn create() -> io::Result<Self> {
        let luid = iface::create_interface()?;

        // Even after retrieving the luid, we might need to wait
        let start = time::Instant::now();
        let handle = loop {
            // If we surpassed 2 seconds just return
            let now = time::Instant::now();
            if now - start > time::Duration::from_secs(2) {
                return Err(io::Error::new(
                    io::ErrorKind::TimedOut,
                    "Interface timed out",
                ));
            }

            match iface::open_interface(&luid) {
                Err(_) => {
                    std::thread::yield_now();
                    continue;
                }
                Ok(handle) => break handle,
            };
        };

        Ok(Self { luid, handle })
    }

    /// Opens an existing tap-windows device by name
    /// Example
    /// ```no_run
    /// use tap_windows::Device;
    ///
    /// let dev = Device::open("My Own Device")
    ///     .expect("Failed to open device");
    ///
    /// println!("{:?}", dev.get_name());
    /// ```
    pub fn open(name: &str) -> io::Result<Self> {
        let name = encode_utf16(name);

        let luid = ffi::alias_to_luid(&name)?;
        iface::check_interface(&luid)?;

        let handle = iface::open_interface(&luid)?;

        Ok(Self { luid, handle })
    }

    /// Deletes the interface before closing it.
    /// By default interfaces are never deleted on Drop,
    /// with this you can choose if you want deletion or not
    /// Example
    /// ```no_run
    /// use tap_windows::Device;
    ///
    /// let dev = Device::create()
    ///     .expect("Failed to create device");
    ///
    /// println!("{:?}", dev.get_name());
    ///
    /// // Perform a quick cleanup before exiting
    /// dev.delete().expect("Failed to delete device");
    /// ```
    pub fn delete(self) -> io::Result<()> {
        iface::delete_interface(&self.luid)?;

        Ok(())
    }

    /// Sets the status of the interface to connected.
    /// Equivalent to `.set_status(true)`
    pub fn up(&self) -> io::Result<()> {
        self.set_status(true)
    }

    /// Sets the status of the interface to disconnected.
    /// Equivalent to `.set_status(false)`
    pub fn down(&self) -> io::Result<()> {
        self.set_status(false)
    }

    /// Retieve the mac of the interface
    pub fn get_mac(&self) -> io::Result<[u8; 6]> {
        let mut mac = [0; 6];

        ffi::device_io_control(
            self.handle,
            CTL_CODE(FILE_DEVICE_UNKNOWN, 1, METHOD_BUFFERED, FILE_ANY_ACCESS),
            &(),
            &mut mac,
        )
        .map(|_| mac)
    }

    /// Retrieve the version of the driver
    pub fn get_version(&self) -> io::Result<[u32; 3]> {
        let mut version = [0; 3];

        ffi::device_io_control(
            self.handle,
            CTL_CODE(FILE_DEVICE_UNKNOWN, 2, METHOD_BUFFERED, FILE_ANY_ACCESS),
            &(),
            &mut version,
        )
        .map(|_| version)
    }

    /// Retieve the mtu of the interface
    pub fn get_mtu(&self) -> io::Result<u32> {
        let mut mtu = 0;

        ffi::device_io_control(
            self.handle,
            CTL_CODE(FILE_DEVICE_UNKNOWN, 3, METHOD_BUFFERED, FILE_ANY_ACCESS),
            &(),
            &mut mtu,
        )
        .map(|_| mtu)
    }

    /// Retrieve the name of the interface
    pub fn get_name(&self) -> io::Result<String> {
        ffi::luid_to_alias(&self.luid).map(|name| decode_utf16(&name))
    }

    /// Set the name of the interface
    pub fn set_name(&self, newname: &str) -> io::Result<()> {
        let name = self.get_name()?;
        netsh::set_interface_name(&name, newname)
    }

    /// Set the ip of the interface
    /// ```no_run
    /// use tap_windows::Device;
    ///
    /// let dev = Device::create()
    ///     .expect("Failed to create device");
    ///
    /// dev.set_ip([192, 168, 60, 1], [255, 255, 255, 0])
    ///     .expect("Failed to set interface ip");
    ///
    /// println!("{:?}", dev.get_name());
    /// ```
    pub fn set_ip<A, B>(&self, address: A, mask: B) -> io::Result<()>
    where
        A: Into<net::Ipv4Addr>,
        B: Into<net::Ipv4Addr>,
    {
        let name = self.get_name()?;
        let address = address.into().to_string();
        let mask = mask.into().to_string();

        netsh::set_interface_ip(&name, &address, &mask)
    }

    /// Set the status of the interface, true for connected,
    /// false for disconnected.
    pub fn set_status(&self, status: bool) -> io::Result<()> {
        let status: u32 = if status { 1 } else { 0 };

        ffi::device_io_control(
            self.handle,
            CTL_CODE(FILE_DEVICE_UNKNOWN, 6, METHOD_BUFFERED, FILE_ANY_ACCESS),
            &status,
            &mut (),
        )
    }
}

impl io::Read for Device {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        ffi::read_file(self.handle, buf).map(|res| res as _)
    }
}

impl io::Write for Device {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        ffi::write_file(self.handle, buf).map(|res| res as _)
    }

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

impl Drop for Device {
    fn drop(&mut self) {
        let _ = ffi::close_handle(self.handle);
    }
}