Skip to main content

network/socket/
icmp.rs

1use crate::{Duration, IoErrorKind, IpAddress, Port, Result, SocketContext};
2use alloc::vec;
3use core::{
4    future::poll_fn,
5    task::{Context, Poll},
6};
7use smoltcp::{socket::icmp, wire};
8
9#[derive(Debug, Default, PartialEq, Eq, PartialOrd, Ord, Clone)]
10pub enum IcmpEndpoint {
11    #[default]
12    Unspecified,
13    Identifier(u16),
14    Udp((Option<IpAddress>, Port)),
15}
16
17impl IcmpEndpoint {
18    pub const fn into_smoltcp(&self) -> icmp::Endpoint {
19        match self {
20            IcmpEndpoint::Unspecified => icmp::Endpoint::Unspecified,
21            IcmpEndpoint::Identifier(id) => icmp::Endpoint::Ident(*id),
22            IcmpEndpoint::Udp((addr_opt, port)) => {
23                let addr = match addr_opt {
24                    Some(a) => Some(a.into_smoltcp()),
25                    None => None,
26                };
27
28                let endpoint = wire::IpListenEndpoint {
29                    addr,
30                    port: port.into_inner(),
31                };
32
33                icmp::Endpoint::Udp(endpoint)
34            }
35        }
36    }
37}
38
39pub struct IcmpSocket {
40    context: SocketContext,
41}
42
43impl IcmpSocket {
44    pub(crate) fn new(context: SocketContext) -> Self {
45        Self { context }
46    }
47
48    pub async fn with<F, R>(&self, f: F) -> R
49    where
50        F: FnOnce(&icmp::Socket<'static>) -> R,
51    {
52        self.context.with(f).await
53    }
54
55    pub async fn with_mutable<F, R>(&self, f: F) -> R
56    where
57        F: FnOnce(&mut icmp::Socket<'static>) -> R,
58    {
59        self.context.with_mutable(f).await
60    }
61
62    pub fn poll_with<F, R>(&self, context: &mut Context<'_>, f: F) -> Poll<R>
63    where
64        F: FnOnce(&icmp::Socket, &mut Context<'_>) -> Poll<R>,
65    {
66        self.context.poll_with(context, f)
67    }
68
69    pub fn poll_with_mutable<F, R>(&self, context: &mut Context<'_>, f: F) -> Poll<R>
70    where
71        F: FnOnce(&mut icmp::Socket, &mut Context<'_>) -> Poll<R>,
72    {
73        self.context.poll_with_mutable(context, f)
74    }
75
76    fn poll_send_to(
77        &self,
78        context: &mut Context<'_>,
79        buffer: &[u8],
80        remote_endpoint: &IpAddress,
81    ) -> Poll<Result<()>> {
82        self.poll_with_mutable(context, |socket, context| {
83            let send_capacity_too_small = socket.payload_send_capacity() < buffer.len();
84            if send_capacity_too_small {
85                return Poll::Ready(Err(IoErrorKind::MessageTooLarge));
86            }
87
88            let remote_endpoint = remote_endpoint.into_smoltcp();
89
90            match socket.send_slice(buffer, remote_endpoint) {
91                Ok(()) => Poll::Ready(Ok(())),
92                Err(icmp::SendError::BufferFull) => {
93                    socket.register_send_waker(context.waker());
94                    Poll::Pending
95                }
96                Err(error @ icmp::SendError::Unaddressable) => {
97                    Poll::Ready(Err(crate::error::icmp_send_error(
98                        error,
99                        socket.is_open(),
100                        !remote_endpoint.is_unspecified(),
101                    )))
102                }
103            }
104        })
105    }
106
107    fn poll_receive_from(
108        &self,
109        context: &mut Context<'_>,
110        buffer: &mut [u8],
111    ) -> Poll<Result<(usize, IpAddress)>> {
112        self.poll_with_mutable(context, |socket, context| match socket.recv_slice(buffer) {
113            Ok((size, remote_endpoint)) => {
114                let remote_endpoint = IpAddress::from_smoltcp(&remote_endpoint);
115                Poll::Ready(Ok((size, remote_endpoint)))
116            }
117            Err(icmp::RecvError::Truncated) => Poll::Ready(Err(IoErrorKind::DatagramTruncated)),
118            Err(icmp::RecvError::Exhausted) => {
119                socket.register_recv_waker(context.waker());
120
121                self.context.stack.wake_runner();
122                Poll::Pending
123            }
124        })
125    }
126
127    pub async fn bind(&self, endpoint: IcmpEndpoint) -> Result<()> {
128        let endpoint = endpoint.into_smoltcp();
129
130        self.with_mutable(|socket: &mut icmp::Socket| socket.bind(endpoint))
131            .await
132            .map_err(crate::error::icmp_bind_error)?;
133        Ok(())
134    }
135
136    pub async fn can_write(&self) -> bool {
137        self.with(icmp::Socket::can_send).await
138    }
139
140    pub async fn can_read(&self) -> bool {
141        self.with(icmp::Socket::can_recv).await
142    }
143
144    pub async fn write_to(&self, buffer: &[u8], endpoint: impl Into<IpAddress>) -> Result<()> {
145        let address: IpAddress = endpoint.into();
146
147        poll_fn(|context| self.poll_send_to(context, buffer, &address)).await
148    }
149
150    pub async fn read_from(&self, buffer: &mut [u8]) -> Result<(usize, IpAddress)> {
151        poll_fn(|context| self.poll_receive_from(context, buffer)).await
152    }
153
154    pub async fn read_from_with_timeout(
155        &self,
156        buffer: &mut [u8],
157        timeout: impl Into<Duration>,
158    ) -> Result<(usize, IpAddress)> {
159        use embassy_futures::select::{Either, select};
160
161        let receive = poll_fn(|context| self.poll_receive_from(context, buffer));
162        let sleep = task::sleep(timeout.into());
163
164        match select(receive, sleep).await {
165            Either::First(result) => result,
166            Either::Second(_) => Err(IoErrorKind::TimedOut),
167        }
168    }
169
170    /// Sends an ICMP echo request (ping) to the specified remote address and waits for a reply.
171    /// Returns the round-trip time if successful.
172    ///
173    /// # Errors
174    ///
175    /// Returns an error if the ping request fails or times out.
176    pub async fn ping(
177        &self,
178        remote_address: &IpAddress,
179        sequence_number: u16,
180        identifier: u16,
181        timeout: Duration,
182        payload_size: usize,
183    ) -> Result<Duration> {
184        use wire::{Icmpv4Packet, Icmpv4Repr, Icmpv6Packet, Icmpv6Repr};
185
186        let mut echo_payload = vec![0u8; payload_size];
187        let start_time = self.context.stack.time_manager().monotonic_now();
188
189        let timestamp_millis = start_time.as_millis() as u64;
190        echo_payload[0..8].copy_from_slice(&timestamp_millis.to_be_bytes());
191
192        let mut stack_lock = self.context.stack.lock().await;
193
194        let src_addr_v6 = if let IpAddress::IPv6(v6_addr) = remote_address {
195            Some(
196                stack_lock
197                    .interface
198                    .get_source_address_ipv6(&v6_addr.into_smoltcp()),
199            )
200        } else {
201            None
202        };
203
204        let socket = stack_lock
205            .sockets
206            .get_mut::<icmp::Socket>(self.context.handle);
207
208        let remote_endpoint = remote_address.into_smoltcp();
209
210        let checksum_caps = smoltcp::phy::ChecksumCapabilities::default();
211
212        match remote_address {
213            IpAddress::IPv4(_) => {
214                let icmp_repr = Icmpv4Repr::EchoRequest {
215                    ident: identifier,
216                    seq_no: sequence_number,
217                    data: &echo_payload,
218                };
219
220                let icmp_payload = socket
221                    .send(icmp_repr.buffer_len(), remote_endpoint)
222                    .map_err(|e| {
223                        crate::error::icmp_send_error(e, true, !remote_endpoint.is_unspecified())
224                    })?;
225
226                let mut icmp_packet = Icmpv4Packet::new_unchecked(icmp_payload);
227                icmp_repr.emit(&mut icmp_packet, &checksum_caps);
228            }
229            IpAddress::IPv6(v6_addr) => {
230                let icmp_repr = Icmpv6Repr::EchoRequest {
231                    ident: identifier,
232                    seq_no: sequence_number,
233                    data: &echo_payload,
234                };
235
236                let icmp_payload = socket
237                    .send(icmp_repr.buffer_len(), remote_endpoint)
238                    .map_err(|e| {
239                        crate::error::icmp_send_error(e, true, !remote_endpoint.is_unspecified())
240                    })?;
241
242                let src_addr = src_addr_v6.unwrap();
243                let mut icmp_packet = Icmpv6Packet::new_unchecked(icmp_payload);
244                icmp_repr.emit(
245                    &src_addr,
246                    &v6_addr.into_smoltcp(),
247                    &mut icmp_packet,
248                    &checksum_caps,
249                );
250            }
251        }
252
253        drop(stack_lock);
254
255        self.context.stack.wake_runner();
256
257        let timeout = core::time::Duration::from(timeout);
258
259        loop {
260            let now = self.context.stack.time_manager().monotonic_now();
261            let remaining = remaining_timeout(start_time, now, timeout)?;
262
263            let mut recv_buffer = [0u8; 256];
264            let result = self
265                .read_from_with_timeout(&mut recv_buffer, remaining)
266                .await;
267
268            match result {
269                Ok((size, addr)) if addr == *remote_address => {
270                    // Parse the received packet
271                    let is_valid_reply = match remote_address {
272                        IpAddress::IPv4(_) => {
273                            if let Ok(packet) = Icmpv4Packet::new_checked(&recv_buffer[..size]) {
274                                if let Ok(repr) = Icmpv4Repr::parse(&packet, &checksum_caps) {
275                                    matches!(
276                                        repr,
277                                        Icmpv4Repr::EchoReply {
278                                            ident: id,
279                                            seq_no,
280                                            ..
281                                        } if id == identifier && seq_no == sequence_number
282                                    )
283                                } else {
284                                    false
285                                }
286                            } else {
287                                false
288                            }
289                        }
290                        IpAddress::IPv6(v6_addr) => {
291                            if let Ok(packet) = Icmpv6Packet::new_checked(&recv_buffer[..size]) {
292                                let src_addr = self
293                                    .context
294                                    .stack
295                                    .with_mutable(|s| s.get_source_ip_v6_address(*v6_addr))
296                                    .await;
297
298                                if let Ok(repr) = Icmpv6Repr::parse(
299                                    &v6_addr.into_smoltcp(),
300                                    &src_addr.into_smoltcp(),
301                                    &packet,
302                                    &checksum_caps,
303                                ) {
304                                    matches!(
305                                        repr,
306                                        Icmpv6Repr::EchoReply {
307                                            ident: id,
308                                            seq_no,
309                                            ..
310                                        } if id == identifier && seq_no == sequence_number
311                                    )
312                                } else {
313                                    false
314                                }
315                            } else {
316                                false
317                            }
318                        }
319                    };
320
321                    if is_valid_reply {
322                        let end_time = self.context.stack.time_manager().monotonic_now();
323                        let rtt = end_time - start_time;
324                        return Ok(rtt.into());
325                    }
326                }
327                Ok(_) => {
328                    continue;
329                }
330                Err(e) => return Err(e),
331            }
332        }
333    }
334
335    pub async fn flush(&self) -> () {
336        poll_fn(|context| {
337            self.poll_with_mutable(context, |socket, context| {
338                if socket.send_queue() == 0 {
339                    Poll::Ready(())
340                } else {
341                    socket.register_send_waker(context.waker());
342                    Poll::Pending
343                }
344            })
345        })
346        .await
347    }
348
349    pub async fn is_open(&self) -> bool {
350        self.with(icmp::Socket::is_open).await
351    }
352
353    pub async fn get_packet_read_capacity(&self) -> usize {
354        self.with(icmp::Socket::packet_recv_capacity).await
355    }
356
357    pub async fn get_packet_write_capacity(&self) -> usize {
358        self.with(icmp::Socket::packet_send_capacity).await
359    }
360
361    pub async fn get_payload_read_capacity(&self) -> usize {
362        self.with(icmp::Socket::payload_recv_capacity).await
363    }
364
365    pub async fn get_payload_write_capacity(&self) -> usize {
366        self.with(icmp::Socket::payload_send_capacity).await
367    }
368
369    pub async fn get_hop_limit(&self) -> Option<u8> {
370        self.with(icmp::Socket::hop_limit).await
371    }
372
373    pub async fn set_hop_limit(&self, hop_limit: Option<u8>) -> () {
374        self.with_mutable(|socket: &mut icmp::Socket| {
375            socket.set_hop_limit(hop_limit);
376        })
377        .await
378    }
379}
380
381fn remaining_timeout(
382    start: core::time::Duration,
383    now: core::time::Duration,
384    timeout: core::time::Duration,
385) -> Result<core::time::Duration> {
386    let remaining = timeout.saturating_sub(now.saturating_sub(start));
387    if remaining.is_zero() {
388        Err(IoErrorKind::TimedOut)
389    } else {
390        Ok(remaining)
391    }
392}
393
394#[cfg(test)]
395mod timeout_tests {
396    use super::*;
397    use core::time::Duration as StdDuration;
398
399    #[test]
400    fn unrelated_packets_do_not_restart_ping_timeout_budget() {
401        let start = StdDuration::from_secs(10);
402        let timeout = StdDuration::from_secs(30);
403        assert_eq!(
404            remaining_timeout(start, StdDuration::from_secs(39), timeout).unwrap(),
405            StdDuration::from_secs(1)
406        );
407        assert_eq!(
408            remaining_timeout(start, StdDuration::from_secs(40), timeout),
409            Err(IoErrorKind::TimedOut)
410        );
411        assert_eq!(
412            remaining_timeout(start, StdDuration::from_secs(41), timeout),
413            Err(IoErrorKind::TimedOut)
414        );
415    }
416}