Skip to main content

pcap_file/pcapng/blocks/
custom.rs

1//! Custom Block.
2
3use std::borrow::Cow;
4use std::error::Error;
5use std::io::Write;
6
7use byteorder_slice::ByteOrder;
8use byteorder_slice::byteorder::{ReadBytesExt, WriteBytesExt};
9use thiserror::Error;
10
11use super::block_common::{Block, PcapNgBlock};
12use crate::pcapng::blocks::opt_common::CommonOption;
13use crate::pcapng::errors::{BlockContentParseError, PcapNgWriteError};
14use crate::pcapng::{OptionEntryError, PcapNgState};
15
16/* ----- traits for Custom Payload ----- */
17
18/// Common interface for copiable custom block and custom option payloads.
19pub trait CustomPayloadCopiable<'a> {
20    /// Private Enterprise Number of the entity which defined this payload format.
21    const PEN: u32;
22
23    /// Error returned by [`CustomPayloadCopiable::from_slice()`].
24    type FromSliceError: Error + Sync + Send + 'static;
25
26    /// Error returned by [`CustomPayloadCopiable::write_to()`].
27    type WriteToError: Error + Sync + Send + 'static;
28
29    /// Try to parse this payload from a slice.
30    fn from_slice(slice: &'a [u8]) -> Result<Option<Self>, Self::FromSliceError>
31    where
32        Self: Sized;
33
34    /// Write this payload into a writer.
35    fn write_to<W: Write>(&self, writer: &mut W) -> Result<(), Self::WriteToError>;
36
37    /// Serialize this payload into bytes.
38    ///
39    /// # Important
40    /// Do not override.
41    fn to_bytes(&self) -> Result<Vec<u8>, CustomError>
42    where
43        Self: Sized,
44    {
45        let mut data = Vec::new();
46        self.write_to(&mut data).map_err(|e| CustomError {
47            pen: Self::PEN,
48            src: e.into(),
49        })?;
50        Ok(data)
51    }
52}
53
54/// Common interface for non-copiable custom block and custom option payloads.
55pub trait CustomPayloadNonCopiable<'a> {
56    /// Private Enterprise Number of the entity which defined this payload format.
57    const PEN: u32;
58
59    /// State that may be required to parse/write the payload.
60    type State;
61
62    /// Error returned by [`CustomPayloadNonCopiable::from_slice()`].
63    type FromSliceError: Error + Sync + Send + 'static;
64
65    /// Error returned by [`CustomPayloadNonCopiable::write_to()`].
66    type WriteToError: Error + Sync + Send + 'static;
67
68    /// Try to parse this payload from a slice.
69    fn from_slice(state: &Self::State, slice: &'a [u8]) -> Result<Option<Self>, Self::FromSliceError>
70    where
71        Self: Sized;
72
73    /// Write this payload into a writer.
74    fn write_to<W: Write>(&self, state: &Self::State, writer: &mut W) -> Result<(), Self::WriteToError>;
75
76    /// Serialize this payload into bytes.
77    ///
78    /// # Important
79    /// Do not override.
80    fn to_bytes(&self, state: &Self::State) -> Result<Vec<u8>, CustomError>
81    where
82        Self: Sized,
83    {
84        let mut data = Vec::new();
85        self.write_to(state, &mut data).map_err(|e| CustomError {
86            pen: Self::PEN,
87            src: e.into(),
88        })?;
89        Ok(data)
90    }
91}
92
93/// Common interface for custom block payloads.
94///
95/// # Important
96/// Any implementor must also implements [`CustomPayloadCopiable`] and/or [`CustomPayloadNonCopiable`].
97pub trait CustomBlockPayload<'a> {
98    /// Convert this payload into a copiable [`CustomBlock`].
99    ///
100    /// # Important
101    /// Do not override.
102    fn into_custom_block_copiable(self) -> Result<CustomBlock<'a, true>, CustomError>
103    where
104        Self: Sized,
105        Self: CustomPayloadCopiable<'a>,
106    {
107        let data = self.to_bytes()?;
108        Ok(CustomBlock {
109            pen: Self::PEN,
110            payload: Cow::Owned(data),
111        })
112    }
113
114    /// Convert this payload into a non-copiable [`CustomBlock`].
115    ///
116    /// # Important
117    /// Do not override.
118    fn into_custom_block_non_copiable(self, state: &Self::State) -> Result<CustomBlock<'a, false>, CustomError>
119    where
120        Self: Sized,
121        Self: CustomPayloadNonCopiable<'a>,
122    {
123        let data = self.to_bytes(state)?;
124        Ok(CustomBlock {
125            pen: Self::PEN,
126            payload: Cow::Owned(data),
127        })
128    }
129}
130
131/// Common interface for custom option payloads.
132///
133/// # Important
134/// Any implementor must also implements [`CustomPayloadCopiable`] and/or [`CustomPayloadNonCopiable`].
135pub trait CustomOptionPayload<'a> {
136    /// Convert this payload into a copiable [`CustomBinaryOption`].
137    ///
138    /// # Important
139    /// Do not override.
140    fn into_custom_binary_option_copiable(self) -> Result<CustomBinaryOption<'a, true>, CustomError>
141    where
142        Self: Sized,
143        Self: CustomPayloadCopiable<'a>,
144    {
145        let data = self.to_bytes()?;
146        Ok(CustomBinaryOption {
147            pen: Self::PEN,
148            value: Cow::Owned(data),
149        })
150    }
151
152    /// Convert this payload into a non-copiable [`CustomBinaryOption`].
153    ///
154    /// # Important
155    /// Do not override.
156    fn into_custom_binary_option_non_copiable(
157        self,
158        state: &Self::State,
159    ) -> Result<CustomBinaryOption<'a, false>, CustomError>
160    where
161        Self: Sized,
162        Self: CustomPayloadNonCopiable<'a>,
163    {
164        let data = self.to_bytes(state)?;
165        Ok(CustomBinaryOption {
166            pen: Self::PEN,
167            value: Cow::Owned(data),
168        })
169    }
170}
171
172/* ----- Custom Error ----- */
173
174/// Error in custom conversion
175#[derive(Debug, Error)]
176#[error("Error in custom conversion for PEN {pen:#X}")]
177pub struct CustomError {
178    /// Pen of the custom block/option
179    pub pen: u32,
180    /// Source of the error
181    #[source]
182    pub src: Box<dyn Error + Sync + Send + 'static>,
183}
184
185/* ----- struct CustomBlock ----- */
186
187/// Custom block
188#[derive(Clone, Debug, Eq, PartialEq)]
189pub struct CustomBlock<'a, const COPIABLE: bool> {
190    /// Private Enterprise Number of the entity which defined this block.
191    pub pen: u32,
192    /// Payload of this block.
193    pub payload: Cow<'a, [u8]>,
194}
195
196impl<'a, const COPIABLE: bool> CustomBlock<'a, COPIABLE> {
197    // The into_owned method must be implemented manually,
198    // since derive_into_owned can't handle the const generic.
199
200    /// Returns a version of self with all fields converted to owning versions.
201    pub fn into_owned(self) -> CustomBlock<'static, COPIABLE> {
202        CustomBlock {
203            pen: self.pen,
204            payload: Cow::Owned(self.payload.into_owned()),
205        }
206    }
207}
208
209impl<'a> CustomBlock<'a, true> {
210    /// Converts this block's payload into a copiable custom payload type.
211    pub fn interpret<T>(&'a self) -> Result<Option<T>, CustomError>
212    where
213        T: CustomPayloadCopiable<'a> + CustomBlockPayload<'a>,
214    {
215        if self.pen != T::PEN {
216            return Ok(None);
217        }
218
219        T::from_slice(&self.payload).map_err(|e| CustomError {
220            pen: T::PEN,
221            src: e.into(),
222        })
223    }
224}
225
226impl<'a> CustomBlock<'a, false> {
227    /// Converts this block's payload into a non-copiable custom payload type.
228    pub fn interpret<T>(&'a self, state: &T::State) -> Result<Option<T>, CustomError>
229    where
230        T: CustomPayloadNonCopiable<'a> + CustomBlockPayload<'a>,
231    {
232        if self.pen != T::PEN {
233            return Ok(None);
234        }
235
236        T::from_slice(state, &self.payload).map_err(|e| CustomError {
237            pen: T::PEN,
238            src: e.into(),
239        })
240    }
241}
242
243impl<'a, const COPIABLE: bool> PcapNgBlock<'a> for CustomBlock<'a, COPIABLE> {
244    fn from_slice<B: ByteOrder>(
245        _state: &PcapNgState,
246        mut slice: &'a [u8],
247    ) -> Result<(&'a [u8], Self), BlockContentParseError>
248    where
249        Self: Sized,
250    {
251        if slice.len() < 4 {
252            return Err(BlockContentParseError::BlockContentTooSmall {
253                needed: 4,
254                actual: slice.len(),
255            });
256        }
257
258        let pen = slice.read_u32::<B>().unwrap();
259        Ok((
260            &[],
261            CustomBlock {
262                pen,
263                payload: Cow::Borrowed(slice),
264            },
265        ))
266    }
267
268    fn write_to<B: ByteOrder, W: Write>(
269        &self,
270        _state: &PcapNgState,
271        writer: &mut W,
272    ) -> Result<usize, PcapNgWriteError> {
273        writer.write_u32::<B>(self.pen)?;
274        writer.write_all(&self.payload)?;
275        Ok(4 + self.payload.len())
276    }
277
278    fn into_block(self) -> Block<'a> {
279        if COPIABLE {
280            Block::CustomCopiable(CustomBlock {
281                pen: self.pen,
282                payload: self.payload,
283            })
284        } else {
285            Block::CustomNonCopiable(CustomBlock {
286                pen: self.pen,
287                payload: self.payload,
288            })
289        }
290    }
291}
292
293/* ----- struct CustomBinaryOption ----- */
294
295/// Custom binary option
296#[derive(Clone, Debug, Eq, PartialEq)]
297pub struct CustomBinaryOption<'a, const COPIABLE: bool> {
298    /// Option PEN identifier
299    pub pen: u32,
300    /// Option value
301    pub value: Cow<'a, [u8]>,
302}
303
304impl<'a, const COPIABLE: bool> CustomBinaryOption<'a, COPIABLE> {
305    /// Parse an [`CustomBinaryOption`] from a slice
306    pub fn from_slice<B: ByteOrder>(mut src: &'a [u8]) -> Result<Self, OptionEntryError> {
307        let pen = src.read_u32::<B>().map_err(|_| OptionEntryError::WrongSize {
308            expected: 4,
309            actual: src.len(),
310        })?;
311        let opt = CustomBinaryOption {
312            pen,
313            value: Cow::Borrowed(src),
314        };
315        Ok(opt)
316    }
317
318    /// Returns a version of self with all fields converted to owning versions.
319    pub fn into_owned(self) -> CustomBinaryOption<'static, COPIABLE> {
320        CustomBinaryOption {
321            pen: self.pen,
322            value: Cow::Owned(self.value.into_owned()),
323        }
324    }
325}
326
327impl<'a> CustomBinaryOption<'a, true> {
328    /// Converts this option's value into a copiable custom payload type.
329    pub fn interpret<T>(&'a self) -> Result<Option<T>, CustomError>
330    where
331        T: CustomPayloadCopiable<'a> + CustomOptionPayload<'a>,
332    {
333        if self.pen != T::PEN {
334            return Ok(None);
335        }
336
337        T::from_slice(&self.value).map_err(|e| CustomError {
338            pen: T::PEN,
339            src: e.into(),
340        })
341    }
342
343    /// Converts this option into a [`CommonOption`].
344    pub fn into_common_option(self) -> CommonOption<'a> {
345        CommonOption::CustomBinaryCopiable(self)
346    }
347}
348
349impl<'a> CustomBinaryOption<'a, false> {
350    /// Converts this option's value into a non-copiable custom payload type.
351    pub fn interpret<T>(&'a self, state: &T::State) -> Result<Option<T>, CustomError>
352    where
353        T: CustomPayloadNonCopiable<'a> + CustomOptionPayload<'a>,
354    {
355        if self.pen != T::PEN {
356            return Ok(None);
357        }
358
359        T::from_slice(state, &self.value).map_err(|e| CustomError {
360            pen: T::PEN,
361            src: e.into(),
362        })
363    }
364
365    /// Converts this option into a [`CommonOption`].
366    pub fn into_common_option(self) -> CommonOption<'a> {
367        CommonOption::CustomBinaryNonCopiable(self)
368    }
369}
370
371/* ----- struct CustomUtf8Option ----- */
372
373/// Custom string (UTF-8) option
374#[derive(Clone, Debug, Eq, PartialEq)]
375pub struct CustomUtf8Option<'a, const COPIABLE: bool> {
376    /// Option PEN identifier
377    pub pen: u32,
378    /// Option value
379    pub value: Cow<'a, str>,
380}
381
382impl<'a, const COPIABLE: bool> CustomUtf8Option<'a, COPIABLE> {
383    /// Parse a [`CustomUtf8Option`] from a slice
384    pub fn from_slice<B: ByteOrder>(mut src: &'a [u8]) -> Result<Self, OptionEntryError> {
385        let pen = src.read_u32::<B>().map_err(|_| OptionEntryError::WrongSize {
386            expected: 4,
387            actual: src.len(),
388        })?;
389        let opt = CustomUtf8Option {
390            pen,
391            value: Cow::Borrowed(std::str::from_utf8(src)?),
392        };
393        Ok(opt)
394    }
395
396    /// Returns a version of self with all fields converted to owning versions.
397    pub fn into_owned(self) -> CustomUtf8Option<'static, COPIABLE> {
398        CustomUtf8Option {
399            pen: self.pen,
400            value: Cow::Owned(self.value.into_owned()),
401        }
402    }
403}