1use std::borrow::Cow;
2use std::io::Write;
3use std::time::Duration;
4
5use byteorder_slice::ByteOrder;
6use byteorder_slice::byteorder::WriteBytesExt;
7use byteorder_slice::result::ReadSlice;
8use derive_into_owned::IntoOwned;
9
10use crate::pcap::{PcapParseError, PcapTsResolution, PcapValidationError, PcapWriteError};
11
12#[derive(Clone, Debug)]
16pub struct PcapPacket<'a> {
17 timestamp: Duration,
19 orig_len: u32,
21 data: Cow<'a, [u8]>,
23}
24
25impl<'a> PcapPacket<'a> {
26 pub fn new(
28 timestamp: Duration,
29 orig_len: u32,
30 data: impl Into<Cow<'a, [u8]>>,
31 ) -> Result<Self, PcapValidationError> {
32 let data = data.into();
33
34 if timestamp.as_secs() > u32::MAX as u64 {
36 return Err(PcapValidationError::TimestampTooBig(timestamp));
37 }
38
39 let Ok(incl_len): Result<u32, _> = data.len().try_into() else {
40 return Err(PcapValidationError::DataTooBig(data.len()));
41 };
42
43 if incl_len > orig_len {
44 return Err(PcapValidationError::OriginLenTooSmall(orig_len, incl_len));
45 }
46
47 Ok(PcapPacket {
48 timestamp,
49 orig_len,
50 data,
51 })
52 }
53
54 pub fn timestamp(&self) -> Duration {
56 self.timestamp
57 }
58
59 pub fn orig_len(&self) -> u32 {
61 self.orig_len
62 }
63
64 pub fn len(&self) -> u32 {
66 self.data
67 .len()
68 .try_into()
69 .expect("PcapPacket::data_len > u32::MAX, should have been validated on PcapPacket creation")
70 }
71
72 pub fn is_empty(&self) -> bool {
74 self.data.is_empty()
75 }
76
77 pub fn data(&self) -> &[u8] {
79 &self.data
80 }
81
82 pub fn into_data(self) -> Cow<'a, [u8]> {
84 self.data
85 }
86
87 pub fn to_owned(&self) -> PcapPacket<'static> {
90 self.clone().into_owned()
91 }
92
93 pub fn into_owned(self) -> PcapPacket<'static> {
96 PcapPacket {
97 timestamp: self.timestamp,
98 orig_len: self.orig_len,
99 data: Cow::Owned(self.data.into_owned()),
100 }
101 }
102
103 pub fn try_from_raw_packet(
105 raw: RawPcapPacket<'a>,
106 ts_resolution: PcapTsResolution,
107 snap_len: u32,
108 ) -> Result<Self, PcapValidationError> {
109 let ts_sec = raw.ts_sec;
111
112 let ts_nsec = if ts_resolution == PcapTsResolution::MicroSecond {
114 let ts_usec = raw.ts_frac;
115 if ts_usec >= 1_000_000 {
116 return Err(PcapValidationError::TsFracMicroTooBig(ts_usec));
117 }
118
119 ts_usec
120 .checked_mul(1000)
121 .expect("ts_usec * 1000 overflow, should have been validated just before")
122 } else {
123 let ts_nsec = raw.ts_frac;
124 if ts_nsec >= 1_000_000_000 {
125 return Err(PcapValidationError::TsFracNanoTooBig(raw.ts_frac));
126 }
127
128 ts_nsec
129 };
130
131 let timestamp = Duration::new(ts_sec as u64, ts_nsec);
132
133 if raw.incl_len > snap_len {
135 return Err(PcapValidationError::IncludedLenTooBig(raw.incl_len, snap_len));
136 }
137
138 Self::new(timestamp, raw.orig_len, raw.data)
139 }
140
141 pub fn into_raw_packet(self, ts_resolution: PcapTsResolution) -> RawPcapPacket<'a> {
143 let (ts_sec, ts_frac, incl_len, orig_len) = self.build_raw_header(ts_resolution);
144 RawPcapPacket {
145 ts_sec,
146 ts_frac,
147 incl_len,
148 orig_len,
149 data: self.data,
150 }
151 }
152
153 pub fn as_raw_packet<'pkt>(&'pkt self, ts_resolution: PcapTsResolution) -> RawPcapPacket<'pkt> {
155 let (ts_sec, ts_frac, incl_len, orig_len) = self.build_raw_header(ts_resolution);
156 RawPcapPacket {
157 ts_sec,
158 ts_frac,
159 incl_len,
160 orig_len,
161 data: Cow::Borrowed(&self.data),
162 }
163 }
164
165 fn build_raw_header(&self, ts_resolution: PcapTsResolution) -> (u32, u32, u32, u32) {
167 let ts_sec: u32 = self
169 .timestamp
170 .as_secs()
171 .try_into()
172 .expect("PcapPacket::timestamp_secs > u32::MAX, should have been validated on PcapPacket creation");
173
174 let mut ts_frac = self.timestamp.subsec_nanos();
175 if ts_resolution == PcapTsResolution::MicroSecond {
176 ts_frac /= 1000;
177 }
178
179 let incl_len: u32 = self
180 .data
181 .len()
182 .try_into()
183 .expect("PcapPacket::data_len > u32::MAX, should have been validated on PcapPacket creation");
184
185 let orig_len = self.orig_len;
186
187 (ts_sec, ts_frac, incl_len, orig_len)
188 }
189}
190
191#[derive(Clone, Debug, IntoOwned)]
195pub struct RawPcapPacket<'a> {
196 pub ts_sec: u32,
198 pub ts_frac: u32,
200 pub incl_len: u32,
202 pub orig_len: u32,
204 pub data: Cow<'a, [u8]>,
206}
207
208impl<'a> RawPcapPacket<'a> {
209 pub fn from_slice<B: ByteOrder>(mut slice: &'a [u8]) -> Result<(&'a [u8], Self), PcapParseError> {
211 if slice.len() < 16 {
213 return Err(PcapParseError::IncompleteBuffer(16, slice.len()));
214 }
215
216 let ts_sec = slice.read_u32::<B>().expect("slice length checked above");
218 let ts_frac = slice.read_u32::<B>().expect("slice length checked above");
219 let incl_len = slice.read_u32::<B>().expect("slice length checked above");
220 let orig_len = slice.read_u32::<B>().expect("slice length checked above");
221
222 let pkt_len = incl_len as usize;
223 if slice.len() < pkt_len {
224 return Err(PcapParseError::IncompleteBuffer(pkt_len, slice.len()));
225 }
226
227 let packet = RawPcapPacket {
228 ts_sec,
229 ts_frac,
230 incl_len,
231 orig_len,
232 data: Cow::Borrowed(&slice[..pkt_len]),
233 };
234 let rem = &slice[pkt_len..];
235
236 Ok((rem, packet))
237 }
238
239 pub fn write_to<W: Write, B: ByteOrder>(&self, writer: &mut W) -> Result<usize, PcapWriteError> {
242 writer
243 .write_u32::<B>(self.ts_sec)
244 .map_err(|e| PcapWriteError::FieldWriteFailed("ts_sec", e))?;
245 writer
246 .write_u32::<B>(self.ts_frac)
247 .map_err(|e| PcapWriteError::FieldWriteFailed("ts_frac", e))?;
248 writer
249 .write_u32::<B>(self.incl_len)
250 .map_err(|e| PcapWriteError::FieldWriteFailed("incl_len", e))?;
251 writer
252 .write_u32::<B>(self.orig_len)
253 .map_err(|e| PcapWriteError::FieldWriteFailed("orig_len", e))?;
254 writer
255 .write_all(&self.data)
256 .map_err(|e| PcapWriteError::FieldWriteFailed("data", e))?;
257
258 Ok(16 + self.data.len())
259 }
260
261 pub fn try_into_pcap_packet(
263 self,
264 ts_resolution: PcapTsResolution,
265 snap_len: u32,
266 ) -> Result<PcapPacket<'a>, PcapValidationError> {
267 PcapPacket::try_from_raw_packet(self, ts_resolution, snap_len)
268 }
269}