Skip to content

Commit

Permalink
Implement AsFd for Capture<Active> (#367)
Browse files Browse the repository at this point in the history
  • Loading branch information
gmacon authored Sep 1, 2024
1 parent 0d60108 commit fc845e6
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## [Unreleased]

### Added

- Added an implementation of `AsFd` on `Capture<Active>` on non-Windows.

## [2.1.0] - 2024-08-27

### Added
Expand Down
35 changes: 34 additions & 1 deletion src/capture/activated/active.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::borrow::Borrow;

#[cfg(not(windows))]
use std::os::unix::io::{AsRawFd, RawFd};
use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd};

use crate::{
capture::{Active, Capture},
Expand Down Expand Up @@ -40,6 +40,20 @@ impl AsRawFd for Capture<Active> {
}
}

#[cfg(not(windows))]
impl AsFd for Capture<Active> {
/// Returns the file descriptor for a live capture.
fn as_fd(&self) -> BorrowedFd {
// SAFETY: pcap_fileno always succeeds on a live capture,
// and we know this capture is live due to its State.
let fd = unsafe { raw::pcap_fileno(self.handle.as_ptr()) };
assert!(fd != -1, "Unable to get file descriptor for live capture");
// SAFETY: The lifetime is bound to self, which is correct.
// We have checked that fd != -1.
unsafe { BorrowedFd::borrow_raw(fd) }
}
}

#[cfg(test)]
mod tests {
use crate::{
Expand Down Expand Up @@ -142,4 +156,23 @@ mod tests {

assert_eq!(capture.as_raw_fd(), 7);
}

#[test]
#[cfg(not(windows))]
fn test_as_fd() {
let _m = RAWMTX.lock();

let mut dummy: isize = 777;
let pcap = as_pcap_t(&mut dummy);

let test_capture = test_capture::<Active>(pcap);
let capture = test_capture.capture;

let ctx = pcap_fileno_context();
ctx.expect()
.withf_st(move |arg1| *arg1 == pcap)
.return_once(|_| 7);

assert_eq!(capture.as_fd().as_raw_fd(), 7);
}
}

0 comments on commit fc845e6

Please sign in to comment.