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
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
//! PCAPNG file format
//!
//! See [https://github.com/pcapng/pcapng](https://github.com/pcapng/pcapng) for details.

use nom::{IResult,Err,ErrorKind,le_u16,le_u32,le_i64};

use capture::Capture;
use packet::{Packet,PacketHeader,Linktype};

use byteorder::{ByteOrder,LittleEndian};

use std::fmt;

/// Section Header Block magic
pub const SHB_MAGIC : u32 = 0x0A0D0D0A;
/// Interface Description Block magic
pub const IDB_MAGIC : u32 = 0x00000001;
/// Simple Packet Block magic
pub const SPB_MAGIC : u32 = 0x00000003;
/// Name Resolution Block magic
pub const NMR_MAGIC : u32 = 0x00000004;
/// Interface Statistic Block magic
pub const IFS_MAGIC : u32 = 0x00000005;
/// Enhanced Packet Block magic
pub const EPB_MAGIC : u32 = 0x00000006;

/// Byte Order magic
pub const BOM_MAGIC : u32 = 0x1A2B3C4D;

#[derive(Clone, Copy, Debug,PartialEq)]
#[repr(u16)]
pub enum OptionCode {
    EndOfOpt = 0,
    Comment = 1,
    ShbHardware = 2,
    ShbOs = 3,
    ShbUserAppl = 4,
    IfTsresol = 9,
    IfTsoffset = 14,
}

#[derive(Debug)]
pub struct PcapNGCapture<'a> {
    pub sections: Vec<Section<'a>>,
}

#[derive(Debug,PartialEq)]
pub enum Block<'a> {
    SectionHeader(SectionHeaderBlock<'a>),
    InterfaceDescription(InterfaceDescriptionBlock<'a>),
    EnhancedPacket(EnhancedPacketBlock<'a>),
    SimplePacket(SimplePacketBlock<'a>),
    Unknown(UnknownBlock<'a>)
}

#[derive(Debug, PartialEq)]
pub struct Section<'a> {
    pub header: SectionHeaderBlock<'a>,

    pub interfaces: Vec<Interface<'a>>,
}

#[derive(PartialEq)]
pub struct Interface<'a> {
    pub header: InterfaceDescriptionBlock<'a>,

    pub blocks: Vec<Block<'a>>,

    // extracted values
    pub if_tsresol: u8,
    pub if_tsoffset: u64
}

/// Compact (debug) display of interface and blocks
impl<'a> fmt::Debug for Interface<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        writeln!(f, "Interface:")?;
        writeln!(f, "    header: {:?}", self.header)?;
        for b in self.blocks.iter() {
            let s = match b {
                &Block::EnhancedPacket(ref e) => format!("EPB(if={}, caplen={}, origlen={})", e.if_id, e.caplen, e.origlen),
                &Block::SimplePacket(ref e)   => format!("SPB(origlen={})", e.origlen),
                &Block::Unknown(ref e)        => format!("Unk(type={}, blocklen={})", e.block_type, e.block_len1),
                _ => format!(""),
            };
            writeln!(f, "    {}", s)?;
        }
        Ok(())
    }
}

impl<'a> Section<'a> {
    pub fn iter_packets(&'a self) -> SectionPacketIterator<'a> {
        SectionPacketIterator{ section: self, index_interface: 0, index_block: 0 }
    }

    pub fn iter_interfaces(&'a self) -> SectionInterfaceIterator<'a> {
        SectionInterfaceIterator{ section: self, index_interface: 0 }
    }

    /// Get a vector of packets, sorted by timestamp
    /// The vector is allocated.
    ///
    /// Choose `sort_by` because it is likely the packets are already almost sorted,
    /// or are series of almost-soted packets (if there are multiple interfaces)
    pub fn sorted_by_timestamp(&self) -> Vec<Packet> {
        let mut v : Vec<_> = self.iter_packets().collect();
        v.sort_by(
            |a, b|
            a.header.ts_sec.cmp(&b.header.ts_sec).then(a.header.ts_usec.cmp(&b.header.ts_usec))
            );
        v
    }
}

// Non-consuming iterator
pub struct SectionInterfaceIterator<'a> {
    section: &'a Section<'a>,
    index_interface: usize,
}

impl<'a> Iterator for SectionInterfaceIterator<'a> {
    type Item = &'a Interface<'a>;

