1use super::addr_util::parse_host_port;
2
3fn parse_ipv4_addr(s: &str) -> Option<[u8; 4]> {
4 let mut ip = [0u8; 4];
5 let mut count = 0;
6 let mut current = 0u32;
7 let mut has_digits = false;
8 for c in s.chars() {
9 if c.is_ascii_digit() {
10 let d = (c as u32) - ('0' as u32);
11 current = current * 10 + d;
12 if current > 255 {
13 return None;
14 }
15 has_digits = true;
16 } else if c == '.' {
17 if count >= 3 || !has_digits {
18 return None;
19 }
20 ip[count] = current as u8;
21 count += 1;
22 current = 0;
23 has_digits = false;
24 } else {
25 return None;
26 }
27 }
28 if count == 3 && has_digits {
29 ip[3] = current as u8;
30 Some(ip)
31 } else {
32 None
33 }
34}
35
36pub fn dns_query_a_via_udp(host: &str) -> Result<[u8; 4], &'static str> {
37 let _p = crate::os_lib::web_engine::perf::start();
38 let r = dns_query_a_via_udp_measured(host);
39 crate::os_lib::web_engine::perf::add(
40 crate::os_lib::web_engine::perf::Slot::DnsQuery,
41 _p,
42 );
43 r
44}
45
46fn dns_query_a_via_udp_measured(host: &str) -> Result<[u8; 4], &'static str> {
47 let (host_only, _) = parse_host_port(host);
48 if let Some(ip) = parse_ipv4_addr(host_only) {
49 return Ok(ip);
50 }
51
52 if let Some(ip) = super::dns_cache_lookup(host_only) {
54 return Ok(ip);
55 }
56
57 let dhcp_dns = super::status().dns;
58 let dhcp_dns2 = super::status().dns2;
59
60 let mut dns_servers = alloc::vec::Vec::new();
62 if dhcp_dns != [0, 0, 0, 0] {
63 dns_servers.push(dhcp_dns);
64 }
65 if dhcp_dns2 != [0, 0, 0, 0] && dhcp_dns2 != dhcp_dns {
66 dns_servers.push(dhcp_dns2);
67 }
68 const FALLBACK_DNS: [[u8; 4]; 2] = [[8, 8, 8, 8], [1, 1, 1, 1]];
69 for &fallback_ip in &FALLBACK_DNS {
70 if !dns_servers.contains(&fallback_ip) {
71 dns_servers.push(fallback_ip);
72 }
73 }
74
75 let mut last_err = "dns response timeout";
76
77 let txid = super::next_dns_txid();
88 let src_port = super::next_dns_src_port();
89
90 for attempt in 0..3 {
91
92 let mut query = [0u8; 256];
93 let q_len = build_dns_query(host_only, txid, &mut query)?;
94
95 let target = dns_servers[(attempt as usize) % dns_servers.len()];
113 let mut any_sent = false;
114 #[allow(unused_assignments, unused_variables)]
115 let mut sent_ok = 0u32;
116 for &dns_ip in core::slice::from_ref(&target) {
117 match super::udp::send_udp_ipv4(dns_ip, src_port, 53, &query[..q_len]) {
118 Ok(_) => { any_sent = true; sent_ok += 1; }
119 Err(e) => {
120 crate::warn!("[NET] DNS: send to {} failed: {}", super::format_ipv4(dns_ip), e);
121 last_err = e;
122 }
123 }
124 }
125 let _ = sent_ok;
126
127 if !any_sent {
128 crate::warn!(
129 "DNS: Attempt {} for host '{}' — send failed to all {} server(s), skipping wait ({}).",
130 attempt + 1,
131 host_only,
132 dns_servers.len(),
133 last_err
134 );
135 crate::kernel::scheduler::sleep(10); continue;
137 }
138
139 crate::warn!(
142 "[NET][DNSSEND] host={} attempt={} src_port={} txid={:#06x} sent_ok={}/{}",
143 host_only, attempt + 1, src_port, txid, sent_ok, dns_servers.len()
144 );
145
146 let start_time = crate::kernel::timer::get_system_time_ms();
147 let timeout_ms = 1500u64 + (attempt as u64) * 1000;
148
149 loop {
150 crate::kernel::usb::poll_ethernet_data_plane_only();
151
152 let matched = super::udp::udp_recv_matching(src_port, |_sip, sport, pl| {
160 sport == 53
161 && pl.len() >= 2
162 && (((pl[0] as u16) << 8) | pl[1] as u16) == txid
163 });
164
165 if let Some(rx) = matched {
166 let purged = super::udp::purge_port(src_port);
172 if purged > 0 {
173 crate::debug!(
174 "[NET] DNS: purged {} duplicate responses for src_port={}",
175 purged,
176 src_port
177 );
178 }
179 if !dns_servers.contains(&rx.src_ip) {
180 crate::debug!(
181 "DNS: response for '{}' from unexpected IP {} (transparent proxy?), accepting anyway",
182 host_only,
183 super::format_ipv4(rx.src_ip)
184 );
185 }
186 match parse_dns_a_response(&rx.payload, txid, host_only) {
187 Ok(Some(parsed)) => {
188 super::dns_cache_insert(host_only, parsed);
189 return Ok(parsed);
190 }
191 Ok(None) => {}
192 Err(e) => {
193 crate::warn!("[NET] DNS parse err from {}: {}", super::format_ipv4(rx.src_ip), e);
194 last_err = e;
195 }
196 }
197 }
198
199 let elapsed = crate::kernel::timer::get_system_time_ms().wrapping_sub(start_time);
200 if elapsed >= timeout_ms {
201 break;
202 }
203
204 crate::kernel::scheduler::sleep(1);
205 }
206
207 let queue_dump = super::udp::udp_queue_lines(None);
214 crate::warn!(
215 "[NET][DIAG] DNS timeout: src_port={} txid={:#06x} udp_queue_len={} entries={:?}",
216 src_port, txid, queue_dump.len(), queue_dump
217 );
218
219 crate::info!(
220 "DNS: Attempt {} for host '{}' timed out. Retrying...",
221 attempt + 1,
222 host_only
223 );
224 }
225
226 Err(last_err)
227}
228
229
230pub fn ntp_query(host: &str) -> Result<u64, &'static str> {
231 let server_ip = dns_query_a_via_udp(host)?;
232
233 let mut req = [0u8; 48];
234 req[0] = 0x23;
236
237 let mut last_err = "ntp response timeout";
238
239 for attempt in 0..3 {
240 let src_port: u16 = 51230u16.wrapping_add((attempt as u16) * 7);
243
244 let nonce = crate::kernel::timer::get_system_time_ms();
247 req[40] = (nonce >> 24) as u8;
248 req[41] = (nonce >> 16) as u8;
249 req[42] = (nonce >> 8) as u8;
250 req[43] = nonce as u8;
251 req[44] = attempt as u8;
252 req[45] = 0;
253 req[46] = 0;
254 req[47] = 0;
255
256 if super::udp::send_udp_ipv4(server_ip, src_port, 123, &req).is_err() {
258 last_err = "ntp send failed";
259 crate::kernel::scheduler::sleep(5); continue;
261 }
262
263 let start_time = crate::kernel::timer::get_system_time_ms();
264 let timeout_ms = 4000u64;
265
266 loop {
267 crate::kernel::usb::poll_ethernet_data_plane_only();
268
269 let matched = super::udp::udp_recv_matching(src_port, |sip, sport, pl| {
271 sip == server_ip && sport == 123 && pl.len() >= 48
272 });
273 if let Some(rx) = matched {
274 let mode = rx.payload[0] & 0x7;
277 let stratum = rx.payload[1];
278 if mode != 4 || stratum == 0 || stratum > 15 {
279 last_err = "ntp invalid response";
280 } else if rx.payload[24..32] != req[40..48] {
282 last_err = "ntp originate timestamp mismatch (replay attack?)";
284 } else {
285 let secs_1900 = ((rx.payload[40] as u64) << 24)
286 | ((rx.payload[41] as u64) << 16)
287 | ((rx.payload[42] as u64) << 8)
288 | (rx.payload[43] as u64);
289 if secs_1900 > crate::kernel::timer::NTP_UNIX_OFFSET {
290 return Ok(secs_1900 - crate::kernel::timer::NTP_UNIX_OFFSET);
291 }
292 last_err = "ntp invalid timestamp";
293 }
294 }
295
296 let elapsed = crate::kernel::timer::get_system_time_ms().wrapping_sub(start_time);
297 if elapsed >= timeout_ms {
298 break;
299 }
300 crate::kernel::scheduler::yield_now();
303 }
304
305 crate::info!(
306 "NTP: Attempt {} for '{}' timed out. Retrying...",
307 attempt + 1,
308 host
309 );
310 crate::kernel::scheduler::sleep(10); }
313
314 Err(last_err)
315}
316
317pub fn ntp_sync() -> Result<u64, &'static str> {
318 const HOSTS: [&str; 3] = ["ntp.nict.jp", "time.cloudflare.com", "pool.ntp.org"];
320 let mut last = "ntp response timeout";
321 for h in HOSTS.iter() {
322 match ntp_query(h) {
323 Ok(unix) => {
324 crate::kernel::timer::set_wall_clock(unix);
325 crate::info!("[NET] NTP: synced via {}. unix={}", h, unix);
326 return Ok(unix);
327 }
328 Err(e) => {
329 crate::warn!("[SYS] NTP: Failed to query {}: {}", h, e);
330 last = e;
331 }
332 }
333 }
334 Err(last)
335}
336
337pub fn build_dns_query(domain: &str, txid: u16, out: &mut [u8]) -> Result<usize, &'static str> {
338 if out.len() < 64 {
339 return Err("buffer too small");
340 }
341
342 out[0] = (txid >> 8) as u8;
343 out[1] = txid as u8;
344 out[2] = 0x01;
345 out[3] = 0x00;
346 out[4] = 0x00;
347 out[5] = 0x01;
348 out[6] = 0x00;
349 out[7] = 0x00;
350 out[8] = 0x00;
351 out[9] = 0x00;
352 out[10] = 0x00;
353 out[11] = 0x00;
354
355 let mut idx = 12usize;
356 for label in domain.split('.') {
357 let l = label.len();
358 if l == 0 || l > 63 || idx + 1 + l >= out.len() {
359 return Err("invalid domain");
360 }
361 out[idx] = l as u8;
362 idx += 1;
363 out[idx..idx + l].copy_from_slice(label.as_bytes());
364 idx += l;
365 }
366
367 if idx + 5 >= out.len() {
368 return Err("buffer too small");
369 }
370
371 out[idx] = 0x00;
372 idx += 1;
373
374 out[idx] = 0x00;
375 out[idx + 1] = 0x01;
376 out[idx + 2] = 0x00;
377 out[idx + 3] = 0x01;
378
379 Ok(idx + 4)
380}
381
382pub fn parse_dns_a_response(
383 packet: &[u8],
384 expected_txid: u16,
385 expected_domain: &str,
386) -> Result<Option<[u8; 4]>, &'static str> {
387 if packet.len() < 12 {
388 return Err("dns packet too short");
389 }
390
391 let rx_txid = ((packet[0] as u16) << 8) | packet[1] as u16;
392 if rx_txid != expected_txid {
393 return Ok(None);
394 }
395
396 let is_response = (packet[2] & 0x80) != 0;
397 if !is_response {
398 return Ok(None);
399 }
400
401 let rcode = packet[3] & 0x0F;
402 if rcode != 0 {
403 return Ok(None);
404 }
405
406 let qdcount = ((packet[4] as u16) << 8) | packet[5] as u16;
407 let ancount = ((packet[6] as u16) << 8) | packet[7] as u16;
408 let nscount = ((packet[8] as u16) << 8) | packet[9] as u16;
409 let arcount = ((packet[10] as u16) << 8) | packet[11] as u16;
410
411 let total_rrs = ancount + nscount + arcount;
412
413 let mut idx = 12usize;
414
415 for _ in 0..qdcount {
416 idx = skip_dns_name(packet, idx)?;
417 if idx + 4 > packet.len() {
418 return Err("dns question truncated");
419 }
420 idx += 4;
421 }
422
423 for _ in 0..total_rrs {
424 let (_matches, next_idx) = compare_dns_name(packet, idx, expected_domain)?;
425 idx = next_idx;
426 if idx + 10 > packet.len() {
427 return Err("dns answer truncated");
428 }
429
430 let rr_type = ((packet[idx] as u16) << 8) | packet[idx + 1] as u16;
431 let _rr_class = ((packet[idx + 2] as u16) << 8) | packet[idx + 3] as u16;
432 let _ttl = ((packet[idx + 4] as u32) << 24)
433 | ((packet[idx + 5] as u32) << 16)
434 | ((packet[idx + 6] as u32) << 8)
435 | packet[idx + 7] as u32;
436 let rdlen = ((packet[idx + 8] as u16) << 8) | packet[idx + 9] as u16;
437 idx += 10;
438
439 if idx + rdlen as usize > packet.len() {
440 return Err("dns rdata truncated");
441 }
442
443 if rr_type == 1 && rdlen == 4 {
444 let ip = [
445 packet[idx],
446 packet[idx + 1],
447 packet[idx + 2],
448 packet[idx + 3],
449 ];
450 unsafe {
451 super::NET_STATE.rx_packets = super::NET_STATE.rx_packets.saturating_add(1);
452 }
453 return Ok(Some(ip));
454 }
455
456 idx += rdlen as usize;
457 }
458
459 Ok(None)
460}
461
462
463
464fn skip_dns_name(packet: &[u8], mut idx: usize) -> Result<usize, &'static str> {
465 if idx >= packet.len() {
466 return Err("dns name out of bounds");
467 }
468
469 loop {
470 if idx >= packet.len() {
471 return Err("dns name truncated");
472 }
473
474 let len = packet[idx];
475
476 if len & 0xC0 == 0xC0 {
477 if idx + 1 >= packet.len() {
478 return Err("dns ptr truncated");
479 }
480 return Ok(idx + 2);
481 }
482
483 idx += 1;
484 if len == 0 {
485 return Ok(idx);
486 }
487
488 idx += len as usize;
489 }
490}
491
492fn compare_dns_name(packet: &[u8], start_idx: usize, expected: &str) -> Result<(bool, usize), &'static str> {
493 let next_idx = skip_dns_name(packet, start_idx)?;
495
496 let expected_bytes = expected.as_bytes();
497 let mut expected_idx = 0;
498
499 let mut cur_idx = start_idx;
500 let mut jumps = 0;
501
502 loop {
503 if jumps > 10 { return Err("dns pointer loop"); }
504 if cur_idx >= packet.len() { return Err("dns name out of bounds"); }
505
506 let len = packet[cur_idx];
507 if len & 0xC0 == 0xC0 {
508 if cur_idx + 1 >= packet.len() { return Err("dns ptr truncated"); }
509 let offset = (((len & 0x3F) as usize) << 8) | (packet[cur_idx + 1] as usize);
510 cur_idx = offset;
511 jumps += 1;
512 continue;
513 }
514
515 cur_idx += 1;
516 if len == 0 {
517 let matches = expected_idx == expected_bytes.len();
518 return Ok((matches, next_idx));
519 }
520
521 let label_len = len as usize;
522 if cur_idx + label_len > packet.len() { return Err("dns name truncated"); }
523
524 if expected_idx > 0 {
525 if expected_idx >= expected_bytes.len() || expected_bytes[expected_idx] != b'.' {
526 return Ok((false, next_idx));
527 }
528 expected_idx += 1;
529 }
530
531 let label = &packet[cur_idx..cur_idx + label_len];
532 if expected_idx + label_len > expected_bytes.len() {
533 return Ok((false, next_idx));
534 }
535
536 if !label.eq_ignore_ascii_case(&expected_bytes[expected_idx..expected_idx + label_len]) {
537 return Ok((false, next_idx));
538 }
539
540 expected_idx += label_len;
541 cur_idx += label_len;
542 }
543}