Skip to content

Commit 5c0f1bf

Browse files
committed
Fix IP_TOS support on macos and BSD
1 parent d6a3d1c commit 5c0f1bf

File tree

1 file changed

+32
-8
lines changed

1 file changed

+32
-8
lines changed

src/cmsg.rs

+32-8
Original file line numberDiff line numberDiff line change
@@ -226,11 +226,13 @@ impl Cmsg {
226226
fn level_type_size(&self) -> (libc::c_int, libc::c_int, libc::c_uint) {
227227
match self {
228228
#[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
229-
Cmsg::IpTos(_) => (
230-
libc::IPPROTO_IP,
231-
libc::IP_TOS,
232-
std::mem::size_of::<u8>() as libc::c_uint,
233-
),
229+
Cmsg::IpTos(_) => {
230+
#[cfg(not(target_os = "macos"))]
231+
let len = std::mem::size_of::<u8>();
232+
#[cfg(target_os = "macos")]
233+
let len = std::mem::size_of::<i32>();
234+
(libc::IPPROTO_IP, libc::IP_TOS, len as libc::c_uint)
235+
}
234236
#[cfg(not(any(target_os = "fuchsia", target_os = "solaris", target_os = "illumos")))]
235237
Cmsg::Ipv6PktInfo { .. } => (
236238
libc::IPPROTO_IPV6,
@@ -248,7 +250,15 @@ impl Cmsg {
248250
match self {
249251
#[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
250252
Cmsg::IpTos(tos) => {
251-
buffer[0] = *tos;
253+
#[cfg(not(target_os = "macos"))]
254+
{
255+
buffer[0] = *tos;
256+
}
257+
#[cfg(target_os = "macos")]
258+
{
259+
let value = *tos as i32;
260+
buffer.copy_from_slice(&value.to_ne_bytes()[..])
261+
}
252262
}
253263
#[cfg(not(any(target_os = "fuchsia", target_os = "solaris", target_os = "illumos")))]
254264
Cmsg::Ipv6PktInfo { addr, ifindex } => {
@@ -283,8 +293,22 @@ impl Cmsg {
283293
match (cmsg_level, cmsg_type) {
284294
#[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
285295
(libc::IPPROTO_IP, libc::IP_TOS) => {
286-
assert_eq!(bytes.len(), std::mem::size_of::<u8>(), "{:?}", bytes);
287-
Cmsg::IpTos(bytes[0])
296+
// Different systems encode received TOS as char or int.
297+
match bytes {
298+
[b] => Cmsg::IpTos(*b),
299+
[a, b, c, d] => Cmsg::IpTos(i32::from_ne_bytes([*a, *b, *c, *d]) as u8),
300+
other => panic!("unexpected length for IP_TOS: {:?}", other),
301+
}
302+
}
303+
#[cfg(any(
304+
target_os = "freebsd",
305+
target_os = "openbsd",
306+
target_os = "netbsd",
307+
target_os = "macos"
308+
))]
309+
(libc::IPPROTO_IP, libc::IP_RECVTOS) => {
310+
// BSD systems use IP_RECVTOS on the receive path.
311+
Self::from_raw(libc::IPPROTO_IP, libc::IP_TOS, bytes)
288312
}
289313
#[cfg(not(any(target_os = "fuchsia", target_os = "solaris", target_os = "illumos")))]
290314
(libc::IPPROTO_IPV6, libc::IPV6_PKTINFO) => {

0 commit comments

Comments
 (0)