1use alloc::string::String;
17use alloc::vec::Vec;
18
19use crate::kernel::reclock::RecoverableMutex;
20
21static HTTPS_ATTEMPT_ORDINAL: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
27
28pub fn next_https_attempt_ordinal() -> u32 {
29 HTTPS_ATTEMPT_ORDINAL.fetch_add(1, core::sync::atomic::Ordering::Relaxed)
30}
31
32pub(crate) mod addr_util;
40pub(crate) mod arp;
41pub(crate) mod arp_cache;
42pub(crate) mod dhcp;
43pub(crate) mod dns;
44pub(crate) mod http;
45pub(crate) mod icmp;
46pub(crate) mod tcp;
47pub(crate) mod tcp_state;
48pub(crate) mod udp;
49pub(crate) mod eth_frame;
50pub(crate) mod tx_queue;
51pub(crate) mod reassembly;
52pub(crate) mod udp_queue;
53
54pub use addr_util::{
55 format_ipv4, format_mac, parse_host_port, parse_host_port_with_default, parse_ipv4, parse_mac,
56};
57pub(crate) use addr_util::{internet_checksum, ipv4_header_checksum};
58
59pub use arp::{
61 arp_cache_lines, build_arp_request, get_next_hop_ip, ingest_ethernet_frame,
62 ingest_nic_ethernet_frame, ingest_nic_ipv4_packet,
63 nic_pop_tx_ipv4_packet, nic_take_tx_ipv4_chunk, transmit_nic_ethernet_frame,
64 transmit_nic_ipv4_packet,
65};
66pub use dhcp::{
67 dhcp_acquire, dhcp_release, dhcp_start_async, dhcp_status_line, dhcp_tick,
68 set_dhcp_auto_pending,
69};
70pub use dns::{
71 build_dns_query, dns_query_a_via_udp, ntp_query, ntp_sync, parse_dns_a_response,
72};
73pub use http::{
74 extract_http_body_binary, http_get_binary, http_get_real, http_get_real_with_referer, http_post_real, http_request_real,
75 https_get_real, parse_http_response, parse_http_response_bytes, parse_http_response_text,
76};
77pub use icmp::{
78 build_icmp_echo_request, parse_icmp_echo_reply_ipv4, ping_once_real,
79};
80pub use tcp::{
81 tcp_close_real, tcp_connect_real, tcp_current_snd_seq, tcp_is_socket_closed,
82 tcp_acked_through, tcp_recv_peek_nonempty, tcp_recv_real, tcp_retransmit_real, tcp_send_real,
83 tcp_socket_lines,
84};
85pub use udp::{
86 send_udp_ipv4, udp_queue_lines, udp_recv_next_datagram,
87 udp_recv_next_line,
88};
89
90pub(crate) static NET_LOCK: RecoverableMutex<()> = RecoverableMutex::new(());
92
93pub fn force_release_locks(cid: i16) {
94 unsafe {
95 NET_LOCK.force_release_if_core(cid);
96 }
97}
98
99#[derive(Copy, Clone)]
101pub struct NetworkState {
102 pub link_up: bool,
103 pub nic_backend: NicBackend,
104 pub mac: [u8; 6],
105 pub ip: [u8; 4],
106 pub gateway: [u8; 4],
107 pub dns: [u8; 4],
108 pub dns2: [u8; 4],
109 pub usb_eth_present: bool,
110 pub usb_eth_addr: u8,
111 pub usb_eth_bulk_in: u8,
112 pub usb_eth_bulk_out: u8,
113 pub usb_eth_mps: u16,
114 pub usb_eth_is_rndis: bool,
115 pub tx_packets: u64,
116 pub rx_packets: u64,
117 pub raw_rx_frames: u64,
121 pub dhcp_active: bool,
122 pub dhcp_server: [u8; 4],
123 pub dhcp_lease_secs: u32,
124 pub dhcp_subnet: [u8; 4],
125 pub dhcp_t1_secs: u32,
126 pub dhcp_t2_secs: u32,
127}
128
129#[derive(Copy, Clone)]
130pub enum NicBackend {
131 SoftwareLoopback,
132 UsbEthernet,
133}
134
135pub use arp_cache::ArpEntry;
139
140#[derive(Copy, Clone)]
141pub struct PingReply {
142 pub src_ip: [u8; 4],
143 pub identifier: u16,
144 pub sequence: u16,
145 pub payload_len: usize,
146}
147
148const ARP_CACHE_SIZE: usize = 16;
149static mut ARP_CACHE: [ArpEntry; ARP_CACHE_SIZE] = [ArpEntry::empty(); ARP_CACHE_SIZE];
150static mut ARP_TICK: u32 = 1;
151static mut ARP_NEG_IP: [u8; 4] = [0; 4];
156static mut ARP_NEG_UNTIL_MS: u64 = 0;
157static mut PING_SEQ: u16 = 1;
158static DNS_TXID: core::sync::atomic::AtomicU16 = core::sync::atomic::AtomicU16::new(0x1200);
161static DNS_SRC_PORT: core::sync::atomic::AtomicU16 =
165 core::sync::atomic::AtomicU16::new(DNS_SRC_PORT_BASE);
166pub(super) const DNS_SRC_PORT_BASE: u16 = 53000;
167pub(super) const DNS_SRC_PORT_RANGE: u16 = 512; const DNS_CACHE_SIZE: usize = 32;
172const DNS_CACHE_NAME_MAX: usize = 64;
173const DNS_CACHE_TTL_MS: u64 = 60_000; #[derive(Copy, Clone)]
176struct DnsCacheEntry {
177 valid: bool,
178 name: [u8; DNS_CACHE_NAME_MAX],
179 name_len: usize,
180 ip: [u8; 4],
181 expires_ms: u64,
182}
183
184impl DnsCacheEntry {
185 const fn empty() -> Self {
186 Self {
187 valid: false,
188 name: [0; DNS_CACHE_NAME_MAX],
189 name_len: 0,
190 ip: [0; 4],
191 expires_ms: 0,
192 }
193 }
194}
195
196static mut DNS_CACHE: [DnsCacheEntry; DNS_CACHE_SIZE] = [DnsCacheEntry::empty(); DNS_CACHE_SIZE];
197
198pub(crate) fn next_dns_src_port() -> u16 {
200 use core::sync::atomic::Ordering;
201 let raw = DNS_SRC_PORT.fetch_add(1, Ordering::Relaxed);
203 if !(DNS_SRC_PORT_BASE..DNS_SRC_PORT_BASE + DNS_SRC_PORT_RANGE).contains(&raw) {
204 DNS_SRC_PORT.store(DNS_SRC_PORT_BASE + 1, Ordering::Relaxed);
205 return DNS_SRC_PORT_BASE;
206 }
207 raw
208}
209
210pub(crate) fn next_dns_txid() -> u16 {
212 DNS_TXID.fetch_add(1, core::sync::atomic::Ordering::Relaxed)
213}
214
215pub(crate) fn dns_cache_lookup(name: &str) -> Option<[u8; 4]> {
217 let nb = name.as_bytes();
218 if nb.len() > DNS_CACHE_NAME_MAX {
219 return None;
220 }
221 let now = crate::kernel::timer::get_system_time_ms();
222 unsafe {
223 let cache = &*core::ptr::addr_of!(DNS_CACHE);
224 for e in cache.iter() {
225 if e.valid
226 && e.name_len == nb.len()
227 && &e.name[..e.name_len] == nb
228 && now < e.expires_ms
229 {
230 return Some(e.ip);
231 }
232 }
233 }
234 None
235}
236
237pub(crate) fn dns_cache_insert(name: &str, ip: [u8; 4]) {
239 let nb = name.as_bytes();
240 if nb.is_empty() || nb.len() > DNS_CACHE_NAME_MAX {
241 return;
242 }
243 let now = crate::kernel::timer::get_system_time_ms();
244 let expires_ms = now.saturating_add(DNS_CACHE_TTL_MS);
245 unsafe {
246 let mut free_idx: Option<usize> = None;
248 let mut oldest_idx = 0usize;
249 let mut oldest_exp = u64::MAX;
250 let cache = &*core::ptr::addr_of!(DNS_CACHE);
251 for (i, e) in cache.iter().enumerate() {
252 if e.valid && e.name_len == nb.len() && &e.name[..e.name_len] == nb {
253 free_idx = Some(i);
254 break;
255 }
256 if free_idx.is_none() && (!e.valid || now >= e.expires_ms) {
257 free_idx = Some(i);
258 }
259 if e.expires_ms < oldest_exp {
260 oldest_exp = e.expires_ms;
261 oldest_idx = i;
262 }
263 }
264 let idx = free_idx.unwrap_or(oldest_idx);
265 let mut entry = DnsCacheEntry::empty();
266 entry.valid = true;
267 entry.name[..nb.len()].copy_from_slice(nb);
268 entry.name_len = nb.len();
269 entry.ip = ip;
270 entry.expires_ms = expires_ms;
271 DNS_CACHE[idx] = entry;
272 }
273}
274
275const UDP_RX_QUEUE_SIZE: usize = 32;
276const TCP_SOCKET_TABLE_SIZE: usize = 32;
283const NIC_TX_QUEUE_SIZE: usize = 64;
292const NIC_TX_MAX_PAYLOAD: usize = 1536;
293
294pub(crate) use udp_queue::UdpRxEntry;
298
299static mut UDP_RX_QUEUE: [UdpRxEntry; UDP_RX_QUEUE_SIZE] = [UdpRxEntry::empty(); UDP_RX_QUEUE_SIZE];
300static mut UDP_RX_TICK: u32 = 1;
301
302#[derive(Copy, Clone)]
303struct NicTxEntry {
304 valid: bool,
305 len: usize,
306 offset: usize,
307 payload: [u8; NIC_TX_MAX_PAYLOAD],
308 age: u32,
309}
310
311impl NicTxEntry {
312 const fn empty() -> Self {
313 Self {
314 valid: false,
315 len: 0,
316 offset: 0,
317 payload: [0; NIC_TX_MAX_PAYLOAD],
318 age: 0,
319 }
320 }
321}
322
323static mut NIC_TX_QUEUE: [NicTxEntry; NIC_TX_QUEUE_SIZE] = [NicTxEntry::empty(); NIC_TX_QUEUE_SIZE];
324static mut NIC_TX_DROPS: u32 = 0;
327static mut NIC_TX_TICK: u32 = 1;
328
329use tcp_state::TcpState;
332
333#[derive(Clone)]
334struct TcpSocket {
335 valid: bool,
336 local_port: u16,
337 remote_ip: [u8; 4],
338 remote_port: u16,
339 state: TcpState,
340 snd_nxt: u32,
341 snd_una: u32,
343 rcv_nxt: u32,
344 rx_buffer: Vec<u8>,
345 fin_received: bool,
346}
347
348impl TcpSocket {
349 const fn empty() -> Self {
350 Self {
351 valid: false,
352 local_port: 0,
353 remote_ip: [0; 4],
354 remote_port: 0,
355 state: TcpState::Closed,
356 snd_nxt: 0,
357 snd_una: 0,
358 rcv_nxt: 0,
359 rx_buffer: Vec::new(),
360 fin_received: false,
361 }
362 }
363}
364
365static mut TCP_SOCKETS: [TcpSocket; TCP_SOCKET_TABLE_SIZE] = [
366 TcpSocket::empty(),
367 TcpSocket::empty(),
368 TcpSocket::empty(),
369 TcpSocket::empty(),
370 TcpSocket::empty(),
371 TcpSocket::empty(),
372 TcpSocket::empty(),
373 TcpSocket::empty(),
374 TcpSocket::empty(),
375 TcpSocket::empty(),
376 TcpSocket::empty(),
377 TcpSocket::empty(),
378 TcpSocket::empty(),
379 TcpSocket::empty(),
380 TcpSocket::empty(),
381 TcpSocket::empty(),
382 TcpSocket::empty(),
383 TcpSocket::empty(),
384 TcpSocket::empty(),
385 TcpSocket::empty(),
386 TcpSocket::empty(),
387 TcpSocket::empty(),
388 TcpSocket::empty(),
389 TcpSocket::empty(),
390 TcpSocket::empty(),
391 TcpSocket::empty(),
392 TcpSocket::empty(),
393 TcpSocket::empty(),
394 TcpSocket::empty(),
395 TcpSocket::empty(),
396 TcpSocket::empty(),
397 TcpSocket::empty(),
398];
399static mut TCP_EPHEMERAL_PORT: u16 = 40000;
400
401pub struct UdpDatagram {
402 pub src_ip: [u8; 4],
403 pub src_port: u16,
404 pub dst_port: u16,
405 pub payload: Vec<u8>,
406}
407
408pub struct HttpGetResult {
409 pub remote_ip: [u8; 4],
410 pub local_port: u16,
411 pub status_code: u16,
412 pub reason: String,
413 pub headers: alloc::collections::BTreeMap<alloc::string::String, alloc::string::String>,
414 pub body: String,
415 pub body_bytes: alloc::vec::Vec<u8>,
417}
418
419pub struct HttpsGetResult {
420 pub remote_ip: [u8; 4],
421 pub local_port: u16,
422 pub tls_version: String,
423 pub cipher_suite: String,
424 pub cert_subject: String,
425 pub cert_issuer: String,
426 pub cert_not_after: String,
427 pub status_code: u16,
428 pub reason: String,
429 pub headers: alloc::collections::BTreeMap<alloc::string::String, alloc::string::String>,
430 pub body: String,
431 pub body_bytes: alloc::vec::Vec<u8>,
434}
435
436pub struct DhcpLease {
437 pub ip: [u8; 4],
438 pub gateway: [u8; 4],
439 pub dns: [u8; 4],
440 pub dns2: [u8; 4],
441 pub server: [u8; 4],
442 pub subnet: [u8; 4],
443 pub lease_secs: u32,
444 pub t1_secs: u32,
445 pub t2_secs: u32,
446}
447
448struct DhcpAckInfo {
449 msg_type: u8,
450 yiaddr: [u8; 4],
451 server: [u8; 4],
452 router: [u8; 4],
453 dns: [u8; 4],
454 dns2: [u8; 4],
455 subnet: [u8; 4],
456 lease_secs: u32,
457 t1_secs: u32,
458 t2_secs: u32,
459}
460
461static mut NET_STATE: NetworkState = NetworkState {
462 link_up: false,
463 nic_backend: NicBackend::SoftwareLoopback,
464 mac: [0x02, 0x00, 0xA1, 0xCE, 0x00, 0x01],
465 ip: [0, 0, 0, 0],
476 gateway: [0, 0, 0, 0],
477 dns: [0, 0, 0, 0],
478 dns2: [0, 0, 0, 0],
479 usb_eth_present: false,
480 usb_eth_addr: 0,
481 usb_eth_bulk_in: 0,
482 usb_eth_bulk_out: 0,
483 usb_eth_mps: 0,
484 usb_eth_is_rndis: false,
485 tx_packets: 0,
486 rx_packets: 0,
487 raw_rx_frames: 0,
488 dhcp_active: false,
489 dhcp_server: [0; 4],
490 dhcp_lease_secs: 0,
491 dhcp_subnet: [0; 4],
492 dhcp_t1_secs: 0,
493 dhcp_t2_secs: 0,
494};
495
496static mut DHCP_XID: u32 = 0x41C3_0001;
497static mut DHCP_SERVICE_TICK: u64 = 0;
498static mut DHCP_LEASE_START_TICK: u64 = 0;
499static mut DHCP_RENEW_STAGE: u8 = 0;
500static mut DHCP_NEXT_RENEW_TICK: u64 = 0;
501static mut DHCP_AUTO_PENDING: bool = true;
502static mut DHCP_LAST_AUTO_ATTEMPT_TICK: u64 = 0;
503static mut DHCP_ASYNC_STATE: u8 = 0; static mut DHCP_ASYNC_XID: u32 = 0;
505static mut DHCP_ASYNC_ATTEMPT: usize = 0;
506static mut DHCP_ASYNC_DEADLINE_TICK: u64 = 0;
507static mut DHCP_ASYNC_RENEWING: bool = false;
508static mut DHCP_ASYNC_REBINDING: bool = false;
509static mut LAST_PING_REPLY: Option<PingReply> = None;
510
511pub fn init() {
514 let _lock = NET_LOCK.lock();
515 unsafe {
516 LAST_PING_REPLY = None;
517 NET_STATE.link_up = false;
518 NET_STATE.nic_backend = NicBackend::SoftwareLoopback;
519 ARP_CACHE = [ArpEntry::empty(); ARP_CACHE_SIZE];
520 ARP_TICK = 1;
521 PING_SEQ = 1;
522 DNS_TXID.store(0x1200, core::sync::atomic::Ordering::Relaxed);
523 DNS_SRC_PORT.store(DNS_SRC_PORT_BASE, core::sync::atomic::Ordering::Relaxed);
524 DNS_CACHE = [DnsCacheEntry::empty(); DNS_CACHE_SIZE];
525 UDP_RX_QUEUE = [UdpRxEntry::empty(); UDP_RX_QUEUE_SIZE];
526 UDP_RX_TICK = 1;
527 NIC_TX_QUEUE = [NicTxEntry::empty(); NIC_TX_QUEUE_SIZE];
528 NIC_TX_TICK = 1;
529 TCP_SOCKETS = [
530 TcpSocket::empty(),
531 TcpSocket::empty(),
532 TcpSocket::empty(),
533 TcpSocket::empty(),
534 TcpSocket::empty(),
535 TcpSocket::empty(),
536 TcpSocket::empty(),
537 TcpSocket::empty(),
538 TcpSocket::empty(),
539 TcpSocket::empty(),
540 TcpSocket::empty(),
541 TcpSocket::empty(),
542 TcpSocket::empty(),
543 TcpSocket::empty(),
544 TcpSocket::empty(),
545 TcpSocket::empty(),
546 TcpSocket::empty(),
547 TcpSocket::empty(),
548 TcpSocket::empty(),
549 TcpSocket::empty(),
550 TcpSocket::empty(),
551 TcpSocket::empty(),
552 TcpSocket::empty(),
553 TcpSocket::empty(),
554 TcpSocket::empty(),
555 TcpSocket::empty(),
556 TcpSocket::empty(),
557 TcpSocket::empty(),
558 TcpSocket::empty(),
559 TcpSocket::empty(),
560 TcpSocket::empty(),
561 TcpSocket::empty(),
562 ];
563 TCP_EPHEMERAL_PORT = 40000;
564 DHCP_XID = 0x41C3_0001;
565 DHCP_SERVICE_TICK = 0;
566 DHCP_LEASE_START_TICK = 0;
567 DHCP_RENEW_STAGE = 0;
568 DHCP_AUTO_PENDING = true;
569 DHCP_LAST_AUTO_ATTEMPT_TICK = 0;
570 DHCP_ASYNC_STATE = 0;
571 DHCP_ASYNC_XID = 0;
572 DHCP_ASYNC_ATTEMPT = 0;
573 DHCP_ASYNC_DEADLINE_TICK = 0;
574 DHCP_ASYNC_RENEWING = false;
575 NET_STATE.dhcp_active = false;
576 NET_STATE.dhcp_server = [0; 4];
577 NET_STATE.dhcp_lease_secs = 0;
578 NET_STATE.dhcp_subnet = [0; 4];
579 NET_STATE.dhcp_t1_secs = 0;
580 NET_STATE.dhcp_t2_secs = 0;
581 }
582
583 if self_test() {
584 crate::debug!("[NET] core initialized (IPv4/UDP/TCP/DNS/ARP/ICMP/HTTP/HTTPS parser ready)");
585 } else {
586 crate::debug!("[NET] core initialized with warnings (self-test failed)");
587 }
588}
589
590pub fn status() -> &'static mut NetworkState {
591 unsafe { &mut *core::ptr::addr_of_mut!(NET_STATE) }
592}
593
594pub fn status_line() -> String {
595 let _lock = NET_LOCK.lock();
596 let st = status();
597
598 let nic = if st.usb_eth_present {
599 alloc::format!(
600 "usb-eth(addr={},in={},out={},mps={},type={})",
601 st.usb_eth_addr,
602 st.usb_eth_bulk_in,
603 st.usb_eth_bulk_out,
604 st.usb_eth_mps,
605 if st.usb_eth_is_rndis {
606 "rndis"
607 } else {
608 "cdc-ecm"
609 }
610 )
611 } else {
612 String::from("none")
613 };
614
615 let mut dns_list = alloc::vec::Vec::new();
616 if st.dns != [0, 0, 0, 0] {
617 dns_list.push(format_ipv4(st.dns));
618 }
619 if st.dns2 != [0, 0, 0, 0] && st.dns2 != st.dns {
620 dns_list.push(format_ipv4(st.dns2));
621 }
622 for fallback in &[[8, 8, 8, 8], [1, 1, 1, 1]] {
623 if st.dns != *fallback && st.dns2 != *fallback {
624 dns_list.push(format_ipv4(*fallback));
625 }
626 }
627 let dns_display = if dns_list.is_empty() {
628 String::from("none")
629 } else {
630 dns_list.join(", ")
631 };
632
633 alloc::format!(
634 "link={}\nbackend={}\nnic={}\nip={}\nmask={}\ngw={}\ndns={}\ntx={}\nrx={}",
635 if st.link_up { "up" } else { "down" },
636 nic_backend_name(st.nic_backend),
637 nic,
638 format_ipv4(st.ip),
639 format_ipv4(st.dhcp_subnet),
640 format_ipv4(st.gateway),
641 dns_display,
642 st.tx_packets,
643 st.rx_packets
644 )
645}
646
647pub fn nic_debug_info() -> String {
648 let _lock = NET_LOCK.lock();
649 let st = status();
650 let async_state = unsafe { DHCP_ASYNC_STATE };
651 let async_attempt = unsafe { DHCP_ASYNC_ATTEMPT };
652 let async_xid = unsafe { DHCP_ASYNC_XID };
653 let tick = unsafe { DHCP_SERVICE_TICK };
654
655 let mut tx_q_count = 0;
656 unsafe {
657 let queue = &*core::ptr::addr_of!(NIC_TX_QUEUE);
658 for e in queue {
659 if e.valid {
660 tx_q_count += 1;
661 }
662 }
663 }
664
665 let state_str = match async_state {
666 0 => {
667 if st.dhcp_active {
668 "Bound"
669 } else {
670 "Idle"
671 }
672 }
673 1 => "WaitOffer",
674 2 => "WaitAck",
675 _ => "Unknown",
676 };
677
678 alloc::format!(
679 "NIC DEBUG INFO:\n\
680 Backend: {} (MAC: {})\n\
681 USB Eth: present={} type={} addr={} in={} out={} mps={}\n\
682 Packets: TX={} RX={} RAW_RX_FRAMES={}\n\
683 TX Queue: {}/{} used\n\
684 DHCP State: active={} auto_pending={}\n\
685 DHCP Async: state={} ({}) attempt={} xid={:#010X} tick={}",
686 nic_backend_name(st.nic_backend),
687 format_mac(st.mac),
688 st.usb_eth_present,
689 if st.usb_eth_is_rndis {
690 "rndis"
691 } else {
692 "cdc-ecm"
693 },
694 st.usb_eth_addr,
695 st.usb_eth_bulk_in,
696 st.usb_eth_bulk_out,
697 st.usb_eth_mps,
698 st.tx_packets,
699 st.rx_packets,
700 st.raw_rx_frames,
701 tx_q_count,
702 NIC_TX_QUEUE_SIZE,
703 st.dhcp_active,
704 unsafe { DHCP_AUTO_PENDING },
705 async_state,
706 state_str,
707 async_attempt,
708 async_xid,
709 tick
710 )
711}
712
713pub fn register_usb_ethernet(
714 address: u8,
715 bulk_in_ep: u8,
716 bulk_out_ep: u8,
717 max_packet: u16,
718 is_rndis: bool,
719 mac: [u8; 6],
720) {
721 let _lock = NET_LOCK.lock();
722 unsafe {
723 NET_STATE.usb_eth_present = true;
724 NET_STATE.nic_backend = NicBackend::UsbEthernet;
725 NET_STATE.usb_eth_addr = address;
726 NET_STATE.usb_eth_bulk_in = bulk_in_ep;
727 NET_STATE.usb_eth_bulk_out = bulk_out_ep;
728 NET_STATE.usb_eth_mps = max_packet;
729 NET_STATE.usb_eth_is_rndis = is_rndis;
730 NET_STATE.mac = mac;
731 NET_STATE.link_up = true;
732 DHCP_AUTO_PENDING = true;
733 DHCP_LAST_AUTO_ATTEMPT_TICK = 0;
734 }
735
736 crate::info!(
737 "NET: USB Ethernet registered at addr {} (in ep {}, out ep {}, mps {}, type={})",
738 address,
739 bulk_in_ep,
740 bulk_out_ep,
741 max_packet,
742 if is_rndis { "RNDIS" } else { "CDC-ECM" }
743 );
744}
745
746pub fn nic_backend_name(backend: NicBackend) -> &'static str {
747 match backend {
748 NicBackend::SoftwareLoopback => "software-loopback",
749 NicBackend::UsbEthernet => "usb-ethernet",
750 }
751}
752
753fn self_test() -> bool {
754 let mut query = [0u8; 128];
755 let qlen = match dns::build_dns_query("example.com", 0xCAFE, &mut query) {
756 Ok(n) => n,
757 Err(_) => return false,
758 };
759
760 if qlen < 20 {
761 return false;
762 }
763
764 let response: [u8; 45] = [
765 0xCA, 0xFE, 0x81, 0x80, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x07, b'e', b'x',
766 b'a', b'm', b'p', b'l', b'e', 0x03, b'c', b'o', b'm', 0x00, 0x00, 0x01, 0x00, 0x01, 0xC0,
767 0x0C, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x3C, 0x00, 0x04, 192, 168, 1, 100,
768 ];
769
770 if !matches!(
771 dns::parse_dns_a_response(&response, 0xCAFE, "example.com"),
772 Ok(Some([192, 168, 1, 100]))
773 ) {
774 return false;
775 }
776
777
778
779 let req = match http::build_http_get_request_pub("example.com", "/") {
780 Ok(v) => v,
781 Err(_) => return false,
782 };
783 if !req.starts_with("GET /") {
784 return false;
785 }
786
787 let sample = "HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nhey";
788 let parsed = match http::parse_http_response(sample) {
789 Ok(v) => v,
790 Err(_) => return false,
791 };
792 if parsed.0 != 200 || parsed.3 != "hey" {
793 return false;
794 }
795
796
797
798 let mut dhcp_discover = [0u8; 320];
799 let discover_len = match dhcp::build_dhcp_discover_payload_pub(
800 0x1122_3344,
801 [2, 0, 0xA1, 0xCE, 0, 1],
802 68,
803 67,
804 &mut dhcp_discover,
805 ) {
806 Ok(v) => v,
807 Err(_) => return false,
808 };
809 if discover_len < 244 {
810 return false;
811 }
812
813 let mut dhcp_ack = [0u8; 320];
814 let ack_len = match dhcp::build_dhcp_ack_payload_pub(
815 0x1122_3344,
816 [2, 0, 0xA1, 0xCE, 0, 1],
817 [192, 168, 2, 200],
818 [192, 168, 2, 1],
819 [192, 168, 2, 1],
820 3600,
821 &mut dhcp_ack,
822 ) {
823 Ok(v) => v,
824 Err(_) => return false,
825 };
826 let parsed_ack = match dhcp::parse_dhcp_ack_payload_pub(&dhcp_ack[..ack_len], 0x1122_3344) {
827 Ok(v) => v,
828 Err(_) => return false,
829 };
830 if parsed_ack.msg_type != 5 {
831 return false;
832 }
833 if parsed_ack.yiaddr != [192, 168, 2, 200] {
834 return false;
835 }
836 if parsed_ack.subnet != [255, 255, 255, 0] {
837 return false;
838 }
839 if parsed_ack.t1_secs == 0 || parsed_ack.t2_secs == 0 {
840 return false;
841 }
842
843 true
844}