Conrad's changes

This commit is contained in:
Conrad Kramer 2023-12-09 18:37:13 -08:00
parent db1750a045
commit 30cd00fc2b
24 changed files with 206 additions and 294 deletions

View file

@ -1,24 +1,24 @@
use std::{
io::{Error, IoSlice},
mem,
mem::{self, ManuallyDrop},
net::{Ipv4Addr, SocketAddrV4},
os::fd::{AsRawFd, RawFd},
os::fd::{AsRawFd, FromRawFd, RawFd},
};
use byteorder::{ByteOrder, NetworkEndian};
use fehler::throws;
use libc::{c_char, iovec, writev, AF_INET, AF_INET6};
use socket2::{Domain, SockAddr, Socket, Type};
use tracing::{self, debug, instrument};
use tracing::{self, instrument};
mod kern_control;
pub mod kern_control;
pub mod sys;
use crate::retrieve;
use kern_control::SysControlSocket;
pub use super::queue::TunQueue;
use super::{ifname_to_string, string_to_ifname, TunOptions};
use super::{ifname_to_string, string_to_ifname};
use crate::TunOptions;
#[derive(Debug)]
pub struct TunInterface {
@ -35,18 +35,41 @@ impl TunInterface {
#[throws]
#[instrument]
pub fn new_with_options(options: TunOptions) -> TunInterface {
debug!("Opening tun interface with options: {:?}", &options);
let ti = if let Some(n) = options.seek_utun {
retrieve().ok_or(Error::new(std::io::ErrorKind::NotFound, "No utun found"))?
} else {
TunInterface::connect(0)?
};
let ti = TunInterface::connect(0)?;
ti.configure(options)?;
ti
}
pub fn retrieve() -> Option<TunInterface> {
(3..100)
.filter_map(|fd| unsafe {
let peer_addr = socket2::SockAddr::init(|storage, len| {
*len = mem::size_of::<sys::sockaddr_ctl>() as u32;
libc::getpeername(fd, storage as *mut _, len);
Ok(())
})
.map(|(_, addr)| (fd, addr));
peer_addr.ok()
})
.filter(|(_fd, addr)| {
let ctl_addr = unsafe { &*(addr.as_ptr() as *const libc::sockaddr_ctl) };
addr.family() == libc::AF_SYSTEM as u8
&& ctl_addr.ss_sysaddr == libc::AF_SYS_CONTROL as u16
})
.map(|(fd, _)| {
let socket = unsafe { socket2::Socket::from_raw_fd(fd) };
TunInterface { socket }
})
.next()
}
#[throws]
fn configure(&self, options: TunOptions) {
if let Some(addr) = options.address {
if let Ok(addr) = addr.parse() {
ti.set_ipv4_addr(addr)?;
self.set_ipv4_addr(addr)?;
}
}
ti
}
#[throws]