Skip to main content

pcap_file/pcapng/
errors.rs

1use std::{fmt::Display, time::Duration};
2
3use thiserror::Error;
4
5use crate::{
6    DataLink,
7    pcapng::blocks::{block_name, interface_description::InterfaceTsResolution},
8};
9
10/* ----- PcapError ----- */
11
12/// Errors that can occur while parsing, reading or writing a pcapng file.
13#[derive(Debug, Error)]
14pub enum PcapNgError {
15    /// Error while parsing pcapng data.
16    #[error(transparent)]
17    Parse(#[from] PcapNgParseError),
18    /// Error while reading pcapng data.
19    #[error(transparent)]
20    Read(#[from] PcapNgReadError),
21    /// Error while writing pcapng data.
22    #[error(transparent)]
23    Write(#[from] PcapNgWriteError),
24    /// Validation error for block or field content.
25    #[error(transparent)]
26    BlockValidation(#[from] ContentValidationError),
27    /// Error while updating the parser or writer state.
28    #[error(transparent)]
29    StateUpdate(#[from] StateUpdateError),
30}
31
32/* ----- PcapNgParseError ----- */
33
34/// Errors that can occur while parsing typed pcapng data.
35#[derive(Debug, Error)]
36pub enum PcapNgParseError {
37    /// The buffer is too small to parse the expected data.
38    /// # Fields
39    /// - 0: needed size to parse the data
40    /// - 1: actual size of the buffer
41    #[error("The buffer is too small: need {0}B, got {1}B")]
42    IncompleteBuffer(usize, usize),
43
44    /// The raw block format is invalid.
45    #[error("Invalid raw block format")]
46    InvalidFormat(#[from] PcapNgFormatError),
47
48    /// Error while converting a raw block into a typed block.
49    #[error(transparent)]
50    BlockConversion(#[from] BlockConversionError),
51
52    /// Error while updating the pcapng state.
53    #[error(transparent)]
54    StateUpdate(#[from] StateUpdateError),
55}
56
57impl From<RawBlockParseError> for PcapNgParseError {
58    fn from(value: RawBlockParseError) -> Self {
59        match value {
60            RawBlockParseError::IncompleteBuffer(needed, actual) => Self::IncompleteBuffer(needed, actual),
61            RawBlockParseError::InvalidFormat(format) => Self::InvalidFormat(format),
62        }
63    }
64}
65
66/* ----- PcapNgReadError ----- */
67
68/// Errors that can occur while reading pcapng data from an I/O source.
69#[derive(Debug, Error)]
70pub enum PcapNgReadError {
71    /// An I/O error occurred while reading the pcapng.
72    #[error("I/O error while reading the pcapng")]
73    Io(#[source] std::io::Error),
74
75    /// The raw block format is invalid.
76    #[error("Invalid raw block format")]
77    InvalidFormat(#[from] PcapNgFormatError),
78
79    /// Error while converting a raw block into a typed block.
80    #[error(transparent)]
81    BlockConversion(#[from] BlockConversionError),
82
83    /// Error while updating the pcapng state.
84    #[error(transparent)]
85    StateUpdate(#[from] StateUpdateError),
86}
87
88impl From<PcapNgParseError> for PcapNgReadError {
89    fn from(value: PcapNgParseError) -> Self {
90        match value {
91            PcapNgParseError::IncompleteBuffer(_, _) => {
92                Self::Io(std::io::Error::from(std::io::ErrorKind::UnexpectedEof))
93            }
94            PcapNgParseError::InvalidFormat(e) => Self::InvalidFormat(e),
95            PcapNgParseError::BlockConversion(e) => Self::BlockConversion(e),
96            PcapNgParseError::StateUpdate(e) => Self::StateUpdate(e),
97        }
98    }
99}
100
101/* ----- enum PcapWriteError ----- */
102
103/// Errors that can occur while writing pcapng data.
104#[derive(Debug, Error)]
105pub enum PcapNgWriteError {
106    /// An I/O error occurred while writing the pcapng stream.
107    #[error("I/O error during writing")]
108    Io(#[from] std::io::Error),
109
110    /// A field failed validation before being written.
111    #[error("Field `{field}` failed validation during writing")]
112    Validation {
113        /// Name of the field that failed validation.
114        field: &'static str,
115        /// Underlying validation error.
116        // Boxed to keep the error small
117        source: Box<ContentValidationError>,
118    },
119
120    /// The raw block format is invalid.
121    #[error("Invalid raw block format")]
122    InvalidFormat(#[from] PcapNgFormatError),
123
124    /// Error while updating the pcapng state.
125    #[error("State update error during writing")]
126    StateUpdate(#[from] StateUpdateError),
127}
128
129impl PcapNgWriteError {
130    /// Creates a write error for a field that failed content validation.
131    pub(crate) fn validation_error(field: &'static str, source: ContentValidationError) -> Self {
132        Self::Validation {
133            field,
134            source: Box::new(source),
135        }
136    }
137}
138
139/* ----- PcapNgFormatError ----- */
140
141/// Format-related errors that prevent further parsing.
142#[derive(Debug, Error)]
143pub enum PcapNgFormatError {
144    /// The file does not start with a Section Header Block.
145    #[error("The section header is missing")]
146    MissingSectionHeader,
147    /// The magic number of the pcapng SectionBlock is invalid.
148    #[error("Invalid magic number: {0:#X}")]
149    InvalidMagicNumber(u32),
150    /// The block length field of a block is not a multiple of 4, which is required by the pcapng specification.
151    #[error("Block length is not a multiple of 4: {0}B")]
152    BlockNotAligned(usize),
153    /// The block is too short to contain its content.
154    /// # Fields
155    /// - 0: minimum block size for the expected block type
156    /// - 1: actual block size
157    #[error("Block is too short: minimum {0}B, actual {1}B")]
158    BlockTooShort(usize, usize),
159    /// The two block length fields do not match.
160    /// # Fields
161    /// - 0: initial length field
162    /// - 1: trailing length field
163    #[error("Block length fields don't match: initial {0}B, trailing {1}B")]
164    BlockLengthMismatch(u32, u32),
165    /// The block length field does not match the raw block body length.
166    #[error("Block length doesn't match body length: expected {expected}B, got {actual}B")]
167    InvalidBlockLength {
168        /// Expected total length based on the raw block body.
169        expected: usize,
170        /// Actual total length field.
171        actual: u32,
172    },
173}
174
175/* ----- RawBlockParseError ----- */
176
177/// Errors that can occur while parsing a raw block from bytes.
178#[derive(Debug, Error)]
179pub enum RawBlockParseError {
180    /// The buffer is too small to parse the expected data.
181    /// # Fields
182    /// - 0: needed size to parse the data
183    /// - 1: actual size of the buffer
184    #[error("The buffer is too small: need {0}B, got {1}B")]
185    IncompleteBuffer(usize, usize),
186
187    /// The raw block format is invalid.
188    #[error("Invalid raw block format")]
189    InvalidFormat(#[from] PcapNgFormatError),
190}
191
192/* ----- BlockConversionError ----- */
193
194/// Errors that can occur while converting a raw block into a typed block.
195#[derive(Debug, Error)]
196pub struct BlockConversionError {
197    /// Numeric block type
198    pub type_: u32,
199    /// Underlying block content parse error
200    // Boxed to keep the error small
201    pub source: Box<BlockContentParseError>,
202}
203
204impl Display for BlockConversionError {
205    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
206        write!(
207            f,
208            "Invalid content for block '{}' ({:#X})",
209            block_name(self.type_),
210            self.type_
211        )
212    }
213}
214
215/* ----- BlockContentParseError ----- */
216
217/// Errors that can occur while parsing the content of a block.
218#[derive(Debug, Error)]
219pub enum BlockContentParseError {
220    /// The block is too short.
221    #[error("Block content too small: need {needed}B, got {actual}B")]
222    BlockContentTooSmall {
223        /// Needed size to parse the block content.
224        needed: usize,
225        /// Actual size of the remaining block content buffer.
226        actual: usize,
227    },
228
229    /// Validation error while decoding block content.
230    #[error(transparent)]
231    Validation(#[from] ContentValidationError),
232
233    /// Error parsing block options.
234    #[error("Error parsing the options")]
235    Option(#[from] OptionParseError),
236}
237
238/* ----- StateUpdateError ----- */
239
240/// Errors that can occur while updating the pcapng state.
241#[derive(Debug, Error)]
242pub enum StateUpdateError {
243    /// A state-relevant raw block could not be converted into a typed block.
244    #[error("Failed to convert raw block to update the pcapng state")]
245    BlockConversion(#[from] BlockConversionError),
246}
247
248/* ----- ContentValidationError ----- */
249
250/// Errors that can occur while validating decoded pcapng content.
251#[derive(Debug, Error)]
252pub enum ContentValidationError {
253    /// The magic number of the pcapng SectionBlock is invalid.
254    #[error("Invalid magic number: {0:#X}")]
255    InvalidMagicNumber(u32),
256    /// A reserved field is not zero.
257    #[error("Invalid reserved field: {0}")]
258    InvalidReservedField(u16),
259    /// The timestamp resolution value is invalid.
260    #[error("Invalid timestamp resolution: {0:#X} (is_bin: {1}, resol:{2})")]
261    InvalidTsResolution(u8, bool, u8),
262    /// The linktype in invalid (superior to u16::MAX)
263    #[error("Invalid Linktype: {0:?}")]
264    InvalidLinktype(DataLink),
265
266    /// No interface in the current section state.
267    #[error("Section without any interface")]
268    NoInterface,
269    /// The interface ID does not exist in the current section state.
270    #[error("Invalid interface ID: {0}")]
271    InvalidInterfaceId(u32),
272
273    /// A raw timestamp and its interface offset could not be represented as a duration since the Unix epoch.
274    #[error(
275        "Failed to decode timestamp (high: {timestamp_high:#X}, low: {timestamp_low:#X}, combined: {}) with resolution {resolution} and offset {offset}s",
276        ((*timestamp_high as u64) << 32) | *timestamp_low as u64
277    )]
278    FailedToDecodeTimestamp {
279        /// Most significant 32 bits of the raw timestamp.
280        timestamp_high: u32,
281        /// Least significant 32 bits of the raw timestamp.
282        timestamp_low: u32,
283        /// Interface timestamp resolution.
284        resolution: InterfaceTsResolution,
285        /// Interface timestamp offset in seconds.
286        offset: i64,
287    },
288
289    /// A timestamp could not be encoded in the raw 64-bit timestamp field.
290    #[error("Failed to encode timestamp {timestamp:?} with resolution {resolution} and offset {offset}s")]
291    FailedToEncodeTimestamp {
292        /// Timestamp supplied for encoding.
293        timestamp: Duration,
294        /// Interface timestamp resolution.
295        resolution: InterfaceTsResolution,
296        /// Interface timestamp offset in seconds.
297        offset: i64,
298    },
299
300    /// The original length of the packet is lower than its actual length
301    #[error("The original length of the packet is lower than its actual length: {0}B on wire, {1}B captured")]
302    InvalidOriginalLen(u32, usize),
303
304    /// The captured length of the packet does not match the expected length.
305    #[error("Invalid captured length: expected {expected}B, got {actual}B")]
306    InvalidCapturedLen {
307        /// Expected captured length
308        expected: usize,
309        /// Actual captured length
310        actual: usize,
311    },
312
313    /// The Name Resolution record entry size is invalid.
314    #[error("Wrong record size: expected {expected}B, got {actual}B")]
315    RecordWrongSize {
316        /// Expected size
317        expected: usize,
318        /// Actual size
319        actual: usize,
320    },
321    /// The Name Resolution record entry is smaller than its minimum valid size.
322    #[error("Wrong record minimum size: expected at least {min}B, got {actual}B")]
323    RecordWrongMinSize {
324        /// Expected size
325        min: usize,
326        /// Actual size
327        actual: usize,
328    },
329    /// The Name Resolution record entry is too big to be written
330    #[error("Record length doesn't fit on a u16: {0}B")]
331    RecordTooBig(usize),
332    /// A record name is not valid UTF-8.
333    #[error("A record name is not valid UTF-8")]
334    RecordNameNotUtf8(#[source] std::str::Utf8Error),
335    /// A Name Resolution record does not contain any names.
336    #[error("Record without any name")]
337    RecordNamesEmpty,
338
339    /// Error converting a custom block payload.
340    #[error("Error in custom block conversion for PEN {0}: {1}")]
341    CustomBlockConversionError(u32, Box<dyn std::error::Error + Sync + Send>),
342
343    /// The content of a block is too big to fit on a block.
344    #[error("Block content doesn't fit on a u32: {0}B")]
345    BlockContentTooBig(u64),
346
347    /// The content of a PcapNgOption is too big to be written
348    #[error("Option content doesn't fit on a u16: {0}B")]
349    OptionTooBig(usize),
350}
351
352/* ----- OptionParseError ----- */
353
354/// Errors that can occur while parsing a block's option list.
355#[derive(Debug, Error)]
356pub enum OptionParseError {
357    /// The buffer is too short to parse the options.
358    #[error("The option field is too small to parse the options: need {needed}B, got {actual}B")]
359    ContentTooSmall {
360        /// Needed size to parse the option list.
361        needed: usize,
362        /// Actual size of the option buffer.
363        actual: usize,
364    },
365    /// An individual option entry is invalid.
366    #[error("Invalid option entry. Code: {code}, Name: {name}")]
367    InvalidEntry {
368        /// Numeric option code.
369        code: u16,
370        /// Human-readable option name.
371        name: &'static str,
372        /// Underlying option entry error.
373        // Boxed to keep the error size small
374        source: Box<OptionEntryError>,
375    },
376}
377
378/* ----- OptionEntryError ----- */
379
380/// Errors that can occur while parsing a single option entry.
381#[derive(Debug, Error)]
382pub enum OptionEntryError {
383    /// The size of the option entry is not correct.
384    #[error("Wrong entry size: expected {expected}B, got {actual}B")]
385    WrongSize {
386        /// Expected size
387        expected: usize,
388        /// Actual size
389        actual: usize,
390    },
391    /// The option payload is not valid UTF-8.
392    #[error("Invalid UTF-8 format")]
393    InvalidUtf8(#[from] std::str::Utf8Error),
394    /// Validation error while decoding an option entry.
395    #[error(transparent)]
396    Validation(#[from] ContentValidationError),
397}