Start Tun Interface at Daemon Command

This commit is contained in:
Jett Chen 2023-12-09 20:13:49 +08:00
parent 2cb9dd75ca
commit 17610ff90d
9 changed files with 83 additions and 52 deletions

View file

@ -13,6 +13,10 @@ pub struct TunOptions {
pub(crate) no_pi: Option<()>,
/// (Linux) Avoid opening an existing persistant device.
pub(crate) tun_excl: Option<()>,
/// (MacOS) Whether to seek the first available utun device.
pub(crate) seek_utun: Option<()>,
/// (Linux) The IP address of the tun interface.
pub(crate) address: Option<String>,
}
impl TunOptions {
@ -27,6 +31,11 @@ impl TunOptions {
pub fn tun_excl(mut self, enable: bool) { self.tun_excl = enable.then_some(()); }
pub fn address(mut self, address: impl ToString) -> Self {
self.address = Some(address.to_string());
self
}
#[throws]
pub fn open(self) -> TunInterface { TunInterface::new_with_options(self)? }
}

View file

@ -10,7 +10,8 @@ pub struct TunInterface {
impl TunInterface {
#[instrument]
pub fn new(tun: crate::TunInterface) -> io::Result<Self> {
pub fn new(mut tun: crate::TunInterface) -> io::Result<Self> {
tun.set_nonblocking(true)?;
Ok(Self {
inner: AsyncFd::new(tun)?,
})

View file

@ -33,8 +33,14 @@ impl TunInterface {
#[throws]
#[instrument]
pub fn new_with_options(_: TunOptions) -> TunInterface {
TunInterface::connect(0)?
pub fn new_with_options(options: TunOptions) -> TunInterface {
let ti = TunInterface::connect(0)?;
if let Some(addr) = options.address{
if let Ok(addr) = addr.parse() {
ti.set_ipv4_addr(addr)?;
}
}
ti
}
#[throws]