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
use crate::interfaces::{Interface, MacAddr};
use std::{
    convert::TryFrom,
    io::{Error, ErrorKind},
    net::Ipv4Addr,
    u16,
};

use num_derive::FromPrimitive;
use num_traits::FromPrimitive;

use pnet::packet::{
    arp::{ArpHardwareTypes, ArpOperation, ArpPacket, MutableArpPacket},
    ethernet::{
        EtherType,
        EtherTypes::{self},
        MutableEthernetPacket,
    },
    MutablePacket, Packet,
};

pub struct ArpMessage {
    pub source_hardware_address: MacAddr,
    pub source_protocol_address: Ipv4Addr,

    pub target_hardware_address: MacAddr,
    pub target_protocol_address: Ipv4Addr,

    pub ethertype: EtherType,
    pub operation: Operation,
}

#[derive(Copy, Clone, FromPrimitive, PartialEq)]
pub enum Operation {
    ArpRequest = 0x1,
    ArpResponse = 0x2,
    RarpRequest = 0x3,
    RarpResponse = 0x4,
}

impl ArpMessage {
    /// Constructs a new ARP message with arbitrary field contents.
    pub fn new(
        ethertype: EtherType,
        source_hardware_address: MacAddr,
        source_protocol_address: Ipv4Addr,
        target_hardware_address: MacAddr,
        target_protocol_address: Ipv4Addr,
        operation: Operation,
    ) -> Self {
        ArpMessage {
            source_hardware_address: source_hardware_address,
            source_protocol_address: source_protocol_address,
            target_hardware_address: target_hardware_address,
            target_protocol_address: target_protocol_address,
            ethertype: ethertype,
            operation: operation,
        }
    }

    /// Constructs a new ARP request message.
    pub fn new_arp_request(
        source_hardware_address: MacAddr,
        source_protocol_address: Ipv4Addr,
        target_protocol_address: Ipv4Addr,
    ) -> Self {
        Self::new(
            EtherTypes::Arp,
            source_hardware_address,
            source_protocol_address,
            MacAddr(0, 0, 0, 0, 0, 0),
            target_protocol_address,
            Operation::ArpRequest,
        )
    }

    /// Constructs a new ARP response message.
    pub fn new_arp_response(
        source_hardware_address: MacAddr,
        source_protocol_address: Ipv4Addr,
        target_hardware_address: MacAddr,
        target_protocol_address: Ipv4Addr,
    ) -> Self {
        Self::new(
            EtherTypes::Arp,
            source_hardware_address,
            source_protocol_address,
            target_hardware_address,
            target_protocol_address,
            Operation::ArpResponse,
        )
    }

    /// Constructs a new RARP request message.
    pub fn new_rarp_request(
        source_hardware_address: MacAddr,
        target_hardware_address: MacAddr,
    ) -> Self {
        Self::new(
            EtherTypes::Rarp,
            source_hardware_address,
            Ipv4Addr::new(0, 0, 0, 0),
            target_hardware_address,
            Ipv4Addr::new(0, 0, 0, 0),
            Operation::RarpRequest,
        )
    }

    /// Constructs a new RARP response message.
    pub fn new_rarp_response(
        source_hardware_address: MacAddr,
        source_protocol_address: Ipv4Addr,
        target_hardware_address: MacAddr,
        target_protocol_address: Ipv4Addr,
    ) -> Self {
        Self::new(
            EtherTypes::Rarp,
            source_hardware_address,
            source_protocol_address,
            target_hardware_address,
            target_protocol_address,
            Operation::RarpResponse,
        )
    }

    /// Sends the message on the given interface.
    /// # Errors
    /// Returns an error when sending fails.
    pub fn send(&self, interface: &Interface) -> Result<(), Error> {
        let mut tx = match interface.create_tx_rx_channels() {
            Ok((tx, _)) => tx,
            Err(err) => return Err(err),
        };

        let mut eth_buf = vec![0; 42];
        let mut eth_packet = MutableEthernetPacket::new(&mut eth_buf).unwrap();

        eth_packet.set_destination(MacAddr::new(0xff, 0xff, 0xff, 0xff, 0xff, 0xff).into());
        eth_packet.set_source(interface.get_mac()?.into());
        eth_packet.set_ethertype(self.ethertype);

        let mut arp_buf = vec![0; 28];
        let mut arp_packet = MutableArpPacket::new(&mut arp_buf).unwrap();

        arp_packet.set_hardware_type(ArpHardwareTypes::Ethernet);
        arp_packet.set_protocol_type(EtherTypes::Ipv4);
        arp_packet.set_hw_addr_len(0x06);
        arp_packet.set_proto_addr_len(0x04);
        arp_packet.set_operation(ArpOperation::new(self.operation as u16));
        arp_packet.set_sender_hw_addr(self.source_hardware_address.into());
        arp_packet.set_sender_proto_addr(self.source_protocol_address);
        arp_packet.set_target_hw_addr(self.target_hardware_address.into());
        arp_packet.set_target_proto_addr(self.target_protocol_address);

        eth_packet.set_payload(arp_packet.packet_mut());

        tx.send_to(eth_packet.packet(), None).unwrap()
    }
}

impl TryFrom<ArpPacket<'_>> for ArpMessage {
    type Error = Error;

    fn try_from(arp_packet: ArpPacket<'_>) -> Result<Self, Self::Error> {
        let operation_raw = arp_packet.get_operation().0;
        let operation = match FromPrimitive::from_u16(operation_raw) {
            Some(op) => op,
            None => {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!(
                        "Could not cast operation raw value {} to enum.",
                        operation_raw
                    ),
                ))
            }
        };

        Ok(ArpMessage::new(
            arp_packet.get_protocol_type(),
            arp_packet.get_sender_hw_addr().into(),
            arp_packet.get_sender_proto_addr(),
            arp_packet.get_target_hw_addr().into(),
            arp_packet.get_target_proto_addr(),
            operation,
        ))
    }
}