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
use std::ffi::{self, CStr};
62
use std::fmt;
63

            
64
use self::Error::*;
65

            
66
mod capture;
67
mod codec;
68
mod device;
69
mod linktype;
70
mod packet;
71

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

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

            
88
mod raw;
89

            
90
#[cfg(windows)]
91
pub mod sendqueue;
92

            
93
#[cfg(feature = "capture-stream")]
94
mod stream;
95
#[cfg(feature = "capture-stream")]
96
pub use stream::PacketStream;
97

            
98
/// An error received from pcap
99
#[derive(Debug, PartialEq, Eq)]
100
pub enum Error {
101
    /// The underlying library returned invalid UTF-8
102
    MalformedError(std::str::Utf8Error),
103
    /// The underlying library returned a null string
104
    InvalidString,
105
    /// The unerlying library returned an error
106
    PcapError(String),
107
    /// The linktype was invalid or unknown
108
    InvalidLinktype,
109
    /// The timeout expired while reading from a live capture
110
    TimeoutExpired,
111
    /// No more packets to read from the file
112
    NoMorePackets,
113
    /// Must be in non-blocking mode to function
114
    NonNonBlock,
115
    /// There is not sufficent memory to create a dead capture
116
    InsufficientMemory,
117
    /// An invalid input string (internal null)
118
    InvalidInputString,
119
    /// An IO error occurred
120
    IoError(std::io::ErrorKind),
121
    #[cfg(not(windows))]
122
    /// An invalid raw file descriptor was provided
123
    InvalidRawFd,
124
    /// Errno error
125
    ErrnoError(errno::Errno),
126
    /// Buffer size overflows capacity
127
    BufferOverflow,
128
}
129

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

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

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

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

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

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

            
206
impl From<ffi::NulError> for Error {
207
2
    fn from(_: ffi::NulError) -> Error {
208
2
        InvalidInputString
209
2
    }
210
}
211

            
212
impl From<std::str::Utf8Error> for Error {
213
4
    fn from(obj: std::str::Utf8Error) -> Error {
214
4
        MalformedError(obj)
215
4
    }
216
}
217

            
218
impl From<std::io::Error> for Error {
219
2
    fn from(obj: std::io::Error) -> Error {
220
2
        obj.kind().into()
221
2
    }
222
}
223

            
224
impl From<std::io::ErrorKind> for Error {
225
2
    fn from(obj: std::io::ErrorKind) -> Error {
226
2
        IoError(obj)
227
2
    }
228
}
229

            
230
#[cfg(test)]
231
mod tests {
232
    use std::error::Error as StdError;
233
    use std::{ffi::CString, io};
234

            
235
    use super::*;
236

            
237
    #[test]
238
    fn test_error_invalid_utf8() {
239
        let bytes: [u8; 8] = [0x78, 0xfe, 0xe9, 0x89, 0x00, 0x00, 0xed, 0x4f];
240
        let error = unsafe { Error::new(&bytes as *const _ as _) };
241
        assert!(matches!(error, Error::MalformedError(_)));
242
    }
243

            
244
    #[test]
245
    fn test_error_null() {
246
        let error = unsafe { Error::new(std::ptr::null()) };
247
        assert_eq!(error, Error::PcapError("".to_string()));
248
    }
249

            
250
    #[test]
251
    #[allow(deprecated)]
252
    fn test_errors() {
253
        let mut errors: Vec<Error> = vec![];
254

            
255
        let bytes: [u8; 8] = [0x78, 0xfe, 0xe9, 0x89, 0x00, 0x00, 0xed, 0x4f];
256
        let cstr = unsafe { CStr::from_ptr(&bytes as *const _ as _) };
257

            
258
        errors.push(cstr.to_str().unwrap_err().into());
259
        errors.push(Error::InvalidString);
260
        errors.push(Error::PcapError("git rekt".to_string()));
261
        errors.push(Error::InvalidLinktype);
262
        errors.push(Error::TimeoutExpired);
263
        errors.push(Error::NoMorePackets);
264
        errors.push(Error::NonNonBlock);
265
        errors.push(Error::InsufficientMemory);
266
        errors.push(CString::new(b"f\0oo".to_vec()).unwrap_err().into());
267
        errors.push(io::Error::new(io::ErrorKind::Interrupted, "error").into());
268
        #[cfg(not(windows))]
269
        errors.push(Error::InvalidRawFd);
270
        errors.push(Error::ErrnoError(errno::Errno(125)));
271
        errors.push(Error::BufferOverflow);
272

            
273
        for error in errors.iter() {
274
            assert!(!error.to_string().is_empty());
275
            assert!(!error.description().is_empty());
276
            match error {
277
                Error::MalformedError(_) => assert!(error.cause().is_some()),
278
                _ => assert!(error.cause().is_none()),
279
            }
280
        }
281
    }
282
}