    fn next(&mut self) -> Option<&'a Interface<'a>> {
        if self.index_interface < self.section.interfaces.len() {
            let idx = self.index_interface;
            self.index_interface += 1;
            Some(&self.section.interfaces[idx])
        } else {
            None
        }
    }
}

// Non-consuming iterator
pub struct SectionPacketIterator<'a> {
    section: &'a Section<'a>,
    index_interface: usize,
    index_block: usize
}

impl<'a> Iterator for SectionPacketIterator<'a> {
    type Item = Packet<'a>;

    fn next(&mut self) -> Option<Packet<'a>> {
        for interface in &self.section.interfaces[self.index_interface..] {
            for block in &interface.blocks[self.index_block..] {
                self.index_block += 1;
                match packet_of_block(interface, block) {
                    Some(pkt) => return Some(pkt),
                    None      => (),
                }
            }
            self.index_block = 0;
            self.index_interface += 1;
        }
        None
    }
}

impl<'a> Interface<'a> {
    pub fn iter_packets(&'a self) -> InterfacePacketIterator<'a> {
        InterfacePacketIterator{ interface: self, index_block: 0 }
    }
}

// Non-consuming iterator
pub struct InterfacePacketIterator<'a> {
    interface: &'a Interface<'a>,
    index_block: usize
}

impl<'a> Iterator for InterfacePacketIterator<'a> {
    type Item = Packet<'a>;

    fn next(&mut self) -> Option<Packet<'a>> {
        for block in &self.interface.blocks[self.index_block..] {
            self.index_block += 1;
            match packet_of_block(self.interface, block) {
                Some(pkt) => return Some(pkt),
                None      => (),
            }
        }
        None
    }
}

fn packet_of_block<'a>(interface: &'a Interface, block: &'a Block) -> Option<Packet<'a>> {
    match block {
        &Block::EnhancedPacket(ref b) => {
            let if_tsoffset = interface.if_tsoffset;
            let if_tsresol = interface.if_tsresol;
            let ts_mode = if_tsresol & 0x70;
            let unit =
                if ts_mode == 0 { 10u64.pow(if_tsresol as u32) }
                else { 2u64.pow((if_tsresol & !0x70) as u32) };
            let ts : u64 = ((b.ts_high as u64) << 32) | (b.ts_low as u64);
            let ts_sec = (if_tsoffset + (ts / unit)) as u32;
            let ts_usec = (ts % unit) as u32;
            Some(
                Packet{
                    header: PacketHeader{
                        ts_sec: ts_sec,
                        ts_usec: ts_usec,
                        caplen: b.caplen,
                        len: b.origlen
                    },
                    data: b.data
                }
            )
        },
        // e => println!("unknown: {:?}", e),
        _ => None,
    }
}

#[derive(Debug,PartialEq)]
pub struct SectionHeaderBlock<'a> {
    pub block_type: u32,
    pub block_len1: u32,
    /// Byte-order magic
    pub bom: u32,
    pub major_version: u16,
    pub minor_version: u16,
    pub section_len: i64,
    pub options: Vec<PcapNGOption<'a>>,
    pub block_len2: u32,
}

#[derive(Debug,PartialEq)]
pub struct InterfaceDescriptionBlock<'a> {
    pub block_type: u32,
    pub block_len1: u32,
    pub linktype: u16,
    pub reserved: u16,
    pub snaplen: u32,
    pub options: Vec<PcapNGOption<'a>>,
    pub block_len2: u32,
}

#[derive(Debug,PartialEq)]
pub struct EnhancedPacketBlock<'a> {
    pub block_type: u32,
    pub block_len1: u32,
    pub if_id: u32,
    pub ts_high: u32,
    pub ts_low: u32,
    /// Captured packet length
    pub caplen: u32,
    /// Original packet length
    pub origlen: u32,
    pub data: &'a [u8],
    pub options: Vec<PcapNGOption<'a>>,
    pub block_len2: u32,
}

#[derive(Debug,PartialEq)]
pub struct SimplePacketBlock<'a> {
    pub block_type: u32,
    pub block_len1: u32,
    /// Original packet length
    pub origlen: u32,
    pub data: &'a [u8],
    pub block_len2: u32,
}

#[derive(Debug,PartialEq)]
pub struct UnknownBlock<'a> {
    pub block_type: u32,
    pub block_len1: u32,
    pub data: &'a [u8],
    pub block_len2: u32,
}

