1pub fn build_icmp_packet_pure(
4 src_ip: [u8; 4],
5 dst_ip: [u8; 4],
6 icmp_type: u8,
7 icmp_code: u8,
8 identifier: u16,
9 sequence: u16,
10 payload: &[u8],
11 out: &mut [u8],
12) -> Result<usize, &'static str> {
13 let total_len = 20usize + 8usize + payload.len();
14 if total_len > out.len() {
15 return Err("buffer too small");
16 }
17
18 out[0] = 0x45;
19 out[1] = 0;
20 out[2] = ((total_len >> 8) & 0xFF) as u8;
21 out[3] = (total_len & 0xFF) as u8;
22 out[4] = 0x43;
23 out[5] = if icmp_type == 8 { 0x21 } else { 0x22 };
24 out[6] = 0;
25 out[7] = 0;
26 out[8] = 64;
27 out[9] = 1; out[10] = 0;
29 out[11] = 0;
30 out[12..16].copy_from_slice(&src_ip);
31 out[16..20].copy_from_slice(&dst_ip);
32
33 let ip_checksum = super::internet_checksum(&out[0..20]);
34 out[10] = (ip_checksum >> 8) as u8;
35 out[11] = ip_checksum as u8;
36
37 let icmp_start = 20usize;
38 out[icmp_start] = icmp_type;
39 out[icmp_start + 1] = icmp_code;
40 out[icmp_start + 2] = 0;
41 out[icmp_start + 3] = 0;
42 out[icmp_start + 4] = (identifier >> 8) as u8;
43 out[icmp_start + 5] = identifier as u8;
44 out[icmp_start + 6] = (sequence >> 8) as u8;
45 out[icmp_start + 7] = sequence as u8;
46
47 let payload_start = icmp_start + 8;
48 let payload_end = payload_start + payload.len();
49 out[payload_start..payload_end].copy_from_slice(payload);
50
51 let icmp_checksum = super::internet_checksum(&out[icmp_start..payload_end]);
52 out[icmp_start + 2] = (icmp_checksum >> 8) as u8;
53 out[icmp_start + 3] = icmp_checksum as u8;
54
55 Ok(total_len)
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum IcmpType {
60 EchoReply,
61 EchoRequest,
62 DestinationUnreachable,
63 TimeExceeded,
64 Other(u8),
65}
66
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct IcmpPacketInfo<'a> {
69 pub src_ip: [u8; 4],
70 pub dst_ip: [u8; 4],
71 pub icmp_type: IcmpType,
72 pub code: u8,
73 pub identifier: u16,
74 pub sequence: u16,
75 pub payload: &'a [u8],
76}
77
78pub fn parse_icmp_packet_pure(packet: &[u8]) -> Result<IcmpPacketInfo<'_>, &'static str> {
80 if packet.len() < 28 {
81 return Err("ipv4 icmp packet too short");
82 }
83
84 let version = packet[0] >> 4;
85 let ihl = (packet[0] & 0x0F) as usize * 4;
86 if version != 4 || ihl < 20 || packet.len() < ihl + 8 {
87 return Err("invalid ipv4 header");
88 }
89 if packet[9] != 1 {
90 return Err("not icmp packet");
91 }
92
93 let total_len = (((packet[2] as u16) << 8) | packet[3] as u16) as usize;
94 if total_len < ihl + 8 || total_len > packet.len() {
95 return Err("invalid ipv4 total length");
96 }
97
98 let src_ip = [packet[12], packet[13], packet[14], packet[15]];
99 let dst_ip = [packet[16], packet[17], packet[18], packet[19]];
100 let icmp = &packet[ihl..total_len];
101
102 if super::internet_checksum(icmp) != 0 {
103 return Err("icmp checksum mismatch");
104 }
105
106 let t = icmp[0];
107 let code = icmp[1];
108 let icmp_type = match t {
109 0 => IcmpType::EchoReply,
110 8 => IcmpType::EchoRequest,
111 3 => IcmpType::DestinationUnreachable,
112 11 => IcmpType::TimeExceeded,
113 other => IcmpType::Other(other),
114 };
115 let identifier = ((icmp[4] as u16) << 8) | icmp[5] as u16;
116 let sequence = ((icmp[6] as u16) << 8) | icmp[7] as u16;
117 let payload = if icmp.len() > 8 { &icmp[8..] } else { &[] };
118
119 Ok(IcmpPacketInfo {
120 src_ip,
121 dst_ip,
122 icmp_type,
123 code,
124 identifier,
125 sequence,
126 payload,
127 })
128}
129
130pub fn build_icmp_echo_request(
131 dst_ip: [u8; 4],
132 identifier: u16,
133 sequence: u16,
134 payload: &[u8],
135 out: &mut [u8],
136) -> Result<usize, &'static str> {
137 let src_ip = super::status().ip;
138 let total_len = build_icmp_packet_pure(
139 src_ip, dst_ip, 8, 0, identifier, sequence, payload, out,
140 )?;
141
142 unsafe {
143 super::NET_STATE.tx_packets = super::NET_STATE.tx_packets.saturating_add(1);
144 }
145
146 Ok(total_len)
147}
148
149pub fn build_icmp_echo_reply(
150 dst_ip: [u8; 4],
151 identifier: u16,
152 sequence: u16,
153 payload: &[u8],
154 out: &mut [u8],
155) -> Result<usize, &'static str> {
156 let src_ip = super::status().ip;
157 let total_len = build_icmp_packet_pure(
158 src_ip, dst_ip, 0, 0, identifier, sequence, payload, out,
159 )?;
160
161 super::arp::transmit_nic_ipv4_packet(&out[..total_len])?;
164
165 unsafe {
166 super::NET_STATE.tx_packets = super::NET_STATE.tx_packets.saturating_add(1);
167 }
168
169 Ok(total_len)
170}
171
172pub fn parse_icmp_echo_reply_ipv4(packet: &[u8]) -> Result<super::PingReply, &'static str> {
173 let parsed = parse_icmp_packet_pure(packet)?;
174
175 match parsed.icmp_type {
176 IcmpType::EchoRequest if parsed.code == 0 => {
177 let mut reply_pkt = [0u8; 1500];
178 if let Err(e) = build_icmp_echo_reply(
179 parsed.src_ip,
180 parsed.identifier,
181 parsed.sequence,
182 parsed.payload,
183 &mut reply_pkt,
184 ) {
185 crate::warn!("[NET] ICMP: echo reply transmit failed: {}", e);
186 return Err("failed to send echo reply");
187 }
188 Err(alloc::format!(
189 "handled echo request (id={:#06X}, seq={})",
190 parsed.identifier,
191 parsed.sequence
192 )
193 .leak())
194 }
195 IcmpType::EchoReply if parsed.code == 0 => {
196 unsafe {
197 super::NET_STATE.rx_packets = super::NET_STATE.rx_packets.saturating_add(1);
198 }
199 Ok(super::PingReply {
200 src_ip: parsed.src_ip,
201 identifier: parsed.identifier,
202 sequence: parsed.sequence,
203 payload_len: parsed.payload.len(),
204 })
205 }
206 _ => Err(alloc::format!("not echo reply (type={:?}, code={})", parsed.icmp_type, parsed.code).leak()),
207 }
208}
209
210
211
212pub fn ping_once_real(dst_ip: [u8; 4]) -> Result<(u16, u32, usize), &'static str> {
213 let identifier: u16 = 0xA11C;
214 let sequence = unsafe {
215 let seq = super::PING_SEQ;
216 super::PING_SEQ = super::PING_SEQ.wrapping_add(1);
217 seq
218 };
219 let payload = b"atmos-ping";
220
221 let next_hop = super::arp::get_next_hop_ip(dst_ip);
223 let mut resolved_mac = super::arp::arp_cache_lookup(next_hop);
224 if resolved_mac.is_none() {
225 let mut arp_req = [0u8; 42];
226 let arp_len = super::arp::build_arp_request(next_hop, &mut arp_req)?;
227 super::arp::transmit_nic_ethernet_frame(&arp_req[..arp_len])?;
230
231 let start_time = crate::kernel::timer::get_system_time_ms();
232 while crate::kernel::timer::get_system_time_ms() - start_time < 500 {
233 crate::kernel::usb::poll_ethernet_data_plane_only();
234 resolved_mac = super::arp::arp_cache_lookup(next_hop);
235 if resolved_mac.is_some() {
236 break;
237 }
238 crate::kernel::scheduler::yield_now();
241 }
242 }
243
244 if resolved_mac.is_none() {
245 return Err("ARP timeout (destination MAC address unresolved)");
246 }
247
248 unsafe {
250 super::LAST_PING_REPLY = None;
251 }
252
253 let mut request = [0u8; 256];
255 let req_len = build_icmp_echo_request(dst_ip, identifier, sequence, payload, &mut request)?;
256 let send_time = crate::kernel::timer::get_system_time_ms();
257 super::arp::transmit_nic_ipv4_packet(&request[..req_len])?;
258
259 while crate::kernel::timer::get_system_time_ms() - send_time < 1000 {
261 crate::kernel::usb::poll_ethernet_data_plane_only();
262
263 unsafe {
264 if let Some(reply) = super::LAST_PING_REPLY {
265 if reply.src_ip == dst_ip
266 && reply.identifier == identifier
267 && reply.sequence == sequence
268 {
269 let rtt = (crate::kernel::timer::get_system_time_ms() - send_time) as u32;
270 super::LAST_PING_REPLY = None;
271 return Ok((sequence, rtt.max(1), reply.payload_len));
272 }
273 }
274 }
275
276 crate::kernel::scheduler::yield_now();
279 }
280
281 Err("ping timeout")
282}