async_icmp/message/
mod.rs

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
//! ICMP message encoding and decoding.

use crate::IpVersion;
use std::io;

#[cfg(test)]
mod tests;

pub mod decode;

/// An ICMP "Echo request" message, suitable for use with [`crate::socket::IcmpSocket::send_to`].
///
/// Sending this ICMP message should result in an "Echo reply" message.
///
/// This message supports both IPv4 and IPv6.
///
/// See RFC 792 and RFC 4443.
pub struct IcmpEchoRequest {
    /// Echo bytes (Following ICMP header):
    ///
    /// - 0-1: id
    /// - 2-3: seq
    /// - 4+ data
    ///
    /// Buffer body is always at least [`Self::ICMP_ECHO_HDR_LEN`] bytes.
    buf: IcmpMessageBuffer,
}

impl IcmpEchoRequest {
    /// Fortunately, both IPv4 and IPv6 Echo use an 4-byte header followed by arbitrary message data
    const ICMP_ECHO_HDR_LEN: usize = 4;

    /// Construct a new ICMP "Echo request" message.
    ///
    /// `id` and `seq` will have their big-endian representations set in the ICMP header.
    ///
    /// `data` is arbitrary data expected to be returned in the Echo reply. Some hosts seem to
    /// append some zero bytes in the reply.
    pub fn new(id: u16, seq: u16, data: &[u8]) -> Self {
        let mut req = Self {
            // Type will be filled in at encode time.
            // Code is always 0.
            // Body holds space for id and seq.
            buf: IcmpMessageBuffer::new(0, 0, &[0; Self::ICMP_ECHO_HDR_LEN]),
        };
        req.set_id(id);
        req.set_seq(seq);
        req.set_data(data);

        req
    }

    /// Set a new id number
    pub fn set_id(&mut self, id: u16) {
        self.buf.body_mut()[..2].copy_from_slice(&id.to_be_bytes());
    }

    /// Set a new sequence number
    pub fn set_seq(&mut self, seq: u16) {
        self.buf.body_mut()[2..4].copy_from_slice(&seq.to_be_bytes());
    }

    /// Set new data to be echoed
    pub fn set_data(&mut self, data: &[u8]) {
        self.buf.truncate_body(Self::ICMP_ECHO_HDR_LEN);
        self.buf.extend_body(data.iter().cloned());
    }
}

impl EncodeIcmpMessage for IcmpEchoRequest {
    fn encode_for_version(&mut self, socket_ip_version: IpVersion) -> Result<&[u8], EncodeError> {
        let msg_type = match &socket_ip_version {
            IpVersion::V4 => IcmpV4MsgType::EchoRequest as u8,
            IpVersion::V6 => IcmpV6MsgType::EchoRequest as u8,
        };
        self.buf.set_type(msg_type);

        // On macOS, ICMPv4 requires the checksum to be set correctly, while
        // ICMPv6 checksums are overwritten by the kernel.
        // On Linux, TBD
        self.buf.calculate_icmpv4_checksum();
        Ok(self.buf.as_slice())
    }
}

/// Encode an ICMP message to be sent via an [`crate::socket::IcmpSocket`].
pub trait EncodeIcmpMessage {
    /// Encode the message for the requested ip version, or [`EncodeError`] if the version is not
    /// supported.
    fn encode_for_version(&mut self, socket_ip_version: IpVersion) -> Result<&[u8], EncodeError>;
}

/// Errors that can occur when encoding a message.
#[derive(Debug, thiserror::Error)]
pub enum EncodeError {
    /// The ICMP message being encoded does not support the socket's IP version
    #[error("ICMP message does not support the socket's IP version: {0}")]
    UnsupportedVersion(IpVersion),
}

/// Squish EncodeError into io::Error to make error propagation ergonomic for callers that don't
/// care
impl From<EncodeError> for io::Error {
    fn from(value: EncodeError) -> Self {
        match value {
            EncodeError::UnsupportedVersion(_) => io::Error::new(io::ErrorKind::InvalidData, value),
        }
    }
}

