Skip to main content

dope_core/io/socket/install/
mod.rs

1pub mod adopt;
2pub mod receive;
3pub mod slot;
4
5mod error;
6
7use std::{mem, net, os::fd};
8
9use dope_sys::{
10    Errno, engine,
11    io::socket::{Domain, Kind, Prepare, Socket as _, addr, option::Source as _},
12    kernel,
13};
14pub use error::Error;
15use fd::AsFd as _;
16
17use crate::{
18    driver::{self, route::indices::SlotIndex},
19    io::{
20        datagram,
21        fd::handles::{Datagram, Descriptor, OwnedSlot},
22        socket,
23    },
24};
25
26/// Operating-system operation that failed while bootstrapping a descriptor.
27#[derive(Clone, Copy, PartialEq, Eq, Debug)]
28#[repr(u8)]
29pub enum Operation {
30    Socket,
31    ReuseAddress,
32    ReusePort,
33    FastOpen,
34    Bind,
35    Listen,
36    Validate,
37    FixedFile,
38}
39
40pub struct Install<'borrow, 'd> {
41    driver: &'borrow mut driver::Local<'d>,
42    reservation: slot::Reserved<'d>,
43}
44
45fn reserve<'d, 'a>(driver: &'a mut driver::Local<'d>) -> Result<Install<'a, 'd>, Error> {
46    Ok(Install {
47        reservation: slot::Reserved::try_new(driver.driver_ref()).map_err(Error::Slot)?,
48        driver,
49    })
50}
51
52fn reserve_datagram<'d, 'a>(
53    driver: &'a mut driver::Local<'d>,
54) -> Result<(Install<'a, 'd>, receive::Capacity<'d>), Error> {
55    let capacity = receive::Capacity::try_new(driver.driver_ref()).map_err(Error::Receive)?;
56    Ok((reserve(driver)?, capacity))
57}
58
59impl<'borrow, 'd> Install<'borrow, 'd> {
60    fn bind<F>(
61        self,
62        addr: net::SocketAddr,
63        config: &socket::Config,
64        depth: Option<socket::Backlog>,
65    ) -> Result<(Descriptor<'d>, net::SocketAddr), Error>
66    where
67        crate::Backend: Prepare<Fast = F>,
68    {
69        let fast = crate::Backend::fast_open(config.fast_open().map(Into::into))
70            .map_err(|error| Error::FastOpen(error.0))?;
71        let domain = Domain::for_addr(&addr);
72        let handle = if depth.is_some() {
73            crate::Backend::listener(domain)
74        } else {
75            crate::Backend::open(domain, Kind::Dgram)
76        }
77        .map_err(Error::create)?;
78        let handle = socket::Handle::new(handle);
79        handle.try_reuse(config).map_err(Error::reuse)?;
80        if let Some(fast) = fast {
81            crate::Backend::set_fast(handle.owned().as_fd(), fast)
82                .map_err(|errno| Error::syscall(Operation::FastOpen, errno))?;
83        }
84        handle
85            .bind(&socket::Inet::from(&addr))
86            .map_err(|errno| Error::syscall(Operation::Bind, errno))?;
87        if let Some(depth) = depth {
88            handle
89                .listen(depth.get())
90                .map_err(|errno| Error::syscall(Operation::Listen, errno))?;
91        }
92        self.finish(handle)
93    }
94
95    fn adopt(file: fd::OwnedFd, kind: Kind) -> Result<socket::Handle, Error> {
96        let handle = socket::Handle::new(crate::Backend::adopt(file).map_err(Error::Setup)?);
97        let actual =
98            crate::Backend::kind::<Errno>(handle.owned().as_fd()).map_err(Error::validate)?;
99        match kind {
100            Kind::Stream if !actual.is_stream() => {
101                return Err(Error::Adopt(adopt::Error::StreamKind {
102                    actual: actual.raw(),
103                }));
104            }
105            Kind::Dgram if !actual.is_datagram() => {
106                return Err(Error::Adopt(adopt::Error::DatagramKind {
107                    actual: actual.raw(),
108                }));
109            }
110            Kind::Stream | Kind::Dgram => {}
111        }
112        Ok(handle)
113    }
114
115    fn finish(self, handle: socket::Handle) -> Result<(Descriptor<'d>, net::SocketAddr), Error> {
116        let local = socket::View::local(handle.owned().as_fd(), &mut addr::Storage::empty())
117            .map_err(Error::LocalAddress)?
118            .into_std()
119            .map_err(Error::Address)?;
120        Ok((self.install(handle.into_inner())?, local))
121    }
122
123    fn install<H, E>(self, handle: H) -> Result<Descriptor<'d>, Error>
124    where
125        crate::Engine: engine::Install<OwnedSlot, H, Error = E>,
126        E: Into<<crate::Backend as kernel::Source>::Failure<SlotIndex>>,
127    {
128        match self.driver.native().install(self.reservation, handle) {
129            Ok(fd) => Ok(fd),
130            Err(cause) => Err(Error::kernel(Operation::FixedFile, cause)),
131        }
132    }
133}
134
135const _: () = {
136    assert!(
137        mem::size_of::<Install<'static, 'static>>()
138            == mem::size_of::<usize>() + mem::size_of::<slot::Reserved<'static>>()
139    );
140    assert!(mem::align_of::<Install<'static, 'static>>() == mem::align_of::<usize>());
141};
142
143impl<'borrow, 'd> Install<'borrow, 'd> {
144    /// Binds a Unix listener without converting its address to an Internet address.
145    pub fn bind_unix(
146        driver: &mut driver::Local<'d>,
147        addr: &socket::Unix,
148        depth: socket::Backlog,
149    ) -> Result<Descriptor<'d>, Error> {
150        let entry = reserve(driver)?;
151        let handle = crate::Backend::listener(Domain::Unix).map_err(Error::create)?;
152        let handle = socket::Handle::new(handle);
153        handle
154            .bind(addr)
155            .map_err(|errno| Error::syscall(Operation::Bind, errno))?;
156        handle
157            .listen(depth.get())
158            .map_err(|errno| Error::syscall(Operation::Listen, errno))?;
159        entry.install(handle.into_inner())
160    }
161
162    pub fn bind_stream(
163        driver: &mut driver::Local<'d>,
164        addr: net::SocketAddr,
165        depth: socket::Backlog,
166        config: &socket::Config,
167    ) -> Result<(Descriptor<'d>, net::SocketAddr), Error> {
168        reserve(driver)?.bind(addr, config, Some(depth))
169    }
170
171    pub fn adopt_stream(
172        driver: &mut driver::Local<'d>,
173        fd: fd::OwnedFd,
174    ) -> Result<(Descriptor<'d>, net::SocketAddr), Error> {
175        let entry = reserve(driver)?;
176        let handle = Self::adopt(fd, Kind::Stream)?;
177        if !crate::Backend::is_listening(handle.owned().as_fd()).map_err(Error::Listening)? {
178            return Err(Error::Adopt(adopt::Error::ListenerState { actual: 0 }));
179        }
180        entry.finish(handle)
181    }
182
183    /// Installs an owned connected Internet stream.
184    pub fn adopt_peer(
185        driver: &mut driver::Local<'d>,
186        fd: fd::OwnedFd,
187    ) -> Result<Descriptor<'d>, Error> {
188        let entry = reserve(driver)?;
189        let handle = Self::adopt(fd, Kind::Stream)?;
190        let mut peer = addr::Storage::empty();
191        crate::Backend::peer_addr::<Errno>(handle.owned().as_fd(), &mut peer)
192            .map_err(Error::validate)?;
193        peer.to_std()
194            .map_err(socket::Error::from)
195            .map_err(Error::Address)?;
196        entry.install(handle.into_inner())
197    }
198
199    /// Installs an owned listener without rechecking its established socket role.
200    pub fn adopt_bound(
201        driver: &mut driver::Local<'d>,
202        listener: socket::Listener,
203    ) -> Result<(Descriptor<'d>, net::SocketAddr), Error> {
204        let entry = reserve(driver)?;
205        let (fd, local) = listener.into_parts();
206        let handle = socket::Handle::new(crate::Backend::adopt(fd).map_err(Error::Setup)?);
207        Ok((entry.install(handle.into_inner())?, local))
208    }
209
210    pub fn adopt_udp(
211        driver: &mut driver::Local<'d>,
212        fd: fd::OwnedFd,
213    ) -> Result<(Datagram<'d>, net::SocketAddr), Error> {
214        let (entry, capacity) = reserve_datagram(driver)?;
215        let handle = Self::adopt(fd, Kind::Dgram)?;
216        let (fd, addr) = entry.finish(handle)?;
217        Ok((Datagram::new(fd, capacity), addr))
218    }
219
220    /// Installs a routed datagram lease with its established socket role.
221    pub fn adopt_routed<'g: 'd>(
222        driver: &mut driver::Local<'d>,
223        socket: datagram::Lease<'g>,
224    ) -> Result<(Datagram<'d>, net::SocketAddr), Error> {
225        let (entry, capacity) = reserve_datagram(driver)?;
226        let (handle, local) = socket.into_parts();
227        let fd = entry.install(handle)?;
228        Ok((Datagram::new(fd, capacity), local))
229    }
230
231    pub fn bind_udp(
232        driver: &mut driver::Local<'d>,
233        addr: net::SocketAddr,
234        config: socket::Config,
235    ) -> Result<(Datagram<'d>, net::SocketAddr), Error> {
236        let (entry, capacity) = reserve_datagram(driver)?;
237        let (fd, addr) = entry.bind(addr, &config, None)?;
238        Ok((Datagram::new(fd, capacity), addr))
239    }
240}