Skip to main content

dope_uring/sockets/
ffi.rs

1use std::{
2    mem, net, num,
3    os::fd::{AsRawFd as _, BorrowedFd},
4    ptr, slice,
5};
6
7use dope_sys::{
8    Errno,
9    io::socket::{
10        gso,
11        msg::source,
12        route::install::{Error, Operation},
13    },
14    kernel,
15};
16use o3::base::Either;
17
18use crate::Backend;
19
20const LENGTH: u32 = mem::size_of::<u16>() as u32;
21// SAFETY: CMSG_SPACE only aligns the compile-time u16 payload length.
22const SPACE: usize = unsafe { libc::CMSG_SPACE(LENGTH) as usize };
23// SAFETY: CMSG_LEN only computes the native header extent for an empty payload.
24const HEADER: usize = unsafe { libc::CMSG_LEN(0) as usize };
25
26const fn header<T>(level: libc::c_int, kind: libc::c_int) -> libc::cmsghdr {
27    libc::cmsghdr {
28        cmsg_len: HEADER + mem::size_of::<T>(),
29        cmsg_level: level,
30        cmsg_type: kind,
31    }
32}
33
34/// Native UDP segmentation authority.
35#[derive(Clone, Copy)]
36pub struct Permit(());
37
38/// Aligned ancillary storage whose payload retains its nonzero segment size.
39#[repr(C, align(8))]
40pub struct Control {
41    header: libc::cmsghdr,
42    size: num::NonZero<u16>,
43    padding: [u8; SPACE - HEADER - LENGTH as usize],
44}
45
46impl gso::Mode for Control {
47    type Capability = self::Permit;
48
49    const CAPABILITY: Option<Self::Capability> = Some(Permit(()));
50
51    fn control(cap: Self::Capability, size: num::NonZero<u16>) -> Self {
52        let Permit(()) = cap;
53        Self {
54            header: header::<u16>(libc::SOL_UDP, libc::UDP_SEGMENT),
55            size,
56            padding: [0; SPACE - HEADER - LENGTH as usize],
57        }
58    }
59
60    fn release(self) -> (Self::Capability, num::NonZero<u16>) {
61        (Permit(()), self.size)
62    }
63
64    fn bytes(&mut self) -> &[u8] {
65        // SAFETY: the asserted ABI has no implicit padding: the native header,
66        // nonzero payload and explicit trailing bytes are all initialized.
67        // The shared byte view cannot alter the retained segment-size proof.
68        unsafe { slice::from_raw_parts(ptr::from_ref(self).cast(), SPACE) }
69    }
70}
71
72/// Precomputed source selection retained through each datagram submission.
73#[derive(Clone, Copy, Debug)]
74#[repr(C, align(8))]
75pub struct Source {
76    header: libc::cmsghdr,
77    address: [u8; 16],
78    index: u32,
79}
80
81impl From<source::Address> for Source {
82    fn from(source: source::Address) -> Self {
83        match source.get() {
84            net::SocketAddr::V4(address) => {
85                const DEST: usize = mem::offset_of!(libc::in_pktinfo, ipi_spec_dst);
86                let mut packet = [0; 16];
87                packet[DEST..DEST + 4].copy_from_slice(&address.ip().octets());
88                Self {
89                    header: header::<libc::in_pktinfo>(libc::IPPROTO_IP, libc::IP_PKTINFO),
90                    address: packet,
91                    index: 0,
92                }
93            }
94            net::SocketAddr::V6(address) => Self {
95                header: header::<libc::in6_pktinfo>(libc::IPPROTO_IPV6, libc::IPV6_PKTINFO),
96                address: address.ip().octets(),
97                index: address.scope_id(),
98            },
99        }
100    }
101}
102
103impl AsRef<[u8]> for Source {
104    fn as_ref(&self) -> &[u8] {
105        // SAFETY: the native length selects only initialized header and packet-info
106        // bytes. It ends before the trailing alignment padding in both families.
107        unsafe { slice::from_raw_parts(ptr::from_ref(self).cast(), self.header.cmsg_len) }
108    }
109}
110
111/// One source with its optional retained segmentation capability.
112#[repr(transparent)]
113pub struct Combined(Either<Source, Segmented>);
114
115#[repr(C)]
116struct Segmented {
117    gso: Control,
118    source: Source,
119}
120
121impl AsRef<[u8]> for Combined {
122    fn as_ref(&self) -> &[u8] {
123        match &self.0 {
124            Either::Left(source) => source.as_ref(),
125            Either::Right(control) => {
126                let len = SPACE + control.source.header.cmsg_len;
127                // SAFETY: the initialized GSO message and its explicit padding
128                // immediately precede the initialized prefix of the source message.
129                unsafe { slice::from_raw_parts(ptr::from_ref(control).cast(), len) }
130            }
131        }
132    }
133}
134
135impl source::Source for Backend {
136    type Control = Source;
137    type Combined = Combined;
138
139    fn compose(source: Source, gso: Option<Control>) -> Combined {
140        Combined(match gso {
141            Some(gso) => Either::Right(Segmented { gso, source }),
142            None => Either::Left(source),
143        })
144    }
145
146    fn release(control: Combined) -> (Source, Option<Control>) {
147        match control.0 {
148            Either::Left(source) => (source, None),
149            Either::Right(control) => (control.source, Some(control.gso)),
150        }
151    }
152}
153
154pub(super) fn attach(
155    socket: BorrowedFd<'_>,
156    code: &[libc::sock_filter],
157    op: Operation,
158) -> Result<(), Error> {
159    let program = libc::sock_fprog {
160        len: code.len() as u16,
161        filter: code.as_ptr().cast_mut(),
162    };
163    let option = match op {
164        Operation::Program => libc::SO_ATTACH_REUSEPORT_CBPF,
165        Operation::Filter => libc::SO_ATTACH_FILTER,
166    };
167    // SAFETY: the bounded instruction array and its descriptor remain borrowed
168    // until setsockopt returns zero or -1 with this thread's errno.
169    unsafe {
170        kernel::raw::Status::new(libc::setsockopt(
171            socket.as_raw_fd(),
172            libc::SOL_SOCKET,
173            option,
174            ptr::from_ref(&program).cast(),
175            mem::size_of_val(&program) as libc::socklen_t,
176        ))
177        .try_zero::<Backend, Errno>()
178    }
179    .map_err(|errno| Error {
180        operation: op,
181        errno,
182    })
183}
184
185const _: () = {
186    assert!(mem::size_of::<Permit>() == 0);
187    assert!(mem::size_of::<libc::cmsghdr>() == HEADER);
188    assert!(mem::offset_of!(libc::cmsghdr, cmsg_len) == 0);
189    assert!(mem::offset_of!(libc::cmsghdr, cmsg_level) == mem::size_of::<usize>());
190    assert!(mem::offset_of!(libc::cmsghdr, cmsg_type) == HEADER - mem::size_of::<libc::c_int>());
191    assert!(HEADER == mem::size_of::<usize>() + 2 * mem::size_of::<libc::c_int>());
192    assert!(mem::offset_of!(Control, size) == HEADER);
193    assert!(mem::offset_of!(Control, padding) == HEADER + LENGTH as usize);
194    assert!(mem::size_of::<Control>() == SPACE);
195    assert!(mem::size_of::<Control>() == 24);
196    assert!(mem::align_of::<Control>() == 8);
197    assert!(mem::size_of::<Option<Control>>() == 24);
198    assert!(mem::align_of::<Control>() >= mem::align_of::<libc::cmsghdr>());
199    assert!(mem::size_of::<libc::in_pktinfo>() == 12);
200    assert!(mem::size_of::<libc::in_addr>() == 4);
201    assert!(mem::offset_of!(libc::in_addr, s_addr) == 0);
202    assert!(mem::size_of::<libc::in6_pktinfo>() == 20);
203    assert!(mem::offset_of!(Source, address) == HEADER);
204    assert!(mem::offset_of!(libc::in6_pktinfo, ipi6_addr) == 0);
205    assert!(mem::offset_of!(libc::in6_addr, s6_addr) == 0);
206    assert!(
207        mem::offset_of!(Source, index) == HEADER + mem::offset_of!(libc::in6_pktinfo, ipi6_ifindex)
208    );
209    assert!(mem::align_of::<Source>() >= mem::align_of::<libc::in_pktinfo>());
210    assert!(mem::align_of::<Source>() >= mem::align_of::<libc::in6_pktinfo>());
211    assert!(mem::size_of::<Source>() == 40);
212    assert!(mem::offset_of!(Segmented, source) == SPACE);
213    assert!(mem::size_of::<Segmented>() == SPACE + mem::size_of::<Source>());
214};