/// A helper for constructing ICMP packets.
///
/// It's an optional convenience for internal use in [`EncodeIcmpMessage`] implementations.
pub struct IcmpMessageBuffer {
    /// Message bytes:
    ///
    /// - 0: type
    /// - 1: code
    /// - 2-3: checksum
    /// - 4+: per-type body
    ///
    /// The buffer is always at least 4 bytes long.
    buf: Vec<u8>,
}

impl IcmpMessageBuffer {
    const ICMP_HDR_LEN: usize = 4;

    /// Create a new buffer with the provided ICMP type `typ`, `code`, and `body`.
    pub fn new(typ: u8, code: u8, body: &[u8]) -> Self {
        let mut buf = vec![typ, code, 0, 0];
        buf.extend_from_slice(body);
        Self { buf }
    }

    /// Set byte 0 with the ICMP message type
    pub fn set_type(&mut self, typ: u8) {
        self.buf[0] = typ;
    }

    /// Set byte 1 with the ICMP message code
    pub fn set_code(&mut self, code: u8) {
        self.buf[1] = code;
    }

    /// Access the message body as a mutable slice.
    pub fn body_mut(&mut self) -> &mut [u8] {
        &mut self.buf[Self::ICMP_HDR_LEN..]
    }

    /// Set the type-specific ICMP message body
    pub fn set_body(&mut self, body: impl IntoIterator<Item = u8>) {
        self.truncate_body(0);
        self.extend_body(body);
    }

    /// Append `body_suffix` to the buffer, leaving the existing body in place
    pub fn extend_body(&mut self, body_suffix: impl IntoIterator<Item = u8>) {
        self.buf.extend(body_suffix);
    }

    /// Truncate the message body at `body_len` bytes
    pub fn truncate_body(&mut self, body_len: usize) {
        self.buf.truncate(Self::ICMP_HDR_LEN + body_len);
    }

    /// Populate bytes 2-3 with the IPv4 ones complement checksum.
    pub fn calculate_icmpv4_checksum(&mut self) {
        // checksum starts at zero
        self.buf[2..4].fill(0);
        let checksum = ones_complement_checksum(&self.buf);
        self.buf[2..4].copy_from_slice(&checksum.to_be_bytes());
    }

    /// The entire buffer (ICMP header and body)
    pub fn as_slice(&self) -> &[u8] {
        &self.buf
    }
}

/// RFC 792 ICMPv4 message types.
///
/// Provided as a reference for the message type magic numbers.
#[repr(u8)]
#[allow(missing_docs)]
pub enum IcmpV4MsgType {
    EchoReply = 0,
    DestinationUnreachable = 3,
    SourceQuench = 4,
    Redirect = 5,
    EchoRequest = 8,
    TimeExceeded = 11,
    ParameterProblem = 12,
    Timestamp = 13,
    TimestampReply = 14,
    InfoRequest = 15,
    InfoReply = 16,
}

/// RFC 4443 ICMPv6 message types.
///
/// Provided as a reference for the message type magic numbers.
#[repr(u8)]
#[allow(missing_docs)]
pub enum IcmpV6MsgType {
    DestinationUnreachable = 1,
    PacketTooBig = 2,
    TimeExceeded = 3,
    ParameterProblem = 4,
    PrivateExperimentationError1 = 100,
    PrivateExperimentationError2 = 101,
    ReservedForExpansionError = 127,
    EchoRequest = 128,
    EchoReply = 129,
    PrivateExperimentationInfo1 = 200,
    PrivateExperimentationInfo2 = 201,
    ReservedForExpansionInfo = 255,
}

/// See https://www.rfc-editor.org/rfc/rfc1071 section 4.1
fn ones_complement_checksum(data: &[u8]) -> u16 {
    let last = if data.len() % 2 == 1 {
        u16::from(data.last().copied().unwrap()) << 8
    } else {
        0_u16
    };

    let mut sum = data
        .chunks_exact(2)
        .map(|chunk| u16::from_be_bytes(chunk.try_into().unwrap()))
        .fold(0_u32, |accum, num| accum.wrapping_add(num.into()))
        .wrapping_add(last.into());

    while (sum >> 16) > 0 {
        sum = (sum & 0xffff) + (sum >> 16);
    }

    !(sum as u16)
}