Skip to main content

strate_net_silo/
icmp.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23use alloc::vec::Vec;
24use smoltcp::{
25    socket::icmp,
26    wire::{IpAddress, Ipv4Address, Ipv6Address},
27};
28use strate_net::syscalls::clock_gettime_ns;
29
30use strate_net::syscalls::call;
31
32use crate::{
33    ip::{icmp_checksum, icmpv6_checksum},
34    state::{NetworkStrate, PendingPing, PING_TIMEOUT_NS},
35};
36
37const MAX_ICMP_QUEUE: usize = 32;
38
39impl NetworkStrate {
40    pub(crate) fn process_icmp(&mut self) {
41        let now_ns = clock_gettime_ns().unwrap_or(0);
42
43        // Expire timed-out pending pings.
44        self.pending_pings
45            .retain(|ping| now_ns.saturating_sub(ping.send_ts_ns) < PING_TIMEOUT_NS);
46
47        // Drain received packets into a temporary buffer to release the
48        // socket borrow before calling handler methods on &mut self.
49        let mut packets: Vec<([u8; 128], IpAddress)> = Vec::new();
50        {
51            let socket = self.sockets.get_mut::<icmp::Socket>(self.icmp_handle);
52            if !socket.can_recv() {
53                return;
54            }
55            while socket.can_recv() && packets.len() < MAX_ICMP_QUEUE {
56                let Ok((data, addr)) = socket.recv() else {
57                    break;
58                };
59                let mut buf = [0u8; 128];
60                let n = data.len().min(128);
61                buf[..n].copy_from_slice(&data[..n]);
62                packets.push((buf, addr));
63            }
64        }
65
66        for (data, addr) in packets.iter() {
67            if data.len() < 8 {
68                let _ = call::debug_log(b"[ping] recv too short\n");
69                continue;
70            }
71
72            match data[0] {
73                8 => self.handle_echo_request_v4(data, *addr),
74                128 => self.handle_echo_request_v6(data, *addr),
75                0 => self.handle_echo_reply_v4(data),
76                129 => self.handle_echo_reply_v6(data),
77                other => {
78                    let _ = call::debug_log(b"[ping] recv unexpected type ");
79                    let _ = call::debug_log(&[other]);
80                    let _ = call::debug_log(b"\n");
81                }
82            }
83        }
84    }
85
86    fn handle_echo_request_v4(&mut self, data: &[u8], addr: IpAddress) {
87        let IpAddress::Ipv4(src) = addr else {
88            return;
89        };
90
91        let socket = self.sockets.get_mut::<icmp::Socket>(self.icmp_handle);
92        if !socket.can_send() {
93            let _ = call::debug_log(b"[ping] echo request v4: can_send false\n");
94            return;
95        }
96
97        // Build echo reply: swap type 8->0, keep ident+seq, recompute checksum.
98        let payload_len = data.len();
99        let Ok(buf) = socket.send(payload_len, IpAddress::Ipv4(src)) else {
100            let _ = call::debug_log(b"[ping] echo request v4: send failed\n");
101            return;
102        };
103        buf.copy_from_slice(data);
104        buf[0] = 0;
105        buf[1] = 0;
106        let checksum = icmp_checksum(buf);
107        buf[2..4].copy_from_slice(&checksum.to_be_bytes());
108
109        let _ = call::debug_log(b"[ping] echo reply v4 sent to ");
110        let octets = src.octets();
111        let _ = call::debug_log(&[octets[0], b'.', octets[1], b'.', octets[2], b'.', octets[3]]);
112        let _ = call::debug_log(b"\n");
113    }
114
115    fn handle_echo_request_v6(&mut self, data: &[u8], addr: IpAddress) {
116        let IpAddress::Ipv6(src) = addr else {
117            return;
118        };
119
120        let socket = self.sockets.get_mut::<icmp::Socket>(self.icmp_handle);
121        if !socket.can_send() {
122            let _ = call::debug_log(b"[ping] echo request v6: can_send false\n");
123            return;
124        }
125
126        // Build echo reply: swap type 128->129, keep ident+seq, recompute checksum.
127        let payload_len = data.len();
128        let Ok(buf) = socket.send(payload_len, IpAddress::Ipv6(src)) else {
129            let _ = call::debug_log(b"[ping] echo request v6: send failed\n");
130            return;
131        };
132        buf.copy_from_slice(data);
133        buf[0] = 129;
134        buf[1] = 0;
135
136        let dst = src.octets();
137        let src_addr = self.link_local_addr;
138        let checksum = icmpv6_checksum(&src_addr.octets(), &dst, buf);
139        buf[2..4].copy_from_slice(&checksum.to_be_bytes());
140
141        let _ = call::debug_log(b"[ping] echo reply v6 sent\n");
142    }
143
144    fn handle_echo_reply_v4(&mut self, data: &[u8]) {
145        if data.len() < 16 {
146            return;
147        }
148        let ident = u16::from_be_bytes([data[4], data[5]]);
149        if ident != self.ping_ident {
150            return;
151        }
152        let token = u64::from_le_bytes(data[8..16].try_into().unwrap_or([0u8; 8]));
153        if let Some(idx) = self
154            .pending_pings
155            .iter()
156            .position(|p| p.token == token && !p.is_v6)
157        {
158            let pending = self.pending_pings.remove(idx);
159            let now_ns = clock_gettime_ns().unwrap_or(0);
160            let rtt_us = now_ns.saturating_sub(pending.send_ts_ns) / 1000;
161            self.ping_replies.push((pending.seq, rtt_us));
162            let _ = call::debug_log(b"[ping] reply seq=");
163            let _ = call::debug_log(&[(pending.seq >> 8) as u8, pending.seq as u8]);
164            let _ = call::debug_log(b" rtt=");
165            let _ = call::debug_log(&[(rtt_us / 1000) as u8]);
166            let _ = call::debug_log(b"ms\n");
167        }
168    }
169
170    fn handle_echo_reply_v6(&mut self, data: &[u8]) {
171        if data.len() < 16 {
172            return;
173        }
174        let ident = u16::from_be_bytes([data[4], data[5]]);
175        if ident != self.ping_ident {
176            return;
177        }
178        let token = u64::from_le_bytes(data[8..16].try_into().unwrap_or([0u8; 8]));
179        if let Some(idx) = self
180            .pending_pings
181            .iter()
182            .position(|p| p.token == token && p.is_v6)
183        {
184            let pending = self.pending_pings.remove(idx);
185            let now_ns = clock_gettime_ns().unwrap_or(0);
186            let rtt_us = now_ns.saturating_sub(pending.send_ts_ns) / 1000;
187            self.ping_replies.push((pending.seq, rtt_us));
188            let _ = call::debug_log(b"[ping] reply v6 seq=");
189            let _ = call::debug_log(&[(pending.seq >> 8) as u8, pending.seq as u8]);
190            let _ = call::debug_log(b" rtt=");
191            let _ = call::debug_log(&[(rtt_us / 1000) as u8]);
192            let _ = call::debug_log(b"ms\n");
193        }
194    }
195
196    pub(crate) fn is_local_ipv4(&self, target: Ipv4Address) -> bool {
197        self.ip_config
198            .as_ref()
199            .is_some_and(|cfg| cfg.host == target)
200    }
201
202    pub(crate) fn is_local_ipv6(&self, target: Ipv6Address) -> bool {
203        if target == self.link_local_addr {
204            return true;
205        }
206        self.ipv6_config
207            .as_ref()
208            .is_some_and(|cfg| cfg.address.address() == target)
209    }
210
211    pub(crate) fn send_ping(&mut self, target: Ipv4Address, seq: u16, _file_id: u64) -> bool {
212        if self.is_local_ipv4(target) {
213            self.ping_replies.push((seq, 1));
214            return true;
215        }
216
217        let token = self.alloc_ping_token();
218
219        let socket = self.sockets.get_mut::<icmp::Socket>(self.icmp_handle);
220        if !socket.is_open() {
221            socket.bind(icmp::Endpoint::Ident(self.ping_ident)).ok();
222        }
223        if !socket.can_send() {
224            let _ = call::debug_log(b"[ping] send_ping v4: can_send false\n");
225            return false;
226        }
227
228        let payload_len = 40;
229        let icmp_len = 8 + payload_len;
230        let Ok(buf) = socket.send(icmp_len, IpAddress::Ipv4(target)) else {
231            return false;
232        };
233        buf[0] = 8;
234        buf[1] = 0;
235        buf[2] = 0;
236        buf[3] = 0;
237        buf[4..6].copy_from_slice(&self.ping_ident.to_be_bytes());
238        buf[6..8].copy_from_slice(&seq.to_be_bytes());
239        buf[8..16].copy_from_slice(&token.to_le_bytes());
240        for byte in buf[16..icmp_len].iter_mut() {
241            *byte = 0xAA;
242        }
243        let checksum = icmp_checksum(buf);
244        buf[2..4].copy_from_slice(&checksum.to_be_bytes());
245
246        let _ = call::debug_log(b"[ping] sent seq=");
247        let _ = call::debug_log(&[(seq >> 8) as u8, seq as u8]);
248        let _ = call::debug_log(b" token=");
249        let _ = call::debug_log(&token.to_le_bytes());
250        let _ = call::debug_log(b"\n");
251
252        self.pending_pings.push(PendingPing {
253            seq,
254            token,
255            send_ts_ns: 0, // stamped by main loop before interface.poll()
256            is_v6: false,
257        });
258        true
259    }
260
261    pub(crate) fn send_ping6(&mut self, target: Ipv6Address, seq: u16, _file_id: u64) -> bool {
262        if self.is_local_ipv6(target) {
263            self.ping_replies.push((seq, 1));
264            return true;
265        }
266
267        let token = self.alloc_ping_token();
268
269        let socket = self.sockets.get_mut::<icmp::Socket>(self.icmp_handle);
270        if !socket.is_open() {
271            socket.bind(icmp::Endpoint::Ident(self.ping_ident)).ok();
272        }
273        if !socket.can_send() {
274            let _ = call::debug_log(b"[ping] send_ping6: can_send false\n");
275            return false;
276        }
277
278        let payload_len = 40;
279        let icmp_len = 8 + payload_len;
280        let Ok(buf) = socket.send(icmp_len, IpAddress::Ipv6(target)) else {
281            return false;
282        };
283        buf[0] = 128;
284        buf[1] = 0;
285        buf[2] = 0;
286        buf[3] = 0;
287        buf[4..6].copy_from_slice(&self.ping_ident.to_be_bytes());
288        buf[6..8].copy_from_slice(&seq.to_be_bytes());
289        buf[8..16].copy_from_slice(&token.to_le_bytes());
290        for byte in buf[16..icmp_len].iter_mut() {
291            *byte = 0xAA;
292        }
293
294        let _ = call::debug_log(b"[ping] sent v6 seq=");
295        let _ = call::debug_log(&[(seq >> 8) as u8, seq as u8]);
296        let _ = call::debug_log(b" token=");
297        let _ = call::debug_log(&token.to_le_bytes());
298        let _ = call::debug_log(b"\n");
299
300        let src = if target.is_unicast_link_local() {
301            self.link_local_addr
302        } else {
303            self.ipv6_config
304                .as_ref()
305                .map(|cfg| cfg.address.address())
306                .unwrap_or(self.link_local_addr)
307        };
308        let checksum = icmpv6_checksum(&src.octets(), &target.octets(), buf);
309        buf[2..4].copy_from_slice(&checksum.to_be_bytes());
310
311        self.pending_pings.push(PendingPing {
312            seq,
313            token,
314            send_ts_ns: 0, // stamped by main loop before interface.poll()
315            is_v6: true,
316        });
317        true
318    }
319}