|
| 1 | +use std::fmt; |
| 2 | +use std::mem; |
| 3 | + |
| 4 | +/// Returns the space required in a control message buffer for a single message |
| 5 | +/// with `data_len` bytes of ancillary data. |
| 6 | +/// |
| 7 | +/// Returns `None` if `data_len` does not fit in `libc::c_uint`. |
| 8 | +/// |
| 9 | +/// Corresponds to `CMSG_SPACE(3)`. |
| 10 | +pub fn cmsg_space(data_len: usize) -> Option<usize> { |
| 11 | + let len = libc::c_uint::try_from(data_len).ok()?; |
| 12 | + // SAFETY: pure arithmetic. |
| 13 | + usize::try_from(unsafe { libc::CMSG_SPACE(len) }).ok() |
| 14 | +} |
| 15 | + |
| 16 | +/// A control message parsed from a `recvmsg(2)` control buffer. |
| 17 | +/// |
| 18 | +/// Returned by [`ControlMessages`]. |
| 19 | +pub struct ControlMessage<'a> { |
| 20 | + cmsg_level: i32, |
| 21 | + cmsg_type: i32, |
| 22 | + data: &'a [u8], |
| 23 | +} |
| 24 | + |
| 25 | +impl<'a> ControlMessage<'a> { |
| 26 | + /// Corresponds to `cmsg_level` in `cmsghdr`. |
| 27 | + pub fn cmsg_level(&self) -> i32 { |
| 28 | + self.cmsg_level |
| 29 | + } |
| 30 | + |
| 31 | + /// Corresponds to `cmsg_type` in `cmsghdr`. |
| 32 | + pub fn cmsg_type(&self) -> i32 { |
| 33 | + self.cmsg_type |
| 34 | + } |
| 35 | + |
| 36 | + /// The ancillary data payload. |
| 37 | + /// |
| 38 | + /// Corresponds to the data portion following the `cmsghdr`. |
| 39 | + pub fn data(&self) -> &'a [u8] { |
| 40 | + self.data |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +impl<'a> fmt::Debug for ControlMessage<'a> { |
| 45 | + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 46 | + "ControlMessage".fmt(fmt) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +/// Iterator over control messages in a `recvmsg(2)` control buffer. |
| 51 | +/// |
| 52 | +/// See [`crate::MsgHdrMut::with_control`] and [`crate::MsgHdrMut::control_len`]. |
| 53 | +pub struct ControlMessages<'a> { |
| 54 | + buf: &'a [u8], |
| 55 | + offset: usize, |
| 56 | +} |
| 57 | + |
| 58 | +impl<'a> ControlMessages<'a> { |
| 59 | + /// Create a new `ControlMessages` from the filled control buffer. |
| 60 | + /// |
| 61 | + /// Pass `&raw_buf[..msg.control_len()]` where `raw_buf` is the slice |
| 62 | + /// passed to [`crate::MsgHdrMut::with_control`] before calling `recvmsg(2)`. |
| 63 | + pub fn new(buf: &'a [u8]) -> Self { |
| 64 | + Self { buf, offset: 0 } |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +impl<'a> Iterator for ControlMessages<'a> { |
| 69 | + type Item = ControlMessage<'a>; |
| 70 | + |
| 71 | + #[allow(clippy::useless_conversion)] |
| 72 | + fn next(&mut self) -> Option<Self::Item> { |
| 73 | + let hdr_size = mem::size_of::<libc::cmsghdr>(); |
| 74 | + // SAFETY: pure arithmetic; gives CMSG_ALIGN(sizeof(cmsghdr)). |
| 75 | + let data_offset: usize = |
| 76 | + usize::try_from(unsafe { libc::CMSG_LEN(0) }).unwrap_or(usize::MAX); |
| 77 | + |
| 78 | + if self.offset + hdr_size > self.buf.len() { |
| 79 | + return None; |
| 80 | + } |
| 81 | + |
| 82 | + // SAFETY: range is within `buf`; read_unaligned handles any alignment. |
| 83 | + let cmsg: libc::cmsghdr = unsafe { |
| 84 | + std::ptr::read_unaligned(self.buf.as_ptr().add(self.offset) as *const libc::cmsghdr) |
| 85 | + }; |
| 86 | + |
| 87 | + let total_len = usize::try_from(cmsg.cmsg_len).unwrap_or(0); |
| 88 | + if total_len < data_offset { |
| 89 | + return None; |
| 90 | + } |
| 91 | + let data_len = total_len - data_offset; |
| 92 | + |
| 93 | + let data_abs_start = self.offset + data_offset; |
| 94 | + let data_abs_end = data_abs_start.saturating_add(data_len); |
| 95 | + if data_abs_end > self.buf.len() { |
| 96 | + return None; |
| 97 | + } |
| 98 | + |
| 99 | + let item = ControlMessage { |
| 100 | + cmsg_level: cmsg.cmsg_level, |
| 101 | + cmsg_type: cmsg.cmsg_type, |
| 102 | + data: &self.buf[data_abs_start..data_abs_end], |
| 103 | + }; |
| 104 | + |
| 105 | + // SAFETY: pure arithmetic; CMSG_SPACE(data_len) == CMSG_ALIGN(total_len). |
| 106 | + let advance = match libc::c_uint::try_from(data_len) { |
| 107 | + Ok(dl) => usize::try_from(unsafe { libc::CMSG_SPACE(dl) }).unwrap_or(usize::MAX), |
| 108 | + Err(_) => return None, |
| 109 | + }; |
| 110 | + self.offset = self.offset.saturating_add(advance); |
| 111 | + |
| 112 | + Some(item) |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +impl<'a> fmt::Debug for ControlMessages<'a> { |
| 117 | + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 118 | + "ControlMessages".fmt(fmt) |
| 119 | + } |
| 120 | +} |
| 121 | + |
| 122 | +/// Builds a control message buffer for use with `sendmsg(2)`. |
| 123 | +/// |
| 124 | +/// See [`crate::MsgHdr::with_control`] and [`cmsg_space`]. |
| 125 | +pub struct ControlMessageEncoder<'a> { |
| 126 | + buf: &'a mut [u8], |
| 127 | + len: usize, |
| 128 | +} |
| 129 | + |
| 130 | +impl<'a> ControlMessageEncoder<'a> { |
| 131 | + /// Create a new `ControlMessageEncoder` backed by `buf`. |
| 132 | + /// |
| 133 | + /// Zeroes `buf` on creation to ensure padding bytes are clean. |
| 134 | + /// Allocate `buf` with the sum of [`cmsg_space`] for each intended message. |
| 135 | + pub fn new(buf: &'a mut [u8]) -> Self { |
| 136 | + buf.fill(0); |
| 137 | + Self { buf, len: 0 } |
| 138 | + } |
| 139 | + |
| 140 | + /// Append a control message carrying `data`. |
| 141 | + /// |
| 142 | + /// Returns `Err` if `data` exceeds `c_uint::MAX` or the buffer is too small. |
| 143 | + pub fn push(&mut self, cmsg_level: i32, cmsg_type: i32, data: &[u8]) -> std::io::Result<()> { |
| 144 | + let data_len_uint = libc::c_uint::try_from(data.len()).map_err(|_| { |
| 145 | + std::io::Error::new( |
| 146 | + std::io::ErrorKind::InvalidInput, |
| 147 | + "ancillary data payload too large (exceeds c_uint::MAX)", |
| 148 | + ) |
| 149 | + })?; |
| 150 | + // SAFETY: pure arithmetic. |
| 151 | + let space: usize = |
| 152 | + usize::try_from(unsafe { libc::CMSG_SPACE(data_len_uint) }).unwrap_or(usize::MAX); |
| 153 | + if self.len + space > self.buf.len() { |
| 154 | + return Err(std::io::Error::new( |
| 155 | + std::io::ErrorKind::InvalidInput, |
| 156 | + "control message buffer too small", |
| 157 | + )); |
| 158 | + } |
| 159 | + // SAFETY: pure arithmetic. |
| 160 | + let cmsg_len = unsafe { libc::CMSG_LEN(data_len_uint) }; |
| 161 | + unsafe { |
| 162 | + // SAFETY: offset is within buf; write_unaligned handles alignment 1. |
| 163 | + // Use zeroed() + field assignment to handle platform-specific padding |
| 164 | + // (e.g. musl adds __pad1); buf is pre-zeroed but the write must be |
| 165 | + // self-contained for correctness. |
| 166 | + let cmsg_ptr = self.buf.as_mut_ptr().add(self.len) as *mut libc::cmsghdr; |
| 167 | + let mut hdr: libc::cmsghdr = mem::zeroed(); |
| 168 | + hdr.cmsg_len = cmsg_len as _; |
| 169 | + hdr.cmsg_level = cmsg_level; |
| 170 | + hdr.cmsg_type = cmsg_type; |
| 171 | + std::ptr::write_unaligned(cmsg_ptr, hdr); |
| 172 | + // SAFETY: CMSG_DATA gives the correct offset past alignment padding. |
| 173 | + let data_ptr = libc::CMSG_DATA(cmsg_ptr); |
| 174 | + std::ptr::copy_nonoverlapping(data.as_ptr(), data_ptr, data.len()); |
| 175 | + } |
| 176 | + self.len += space; |
| 177 | + Ok(()) |
| 178 | + } |
| 179 | + |
| 180 | + /// Returns the encoded bytes. |
| 181 | + /// |
| 182 | + /// Corresponds to the slice to pass to [`crate::MsgHdr::with_control`]. |
| 183 | + pub fn as_bytes(&self) -> &[u8] { |
| 184 | + &self.buf[..self.len] |
| 185 | + } |
| 186 | + |
| 187 | + /// Returns the number of bytes written. |
| 188 | + pub fn len(&self) -> usize { |
| 189 | + self.len |
| 190 | + } |
| 191 | + |
| 192 | + /// Returns `true` if no control messages have been pushed. |
| 193 | + pub fn is_empty(&self) -> bool { |
| 194 | + self.len == 0 |
| 195 | + } |
| 196 | +} |
| 197 | + |
| 198 | +impl<'a> fmt::Debug for ControlMessageEncoder<'a> { |
| 199 | + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 200 | + "ControlMessageEncoder".fmt(fmt) |
| 201 | + } |
| 202 | +} |
0 commit comments