#[derive(Debug,PartialEq)]
pub struct PcapNGOption<'a> {
    pub code: u16,
    pub len: u16,
    pub value: &'a [u8],
}

#[derive(Debug,PartialEq)]
pub struct PcapNGHeader {
    pub magic_number: u32,
    pub version_major: u16,
    pub version_minor: u16,
    pub thiszone: i32,
    pub sigfigs: u32,
    /// max len of captured packets, in octets
    pub snaplen: u32,
    /// Data link type
    pub network: u32
}

impl<'a> Capture for PcapNGCapture<'a> {
    fn get_datalink(&self) -> Linktype {
        // assume first linktype is the same
        assert!(self.sections.len() > 0);
        let section = &self.sections[0];
        assert!(section.interfaces.len() > 0);
        let interface = &section.interfaces[0];
        Linktype(interface.header.linktype as i32)
    }

    fn get_snaplen(&self) -> u32 {
        // assume first linktype is the same
        assert!(self.sections.len() > 0);
        let section = &self.sections[0];
        assert!(section.interfaces.len() > 0);
        let interface = &section.interfaces[0];
        interface.header.snaplen
    }

    fn iter_packets<'b>(&'b self) -> Box<Iterator<Item=Packet> + 'b> {
        Box::new(self.iter())
    }
}




/// true only if n is a power of 2
macro_rules! align_n2 {
    ($x:expr, $n:expr) => ( ($x + ($n - 1)) & !($n - 1) );
}

macro_rules! align32 {
    ($x:expr) => ( align_n2!($x, 4u32) );
}


// Non-consuming iterator
pub struct PcapNGCaptureIterator<'a> {
    pcap: &'a PcapNGCapture<'a>,
    index_section: usize,
    it: SectionPacketIterator<'a>,
}

impl<'a> PcapNGCapture<'a> {
    pub fn from_file(i: &[u8]) -> Result<PcapNGCapture,IResult<&[u8],PcapNGCapture>> { // XXX change return type to just an IResult
        match parse_pcapng(i) {
            Ok((_, pcap))  => Ok(pcap),
            e              => Err(e)
        }
    }

    pub fn iter(&'a self) -> PcapNGCaptureIterator<'a> {
        assert!(self.sections.len() > 0);
        PcapNGCaptureIterator{
            pcap: self,
            index_section: 0,
            it: self.sections[0].iter_packets()
        }
    }
}

// XXX IntoIterator seems to generate only consuming iterators, or I don't understand how to use it

// impl<'a> IntoIterator for PcapNGCapture<'a> {
//     type Item = Packet<'a>;
//     type IntoIter = PcapNGCaptureIterator<'a>;
// 
//     fn into_iter(self) -> Self::IntoIter {
//         PcapNGCaptureIterator{ pcap: self, index: 0 }
//     }
// }

impl<'a> Iterator for PcapNGCaptureIterator<'a> {
    type Item = Packet<'a>;

    fn next(&mut self) -> Option<Packet<'a>> {
        loop {
            match self.it.next() {
                Some(p) => { return Some(p); },
                _       => (),
            }
            self.index_section += 1;
            if self.index_section >= self.pcap.sections.len() { break; }
            self.it = self.pcap.sections[self.index_section].iter_packets();
        }
        None
    }
}






pub fn parse_option(i: &[u8]) -> IResult<&[u8],PcapNGOption> {
    do_parse!(i,
              code:  le_u16 >>
              len:   le_u16 >>
              value: take!(align32!(len as u32)) >>
              ( PcapNGOption{
                  code: code,
                  len: len,
                  value: value,
              })
    )
}

pub fn parse_sectionheaderblock(i: &[u8]) -> IResult<&[u8],SectionHeaderBlock> {
    do_parse!(i,
              magic:   verify!(le_u32, |x:u32| x == SHB_MAGIC) >>
              len1:    le_u32 >>
              bom:     verify!(le_u32, |x:u32| x == BOM_MAGIC) >>
              major:   le_u16 >>
              minor:   le_u16 >>
              slen:    le_i64 >>
              // options
              options: cond!(
                    len1 > 28,
                    flat_map!(
                        take!(len1 - 28),
                        many0!(complete!(parse_option))
                        )
                  ) >>
              len2:    verify!(le_u32, |x:u32| x == len1) >>
              (
                  SectionHeaderBlock{
                      block_type: magic,
                      block_len1: len1,
                      bom: bom,
                      major_version: major,
                      minor_version: minor,
                      section_len: slen,
                      options: options.unwrap_or(Vec::new()),
                      block_len2: len2
                  }
              )
    )
}

