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

            
63
use std::ffi::{self, CStr};
64
use std::fmt;
65

            
66
use self::Error::*;
67

            
68
mod capture;
69
mod codec;
70
mod device;
71
mod linktype;
72
mod packet;
73

            
74
#[cfg(not(windows))]
75
pub use capture::activated::open_raw_fd;
76
pub use capture::{
77
    activated::{iterator::PacketIter, BpfInstruction, BpfProgram, Direction, Savefile, Stat},
78
    inactive::TimestampType,
79
    {Activated, Active, Capture, Dead, Inactive, Offline, Precision, State},
80
};
81
pub use codec::PacketCodec;
82
pub use device::{Address, ConnectionStatus, Device, DeviceFlags, IfFlags};
83
pub use linktype::Linktype;
84
pub use packet::{Packet, PacketHeader};
85

            
86
#[deprecated(note = "Renamed to TimestampType")]
87
/// An old name for `TimestampType`, kept around for backward-compatibility.
88
pub type TstampType = TimestampType;
89

            
90
mod raw;
91

            
92
#[cfg(windows)]
93
#[cfg_attr(docsrs, doc(cfg(windows)))]
94
pub mod sendqueue;
95

            
96
#[cfg(feature = "capture-stream")]
97
mod stream;
98
#[cfg(feature = "capture-stream")]
99
#[cfg_attr(docsrs, doc(cfg(feature = "capture-stream")))]
100
pub use stream::PacketStream;
101

            
102
/// An error received from pcap
103
#[derive(Debug, PartialEq, Eq)]
104
pub 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

            
134
impl Error {
135
47
    unsafe fn new(ptr: *const libc::c_char) -> Error {
136
47
        match cstr_to_string(ptr) {
137
2
            Err(e) => e as Error,
138
45
            Ok(string) => PcapError(string.unwrap_or_default()),
139
        }
140
47
    }
141

            
142
54
    fn with_errbuf<T, F>(func: F) -> Result<T, Error>
143
54
    where
144
54
        F: FnOnce(*mut libc::c_char) -> Result<T, Error>,
145
54
    {
146
54
        let mut errbuf = [0i8; 256];
147
54
        func(errbuf.as_mut_ptr() as _)
148
54
    }
149
}
150

            
151
72
unsafe fn cstr_to_string(ptr: *const libc::c_char) -> Result<Option<String>, Error> {
152
72
    let string = if ptr.is_null() {
153
2
        None
154
    } else {
155
70
        Some(CStr::from_ptr(ptr as _).to_str()?.to_owned())
156
    };
157
70
    Ok(string)
158
72
}
159

            
160
impl fmt::Display for Error {
161
26
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162
26
        match *self {
163
2
            MalformedError(ref e) => write!(f, "libpcap returned invalid UTF-8: {}", e),
164
2
            InvalidString => write!(f, "libpcap returned a null string"),
165
2
            PcapError(ref e) => write!(f, "libpcap error: {}", e),
166
2
            InvalidLinktype => write!(f, "invalid or unknown linktype"),
167
2
            TimeoutExpired => write!(f, "timeout expired while reading from a live capture"),
168
2
            NonNonBlock => write!(f, "must be in non-blocking mode to function"),
169
2
            NoMorePackets => write!(f, "no more packets to read from the file"),
170
2
            InsufficientMemory => write!(f, "insufficient memory"),
171
2
            InvalidInputString => write!(f, "invalid input string (internal null)"),
172
2
            IoError(ref e) => write!(f, "io error occurred: {:?}", e),
173
            #[cfg(not(windows))]
174
2
            InvalidRawFd => write!(f, "invalid raw file descriptor provided"),
175
2
            ErrnoError(ref e) => write!(f, "libpcap os errno: {}", e),
176
2
            BufferOverflow => write!(f, "buffer size too large"),
177
        }
178
26
    }
179
}
180

            
181
// Using description is deprecated. Remove in next version.
182
impl std::error::Error for Error {
183
26
    fn description(&self) -> &str {
184
26
        match *self {
185
2
            MalformedError(..) => "libpcap returned invalid UTF-8",
186
2
            PcapError(..) => "libpcap FFI error",
187
2
            InvalidString => "libpcap returned a null string",
188
2
            InvalidLinktype => "invalid or unknown linktype",
189
2
            TimeoutExpired => "timeout expired while reading from a live capture",
190
2
            NonNonBlock => "must be in non-blocking mode to function",
191
2
            NoMorePackets => "no more packets to read from the file",
192
2
            InsufficientMemory => "insufficient memory",
193
2
            InvalidInputString => "invalid input string (internal null)",
194
2
            IoError(..) => "io error occurred",
195
            #[cfg(not(windows))]
196
2
            InvalidRawFd => "invalid raw file descriptor provided",
197
2
            ErrnoError(..) => "internal error, providing errno",
198
2
            BufferOverflow => "buffer size too large",
199
        }
200
26
    }
201

            
202
26
    fn cause(&self) -> Option<&dyn std::error::Error> {
203
26
        match *self {
204
2
            MalformedError(ref e) => Some(e),
205
24
            _ => None,
206
        }
207
26
    }
208
}
209

            
210
impl From<ffi::NulError> for Error {
211
2
    fn from(_: ffi::NulError) -> Error {
212
2
        InvalidInputString
213
2
    }
214
}
215

            
216
impl From<std::str::Utf8Error> for Error {
217
4
    fn from(obj: std::str::Utf8Error) -> Error {
218
4
        MalformedError(obj)
219
4
    }
220
}
221

            
222
impl From<std::io::Error> for Error {
223
2
    fn from(obj: std::io::Error) -> Error {
224
2
        obj.kind().into()
225
2
    }
226
}
227

            
228
impl From<std::io::ErrorKind> for Error {
229
2
    fn from(obj: std::io::ErrorKind) -> Error {
230
2
        IoError(obj)
231
2
    }
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.
238
2
pub const fn packet_header_size() -> usize {
239
2
    std::mem::size_of::<raw::pcap_pkthdr>()
240
2
}
241

            
242
#[cfg(test)]
243
mod 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
}