dope_sys/io/socket/option/
source.rs1use std::{
2 array, mem,
3 num::NonZero,
4 os::fd::{self, AsFd, BorrowedFd},
5};
6
7use crate::{
8 Errno,
9 io::{
10 socket,
11 socket::option::{Kind, Value},
12 },
13 kernel::errno,
14};
15
16pub trait Source: errno::Source {
18 type Listening;
19
20 const KEEP_IDLE: libc::c_int;
21
22 fn reset<E: From<Errno>>(file: impl AsFd) -> Result<(), E> {
24 const {
25 assert!(size_of::<libc::linger>() == size_of::<[libc::c_int; 2]>());
26 assert!(align_of::<libc::linger>() == align_of::<[libc::c_int; 2]>());
27 assert!(mem::offset_of!(libc::linger, l_onoff) == 0);
28 assert!(mem::offset_of!(libc::linger, l_linger) == size_of::<libc::c_int>());
29 }
30 socket::raw::set_option::<Self, E, 2>(
31 file.as_fd(),
32 libc::SOL_SOCKET,
33 libc::SO_LINGER,
34 &[1, 0],
35 )
36 }
37
38 fn kind<E: From<Errno>>(file: BorrowedFd<'_>) -> Result<socket::Type, E> {
40 Self::get_option::<{ libc::SO_TYPE }, E>(file).map(socket::Type)
41 }
42
43 fn take_error(file: BorrowedFd<'_>) -> Result<Option<Errno>, Errno> {
45 let error = socket::raw::get_option::<Self, Errno, { libc::SO_ERROR }>(file)?;
46 Ok(NonZero::new(error).map(Errno))
47 }
48
49 fn is_listening(file: BorrowedFd<'_>) -> Result<bool, Self::Listening>;
51
52 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 socket::raw::get_option::<Self, E, OPTION>(file)
65 }
66
67 fn set_option<E: From<Errno>>(
68 file: BorrowedFd<'_>,
69 level: libc::c_int,
70 option: libc::c_int,
71 value: &libc::c_int,
72 ) -> Result<(), E> {
73 socket::raw::set_option::<Self, E, 1>(file, level, option, array::from_ref(value))
74 }
75
76 fn option(kind: Kind) -> (libc::c_int, libc::c_int) {
77 match kind {
78 Kind::NoDelay => (libc::IPPROTO_TCP, libc::TCP_NODELAY),
79 Kind::KeepAlive => (libc::SOL_SOCKET, libc::SO_KEEPALIVE),
80 Kind::RecvBuffer => (libc::SOL_SOCKET, libc::SO_RCVBUF),
81 Kind::SendBuffer => (libc::SOL_SOCKET, libc::SO_SNDBUF),
82 Kind::KeepAliveIdle => (libc::IPPROTO_TCP, Self::KEEP_IDLE),
83 Kind::KeepAliveInterval => (libc::IPPROTO_TCP, libc::TCP_KEEPINTVL),
84 Kind::KeepAliveRetries => (libc::IPPROTO_TCP, libc::TCP_KEEPCNT),
85 }
86 }
87
88 fn set(fd: fd::BorrowedFd<'_>, kind: Kind, value: &Value) -> Result<(), Errno> {
89 let (level, name) = Self::option(kind);
90 Self::set_option(fd, level, name, &value.raw())
91 }
92}