1use alloc::string::String;
2use alloc::vec::Vec;
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub enum ArpOperation {
7 Request = 1,
8 Reply = 2,
9}
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct ArpPacketInfo {
14 pub operation: ArpOperation,
15 pub sender_mac: [u8; 6],
16 pub sender_ip: [u8; 4],
17 pub target_mac: [u8; 6],
18 pub target_ip: [u8; 4],
19}
20
21pub fn build_arp_packet_pure(
24 oper: ArpOperation,
25 sender_mac: [u8; 6],
26 sender_ip: [u8; 4],
27 target_mac: [u8; 6],
28 target_ip: [u8; 4],
29 out: &mut [u8],
30) -> Result<usize, &'static str> {
31 if out.len() < 42 {
32 return Err("buffer too small");
33 }
34
35 let eth_dst_mac = match oper {
39 ArpOperation::Request => [0xFF; 6],
40 ArpOperation::Reply => target_mac,
41 };
42
43 out[0..6].copy_from_slice(ð_dst_mac);
44 out[6..12].copy_from_slice(&sender_mac);
45 out[12] = 0x08;
46 out[13] = 0x06;
47
48 out[14] = 0x00;
50 out[15] = 0x01; out[16] = 0x08;
52 out[17] = 0x00; out[18] = 0x06; out[19] = 0x04; out[20] = 0x00;
56 out[21] = oper as u8; out[22..28].copy_from_slice(&sender_mac);
60 out[28..32].copy_from_slice(&sender_ip);
61
62 let arp_target_mac = match oper {
64 ArpOperation::Request => [0x00; 6],
65 ArpOperation::Reply => target_mac,
66 };
67 out[32..38].copy_from_slice(&arp_target_mac);
68 out[38..42].copy_from_slice(&target_ip);
69
70 Ok(42)
71}
72
73pub fn parse_arp_packet_pure(frame: &[u8]) -> Result<ArpPacketInfo, &'static str> {
76 if frame.len() < 42 {
77 return Err("arp frame too short");
78 }
79
80 let htype = ((frame[14] as u16) << 8) | frame[15] as u16;
81 let ptype = ((frame[16] as u16) << 8) | frame[17] as u16;
82 let hlen = frame[18];
83 let plen = frame[19];
84 let oper_val = ((frame[20] as u16) << 8) | frame[21] as u16;
85
86 if htype != 1 || ptype != 0x0800 || hlen != 6 || plen != 4 {
87 return Err("unsupported arp format");
88 }
89
90 let operation = match oper_val {
91 1 => ArpOperation::Request,
92 2 => ArpOperation::Reply,
93 _ => return Err("unsupported arp operation"),
94 };
95
96 let sender_mac = [
97 frame[22], frame[23], frame[24], frame[25], frame[26], frame[27],
98 ];
99 let sender_ip = [frame[28], frame[29], frame[30], frame[31]];
100 let target_mac = [
101 frame[32], frame[33], frame[34], frame[35], frame[36], frame[37],
102 ];
103 let target_ip = [frame[38], frame[39], frame[40], frame[41]];
104
105 Ok(ArpPacketInfo {
106 operation,
107 sender_mac,
108 sender_ip,
109 target_mac,
110 target_ip,
111 })
112}
113
114pub fn build_ethernet_frame_pure(
116 ethertype: u16,
117 src_mac: [u8; 6],
118 dst_mac: [u8; 6],
119 payload: &[u8],
120 out: &mut [u8],
121) -> Result<usize, &'static str> {
122 let frame_len = 14usize.checked_add(payload.len()).ok_or("frame too large")?;
123 if out.len() < frame_len {
124 return Err("buffer too small");
125 }
126
127 out[0..6].copy_from_slice(&dst_mac);
128 out[6..12].copy_from_slice(&src_mac);
129 out[12] = (ethertype >> 8) as u8;
130 out[13] = (ethertype & 0xFF) as u8;
131 out[14..frame_len].copy_from_slice(payload);
132
133 Ok(frame_len)
134}
135
136pub fn get_next_hop_ip_pure(
138 dst_ip: [u8; 4],
139 local_ip: [u8; 4],
140 subnet_mask: [u8; 4],
141 gateway: [u8; 4],
142) -> [u8; 4] {
143 if dst_ip == [255, 255, 255, 255] {
144 return dst_ip;
145 }
146 let mask = if subnet_mask == [0; 4] {
147 [255, 255, 255, 0]
148 } else {
149 subnet_mask
150 };
151 let is_local = (dst_ip[0] & mask[0] == local_ip[0] & mask[0])
152 && (dst_ip[1] & mask[1] == local_ip[1] & mask[1])
153 && (dst_ip[2] & mask[2] == local_ip[2] & mask[2])
154 && (dst_ip[3] & mask[3] == local_ip[3] & mask[3]);
155
156 if is_local {
157 dst_ip
158 } else if gateway != [0; 4] {
159 gateway
160 } else {
161 dst_ip
162 }
163}
164
165pub fn arp_cache_lines() -> Vec<String> {
166 let mut lines: Vec<String> = Vec::new();
167
168 unsafe {
169 for i in 0..super::ARP_CACHE_SIZE {
170 let e = super::ARP_CACHE[i];
171 if !e.valid {
172 continue;
173 }
174 lines.push(alloc::format!(
175 "{} -> {} (age={})",
176 super::format_ipv4(e.ip),
177 super::format_mac(e.mac),
178 e.age
179 ));
180 }
181 }
182
183 lines
184}
185
186pub fn build_arp_request(target_ip: [u8; 4], out: &mut [u8]) -> Result<usize, &'static str> {
187 let st = super::status();
188 let n = build_arp_packet_pure(
189 ArpOperation::Request,
190 st.mac,
191 st.ip,
192 [0x00; 6],
193 target_ip,
194 out,
195 )?;
196
197 unsafe {
198 super::NET_STATE.tx_packets = super::NET_STATE.tx_packets.saturating_add(1);
199 }
200
201 Ok(n)
202}
203
204
205
206pub fn ingest_ethernet_frame(frame: &[u8]) -> Result<(), &'static str> {
207 unsafe {
210 super::NET_STATE.raw_rx_frames = super::NET_STATE.raw_rx_frames.saturating_add(1);
211 }
212
213 use super::eth_frame::{dispatch, Dispatch, FrameError};
221 let d = dispatch(frame);
224 unsafe {
225 match &d {
226 Ok(Dispatch::Arp) => ETH_CNT_ARP += 1,
227 Ok(Dispatch::Ipv4 { .. }) => ETH_CNT_IPV4 += 1,
228 Ok(Dispatch::Unsupported { .. }) => ETH_CNT_OTHER += 1,
229 Err(_) => ETH_CNT_ERR += 1,
230 }
231 }
232 match d {
233 Ok(Dispatch::Arp) => {
234 parse_arp_packet(frame)?;
235 Ok(())
236 }
237 Ok(Dispatch::Ipv4 { start, end }) => {
238 let payload = frame.get(start..end).ok_or("ipv4 payload out of range")?;
239 parse_ipv4_packet(payload)?;
240 Ok(())
241 }
242 Ok(Dispatch::Unsupported { .. }) => Err("unsupported ethertype"),
243 Err(FrameError::TooShort { .. }) => Err("ethernet frame too short"),
244 Err(FrameError::TruncatedVlan { .. }) => Err("truncated vlan tag"),
245 }
246}
247
248pub static mut ETH_CNT_IPV4: u32 = 0;
250pub static mut ETH_CNT_ARP: u32 = 0;
251pub static mut ETH_CNT_OTHER: u32 = 0;
252pub static mut ETH_CNT_ERR: u32 = 0;
253
254pub fn eth_dispatch_counts() -> (u32, u32, u32, u32) {
256 unsafe { (ETH_CNT_IPV4, ETH_CNT_ARP, ETH_CNT_OTHER, ETH_CNT_ERR) }
257}
258
259pub fn ingest_nic_ethernet_frame(frame: &[u8]) -> Result<(), &'static str> {
260 match super::status().nic_backend {
261 super::NicBackend::SoftwareLoopback => ingest_ethernet_frame(frame),
262 super::NicBackend::UsbEthernet => ingest_ethernet_frame(frame),
263 }
264}
265
266pub fn ingest_nic_ipv4_packet(packet: &[u8]) -> Result<(), &'static str> {
267 match super::status().nic_backend {
268 super::NicBackend::SoftwareLoopback => parse_ipv4_packet(packet),
269 super::NicBackend::UsbEthernet => parse_ipv4_packet(packet),
270 }
271}
272
273pub fn nic_pop_tx_ipv4_packet(out: &mut [u8]) -> Option<usize> {
274 nic_take_tx_ipv4_chunk(out.len(), out)
275}
276
277pub fn nic_take_tx_ipv4_chunk(max_len: usize, out: &mut [u8]) -> Option<usize> {
278 if max_len == 0 || out.is_empty() {
279 return None;
280 }
281
282 unsafe {
283 let mut best_idx: Option<usize> = None;
284 let mut best_age: u32 = 0;
285
286 for i in 0..super::NIC_TX_QUEUE_SIZE {
287 let e = &super::NIC_TX_QUEUE[i];
299 if !e.valid {
300 continue;
301 }
302 if best_idx.is_none() || e.age < best_age {
303 best_idx = Some(i);
304 best_age = e.age;
305 }
306 }
307
308 let idx = best_idx?;
309 let entry = &mut super::NIC_TX_QUEUE[idx];
310 if entry.len == 0 || entry.offset >= entry.len {
311 entry.valid = false;
317 entry.len = 0;
318 entry.offset = 0;
319 return None;
320 }
321
322 let remain = entry.len - entry.offset;
323 let chunk_len = remain.min(max_len).min(out.len());
324 let start = entry.offset;
325 let end = start + chunk_len;
326 out[..chunk_len].copy_from_slice(&entry.payload[start..end]);
327 entry.offset = end;
328
329 if entry.offset >= entry.len {
330 entry.valid = false;
332 entry.len = 0;
333 entry.offset = 0;
334 }
335
336 Some(chunk_len)
337 }
338}
339
340pub fn transmit_nic_ipv4_packet(packet: &[u8]) -> Result<usize, &'static str> {
341 if packet.is_empty() {
342 return Err("empty packet");
343 }
344 if packet.len() > super::NIC_TX_MAX_PAYLOAD {
345 return Err("packet too large");
346 }
347
348 match super::status().nic_backend {
349 super::NicBackend::SoftwareLoopback => {
350 unsafe {
351 super::NET_STATE.tx_packets = super::NET_STATE.tx_packets.saturating_add(1);
352 }
353 Ok(packet.len())
354 }
355 super::NicBackend::UsbEthernet => {
356 unsafe {
370 let mut slot: Option<usize> = None;
371 for i in 0..super::NIC_TX_QUEUE_SIZE {
372 if !super::NIC_TX_QUEUE[i].valid {
373 slot = Some(i);
374 break;
375 }
376 }
377
378 let idx = match slot {
379 Some(v) => v,
380 None => {
381 super::NIC_TX_DROPS = super::NIC_TX_DROPS.saturating_add(1);
387 if super::NIC_TX_DROPS <= 4 || super::NIC_TX_DROPS.is_multiple_of(16) {
388 crate::warn!(
389 "[NET][DIAG] nic tx queue FULL (size={}) dropped_total={}",
390 super::NIC_TX_QUEUE_SIZE,
391 super::NIC_TX_DROPS
392 );
393 }
394 return Err("nic tx queue full");
395 }
396 };
397
398 let entry = &mut super::NIC_TX_QUEUE[idx];
402 let frame_len = build_usb_ethernet_ipv4_frame(packet, &mut entry.payload)?;
403 entry.valid = true;
404 entry.len = frame_len;
405 entry.offset = 0;
406 entry.age = super::NIC_TX_TICK;
407 super::NIC_TX_TICK = super::NIC_TX_TICK.saturating_add(1);
408
409 super::NET_STATE.tx_packets = super::NET_STATE.tx_packets.saturating_add(1);
410 Ok(frame_len)
411 }
412 }
413 }
414}
415
416pub fn transmit_nic_ethernet_frame(frame: &[u8]) -> Result<usize, &'static str> {
417 if frame.is_empty() {
418 return Err("empty frame");
419 }
420 if frame.len() > super::NIC_TX_MAX_PAYLOAD {
421 return Err("frame too large");
422 }
423
424 match super::status().nic_backend {
425 super::NicBackend::SoftwareLoopback => {
426 unsafe {
427 super::NET_STATE.tx_packets = super::NET_STATE.tx_packets.saturating_add(1);
428 }
429 Ok(frame.len())
430 }
431 super::NicBackend::UsbEthernet => {
432 unsafe {
433 let mut slot: Option<usize> = None;
434 for i in 0..super::NIC_TX_QUEUE_SIZE {
435 if !super::NIC_TX_QUEUE[i].valid {
436 slot = Some(i);
437 break;
438 }
439 }
440
441 let idx = match slot {
442 Some(v) => v,
443 None => {
444 super::NIC_TX_DROPS = super::NIC_TX_DROPS.saturating_add(1);
450 if super::NIC_TX_DROPS <= 4 || super::NIC_TX_DROPS.is_multiple_of(16) {
451 crate::warn!(
452 "[NET][DIAG] nic tx queue FULL (size={}) dropped_total={}",
453 super::NIC_TX_QUEUE_SIZE,
454 super::NIC_TX_DROPS
455 );
456 }
457 return Err("nic tx queue full");
458 }
459 };
460
461 let mut entry = super::NicTxEntry::empty();
462 entry.valid = true;
463 entry.len = frame.len();
464 entry.offset = 0;
465 entry.payload[..frame.len()].copy_from_slice(frame);
466 entry.age = super::NIC_TX_TICK;
467 super::NIC_TX_TICK = super::NIC_TX_TICK.saturating_add(1);
468 super::NIC_TX_QUEUE[idx] = entry;
469
470 super::NET_STATE.tx_packets = super::NET_STATE.tx_packets.saturating_add(1);
471 }
472 Ok(frame.len())
473 }
474 }
475}
476
477pub fn get_next_hop_ip(dst_ip: [u8; 4]) -> [u8; 4] {
478 let st = super::status();
479 get_next_hop_ip_pure(dst_ip, st.ip, st.dhcp_subnet, st.gateway)
480}
481
482fn build_usb_ethernet_ipv4_frame(packet: &[u8], out: &mut [u8]) -> Result<usize, &'static str> {
483 if packet.len() < 20 {
484 return Err("ipv4 packet too short");
485 }
486
487 let total_len = (((packet[2] as u16) << 8) | packet[3] as u16) as usize;
488 if total_len < 20 || total_len > packet.len() {
489 return Err("invalid ipv4 total length");
490 }
491
492 let dst_ip = [packet[16], packet[17], packet[18], packet[19]];
493 let src_ip = [packet[12], packet[13], packet[14], packet[15]];
494
495 let next_hop = get_next_hop_ip(dst_ip);
496
497 let dst_mac = if dst_ip == [255, 255, 255, 255] {
498 [0xFF; 6]
499 } else if let Some(mac) = arp_cache_lookup(next_hop) {
500 mac
501 } else if src_ip == [0, 0, 0, 0] {
502 [0xFF; 6]
503 } else if unsafe {
504 let now = crate::kernel::timer::get_system_time_ms();
505 super::ARP_NEG_IP == next_hop && now < super::ARP_NEG_UNTIL_MS
506 } {
507 crate::debug!(
510 "ARP: skipping resolve for {} (recently failed, negative-cached)",
511 super::format_ipv4(next_hop)
512 );
513 return Err("destination mac unresolved (recently failed)");
514 } else {
515 let mut resolved_mac = None;
517 'outer: for attempt in 0..4u32 {
519 let mut arp_req = [0u8; 42];
520 match build_arp_request(next_hop, &mut arp_req) {
523 Ok(arp_len) => {
524 if let Err(e) = transmit_nic_ethernet_frame(&arp_req[..arp_len]) {
525 crate::warn!(
526 "[NET] ARP: request transmit failed for {}: {}",
527 super::format_ipv4(next_hop),
528 e
529 );
530 }
531 }
532 Err(e) => {
533 crate::warn!(
534 "[NET] ARP: failed to build request for {}: {}",
535 super::format_ipv4(next_hop),
536 e
537 );
538 }
539 }
540 let start = crate::kernel::timer::get_system_time_ms();
541 while crate::kernel::timer::get_system_time_ms().wrapping_sub(start) < 500 {
542 crate::kernel::usb::poll_ethernet_data_plane_only();
543 if let Some(mac) = arp_cache_lookup(next_hop) {
544 resolved_mac = Some(mac);
545 break 'outer;
546 }
547 crate::kernel::scheduler::yield_now();
550 }
551 crate::warn!(
552 "ARP: no reply for {} (attempt {})",
553 super::format_ipv4(next_hop),
554 attempt + 1
555 );
556 }
557
558 if let Some(mac) = resolved_mac {
559 mac
565 } else {
566 unsafe {
568 super::ARP_NEG_IP = next_hop;
569 super::ARP_NEG_UNTIL_MS = crate::kernel::timer::get_system_time_ms() + 3000;
570 }
571 return Err("destination mac unresolved");
572 }
573 };
574
575 let st = super::status();
576 build_ethernet_frame_pure(0x0800, st.mac, dst_mac, &packet[..total_len], out)
577}
578
579pub(crate) fn arp_cache_lookup(ip: [u8; 4]) -> Option<[u8; 6]> {
580 unsafe {
581 let table = &*core::ptr::addr_of!(super::ARP_CACHE);
582 super::arp_cache::lookup(table, ip)
583 }
584}
585
586fn arp_cache_upsert(ip: [u8; 4], mac: [u8; 6]) {
591 unsafe {
592 let age = super::ARP_TICK;
593 super::ARP_TICK = super::ARP_TICK.saturating_add(1);
594
595 let table = &mut *core::ptr::addr_of_mut!(super::ARP_CACHE);
596 let _outcome = super::arp_cache::upsert(table, ip, mac, age);
597
598 }
609}
610
611fn parse_arp_packet(frame: &[u8]) -> Result<(), &'static str> {
612 let info = parse_arp_packet_pure(frame)?;
613
614 arp_cache_upsert(info.sender_ip, info.sender_mac);
615
616 let st = super::status();
617 st.rx_packets = st.rx_packets.saturating_add(1);
618
619 if info.operation == ArpOperation::Request && info.target_ip == st.ip {
620 let mut reply = [0u8; 42];
621 build_arp_packet_pure(
622 ArpOperation::Reply,
623 st.mac,
624 st.ip,
625 info.sender_mac,
626 info.sender_ip,
627 &mut reply,
628 )?;
629
630 if let Err(e) = transmit_nic_ethernet_frame(&reply) {
633 crate::warn!(
634 "[NET] ARP: reply transmit failed to {}: {}",
635 super::format_ipv4(info.sender_ip),
636 e
637 );
638 }
639 }
640
641 Ok(())
642}
643
644fn parse_ipv4_packet(packet: &[u8]) -> Result<(), &'static str> {
645 if packet.len() < 20 {
646 return Err("ipv4 packet too short");
647 }
648
649 let version = packet[0] >> 4;
650 if version != 4 {
651 return Err("invalid ipv4 version");
652 }
653
654 let ihl = ((packet[0] & 0x0F) as usize) * 4;
655 if ihl < 20 || packet.len() < ihl {
656 return Err("invalid ipv4 header length");
657 }
658
659 let total_len = (((packet[2] as u16) << 8) | packet[3] as u16) as usize;
660 if total_len < ihl || total_len > packet.len() {
661 return Err("invalid ipv4 total length");
662 }
663
664 match packet[9] {
665 1 => {
666 let src_ip = [packet[12], packet[13], packet[14], packet[15]];
670 match super::icmp::parse_icmp_echo_reply_ipv4(packet) {
671 Ok(reply) => {
672 unsafe {
679 super::LAST_PING_REPLY = Some(reply);
680 }
681 }
682 Err(e) => {
683 crate::warn!(
684 "ICMP: packet from {} rejected: {}",
685 super::format_ipv4(src_ip),
686 e
687 );
688 }
689 }
690 Ok(())
691 }
692 17 => super::udp::parse_udp_ipv4_packet(packet),
693 6 => super::tcp::parse_tcp_ipv4_packet(packet),
694 _ => Err("unsupported ipv4 protocol"),
695 }
696}
697
698