pub fn parse_sectionheader(i: &[u8]) -> IResult<&[u8],Block> {
    do_parse!(i,
              magic:   verify!(le_u32, |x:u32| x == SHB_MAGIC) >>
              len1:    le_u32 >>
              bom:     verify!(le_u32, |x:u32| x == BOM_MAGIC) >>
              major:   le_u16 >>
              minor:   le_u16 >>
              slen:    le_i64 >>
              // options
              options: cond!(
                    len1 > 28,
                    flat_map!(
                        take!(len1 - 28),
                        many0!(complete!(parse_option))
                        )
                  ) >>
              len2:    verify!(le_u32, |x:u32| x == len1) >>
              (
                  Block::SectionHeader(SectionHeaderBlock{
                      block_type: magic,
                      block_len1: len1,
                      bom: bom,
                      major_version: major,
                      minor_version: minor,
                      section_len: slen,
                      options: options.unwrap_or(Vec::new()),
                      block_len2: len2
                  })
              )
    )
}

pub fn parse_interfacedescriptionblock(i: &[u8]) -> IResult<&[u8],InterfaceDescriptionBlock> {
    do_parse!(i,
              magic:      verify!(le_u32, |x:u32| x == IDB_MAGIC) >>
              len1:       le_u32 >>
              linktype:   le_u16 >>
              reserved:   le_u16 >>
              snaplen:    le_u32 >>
              // options
              options: cond!(
                    len1 > 20,
                    flat_map!(
                        take!(len1 - 20),
                        many0!(complete!(parse_option))
                        )
                  ) >>
              len2:    verify!(le_u32, |x:u32| x == len1) >>
              (
                  InterfaceDescriptionBlock{
                      block_type: magic,
                      block_len1: len1,
                      linktype: linktype,
                      reserved: reserved,
                      snaplen: snaplen,
                      options: options.unwrap_or(Vec::new()),
                      block_len2: len2
                  }
              )
    )
}

pub fn parse_interfacedescription(i: &[u8]) -> IResult<&[u8],Block> {
    do_parse!(i,
              magic:      verify!(le_u32, |x:u32| x == IDB_MAGIC) >>
              len1:       le_u32 >>
              linktype:   le_u16 >>
              reserved:   le_u16 >>
              snaplen:    le_u32 >>
              // options
              options: cond!(
                    len1 > 20,
                    flat_map!(
                        take!(len1 - 20),
                        many0!(complete!(parse_option))
                        )
                  ) >>
              len2:    verify!(le_u32, |x:u32| x == len1) >>
              (
                  Block::InterfaceDescription(InterfaceDescriptionBlock{
                      block_type: magic,
                      block_len1: len1,
                      linktype: linktype,
                      reserved: reserved,
                      snaplen: snaplen,
                      options: options.unwrap_or(Vec::new()),
                      block_len2: len2
                  })
              )
    )
}

pub fn parse_simplepacketblock(i: &[u8]) -> IResult<&[u8],Block> {
    do_parse!(i,
              magic:     verify!(le_u32, |x:u32| x == EPB_MAGIC) >>
              len1:      verify!(le_u32, |val:u32| val >= 32) >>
              origlen:   le_u32 >>
              // XXX if snaplen is < origlen, we MUST use snaplen
              al_len:    value!(align32!(origlen)) >>
              data:      take!(al_len) >>
              len2:      verify!(le_u32, |x:u32| x == len1) >>
              (
                  Block::SimplePacket(SimplePacketBlock{
                      block_type: magic,
                      block_len1: len1,
                      origlen: origlen,
                      data: data,
                      block_len2: len2
                  })
              )
    )
}

