1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
pub mod block;
pub mod iface;
use crate::block::{Block, BlockError, BlockReader, BlockType, FrameError, NameResolution};
use crate::iface::{InterfaceId, InterfaceInfo};
use bytes::Bytes;
use std::{
io::{Read, Seek},
time::SystemTime,
};
use thiserror::Error;
use tracing::*;
pub(crate) type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug, Error)]
pub enum Error {
#[error("Error while parsing a frame (fatal)")]
Frame(#[from] FrameError),
#[error("Error while parsing a {0:?} block (non-fatal)")]
Block(BlockType, #[source] BlockError),
#[error("IO error")]
IO(#[from] std::io::Error),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Packet {
pub timestamp: Option<SystemTime>,
pub interface: Option<InterfaceId>,
pub data: Bytes,
}
pub struct Capture<R> {
inner: BlockReader<R>,
current_section: u32,
interfaces: Vec<Option<InterfaceInfo>>,
resolved_names: Vec<NameResolution>,
}
impl<R> Capture<R> {
pub fn new(rdr: R) -> Capture<R> {
Capture {
inner: BlockReader::new(rdr),
current_section: 0,
interfaces: Vec::new(),
resolved_names: Vec::new(),
}
}
pub fn rewind(&mut self) -> Result<()>
where
R: Seek,
{
self.inner.rewind()?;
self.interfaces.clear();
self.resolved_names.clear();
Ok(())
}
pub fn lookup_interface(&self, interface_id: InterfaceId) -> Option<&InterfaceInfo> {
if interface_id.0 != self.current_section {
None
} else {
self.interfaces.get(interface_id.1 as usize)?.as_ref()
}
}
}
impl<R: Read> Iterator for Capture<R> {
type Item = Result<Packet>;
fn next(&mut self) -> Option<Self::Item> {
self.try_next().transpose()
}
}
impl<R: Read> Capture<R> {
fn try_next(&mut self) -> Result<Option<Packet>> {
loop {
let block = match self.inner.try_next() {
Ok(Some(block)) => block,
Ok(None) => return Ok(None),
Err(e) => {
if let Error::Block(block_type, _) = e {
self.handle_corrupt_block(block_type);
}
return Err(e);
}
};
self.handle_block(&block);
let Some((meta, data)) = block.into_pkt() else { continue };
let interface = meta.map(|(_, iface)| InterfaceId(self.current_section, iface));
let timestamp = meta.and_then(|(ts, iface)| {
let iface = self.interfaces.get(iface as usize)?.as_ref()?;
Some(iface.resolve_ts(ts))
});
return Ok(Some(Packet {
timestamp,
interface,
data,
}));
}
}
fn start_new_section(&mut self) {
self.interfaces.clear();
self.resolved_names.clear();
self.current_section += 1;
debug!("Starting new section (#{})", self.current_section);
}
fn handle_block(&mut self, block: &Block) {
match block {
Block::SectionHeader(_) => self.start_new_section(),
Block::InterfaceDescription(descr) => {
debug!("Defined a new interface: {:?}", descr);
if descr.snap_len.unwrap_or(0) > BlockReader::<R>::BUF_CAPACITY as u32 {
warn!(
"The max packet length for this interface is greater \
than the length of our buffer."
);
}
let iface = InterfaceInfo {
descr: descr.clone(),
stats: None,
};
debug!("Parsed: {iface:?}");
self.interfaces.push(Some(iface));
}
Block::NameResolution(x) => {
debug!("Defined a new resolved name: {x:?}");
self.resolved_names.push(x.clone());
}
Block::InterfaceStatistics(stats) => {
debug!("Got some interface statistics: {stats:?}");
match self
.interfaces
.get_mut(stats.interface_id as usize)
.and_then(|x| x.as_mut())
{
Some(x) => x.stats = Some(stats.clone()),
None => warn!("Saw statistics for an undefined interface"),
}
}
Block::EnhancedPacket(pkt) => trace!("Got a packet: {pkt:?}"),
Block::SimplePacket(pkt) => trace!("Got a packet: {pkt:?}"),
Block::ObsoletePacket(pkt) => trace!("Got a packet: {pkt:?}"),
Block::Unparsed(block_type) => {
warn!("{block_type:?} blocks are ignored")
}
}
}
fn handle_corrupt_block(&mut self, block_type: BlockType) {
use crate::block::BlockType as BT;
match block_type {
BT::SectionHeader => self.start_new_section(),
BT::InterfaceDescription => self.interfaces.push(None),
BT::NameResolution | BT::InterfaceStatistics => (),
BT::ObsoletePacket | BT::SimplePacket | BT::EnhancedPacket => (),
_ => (),
}
}
}