Skip to content

Add a borrowing cmsg api #2646

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 23 additions & 5 deletions src/sys/socket/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -725,19 +725,37 @@ impl Iterator for CmsgIterator<'_> {
type Item = ControlMessageOwned;

fn next(&mut self) -> Option<ControlMessageOwned> {
// Safe if cmsghdr points to valid data returned by recvmsg(2)
self.next_raw().map(|(hdr, _)| unsafe { ControlMessageOwned::decode_from(hdr) })
}
}

impl CmsgIterator<'_> {
pub fn next_raw(&mut self) -> Option<(&cmsghdr, &[u8])> {
match self.cmsghdr {
None => None, // No more messages
Some(hdr) => {
Some(header) => {
// Get the data.
// Safe if cmsghdr points to valid data returned by recvmsg(2)
let cm = unsafe { Some(ControlMessageOwned::decode_from(hdr))};
let p = unsafe { CMSG_DATA(header) };

// Determine the length of the control message data
// The cast is not unnecessary on all platforms.
#[allow(clippy::unnecessary_cast)]
let len = header as *const _ as usize + header.cmsg_len as usize
- p as usize;

// Read the value as a slice (This slice is the same one that ControlMessageOwned::Unknown copies)
let value = unsafe { core::slice::from_raw_parts(p, len) };

// Advance the internal pointer. Safe if mhdr and cmsghdr point
// to valid data returned by recvmsg(2)
self.cmsghdr = unsafe {
let p = CMSG_NXTHDR(self.mhdr as *const _, hdr as *const _);
let p = CMSG_NXTHDR(self.mhdr as *const _, header as *const _);
p.as_ref()
};
cm

// Return the header and data
Some((header, value))
}
}
}
Expand Down