tun-rs 2.8.3

Cross-platform TUN and TAP library
Documentation
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
/*
link https://github.com/apple-oss-distributions/xnu/blob/main/bsd/sys/sockio.h
link https://github.com/apple-oss-distributions/xnu/blob/main/bsd/net/if_fake.c
link https://www.zerotier.com/blog/how-zerotier-eliminated-kernel-extensions-on-macos/
 */
/*
* link https://github.com/zerotier/ZeroTierOne/blob/dev/osdep/MacEthernetTapAgent.c
*
* This creates a pair of feth devices with the lower numbered device
* being the virtual interface and the other being the device
* used to actually read and write packets. The latter gets no IP config
* and is only used for I/O. The behavior of feth is similar to the
* veth pairs that exist on Linux.
*
* The feth device has only existed since MacOS Sierra, but that's fairly
* long ago in Mac terms.
*
* I/O with feth must be done using two different sockets. The BPF socket
* is used to receive packets, while an AF_NDRV (low-level network driver
* access) socket must be used to inject. AF_NDRV can't read IP frames
* since BSD doesn't forward packets out the NDRV tap if they've already
* been handled, and while BPF can inject its MTU for injected packets
* is limited to 2048.
*
* All this stuff is basically undocumented. A lot of tracing through
* the Darwin/XNU kernel source was required to figure out how to make
* this actually work.

*
* See also:
*
* https://apple.stackexchange.com/questions/337715/fake-ethernet-interfaces-feth-if-fake-anyone-ever-seen-this
*
*/
use crate::builder::DeviceConfig;
use crate::platform::macos::sys::siocifcreate;
use crate::platform::unix::Fd;
use bytes::BytesMut;
use libc::{ifreq, IFNAMSIZ};
use nix::errno::Errno;
use std::collections::VecDeque;
use std::ffi::{CStr, CString};
use std::io;
use std::io::{IoSlice, IoSliceMut};
use std::os::fd::{AsRawFd, IntoRawFd, RawFd};
use std::sync::Mutex;

const FETH: &str = "feth";
const BUFFER_LEN: usize = 131072;
pub(crate) fn run_command(command: &str, args: &[&str]) -> io::Result<()> {
    let out = std::process::Command::new(command).args(args).output()?;
    if !out.status.success() {
        let err = String::from_utf8_lossy(if out.stderr.is_empty() {
            &out.stdout
        } else {
            &out.stderr
        });
        let info = format!("{command} failed with: \"{err}\"");
        return Err(io::Error::other(info));
    }
    Ok(())
}

