Skip to content

Commit 1e3e03a

Browse files
committed
Add a borrowing cmsg api
This is mainly to support implementing custom control messages.
1 parent a72936d commit 1e3e03a

File tree

1 file changed

+29
-5
lines changed

1 file changed

+29
-5
lines changed

src/sys/socket/mod.rs

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -725,19 +725,43 @@ impl Iterator for CmsgIterator<'_> {
725725
type Item = ControlMessageOwned;
726726

727727
fn next(&mut self) -> Option<ControlMessageOwned> {
728-
match self.cmsghdr {
728+
match self.next_raw() {
729729
None => None, // No more messages
730-
Some(hdr) => {
730+
Some((hdr, _)) => {
731731
// Get the data.
732732
// Safe if cmsghdr points to valid data returned by recvmsg(2)
733-
let cm = unsafe { Some(ControlMessageOwned::decode_from(hdr))};
733+
unsafe { Some(ControlMessageOwned::decode_from(hdr))}
734+
}
735+
}
736+
}
737+
}
738+
739+
impl CmsgIterator<'_> {
740+
pub fn next_raw(&mut self) -> Option<(&cmsghdr, &[u8])> {
741+
match self.cmsghdr {
742+
None => None, // No more messages
743+
Some(header) => {
744+
// Get the data.
745+
let p = unsafe { CMSG_DATA(header) };
746+
747+
// Determine the length of the control message data
748+
// The cast is not unnecessary on all platforms.
749+
#[allow(clippy::unnecessary_cast)]
750+
let len = header as *const _ as usize + header.cmsg_len as usize
751+
- p as usize;
752+
753+
// Read the value as a slice (This slice is the same one that ControlMessageOwned::Unknown copies)
754+
let value = unsafe { core::slice::from_raw_parts(p, len) };
755+
734756
// Advance the internal pointer. Safe if mhdr and cmsghdr point
735757
// to valid data returned by recvmsg(2)
736758
self.cmsghdr = unsafe {
737-
let p = CMSG_NXTHDR(self.mhdr as *const _, hdr as *const _);
759+
let p = CMSG_NXTHDR(self.mhdr as *const _, header as *const _);
738760
p.as_ref()
739761
};
740-
cm
762+
763+
// Return the header and data
764+
Some((header, value))
741765
}
742766
}
743767
}

0 commit comments

Comments
 (0)