Skip to main content

dope_sys/io/socket/option/
source.rs

1use std::{
2    mem,
3    os::fd::{self, AsFd, AsRawFd as _, BorrowedFd},
4    ptr,
5};
6
7use libc::socklen_t;
8
9use crate::{
10    Errno,
11    io::{
12        socket,
13        socket::option::{Kind, Value},
14    },
15    kernel::{self, errno},
16};
17
18/// Native socket option selection and access.
19pub trait Source: errno::Source {
20    type Listening;
21
22    const KEEP_IDLE: libc::c_int;
23
24    /// Makes closing this exclusively owned connection send a reset.
25    fn reset<E: From<Errno>>(file: impl AsFd) -> Result<(), E> {
26        let linger = libc::linger {
27            l_onoff: 1,
28            l_linger: 0,
29        };
30        // SAFETY: the live descriptor and complete native value outlive the call.
31        let raw = unsafe {
32            libc::setsockopt(
33                file.as_fd().as_raw_fd(),
34                libc::SOL_SOCKET,
35                libc::SO_LINGER,
36                ptr::from_ref(&linger).cast(),
37                mem::size_of_val(&linger) as socklen_t,
38            )
39        };
40        // SAFETY: setsockopt returns zero or -1; errno is captured immediately.
41        unsafe { kernel::raw::Status::new(raw).try_zero::<Self, E>() }
42    }
43
44    /// Observes the socket type of one adopted descriptor.
45    fn kind<E: From<Errno>>(file: BorrowedFd<'_>) -> Result<socket::Type, E> {
46        Self::get_option::<{ libc::SO_TYPE }, E>(file).map(socket::Type)
47    }
48
49    /// Whether one adopted descriptor is already listening.
50    fn is_listening(file: BorrowedFd<'_>) -> Result<bool, Self::Listening>;
51
52    /// Admits the requested address reuse on one socket.
53    fn set_reuse<E: From<Errno>>(file: BorrowedFd<'_>, reuse: socket::Reuse) -> Result<(), E> {
54        let option = match reuse {
55            socket::Reuse::Address => libc::SO_REUSEADDR,
56            socket::Reuse::Port => libc::SO_REUSEPORT,
57        };
58        Self::set_option(file, libc::SOL_SOCKET, option, &1)
59    }
60
61    fn get_option<const OPTION: libc::c_int, E: From<Errno>>(
62        file: BorrowedFd<'_>,
63    ) -> Result<libc::c_int, E> {
64        const {
65            assert!(
66                OPTION == libc::SO_TYPE
67                    || OPTION == libc::SO_ACCEPTCONN
68                    || OPTION == libc::SO_ERROR
69            );
70        }
71        let mut value = 0;
72        let mut len = mem::size_of::<libc::c_int>() as socklen_t;
73        let raw = unsafe {
74            libc::getsockopt(
75                file.as_raw_fd(),
76                libc::SOL_SOCKET,
77                OPTION,
78                ptr::from_mut(&mut value).cast(),
79                &mut len,
80            )
81        };
82        // SAFETY: getsockopt returns exactly zero or minus one.
83        unsafe { kernel::raw::Status::new(raw).try_zero::<Self, E>() }?;
84        Ok(value)
85    }
86
87    fn set_option<E: From<Errno>>(
88        file: BorrowedFd<'_>,
89        level: libc::c_int,
90        option: libc::c_int,
91        value: &libc::c_int,
92    ) -> Result<(), E> {
93        let raw = unsafe {
94            libc::setsockopt(
95                file.as_raw_fd(),
96                level,
97                option,
98                ptr::from_ref(value).cast(),
99                mem::size_of::<libc::c_int>() as socklen_t,
100            )
101        };
102        // SAFETY: setsockopt returns exactly zero or minus one.
103        unsafe { kernel::raw::Status::new(raw).try_zero::<Self, E>() }
104    }
105
106    fn option(kind: Kind) -> (libc::c_int, libc::c_int) {
107        match kind {
108            Kind::NoDelay => (libc::IPPROTO_TCP, libc::TCP_NODELAY),
109            Kind::KeepAlive => (libc::SOL_SOCKET, libc::SO_KEEPALIVE),
110            Kind::RecvBuffer => (libc::SOL_SOCKET, libc::SO_RCVBUF),
111            Kind::SendBuffer => (libc::SOL_SOCKET, libc::SO_SNDBUF),
112            Kind::KeepAliveIdle => (libc::IPPROTO_TCP, Self::KEEP_IDLE),
113            Kind::KeepAliveInterval => (libc::IPPROTO_TCP, libc::TCP_KEEPINTVL),
114            Kind::KeepAliveRetries => (libc::IPPROTO_TCP, libc::TCP_KEEPCNT),
115        }
116    }
117
118    fn set(fd: fd::BorrowedFd<'_>, kind: Kind, value: &Value) -> Result<(), Errno> {
119        let (level, name) = Self::option(kind);
120        Self::set_option(fd, level, name, &value.raw())
121    }
122}