pub struct Tap {
    s_bpf_fd: Fd,
    s_ndrv_fd: Fd,
    peer_feth: Feth,
    dev_feth: Feth,
    buffer: Mutex<VecDeque<BytesMut>>,
}
struct Feth {
    is_drop: bool,
    name: String,
}
impl Drop for Feth {
    fn drop(&mut self) {
        if self.is_drop {
            _ = run_command("ifconfig", &[&self.name, "destroy"]);
            self.is_drop = false;
        }
    }
}
impl IntoRawFd for Tap {
    fn into_raw_fd(mut self) -> RawFd {
        self.peer_feth.is_drop = false;
        self.dev_feth.is_drop = false;
        self.s_bpf_fd.into_raw_fd()
    }
}
impl Tap {
    pub fn new(config: &DeviceConfig) -> io::Result<Tap> {
        unsafe {
            let s_ndrv_fd = libc::socket(libc::AF_NDRV, libc::SOCK_RAW, 0);
            let s_ndrv_fd = Fd::new(s_ndrv_fd)?;
            _ = s_ndrv_fd.set_cloexec();
            let mut ifr = new_ifreq(config.dev_name.as_ref())?;
            if let Err(e) = siocifcreate(s_ndrv_fd.inner, &mut ifr) {
                if e != Errno::EEXIST || !config.reuse_dev.unwrap_or(true) {
                    return Err(e.into());
                }
            }

            let dev_name = CStr::from_ptr(ifr.ifr_name.as_ptr())
                .to_string_lossy()
                .into_owned();
            let dev_feth = Feth {
                is_drop: !config.persist.unwrap_or(false),
                name: dev_name,
            };
            std::thread::sleep(std::time::Duration::from_millis(1));
            let mut peer_ifr = new_ifreq(config.peer_feth.as_ref())?;
            if let Err(e) = siocifcreate(s_ndrv_fd.inner, &mut peer_ifr) {
                if e != Errno::EEXIST || !config.reuse_dev.unwrap_or(true) {
                    return Err(e.into());
                }
            }
            let peer_name = CStr::from_ptr(peer_ifr.ifr_name.as_ptr())
                .to_string_lossy()
                .into_owned();
            let peer_feth = Feth {
                is_drop: !config.persist.unwrap_or(false),
                name: peer_name,
            };
            std::thread::sleep(std::time::Duration::from_millis(1));
            run_command("ifconfig", &[&peer_feth.name, "peer", &dev_feth.name])?;
            let mut nd: libc::sockaddr_ndrv = std::mem::zeroed();
            nd.snd_len = size_of::<libc::sockaddr_ndrv>() as u8;
            nd.snd_family = libc::AF_NDRV as u8;
            // Ensure the name fits within snd_name to prevent buffer overflow
            let name_bytes = peer_feth.name.as_bytes();
            if name_bytes.len() > nd.snd_name.len() {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!(
                        "Interface name '{}' is too long (max {} bytes)",
                        peer_feth.name,
                        nd.snd_name.len()
                    ),
                ));
            }
            nd.snd_name[..name_bytes.len()].copy_from_slice(name_bytes);
            if libc::bind(
                s_ndrv_fd.inner,
                &nd as *const _ as *const libc::sockaddr,
                size_of::<libc::sockaddr_ndrv>() as u32,
            ) != 0
            {
                return Err(io::Error::last_os_error());
            }
            if libc::connect(
                s_ndrv_fd.inner,
                &nd as *const _ as *const libc::sockaddr,
                size_of::<libc::sockaddr_ndrv>() as u32,
            ) != 0
            {
                return Err(io::Error::last_os_error());
            }
            let s_bpf_fd = open_bpf()?;
            let mut buffer_len = BUFFER_LEN;
            let rs = libc::ioctl(s_bpf_fd.inner, libc::BIOCSBLEN, &mut buffer_len);
            if rs != 0 {
                return Err(io::Error::last_os_error());
            }
            let mut enable = 1i32;
            let mut disable = 0i32;
            let rs = libc::ioctl(s_bpf_fd.inner, libc::BIOCIMMEDIATE, &mut enable);
            if rs != 0 {
                return Err(io::Error::last_os_error());
            }
            let rs = libc::ioctl(s_bpf_fd.inner, libc::BIOCSSEESENT, &mut disable);
            if rs != 0 {
                return Err(io::Error::last_os_error());
            }

