use std::{
mem,
os::fd::{AsRawFd as _, BorrowedFd},
ptr,
};
use dope_sys::io::socket::route::{
Attach, Plan,
count::Index,
install::{Error, Operation},
};
use crate::Backend;
use dope_sys::{Errno, kernel};
mod program;
mod source;
pub struct Installer<'a> {
pub(super) plan: Plan,
pub(super) filter: &'a mut [libc::sock_filter],
}
impl Attach for Installer<'_> {
fn try_attach(&self, socket: BorrowedFd<'_>) -> Result<(), Error> {
let mut code = [program::EMPTY; program::MAX];
attach(
socket,
program::build(&mut code, self.plan, None),
Operation::Program,
)
}
fn try_filter(&mut self, key: Index, socket: BorrowedFd<'_>) -> Result<(), Error> {
let index = self.filter.len() - 3;
self.filter[index].k = key.into_raw() as u32;
attach(socket, self.filter, Operation::Filter)
}
}
fn attach(socket: BorrowedFd<'_>, code: &[libc::sock_filter], op: Operation) -> Result<(), Error> {
let program = libc::sock_fprog {
len: code.len() as u16,
filter: code.as_ptr().cast_mut(),
};
let option = match op {
Operation::Program => libc::SO_ATTACH_REUSEPORT_CBPF,
Operation::Filter => libc::SO_ATTACH_FILTER,
};
let result = unsafe {
libc::setsockopt(
socket.as_raw_fd(),
libc::SOL_SOCKET,
option,
ptr::from_ref(&program).cast(),
mem::size_of_val(&program) as libc::socklen_t,
)
};
unsafe { kernel::raw::Status::new(result).try_zero::<Backend, Errno>() }.map_err(|errno| {
Error {
operation: op,
errno,
}
})
}