Skip to main content

pcap_file/pcapng/blocks/
interface_description.rs

1#![allow(clippy::cast_lossless)]
2
3//! Interface Description Block (IDB).
4
5use std::borrow::Cow;
6use std::fmt::Display;
7use std::io::Write;
8use std::time::Duration;
9
10use byteorder_slice::ByteOrder;
11use byteorder_slice::byteorder::WriteBytesExt;
12use byteorder_slice::result::ReadSlice;
13use derive_into_owned::IntoOwned;
14use once_cell::sync::Lazy;
15
16use super::block_common::{Block, PcapNgBlock};
17use super::opt_common::{CommonOption, PcapNgOption, WriteOpt};
18use crate::DataLink;
19use crate::pcapng::PcapNgState;
20use crate::pcapng::errors::{BlockContentParseError, ContentValidationError, OptionEntryError, PcapNgWriteError};
21
22/* ----- InterfaceDescriptionBlock ----- */
23
24/// An Interface Description Block (IDB) is the container for information describing an interface
25/// on which packet data is captured.
26#[derive(Clone, Debug, IntoOwned, Eq, PartialEq)]
27pub struct InterfaceDescriptionBlock<'a> {
28    /// A value that defines the link layer type of this interface.
29    ///
30    /// The list of Standardized Link Layer Type codes is available in the
31    /// [tcpdump.org link-layer header types registry.](http://www.tcpdump.org/linktypes.html).
32    pub linktype: DataLink,
33
34    /// Maximum number of octets captured from each packet.
35    ///
36    /// The portion of each packet that exceeds this value will not be stored in the file.
37    /// A value of zero indicates no limit.
38    pub snaplen: u32,
39
40    /// Options
41    pub options: Vec<InterfaceDescriptionOption<'a>>,
42}
43
44impl<'a> PcapNgBlock<'a> for InterfaceDescriptionBlock<'a> {
45    fn from_slice<B: ByteOrder>(
46        state: &PcapNgState,
47        mut slice: &'a [u8],
48    ) -> Result<(&'a [u8], Self), BlockContentParseError> {
49        if slice.len() < 8 {
50            return Err(BlockContentParseError::BlockContentTooSmall {
51                needed: 8,
52                actual: slice.len(),
53            });
54        }
55
56        let linktype = (slice.read_u16::<B>().unwrap() as u32).into();
57
58        let reserved = slice.read_u16::<B>().unwrap();
59        if reserved != 0 {
60            return Err(ContentValidationError::InvalidReservedField(reserved).into());
61        }
62
63        let snaplen = slice.read_u32::<B>().unwrap();
64        let (slice, options) = InterfaceDescriptionOption::opts_from_slice::<B>(state, None, slice)?;
65
66        let block = InterfaceDescriptionBlock {
67            linktype,
68            snaplen,
69            options,
70        };
71
72        Ok((slice, block))
73    }
74
75    fn write_to<B: ByteOrder, W: Write>(&self, state: &PcapNgState, writer: &mut W) -> Result<usize, PcapNgWriteError> {
76        let datalink: u16 = u32::from(self.linktype).try_into().map_err(|_| {
77            PcapNgWriteError::validation_error(
78                "InterfaceDescriptionBlock.linktype",
79                ContentValidationError::InvalidLinktype(self.linktype),
80            )
81        })?;
82
83        writer.write_u16::<B>(datalink)?;
84        writer.write_u16::<B>(0)?;
85        writer.write_u32::<B>(self.snaplen)?;
86
87        let opt_len = InterfaceDescriptionOption::write_opts_to::<B, W>(&self.options, state, None, writer)?;
88        Ok(8 + opt_len)
89    }
90
91    fn into_block(self) -> Block<'a> {
92        Block::InterfaceDescription(self)
93    }
94}
95
96impl<'a> InterfaceDescriptionBlock<'a> {
97    /// Creates a new [`InterfaceDescriptionBlock`]
98    pub fn new(linktype: DataLink, snaplen: u32) -> Self {
99        Self {
100            linktype,
101            snaplen,
102            options: vec![],
103        }
104    }
105
106    /// Returns the timestamp resolution of the interface.
107    /// If no ts_resolution is set, defaults to μs.
108    pub fn ts_resolution(&self) -> InterfaceTsResolution {
109        let mut ts_resol = InterfaceTsResolution::default();
110
111        for opt in &self.options {
112            if let InterfaceDescriptionOption::IfTsResol(resol) = opt {
113                ts_resol = *resol;
114                break;
115            }
116        }
117
118        ts_resol
119    }
120
121    /// Returns the timestamp offset of the interface, or zero if it has none.
122    pub fn ts_offset(&self) -> i64 {
123        for opt in &self.options {
124            if let InterfaceDescriptionOption::IfTsOffset(offset) = opt {
125                return *offset;
126            }
127        }
128
129        0
130    }
131}
132
133/* ----- InterfaceDescriptionOption ----- */
134
135/// The Interface Description Block (IDB) options
136#[derive(Clone, Debug, IntoOwned, Eq, PartialEq)]
137pub enum InterfaceDescriptionOption<'a> {
138    /// The if_name option is a UTF-8 string containing the name of the device used to capture data.
139    IfName(Cow<'a, str>),
140
141    /// The if_description option is a UTF-8 string containing the description of the device used to capture data.
142    IfDescription(Cow<'a, str>),
143
144    /// The if_IPv4addr option is an IPv4 network address and corresponding netmask for the interface.
145    IfIpv4Addr(Cow<'a, [u8]>),
146
147    /// The if_IPv6addr option is an IPv6 network address and corresponding prefix length for the interface.
148    IfIpv6Addr(Cow<'a, [u8]>),
149
150    /// The if_MACaddr option is the Interface Hardware MAC address (48 bits), if available.
151    IfMacAddr(Cow<'a, [u8]>),
152
153    /// The if_EUIaddr option is the Interface Hardware EUI address (64 bits), if available.
154    IfEuIAddr(u64),
155
156    /// The if_speed option is a 64-bit number for the Interface speed (in bits per second).
157    IfSpeed(u64),
158
159    /// The if_tsresol option identifies the resolution of timestamps.
160    IfTsResol(InterfaceTsResolution),
161
162    /// The if_tzone option identifies the time zone for GMT support.
163    IfTzone(u32),
164
165    /// The if_filter option identifies the filter (e.g. "capture only TCP traffic") used to capture traffic.
166    IfFilter(Cow<'a, [u8]>),
167
168    /// The if_os option is a UTF-8 string containing the name of the operating system
169    /// of the machine in which this interface is installed.
170    IfOs(Cow<'a, str>),
171
172    /// The if_fcslen option is an 8-bit unsigned integer value that specifies
173    /// the length of the Frame Check Sequence (in bits) for this interface.
174    IfFcsLen(u8),
175
176    /// The if_tsoffset option is a 64-bit integer value that specifies an offset (in seconds)
177    /// that must be added to the timestamp of each packet to obtain the absolute timestamp of a packet.
178    IfTsOffset(i64),
179
180    /// The if_hardware option is a UTF-8 string containing the description of the interface hardware.
181    IfHardware(Cow<'a, str>),
182
183    /// A common option applicable to any block type.
184    Common(CommonOption<'a>),
185}
186
187impl InterfaceDescriptionOption<'_> {
188    const IF_NAME: u16 = 2;
189    const IF_DESCRIPTION: u16 = 3;
190    const IF_IPV4_ADDR: u16 = 4;
191    const IF_IPV6_ADDR: u16 = 5;
192    const IF_MAC_ADDR: u16 = 6;
193    const IF_EU_ADDR: u16 = 7;
194    const IF_SPEED: u16 = 8;
195    const IF_TS_RESOL: u16 = 9;
196    const IF_T_ZONE: u16 = 10;
197    const IF_FILTER: u16 = 11;
198    const IF_OS: u16 = 12;
199    const IF_FCS_LEN: u16 = 13;
200    const IF_TS_OFFSET: u16 = 14;
201    const IF_HARDWARE: u16 = 15;
202}
203
204impl<'a> PcapNgOption<'a> for InterfaceDescriptionOption<'a> {
205    fn from_slice<B: ByteOrder>(
206        _state: &PcapNgState,
207        _interface_id: Option<u32>,
208        code: u16,
209        mut slice: &'a [u8],
210    ) -> Result<Self, OptionEntryError> {
211        let opt = match code {
212            Self::IF_NAME => InterfaceDescriptionOption::IfName(Cow::Borrowed(std::str::from_utf8(slice)?)),
213            Self::IF_DESCRIPTION => {
214                InterfaceDescriptionOption::IfDescription(Cow::Borrowed(std::str::from_utf8(slice)?))
215            }
216            Self::IF_IPV4_ADDR => {
217                if slice.len() != 8 {
218                    return Err(OptionEntryError::WrongSize {
219                        expected: 8,
220                        actual: slice.len(),
221                    });
222                }
223                InterfaceDescriptionOption::IfIpv4Addr(Cow::Borrowed(slice))
224            }
225            Self::IF_IPV6_ADDR => {
226                if slice.len() != 17 {
227                    return Err(OptionEntryError::WrongSize {
228                        expected: 17,
229                        actual: slice.len(),
230                    });
231                }
232                InterfaceDescriptionOption::IfIpv6Addr(Cow::Borrowed(slice))
233            }
234            Self::IF_MAC_ADDR => {
235                if slice.len() != 6 {
236                    return Err(OptionEntryError::WrongSize {
237                        expected: 6,
238                        actual: slice.len(),
239                    });
240                }
241                InterfaceDescriptionOption::IfMacAddr(Cow::Borrowed(slice))
242            }
243            Self::IF_EU_ADDR => {
244                if slice.len() != 8 {
245                    return Err(OptionEntryError::WrongSize {
246                        expected: 8,
247                        actual: slice.len(),
248                    });
249                }
250                InterfaceDescriptionOption::IfEuIAddr(slice.read_u64::<B>().unwrap())
251            }
252            Self::IF_SPEED => {
253                if slice.len() != 8 {
254                    return Err(OptionEntryError::WrongSize {
255                        expected: 8,
256                        actual: slice.len(),
257                    });
258                }
259                InterfaceDescriptionOption::IfSpeed(slice.read_u64::<B>().unwrap())
260            }
261            Self::IF_TS_RESOL => {
262                if slice.len() != 1 {
263                    return Err(OptionEntryError::WrongSize {
264                        expected: 1,
265                        actual: slice.len(),
266                    });
267                }
268
269                let raw_resol = slice.read_u8().unwrap();
270                let resol = InterfaceTsResolution::from_u8(raw_resol)?;
271                InterfaceDescriptionOption::IfTsResol(resol)
272            }
273            Self::IF_T_ZONE => {
274                if slice.len() != 4 {
275                    return Err(OptionEntryError::WrongSize {
276                        expected: 4,
277                        actual: slice.len(),
278                    });
279                }
280                InterfaceDescriptionOption::IfTzone(slice.read_u32::<B>().unwrap())
281            }
282            Self::IF_FILTER => {
283                if slice.is_empty() {
284                    return Err(OptionEntryError::WrongSize {
285                        expected: 0,
286                        actual: slice.len(),
287                    });
288                }
289                InterfaceDescriptionOption::IfFilter(Cow::Borrowed(slice))
290            }
291            Self::IF_OS => InterfaceDescriptionOption::IfOs(Cow::Borrowed(std::str::from_utf8(slice)?)),
292            Self::IF_FCS_LEN => {
293                if slice.len() != 1 {
294                    return Err(OptionEntryError::WrongSize {
295                        expected: 1,
296                        actual: slice.len(),
297                    });
298                }
299                InterfaceDescriptionOption::IfFcsLen(slice.read_u8().unwrap())
300            }
301            Self::IF_TS_OFFSET => {
302                if slice.len() != 8 {
303                    return Err(OptionEntryError::WrongSize {
304                        expected: 8,
305                        actual: slice.len(),
306                    });
307                }
308                InterfaceDescriptionOption::IfTsOffset(slice.read_i64::<B>().unwrap())
309            }
310            Self::IF_HARDWARE => InterfaceDescriptionOption::IfHardware(Cow::Borrowed(std::str::from_utf8(slice)?)),
311
312            _ => InterfaceDescriptionOption::Common(CommonOption::new::<B>(code, slice)?),
313        };
314
315        Ok(opt)
316    }
317
318    fn write_to<B: ByteOrder, W: Write>(
319        &self,
320        _state: &PcapNgState,
321        _interface_id: Option<u32>,
322        writer: &mut W,
323    ) -> Result<usize, PcapNgWriteError> {
324        match self {
325            InterfaceDescriptionOption::IfName(a) => a.write_opt::<B, W>(Self::IF_NAME, writer),
326            InterfaceDescriptionOption::IfDescription(a) => a.write_opt::<B, W>(Self::IF_DESCRIPTION, writer),
327            InterfaceDescriptionOption::IfIpv4Addr(a) => a.write_opt::<B, W>(Self::IF_IPV4_ADDR, writer),
328            InterfaceDescriptionOption::IfIpv6Addr(a) => a.write_opt::<B, W>(Self::IF_IPV6_ADDR, writer),
329            InterfaceDescriptionOption::IfMacAddr(a) => a.write_opt::<B, W>(Self::IF_MAC_ADDR, writer),
330            InterfaceDescriptionOption::IfEuIAddr(a) => a.write_opt::<B, W>(Self::IF_EU_ADDR, writer),
331            InterfaceDescriptionOption::IfSpeed(a) => a.write_opt::<B, W>(Self::IF_SPEED, writer),
332            InterfaceDescriptionOption::IfTsResol(a) => a.to_u8().write_opt::<B, W>(Self::IF_TS_RESOL, writer),
333            InterfaceDescriptionOption::IfTzone(a) => a.write_opt::<B, W>(Self::IF_T_ZONE, writer),
334            InterfaceDescriptionOption::IfFilter(a) => a.write_opt::<B, W>(Self::IF_FILTER, writer),
335            InterfaceDescriptionOption::IfOs(a) => a.write_opt::<B, W>(Self::IF_OS, writer),
336            InterfaceDescriptionOption::IfFcsLen(a) => a.write_opt::<B, W>(Self::IF_FCS_LEN, writer),
337            InterfaceDescriptionOption::IfTsOffset(a) => a.write_opt::<B, W>(Self::IF_TS_OFFSET, writer),
338            InterfaceDescriptionOption::IfHardware(a) => a.write_opt::<B, W>(Self::IF_HARDWARE, writer),
339            InterfaceDescriptionOption::Common(a) => a.write_opt::<B, W>(a.code(), writer),
340        }
341    }
342
343    fn code_name(code: u16) -> &'static str {
344        match code {
345            Self::IF_NAME => "IfName",
346            Self::IF_DESCRIPTION => "IfDescription",
347            Self::IF_IPV4_ADDR => "IfIpv4Addr",
348            Self::IF_IPV6_ADDR => "IfIpv6Addr",
349            Self::IF_MAC_ADDR => "IfMacAddr",
350            Self::IF_EU_ADDR => "IfEuIAddr",
351            Self::IF_SPEED => "IfSpeed",
352            Self::IF_TS_RESOL => "IfTsResol",
353            Self::IF_T_ZONE => "IfTzone",
354            Self::IF_FILTER => "IfFilter",
355            Self::IF_OS => "IfOs",
356            Self::IF_FCS_LEN => "IfFcsLen",
357            Self::IF_TS_OFFSET => "IfTsOffset",
358            Self::IF_HARDWARE => "IfHardware",
359            _ => CommonOption::code_name(code),
360        }
361    }
362}
363
364/* ----- TsResolution ----- */
365
366static TS_RESOL_DEC_TO_DURATION: Lazy<Vec<u128>> = Lazy::new(|| (0..10).map(|i| 10_u128.pow(9 - i)).collect());
367
368/// Timestamp resolution of an interface.
369///
370/// Can be either binary (2^-resol)s or decimal (10^-resol)s.
371#[derive(Copy, Clone, Debug, PartialEq, Eq)]
372pub struct InterfaceTsResolution {
373    /// Whether the resolution is binary or decimal.
374    is_bin: bool,
375    /// The resolution itself.
376    resol: u8,
377}
378
379impl InterfaceTsResolution {
380    /// Second resolution
381    pub const SEC: Self = InterfaceTsResolution {
382        is_bin: false,
383        resol: 0,
384    };
385    /// Milli-second resolution
386    pub const MILLI: Self = InterfaceTsResolution {
387        is_bin: false,
388        resol: 3,
389    };
390    /// Micro-second resolution
391    pub const MICRO: Self = InterfaceTsResolution {
392        is_bin: false,
393        resol: 6,
394    };
395    /// Nano-second resolution
396    pub const NANO: Self = InterfaceTsResolution {
397        is_bin: false,
398        resol: 9,
399    };
400
401    /// Creates a new [`InterfaceTsResolution`].
402    ///
403    /// - If binary, the resolution must be in the range [0-29].
404    /// - If decimal, the resolution must be in the range [0-9].
405    pub fn new(is_bin: bool, resol: u8) -> Result<Self, ContentValidationError> {
406        // 2^29 is the last power of 2 inferior to 1_000_000_000 which is the number of nanosec in one second
407        if is_bin && resol > 29 {
408            let resol_enc = InterfaceTsResolution { is_bin, resol }.to_u8();
409            return Err(ContentValidationError::InvalidTsResolution(resol_enc, is_bin, resol));
410        }
411
412        if !is_bin && resol > 9 {
413            let resol_enc = InterfaceTsResolution { is_bin, resol }.to_u8();
414            return Err(ContentValidationError::InvalidTsResolution(resol_enc, is_bin, resol));
415        }
416
417        Ok(InterfaceTsResolution { is_bin, resol })
418    }
419
420    /// Creates a new [`InterfaceTsResolution`] from a [`u8`].
421    ///
422    /// - If binary, the resolution must be in the range [0-29].
423    /// - If decimal, the resolution must be in the range [0-9].
424    pub fn from_u8(ts_resol: u8) -> Result<Self, ContentValidationError> {
425        let is_bin = (ts_resol >> 7) & 0x1 == 1;
426        let resol = ts_resol & 0x7F;
427
428        Self::new(is_bin, resol)
429    }
430
431    /// Encodes the [`InterfaceTsResolution`] into a [`u8`] for storage in the file.
432    pub fn to_u8(self) -> u8 {
433        (self.is_bin as u8) << 7 | self.resol
434    }
435
436    /// Decode an encoded timestamp using the current resolution.
437    pub fn decode_timestamp(&self, ts_raw: u64) -> Duration {
438        let timestamp_ns = if self.is_bin {
439            // We don't use a pre-computed TS_RESOL_BIN here because we would lose too much precision for higher resolutions.
440            // Example: 2^29 resol => 10^9 / 2^29 => 1.86ns resolution rounded to 1ns
441            (ts_raw as u128 * 1_000_000_000_u128) >> self.resol
442        } else {
443            ts_raw as u128 * TS_RESOL_DEC_TO_DURATION[self.resol as usize]
444        };
445
446        duration_from_nanos(timestamp_ns)
447    }
448
449    /// Encode a timestamp with the current resolution.
450    ///
451    /// # Errors
452    /// - Timestamp can't be encoded with the current resolution on a u64
453    pub fn encode_timestamp(&self, timestamp: Duration) -> Result<u64, ContentValidationError> {
454        let timestamp_ns = timestamp.as_nanos();
455        let ts = if self.is_bin {
456            timestamp_ns
457                .checked_shl(self.resol.into())
458                .ok_or(ContentValidationError::FailedToEncodeTimestamp {
459                    timestamp,
460                    resolution: *self,
461                    offset: 0,
462                })?
463                / 1_000_000_000_u128
464        } else {
465            timestamp_ns / TS_RESOL_DEC_TO_DURATION[self.resol as usize]
466        };
467
468        ts.try_into()
469            .map_err(|_| ContentValidationError::FailedToEncodeTimestamp {
470                timestamp,
471                resolution: *self,
472                offset: 0,
473            })
474    }
475
476    /// Returns whether the resolution is binary or decimal.
477    pub fn is_bin(&self) -> bool {
478        self.is_bin
479    }
480
481    /// Returns the resolution value.
482    pub fn resolution(&self) -> u8 {
483        self.resol
484    }
485}
486
487/// Builds a [`Duration`] from a nanosecond count.
488///
489/// `Duration::from_nanos_u128` requires Rust 1.93. Seconds always fit in `u64`
490/// because `decode_timestamp` starts from a `u64` tick count.
491fn duration_from_nanos(timestamp_ns: u128) -> Duration {
492    const NANOS_PER_SEC: u128 = 1_000_000_000;
493    Duration::new(
494        timestamp_ns.wrapping_div(NANOS_PER_SEC) as u64,
495        timestamp_ns.wrapping_rem(NANOS_PER_SEC) as u32,
496    )
497}
498
499impl Default for InterfaceTsResolution {
500    /// Default to micro-seconds resolution
501    fn default() -> Self {
502        Self::MICRO
503    }
504}
505
506impl Display for InterfaceTsResolution {
507    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
508        if self.is_bin {
509            write!(f, "2^-{}s", self.resol)
510        } else {
511            write!(f, "10^-{}s", self.resol)
512        }
513    }
514}
515
516#[cfg(test)]
517mod tests {
518    use std::time::Duration;
519
520    use super::{ContentValidationError, InterfaceTsResolution};
521
522    /// Test that multiple encode / decode doesn't drift more than by one step.
523    #[test]
524    fn binary_timestamp_roundtrip_loses_at_most_one_tick_min() {
525        let resolution = InterfaceTsResolution::new(true, 10).unwrap();
526
527        let mut raw = 1;
528        for _ in 0..100 {
529            let ts = resolution.decode_timestamp(raw);
530            raw = resolution.encode_timestamp(ts).unwrap();
531        }
532
533        assert_eq!(raw, 0);
534    }
535
536    /// Test that multiple encode / decode doesn't drift more than by one step.
537    #[test]
538    fn binary_timestamp_roundtrip_loses_at_most_one_tick_max() {
539        let resolution = InterfaceTsResolution::new(true, 10).unwrap();
540
541        let mut raw = u64::MAX;
542        for _ in 0..100 {
543            let ts = resolution.decode_timestamp(raw);
544            raw = resolution.encode_timestamp(ts).unwrap();
545        }
546
547        assert_eq!(raw, 18446744073709551614);
548    }
549
550    #[test]
551    fn binary_timestamp_encode_overflow_returns_invalid_timestamp() {
552        let resolution = InterfaceTsResolution::new(true, 29).unwrap();
553
554        let error = resolution.encode_timestamp(Duration::MAX).unwrap_err();
555
556        assert!(matches!(
557            error,
558            ContentValidationError::FailedToEncodeTimestamp {
559                timestamp,
560                resolution: error_resolution,
561                offset,
562            } if timestamp == Duration::MAX
563                    && error_resolution == resolution
564                    && offset == 0
565        ));
566    }
567}