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
//! Ethernet related packet processing
use prelude::*;

/// The Ethernet parser
pub struct EthernetParser;

impl Parsable<PathIp> for EthernetParser {
    /// Parse an `EthernetPacket` from an `&[u8]`
    fn parse<'a>(&mut self,
                 input: &'a [u8],
                 _: Option<&ParserResultVec>,
                 _: Option<&mut PathIp>)
                 -> IResult<&'a [u8], ParserResult> {
        do_parse!(input,
            d: take!(6) >>
            s: take!(6) >>
            e: map_opt!(be_u16, EtherType::from_u16) >>

            (Box::new(EthernetPacket {
                dst: MacAddress(d[0], d[1], d[2], d[3], d[4], d[5]),
                src: MacAddress(s[0], s[1], s[2], s[3], s[4], s[5]),
                ethertype: e,
            }))
        )
    }
}

impl fmt::Display for EthernetParser {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Ethernet")
    }
}

#[derive(Debug, Eq, PartialEq)]
/// Representation of the Ethernet structure
pub struct EthernetPacket {
    /// Destination mac address
    pub dst: MacAddress,

    /// Source mac address
    pub src: MacAddress,

    /// EtherType of the packet
    pub ethertype: EtherType,
}

#[derive(Debug, Default, Eq, PartialEq)]
/// Representation of a mac network address, usually in the format "ff:ff:ff:ff:ff:ff"
pub struct MacAddress(pub u8, pub u8, pub u8, pub u8, pub u8, pub u8);

#[derive(Debug, Eq, PartialEq)]
/// Supported `EtherType`
pub enum EtherType {
    /// Internet Protocol Version 4
    Ipv4,

    /// Address Resolution Protocol
    Arp,

    /// Internet Protocol Version 6
    Ipv6,
}

impl EtherType {
    /// Convert a u16 to an `EtherType`. Returns None if the type is not supported or generally
    /// invalid.
    pub fn from_u16(input: u16) -> Option<EtherType> {
        match input {
            0x0800 => Some(EtherType::Ipv4),
            0x0806 => Some(EtherType::Arp),
            0x86DD => Some(EtherType::Ipv6),
            _ => None,
        }
    }
}