pcap/
lib.rs

1//! pcap is a packet capture library available on Linux, Windows and Mac. This
2//! crate supports creating and configuring capture contexts, sniffing packets,
3//! sending packets to interfaces, listing devices, and recording packet captures
4//! to pcap-format dump files.
5//!
6//! # Capturing packets
7//! The easiest way to open an active capture handle and begin sniffing is to
8//! use `.open()` on a `Device`. You can obtain the "default" device using
9//! `Device::lookup()`, or you can obtain the device(s) you need via `Device::list()`.
10//!
11//! ```no_run
12//! use pcap::Device;
13//!
14//! let mut cap = Device::lookup().unwrap().unwrap().open().unwrap();
15//!
16//! while let Ok(packet) = cap.next_packet() {
17//!     println!("received packet! {:?}", packet);
18//! }
19//!
20//! ```
21//!
22//! `Capture`'s `.next_packet()` will produce a `Packet` which can be dereferenced to access the
23//! `&[u8]` packet contents.
24//!
25//! # Custom configuration
26//!
27//! You may want to configure the `timeout`, `snaplen` or other parameters for the capture
28//! handle. In this case, use `Capture::from_device()` to obtain a `Capture<Inactive>`, and
29//! proceed to configure the capture handle. When you're finished, run `.open()` on it to
30//! turn it into a `Capture<Active>`.
31//!
32//! ```no_run
33//! use pcap::{Device, Capture};
34//!
35//! let main_device = Device::lookup().unwrap().unwrap();
36//! let mut cap = Capture::from_device(main_device).unwrap()
37//!                   .promisc(true)
38//!                   .snaplen(5000)
39//!                   .open().unwrap();
40//!
41//! while let Ok(packet) = cap.next_packet() {
42//!     println!("received packet! {:?}", packet);
43//! }
44//! ```
45//!
46//! # Abstracting over different capture types
47//!
48//! You can abstract over live captures (`Capture<Active>`) and file captures
49//! (`Capture<Offline>`) using generics and the [`Activated`] trait, for example:
50//!
51//! ```
52//! use pcap::{Activated, Capture};
53//!
54//! fn read_packets<T: Activated>(mut capture: Capture<T>) {
55//!     while let Ok(packet) = capture.next_packet() {
56//!         println!("received packet! {:?}", packet);
57//!     }
58//! }
59//! ```
60
61#![cfg_attr(docsrs, feature(doc_cfg))]
62
63use std::ffi::{self, CStr};
64use std::fmt;
65
66use self::Error::*;
67
68mod capture;
69mod codec;
70mod device;
71mod linktype;
72mod packet;
73
74#[cfg(not(windows))]
75pub use capture::activated::open_raw_fd;
76pub use capture::{
77    activated::{iterator::PacketIter, BpfInstruction, BpfProgram, Direction, Savefile, Stat},
78    inactive::TimestampType,
79    {Activated, Active, Capture, Dead, Inactive, Offline, Precision, State},
80};
81pub use codec::PacketCodec;
82pub use device::{Address, ConnectionStatus, Device, DeviceFlags, IfFlags};
83pub use linktype::Linktype;
84pub use packet::{Packet, PacketHeader};
85
86#[deprecated(note = "Renamed to TimestampType")]
87/// An old name for `TimestampType`, kept around for backward-compatibility.
88pub type TstampType = TimestampType;
89
90mod raw;
91
92#[cfg(windows)]
93#[cfg_attr(docsrs, doc(cfg(windows)))]
94pub mod sendqueue;
95
96#[cfg(feature = "capture-stream")]
97mod stream;
98#[cfg(feature = "capture-stream")]
99#[cfg_attr(docsrs, doc(cfg(feature = "capture-stream")))]
100pub use stream::PacketStream;
101
102/// An error received from pcap
103#[derive(Debug, PartialEq, Eq)]
104pub enum Error {
105    /// The underlying library returned invalid UTF-8
106    MalformedError(std::str::Utf8Error),
107    /// The underlying library returned a null string
108    InvalidString,
109    /// The unerlying library returned an error
110    PcapError(String),
111    /// The linktype was invalid or unknown
112    InvalidLinktype,
113    /// The timeout expired while reading from a live capture
114    TimeoutExpired,
115    /// No more packets to read from the file
116    NoMorePackets,
117    /// Must be in non-blocking mode to function
118    NonNonBlock,
119    /// There is not sufficent memory to create a dead capture
120    InsufficientMemory,
121    /// An invalid input string (internal null)
122    InvalidInputString,
123    /// An IO error occurred
124    IoError(std::io::ErrorKind),
125    #[cfg(not(windows))]
126    /// An invalid raw file descriptor was provided
127    InvalidRawFd,
128    /// Errno error
129    ErrnoError(errno::Errno),
130    /// Buffer size overflows capacity
131    BufferOverflow,
132}
133
134impl Error {
135    unsafe fn new(ptr: *const libc::c_char) -> Error {
136        match cstr_to_string(ptr) {
137            Err(e) => e as Error,
138            Ok(string) => PcapError(string.unwrap_or_default()),
139        }
140    }
141
142    fn with_errbuf<T, F>(func: F) -> Result<T, Error>
143    where
144        F: FnOnce(*mut libc::c_char) -> Result<T, Error>,
145    {
146        let mut errbuf = [0i8; 256];
147        func(errbuf.as_mut_ptr() as _)
148    }
149}
150
151unsafe fn cstr_to_string(ptr: *const libc::c_char) -> Result<Option<String>, Error> {
152    let string = if ptr.is_null() {
153        None
154    } else {
155        Some(CStr::from_ptr(ptr as _).to_str()?.to_owned())
156    };
157    Ok(string)
158}
159
160impl fmt::Display for Error {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        match *self {
163            MalformedError(ref e) => write!(f, "libpcap returned invalid UTF-8: {e}"),
164            InvalidString => write!(f, "libpcap returned a null string"),
165            PcapError(ref e) => write!(f, "libpcap error: {e}"),
166            InvalidLinktype => write!(f, "invalid or unknown linktype"),
167            TimeoutExpired => write!(f, "timeout expired while reading from a live capture"),
168            NonNonBlock => write!(f, "must be in non-blocking mode to function"),
169            NoMorePackets => write!(f, "no more packets to read from the file"),
170            InsufficientMemory => write!(f, "insufficient memory"),
171            InvalidInputString => write!(f, "invalid input string (internal null)"),
172            IoError(ref e) => write!(f, "io error occurred: {e:?}"),
173            #[cfg(not(windows))]
174            InvalidRawFd => write!(f, "invalid raw file descriptor provided"),
175            ErrnoError(ref e) => write!(f, "libpcap os errno: {e}"),
176            BufferOverflow => write!(f, "buffer size too large"),
177        }
178    }
179}
180
181// Using description is deprecated. Remove in next version.
182impl std::error::Error for Error {
183    fn description(&self) -> &str {
184        match *self {
185            MalformedError(..) => "libpcap returned invalid UTF-8",
186            PcapError(..) => "libpcap FFI error",
187            InvalidString => "libpcap returned a null string",
188            InvalidLinktype => "invalid or unknown linktype",
189            TimeoutExpired => "timeout expired while reading from a live capture",
190            NonNonBlock => "must be in non-blocking mode to function",
191            NoMorePackets => "no more packets to read from the file",
192            InsufficientMemory => "insufficient memory",
193            InvalidInputString => "invalid input string (internal null)",
194            IoError(..) => "io error occurred",
195            #[cfg(not(windows))]
196            InvalidRawFd => "invalid raw file descriptor provided",
197            ErrnoError(..) => "internal error, providing errno",
198            BufferOverflow => "buffer size too large",
199        }
200    }
201
202    fn cause(&self) -> Option<&dyn std::error::Error> {
203        match *self {
204            MalformedError(ref e) => Some(e),
205            _ => None,
206        }
207    }
208}
209
210impl From<ffi::NulError> for Error {
211    fn from(_: ffi::NulError) -> Error {
212        InvalidInputString
213    }
214}
215
216impl From<std::str::Utf8Error> for Error {
217    fn from(obj: std::str::Utf8Error) -> Error {
218        MalformedError(obj)
219    }
220}
221
222impl From<std::io::Error> for Error {
223    fn from(obj: std::io::Error) -> Error {
224        obj.kind().into()
225    }
226}
227
228impl From<std::io::ErrorKind> for Error {
229    fn from(obj: std::io::ErrorKind) -> Error {
230        IoError(obj)
231    }
232}
233
234/// Return size of a commonly used packet header.
235///
236/// On Windows this packet header is implicitly added to send queues, so this size must be known
237/// if an application needs to precalculate the exact send queue buffer size.
238pub const fn packet_header_size() -> usize {
239    std::mem::size_of::<raw::pcap_pkthdr>()
240}
241
242#[cfg(test)]
243mod tests {
244    use std::error::Error as StdError;
245    use std::{ffi::CString, io};
246
247    use super::*;
248
249    #[test]
250    fn test_error_invalid_utf8() {
251        let bytes: [u8; 8] = [0x78, 0xfe, 0xe9, 0x89, 0x00, 0x00, 0xed, 0x4f];
252        let error = unsafe { Error::new(&bytes as *const _ as _) };
253        assert!(matches!(error, Error::MalformedError(_)));
254    }
255
256    #[test]
257    fn test_error_null() {
258        let error = unsafe { Error::new(std::ptr::null()) };
259        assert_eq!(error, Error::PcapError("".to_string()));
260    }
261
262    #[test]
263    #[allow(deprecated)]
264    fn test_errors() {
265        let mut errors: Vec<Error> = vec![];
266
267        let bytes: [u8; 8] = [0x78, 0xfe, 0xe9, 0x89, 0x00, 0x00, 0xed, 0x4f];
268        let cstr = unsafe { CStr::from_ptr(&bytes as *const _ as _) };
269
270        errors.push(cstr.to_str().unwrap_err().into());
271        errors.push(Error::InvalidString);
272        errors.push(Error::PcapError("git rekt".to_string()));
273        errors.push(Error::InvalidLinktype);
274        errors.push(Error::TimeoutExpired);
275        errors.push(Error::NoMorePackets);
276        errors.push(Error::NonNonBlock);
277        errors.push(Error::InsufficientMemory);
278        errors.push(CString::new(b"f\0oo".to_vec()).unwrap_err().into());
279        errors.push(io::Error::new(io::ErrorKind::Interrupted, "error").into());
280        #[cfg(not(windows))]
281        errors.push(Error::InvalidRawFd);
282        errors.push(Error::ErrnoError(errno::Errno(125)));
283        errors.push(Error::BufferOverflow);
284
285        for error in errors.iter() {
286            assert!(!error.to_string().is_empty());
287            assert!(!error.description().is_empty());
288            match error {
289                Error::MalformedError(_) => assert!(error.cause().is_some()),
290                _ => assert!(error.cause().is_none()),
291            }
292        }
293    }
294
295    #[test]
296    fn test_packet_size() {
297        assert_eq!(
298            packet_header_size(),
299            std::mem::size_of::<raw::pcap_pkthdr>()
300        );
301    }
302}