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
use byteorder::{BigEndian, LittleEndian};

use crate::{
    Endianness,
    errors::*,
    pcap::Packet,
    pcap::PcapHeader
};


/// Parser for a Pcap formated stream.
///
/// # Examples
///
/// ```no_run
/// use pcap_file::pcap::PcapParser;
/// use pcap_file::PcapError;
///
/// let pcap = vec![0_u8; 0];
/// let mut src = &pcap[..];
///
/// // Creates a new parser and parse the pcap header
/// let (rem, pcap_parser) = PcapParser::new(&pcap[..]).unwrap();
/// src = rem;
///
/// loop {
///
///     match pcap_parser.next_packet(src) {
///         Ok((rem, packet)) => {
///             // Do something
///
///             // Don't forget to update src
///             src = rem;
///
///             // No more data, if no more incoming either then this is the end of the file
///             if rem.is_empty() {
///                 break;
///             }
///         },
///         Err(PcapError::IncompleteBuffer(needed)) => {},// Load more data into src
///         Err(_) => {}// Parsing error
///     }
/// }
/// ```
#[derive(Debug)]
pub struct PcapParser {
    header: PcapHeader
}

impl PcapParser {

    /// Creates a new `PcapParser`.
    /// Returns the parser and the remainder.
    pub fn new(slice: &[u8]) -> ResultParsing<(&[u8], PcapParser)> {

        let (slice, header) = PcapHeader::from_slice(slice)?;

        let parser = PcapParser {
            header
        };

        Ok((slice, parser))
    }

    /// Returns the next packet and the remainder.
    pub fn next_packet<'a>(&self, slice: &'a[u8]) -> ResultParsing<(&'a [u8], Packet<'a>)> {

        let ts_resolution = self.header.ts_resolution();

        match self.header.endianness() {
            Endianness::Big => Packet::from_slice::<BigEndian>(slice, ts_resolution),
            Endianness::Little => Packet::from_slice::<LittleEndian>(slice, ts_resolution)
        }
    }
}