            let rs = libc::ioctl(s_bpf_fd.inner, libc::BIOCSETIF, &mut peer_ifr);
            if rs != 0 {
                return Err(io::Error::last_os_error());
            }
            let rs = libc::ioctl(s_bpf_fd.inner, libc::BIOCSHDRCMPLT, &mut enable);
            if rs != 0 {
                return Err(io::Error::last_os_error());
            }
            let rs = libc::ioctl(s_bpf_fd.inner, libc::BIOCPROMISC as u64, &mut enable);
            if rs != 0 {
                return Err(io::Error::last_os_error());
            }
            Ok(Self {
                s_bpf_fd,
                s_ndrv_fd,
                dev_feth,
                peer_feth,
                buffer: Default::default(),
            })
        }
    }
    // pub fn as_s_ndrv_fd(&self) -> RawFd {
    //     self.s_ndrv_fd.as_raw_fd()
    // }
    // pub fn as_s_bpf_fd(&self) -> RawFd {
    //     self.s_bpf_fd.as_raw_fd()
    // }
    pub fn name(&self) -> &String {
        &self.dev_feth.name
    }
    pub fn peer_name(&self) -> &String {
        &self.peer_feth.name
    }
    pub fn is_nonblocking(&self) -> io::Result<bool> {
        self.s_bpf_fd.is_nonblocking()
    }
    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
        self.s_bpf_fd.set_nonblocking(nonblocking)?;
        self.s_ndrv_fd.set_nonblocking(nonblocking)?;
        Ok(())
    }
    #[inline]
    pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
        self.s_ndrv_fd.write(buf)
    }
    #[inline]
    pub fn send_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
        self.s_ndrv_fd.writev(bufs)
    }
    pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
        let mut guard = self.buffer.lock().unwrap();
        if guard.is_empty() {
            self.recv_to_buffer(&mut guard)?;
        }

        let Some(buffer) = guard.pop_front() else {
            return Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "recv buffer is empty",
            ));
        };
        if buf.len() < buffer.len() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "buffer too small",
            ));
        }
        buf[..buffer.len()].copy_from_slice(&buffer);
        Ok(buffer.len())
    }
    fn recv_to_buffer(&self, bufs: &mut VecDeque<BytesMut>) -> io::Result<()> {
        let mut buffer = [0; BUFFER_LEN];
        let len = self.s_bpf_fd.read(&mut buffer)?;
        if len > 0 {
            let mut p = 0;
            unsafe {
                while p < len {
                    let hdr = buffer.as_ptr().add(p) as *const libc::bpf_hdr;
                    let bh_caplen = (*hdr).bh_caplen as usize;
                    let bh_hdrlen = (*hdr).bh_hdrlen as usize;
                    if bh_caplen > 0 && p + bh_hdrlen + bh_caplen <= len {
                        let buf = &buffer[p + bh_hdrlen..p + bh_hdrlen + bh_caplen];
                        bufs.push_back(buf.into());
                    }
                    p += ((*hdr).bh_hdrlen as usize + bh_caplen + 3) & !3;
                }
            }
        }
        Ok(())
    }
    #[allow(dead_code)]
    pub fn recv_multiple<B: AsRef<[u8]> + AsMut<[u8]>>(
        &self,
        bufs: &mut [B],
        sizes: &mut [usize],
    ) -> io::Result<usize> {
        let mut buffer = [0; BUFFER_LEN];
        let len = self.s_bpf_fd.read(&mut buffer)?;
        let mut num = 0;
        if len > 0 {
            let mut p = 0;
            unsafe {
                while p < len {
                    let hdr = buffer.as_ptr().add(p) as *const libc::bpf_hdr;
                    let bh_caplen = (*hdr).bh_caplen as usize;
                    let bh_hdrlen = (*hdr).bh_hdrlen as usize;
                    if bh_caplen > 0 && p + bh_hdrlen + bh_caplen <= len {
                        let buf = &buffer[p + bh_hdrlen..p + bh_hdrlen + bh_caplen];
                        if let Some(dst) = bufs.get_mut(num) {
                            let dst = dst.as_mut();
                            if dst.len() < buf.len() {
                                return Err(io::Error::new(
                                    io::ErrorKind::InvalidData,
                                    "buffer too small",
                                ));
                            }
                            dst[..buf.len()].copy_from_slice(buf);
                            sizes[num] = buf.len();
                            num += 1;
                        } else {
                            break;
                        }
                    }
                    p += ((*hdr).bh_hdrlen as usize + bh_caplen + 3) & !3;
                }
            }
        }
        Ok(num)
    }
    pub fn recv_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
        let mut guard = self.buffer.lock().unwrap();
        if guard.is_empty() {
            self.recv_to_buffer(&mut guard)?;
        }

        let Some(buf) = guard.pop_front() else {
            return Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "recv buffer is empty",
            ));
        };
        let len: usize = bufs.iter().map(|v| v.len()).sum();
        if len < buf.len() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "buffer too small",
            ));
        }
        let mut pos = 0;
        for b in bufs {
            let n = b.len().min(buf.len() - pos);
            if n == 0 {
                break;
            }
            b[..n].copy_from_slice(&buf[pos..pos + n]);
            pos += n;
            if pos == buf.len() {
                break;
            }
        }
        Ok(pos)
    }
    #[cfg(feature = "interruptible")]
    #[inline]
    pub(crate) fn read_interruptible(
        &self,
        buf: &mut [u8],
        event: &crate::InterruptEvent,
        timeout: Option<std::time::Duration>,
    ) -> io::Result<usize> {
        loop {
            self.wait_readable_interruptible(event, timeout)?;
            match self.recv(buf) {
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue,
                rs => return rs,
            }
        }
    }
    #[cfg(feature = "interruptible")]
    #[inline]
    pub(crate) fn readv_interruptible(
        &self,
        bufs: &mut [IoSliceMut<'_>],
        event: &crate::InterruptEvent,
        timeout: Option<std::time::Duration>,
    ) -> io::Result<usize> {
        loop {
            self.wait_readable_interruptible(event, timeout)?;
            match self.recv_vectored(bufs) {
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue,
                rs => return rs,
            }
        }
    }
    #[cfg(feature = "interruptible")]
    #[inline]
    pub(crate) fn wait_readable_interruptible(
        &self,
        event: &crate::InterruptEvent,
        timeout: Option<std::time::Duration>,
    ) -> io::Result<()> {
        self.s_bpf_fd.wait_readable(Some(event), timeout)
    }
    #[cfg(feature = "interruptible")]
    #[inline]
    pub(crate) fn write_interruptible(
        &self,
        buf: &[u8],
        event: &crate::InterruptEvent,
    ) -> io::Result<usize> {
        loop {
            self.wait_writable_interruptible(event)?;
            return match self.s_ndrv_fd.write(buf) {
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                    continue;
                }
                rs => rs,
            };
        }
    }
    #[cfg(feature = "interruptible")]
    #[inline]
    pub(crate) fn writev_interruptible(
        &self,
        bufs: &[IoSlice<'_>],
        event: &crate::InterruptEvent,
    ) -> io::Result<usize> {
        loop {
            self.wait_writable_interruptible(event)?;
            return match self.s_ndrv_fd.writev(bufs) {
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                    continue;
                }
                rs => rs,
            };
        }
    }
    #[cfg(feature = "interruptible")]
    #[inline]
    pub(crate) fn wait_writable_interruptible(
        &self,
        event: &crate::InterruptEvent,
    ) -> io::Result<()> {
        self.s_ndrv_fd.wait_writable(Some(event), None)
    }
}
impl AsRawFd for Tap {
    fn as_raw_fd(&self) -> RawFd {
        self.s_bpf_fd.as_raw_fd()
    }
}

