Skip to main content

dope_uring/sockets/
source.rs

1use std::{mem, net, ptr, slice};
2
3use dope_sys::io::socket::msg::source;
4
5use crate::{Backend, sockets::controls};
6
7// SAFETY: CMSG_SPACE only aligns these fixed native packet-info payload sizes.
8const V4: usize = unsafe { libc::CMSG_SPACE(mem::size_of::<libc::in_pktinfo>() as u32) as usize };
9const V6: usize = unsafe { libc::CMSG_SPACE(mem::size_of::<libc::in6_pktinfo>() as u32) as usize };
10
11/// Precomputed source selection retained through each datagram submission.
12#[derive(Clone, Copy, Debug)]
13#[repr(C, align(8))]
14pub struct Source {
15    bytes: [u8; V6],
16}
17
18/// One source with its optional retained segmentation capability.
19#[repr(transparent)]
20pub struct Combined(Kind);
21
22enum Kind {
23    Source(Source),
24    Segmented(Segmented),
25}
26
27/// One contiguous native GSO message followed by its selected source message.
28#[repr(C)]
29struct Segmented {
30    gso: controls::Control,
31    source: Source,
32}
33
34impl AsRef<[u8]> for Combined {
35    fn as_ref(&self) -> &[u8] {
36        match &self.0 {
37            Kind::Source(source) => source.as_ref(),
38            Kind::Segmented(control) => {
39                let length = mem::size_of::<controls::Control>() + control.source.as_ref().len();
40                // SAFETY: this repr(C) payload, excluding the enclosing enum, keeps
41                // the initialized GSO message and padding immediately before the
42                // source message. Its final CMSG_LEN bounds this exact owner.
43                unsafe { slice::from_raw_parts(ptr::from_ref(control).cast(), length) }
44            }
45        }
46    }
47}
48
49impl AsRef<[u8]> for Source {
50    fn as_ref(&self) -> &[u8] {
51        // SAFETY: the private constructor writes this aligned header's length
52        // once, bounded by the initialized native message storage. A final
53        // control message does not need trailing CMSG_SPACE padding.
54        unsafe {
55            let length = (*self.bytes.as_ptr().cast::<libc::cmsghdr>()).cmsg_len;
56            slice::from_raw_parts(self.bytes.as_ptr(), length)
57        }
58    }
59}
60
61const _: () = {
62    assert!(V4 <= V6);
63    assert!(mem::size_of::<libc::in_pktinfo>() == 12);
64    assert!(mem::size_of::<libc::in6_pktinfo>() == 20);
65    assert!(mem::align_of::<Source>() >= mem::align_of::<libc::cmsghdr>());
66    assert!(mem::align_of::<Source>() >= mem::align_of::<libc::in_pktinfo>());
67    assert!(mem::align_of::<Source>() >= mem::align_of::<libc::in6_pktinfo>());
68    assert!(mem::size_of::<Source>() == 40);
69    assert!(mem::offset_of!(Segmented, gso) == 0);
70    assert!(mem::offset_of!(Segmented, source) == mem::size_of::<controls::Control>());
71    assert!(
72        mem::size_of::<Segmented>()
73            == mem::size_of::<controls::Control>() + mem::size_of::<Source>()
74    );
75    assert!(mem::align_of::<Segmented>() == mem::align_of::<Source>());
76};
77
78impl From<source::Address> for Source {
79    fn from(source: source::Address) -> Self {
80        let address = source.get();
81        let mut control = Source { bytes: [0; V6] };
82        let header = control.bytes.as_mut_ptr().cast::<libc::cmsghdr>();
83        // SAFETY: Source owns aligned, zero-initialized storage for either
84        // complete native message. Both packet-info layouts have no padding.
85        unsafe {
86            let payload = libc::CMSG_DATA(header);
87            let length = match address {
88                net::SocketAddr::V4(address) => {
89                    (*header).cmsg_level = libc::IPPROTO_IP;
90                    (*header).cmsg_type = libc::IP_PKTINFO;
91                    payload.cast::<libc::in_pktinfo>().write(libc::in_pktinfo {
92                        ipi_ifindex: 0,
93                        ipi_spec_dst: libc::in_addr {
94                            s_addr: u32::from_ne_bytes(address.ip().octets()),
95                        },
96                        ipi_addr: libc::in_addr { s_addr: 0 },
97                    });
98                    mem::size_of::<libc::in_pktinfo>()
99                }
100                net::SocketAddr::V6(address) => {
101                    (*header).cmsg_level = libc::IPPROTO_IPV6;
102                    (*header).cmsg_type = libc::IPV6_PKTINFO;
103                    payload
104                        .cast::<libc::in6_pktinfo>()
105                        .write(libc::in6_pktinfo {
106                            ipi6_addr: libc::in6_addr {
107                                s6_addr: address.ip().octets(),
108                            },
109                            ipi6_ifindex: address.scope_id(),
110                        });
111                    mem::size_of::<libc::in6_pktinfo>()
112                }
113            };
114            (*header).cmsg_len = libc::CMSG_LEN(length as u32) as _;
115        }
116        control
117    }
118}
119
120impl source::Source for Backend {
121    type Control = Source;
122    type Combined = Combined;
123
124    fn compose(source: Source, gso: Option<controls::Control>) -> Combined {
125        Combined(match gso {
126            Some(gso) => Kind::Segmented(Segmented { gso, source }),
127            None => Kind::Source(source),
128        })
129    }
130
131    fn release(control: Combined) -> (Source, Option<controls::Control>) {
132        match control.0 {
133            Kind::Source(source) => (source, None),
134            Kind::Segmented(control) => (control.source, Some(control.gso)),
135        }
136    }
137}