pub fn parse_enhancedpacketblock(i: &[u8]) -> IResult<&[u8],Block> {
    do_parse!(i,
                         verify!(le_u32, |x:u32| x == EPB_MAGIC) >>
              len1:      verify!(le_u32, |val:u32| val >= 32) >>
              if_id:     le_u32 >>
              ts_high:   le_u32 >>
              ts_low:    le_u32 >>
              caplen:    verify!(le_u32, |x| x < ::std::u32::MAX - 4) >>
              origlen:   le_u32 >>
              al_len:    value!(align32!(caplen)) >>
              data:      take!(al_len) >>
              options:   cond!(
                    len1 > 32 + al_len,
                    flat_map!(
                        take!(len1 - (32 + al_len)),
                        many0!(complete!(parse_option))
                        )
                  ) >>
              len2:      verify!(le_u32, |x:u32| x == len1) >>
              (
                  Block::EnhancedPacket(EnhancedPacketBlock{
                      block_type: EPB_MAGIC,
                      block_len1: len1,
                      if_id: if_id,
                      ts_high: ts_high,
                      ts_low: ts_low,
                      caplen: caplen,
                      origlen: origlen,
                      data: data,
                      options: options.unwrap_or(Vec::new()),
                      block_len2: len2
                  })
              )
    )
}

pub fn parse_unknownblock(i: &[u8]) -> IResult<&[u8],Block> {
    // debug!("Unknown block of ID {:x}", peek!(i, le_u32).unwrap().1);
    do_parse!(i,
              blocktype: le_u32 >>
              len1:      verify!(le_u32, |val:u32| val >= 12) >>
              data:      take!(len1 - 12) >>
              len2:      verify!(le_u32, |x:u32| x == len1) >>
              (
                  Block::Unknown(UnknownBlock{
                      block_type: blocktype,
                      block_len1: len1,
                      data: data,
                      block_len2: len2
                  })
              )
    )
}

pub fn parse_block(i: &[u8]) -> IResult<&[u8],Block> {
    match peek!(i, le_u32) {
        Ok((rem, id)) => {
            match id {
                SHB_MAGIC => call!(rem, parse_sectionheader),
                IDB_MAGIC => call!(rem, parse_interfacedescription),
                SPB_MAGIC => call!(rem, parse_simplepacketblock),
                EPB_MAGIC => call!(rem, parse_enhancedpacketblock),
                _         => call!(rem, parse_unknownblock)
            }
        },
        Err(e)        => Err(e)
    }
}

pub fn parse_section(i: &[u8]) -> IResult<&[u8],Section> {
    do_parse!(
        i,
        shb: parse_sectionheaderblock >>
        ifs: many0!(complete!(parse_interface)) >>
        ({
            Section {
                header: shb,
                interfaces: ifs,
            }
        })
    )
}

pub fn parse_interface(i: &[u8]) -> IResult<&[u8],Interface> {
    do_parse!(
        i,
        idb: parse_interfacedescriptionblock >>
        blocks: many0!(complete!(parse_content_block)) >>
        ({
            // XXX extract if_tsoffset and if_tsresol
            let mut if_tsresol : u8 = 6;
            let mut if_tsoffset : u64 = 0;
            for opt in idb.options.iter() {
                match opt.code {
                    9 /* OptionCode::IfTsresol */ => { if !opt.value.is_empty() { if_tsresol =  opt.value[0]; } },
                    14 /* OptionCode::IfTsoffset */ => { if opt.value.len() >= 8 { if_tsoffset = LittleEndian::read_u64(opt.value); } },
                    _ => (),
                }
            }
            Interface {
                header: idb,
                blocks: blocks,
                if_tsresol: if_tsresol,
                if_tsoffset: if_tsoffset
            }
        })
    )
}

pub fn parse_content_block(i: &[u8]) -> IResult<&[u8],Block> {
    match peek!(i, le_u32) {
        Ok((rem, id)) => {
            match id {
                SHB_MAGIC => Err(Err::Error(error_position!(i, ErrorKind::Tag))),
                IDB_MAGIC => Err(Err::Error(error_position!(i, ErrorKind::Tag))),
                SPB_MAGIC => call!(rem, parse_simplepacketblock),
                EPB_MAGIC => call!(rem, parse_enhancedpacketblock),
                _         => call!(rem, parse_unknownblock)
            }
        },
        Err(e)        => Err(e)
    }
}

pub fn parse_pcapng(i: &[u8]) -> IResult<&[u8],PcapNGCapture> {
    do_parse!(
        i,
        sections: many1!(complete!(parse_section)) >>
        (
            PcapNGCapture{
                sections: sections,
            }
        )
    )
}