fn open_bpf() -> io::Result<Fd> {
    for i in 1..5000 {
        let path = CString::new(format!("/dev/bpf{i}").into_bytes())?;
        let bpf_fd = unsafe { libc::open(path.as_ptr(), libc::O_RDWR) };
        match Fd::new(bpf_fd) {
            Ok(fd) => {
                _ = fd.set_cloexec();
                return Ok(fd);
            }
            Err(e) => {
                if e.raw_os_error() == Some(libc::EBUSY) {
                    continue;
                } else {
                    return Err(e);
                }
            }
        }
    }
    Err(io::Error::new(
        io::ErrorKind::NotFound,
        "No available /dev/bpf",
    ))
}
fn new_ifreq(name: Option<&String>) -> io::Result<ifreq> {
    if let Some(name) = name {
        new_ifreq_str(name.as_str())
    } else {
        new_ifreq_str(FETH)
    }
}
fn new_ifreq_str(name: &str) -> io::Result<ifreq> {
    let bytes = name.as_bytes();
    if bytes.len() >= IFNAMSIZ {
        return Err(io::Error::new(io::ErrorKind::InvalidInput, "name too long"));
    }
    if bytes.len() < 4 || &bytes[..4] != FETH.as_bytes() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "The prefix of the network card name must be 'feth'",
        ));
    }
    let mut ifr: ifreq = unsafe { std::mem::zeroed() };
    for (i, &b) in bytes.iter().enumerate() {
        ifr.ifr_name[i] = b as libc::c_char;
    }
    ifr.ifr_name[bytes.len()] = 0;
    Ok(ifr)
}