Skip to content

Commit

Permalink
Add support for getting SO_COOKIE socket option on linux
Browse files Browse the repository at this point in the history
Signed-off-by: Benjamin Leggett <benjamin.leggett@solo.io>
  • Loading branch information
bleggett authored and Thomasdezeeuw committed Apr 26, 2023
1 parent 6713533 commit 488441a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/sys/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2418,6 +2418,18 @@ impl crate::Socket {
unsafe { setsockopt(self.as_raw(), libc::SOL_SOCKET, libc::SO_DETACH_FILTER, 0) }
}

/// Gets the value for the `SO_COOKIE` option on this socket.
///
/// The socket cookie is a unique, kernel-managed identifier tied to each socket.
/// Therefore, there is no corresponding `set` helper.
///
/// For more information about this option, see [Linux patch](https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=5daab9db7b65df87da26fd8cfa695fb9546a1ddb)
#[cfg(all(feature = "all", any(target_os = "linux")))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", any(target_os = "linux")))))]
pub fn cookie(&self) -> io::Result<u64> {
unsafe { getsockopt::<libc::c_ulonglong>(self.as_raw(), libc::SOL_SOCKET, libc::SO_COOKIE) }
}

/// Get the value of the `IPV6_TCLASS` option for this socket.
///
/// For more information about this option, see [`set_tclass_v6`].
Expand Down
18 changes: 18 additions & 0 deletions tests/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1528,3 +1528,21 @@ fn dccp() {
let mut recv_buf = [0_u8; 64];
assert!(accepted.read(&mut recv_buf).unwrap() == msg.len());
}

#[test]
#[cfg(all(feature = "all", target_os = "linux"))]
fn cookie() {
let socket = Socket::new(Domain::IPV4, Type::STREAM, None).unwrap();
let first_socket_cookie = socket.cookie();
match first_socket_cookie {
Ok(_) => {}
Err(err) => panic!("Could not get socket cookie, err: {err}"),
}

//Fetch cookie again and make sure it's the same value (ALWAYS should be, smoke test)
let second_socket_cookie = socket.cookie();
match second_socket_cookie {
Ok(cookie) => assert_eq!(cookie, first_socket_cookie.unwrap()),
Err(err) => panic!("Could not get socket cookie a second time, err: {err}"),
}
}

0 comments on commit 488441a

Please sign in to comment.