1#![allow(dead_code)]
2
3extern crate alloc;
4use alloc::string::String;
5use alloc::vec::Vec;
6
7use embedded_tls::blocking::{TlsConnection, TlsContext};
8use embedded_tls::TlsConfig;
9use rand_core::{CryptoRng, RngCore};
10
11pub struct OsRng {
14 state: u32,
15}
16
17impl Default for OsRng {
18 fn default() -> Self {
19 Self::new()
20 }
21}
22
23static OS_RNG_CALL_COUNTER: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
30
31impl OsRng {
32 pub fn new() -> Self {
33 let t = crate::kernel::timer::get_ticks() as u32;
34 let call_no = OS_RNG_CALL_COUNTER.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
35 let seed = t ^ call_no.wrapping_mul(0x9E37_79B9);
36 Self {
37 state: if seed == 0 { 0xA11C0B0B } else { seed },
38 }
39 }
40}
41
42impl RngCore for OsRng {
43 fn next_u32(&mut self) -> u32 {
44 let mut x = self.state;
45 x ^= x << 13;
46 x ^= x >> 17;
47 x ^= x << 5;
48 self.state = x;
49 x
50 }
51 fn next_u64(&mut self) -> u64 {
52 ((self.next_u32() as u64) << 32) | (self.next_u32() as u64)
53 }
54 fn fill_bytes(&mut self, dest: &mut [u8]) {
55 for chunk in dest.chunks_mut(4) {
56 let val = self.next_u32().to_le_bytes();
57 let len = chunk.len();
58 chunk.copy_from_slice(&val[..len]);
59 }
60 }
61 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
62 self.fill_bytes(dest);
63 Ok(())
64 }
65}
66
67impl CryptoRng for OsRng {}
68
69pub static WRITE_WAIT_TICKS: core::sync::atomic::AtomicU32 =
75 core::sync::atomic::AtomicU32::new(0);
76pub static WRITE_WAIT_CALLS: core::sync::atomic::AtomicU32 =
77 core::sync::atomic::AtomicU32::new(0);
78pub static WRITE_RETX_COUNT: core::sync::atomic::AtomicU32 =
80 core::sync::atomic::AtomicU32::new(0);
81
82pub struct TcpIoWrapper {
85 pub local_port: u16,
86 buffer: Vec<u8>,
87 pos: usize,
103 retry_write: core::sync::atomic::AtomicBool,
111}
112
113impl TcpIoWrapper {
114 pub fn new(local_port: u16) -> Self {
115 Self {
116 local_port,
117 buffer: Vec::new(),
118 pos: 0,
119 retry_write: core::sync::atomic::AtomicBool::new(false),
120 }
121 }
122
123 pub fn new_with_retry_write(local_port: u16) -> Self {
124 Self {
125 local_port,
126 buffer: Vec::new(),
127 pos: 0,
128 retry_write: core::sync::atomic::AtomicBool::new(true),
129 }
130 }
131
132 pub fn set_retry_write(&self, retry: bool) {
133 self.retry_write
134 .store(retry, core::sync::atomic::Ordering::Relaxed);
135 }
136}
137
138#[inline]
140fn safe_tcp_close(local_port: u16, context: &str) {
141 if let Err(e) = crate::kernel::net::tcp_close_real(local_port) {
142 crate::warn!("[WARN ][NET] tcp_close_real 失敗 ({}) port={}: {}", context, local_port, e);
143 }
144}
145
146impl embedded_io::ErrorType for TcpIoWrapper {
147 type Error = embedded_io::ErrorKind;
148}
149
150impl embedded_io::Read for TcpIoWrapper {
151 fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
152 if buf.is_empty() {
153 return Ok(0);
154 }
155 let _pr = crate::os_lib::web_engine::perf::start();
156 let start_tick = crate::kernel::timer::get_ticks();
157 let timeout_ticks = 1500usize; loop {
185 if self.pos < self.buffer.len() {
186 let avail = self.buffer.len() - self.pos;
187 let len = avail.min(buf.len());
188 buf[..len].copy_from_slice(&self.buffer[self.pos..self.pos + len]);
189 self.pos += len;
190 if self.pos == self.buffer.len() {
192 self.buffer.clear();
193 self.pos = 0;
194 }
195 crate::os_lib::web_engine::perf::add(
196 crate::os_lib::web_engine::perf::Slot::TlsReadWait,
197 _pr,
198 );
199 return Ok(len);
200 }
201
202 if let Ok(chunk) = crate::kernel::net::tcp_recv_real(self.local_port, 1) {
207 if !chunk.is_empty() {
208 if self.pos > 0 {
211 self.buffer.drain(0..self.pos);
212 self.pos = 0;
213 }
214 self.buffer.extend_from_slice(&chunk);
215 crate::kernel::sync_fetch::note_received(chunk.len());
217 continue; }
219 }
220
221 if crate::kernel::net::tcp_is_socket_closed(self.local_port)
222 && self.pos >= self.buffer.len()
223 {
224 return Ok(0); }
232
233 let elapsed = crate::kernel::timer::get_ticks().wrapping_sub(start_tick);
235 if elapsed >= timeout_ticks {
236 crate::warn!(
241 "[TLS][TIMEOUT] 受信タイムアウト local_port={} elapsed_ticks={} timeout_ticks={} seg_accepted={} seg_dropped={}",
242 self.local_port,
243 elapsed,
244 timeout_ticks,
245 crate::kernel::net::tcp::SEG_ACCEPTED.load(core::sync::atomic::Ordering::Relaxed),
246 crate::kernel::net::tcp::SEG_DROPPED.load(core::sync::atomic::Ordering::Relaxed)
247 );
248 return Err(embedded_io::ErrorKind::TimedOut);
249 }
250
251 let port = self.local_port;
263 if crate::kernel::window_mgr::abort_wait_if_stopped(|| safe_tcp_close(port, "killed app")) {
264 return Err(embedded_io::ErrorKind::ConnectionAborted);
265 }
266 if crate::kernel::sync_fetch::over_limit() {
269 return Err(embedded_io::ErrorKind::TimedOut);
270 }
271 crate::kernel::scheduler::sleep(1);
272 }
273 }
274}
275
276impl embedded_io::Write for TcpIoWrapper {
277 fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
278 const MAX_TCP_PAYLOAD: usize = 1400;
295 let buf = if buf.len() > MAX_TCP_PAYLOAD {
296 &buf[..MAX_TCP_PAYLOAD]
297 } else {
298 buf
299 };
300 let seq_at_send = crate::kernel::net::tcp_current_snd_seq(self.local_port);
309 if crate::kernel::net::tcp_send_real(self.local_port, buf).is_err() {
310 return Err(embedded_io::ErrorKind::BrokenPipe);
311 }
312 if self.retry_write.load(core::sync::atomic::Ordering::Relaxed) {
313 if let Some(seq) = seq_at_send {
314 const POLL_STEP: usize = 3;
331 const WAIT_PER_TRY: usize = 60;
333 let t_w0 = crate::kernel::timer::get_ticks();
334 let _pw = crate::os_lib::web_engine::perf::start();
335 WRITE_WAIT_CALLS.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
336 'retry: for _ in 0..4 {
337 let t_wait0 = crate::kernel::timer::get_ticks();
356 while crate::kernel::timer::get_ticks().wrapping_sub(t_wait0)
357 < WAIT_PER_TRY
358 {
359 let _ps = crate::os_lib::web_engine::perf::start();
363 crate::kernel::scheduler::sleep(POLL_STEP);
364 crate::os_lib::web_engine::perf::add(
365 crate::os_lib::web_engine::perf::Slot::SleepActual,
366 _ps,
367 );
368 let _pe = crate::os_lib::web_engine::perf::start();
369 crate::kernel::usb::poll_ethernet_data_plane_only();
370 crate::os_lib::web_engine::perf::add(
371 crate::os_lib::web_engine::perf::Slot::EthPoll,
372 _pe,
373 );
374 let _pk = crate::os_lib::web_engine::perf::start();
375 let done = crate::kernel::net::tcp_acked_through(
380 self.local_port,
381 seq.wrapping_add(buf.len() as u32),
382 ) || crate::kernel::net::tcp_recv_peek_nonempty(self.local_port)
383 || crate::kernel::net::tcp_is_socket_closed(self.local_port);
384 crate::os_lib::web_engine::perf::add(
385 crate::os_lib::web_engine::perf::Slot::PeekCheck,
386 _pk,
387 );
388 if done {
389 break 'retry;
390 }
391 }
392 WRITE_RETX_COUNT.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
394 if let Err(e) = crate::kernel::net::tcp_retransmit_real(self.local_port, buf, seq) {
395 crate::warn!("[WARN ][NET] TLS write再送失敗 port={}: {}", self.local_port, e);
396 }
397 }
398 WRITE_WAIT_TICKS.fetch_add(
399 crate::kernel::timer::get_ticks().wrapping_sub(t_w0) as u32,
400 core::sync::atomic::Ordering::Relaxed,
401 );
402 crate::os_lib::web_engine::perf::add(
403 crate::os_lib::web_engine::perf::Slot::TlsWriteWait,
404 _pw,
405 );
406 }
407 }
408 Ok(buf.len())
409 }
410
411 fn flush(&mut self) -> Result<(), Self::Error> {
412 Ok(())
413 }
414}
415
416
417pub mod stats {
425 use core::sync::atomic::{AtomicU32, Ordering::Relaxed};
426 pub static OK: AtomicU32 = AtomicU32::new(0);
427 pub static DNS_FAIL: AtomicU32 = AtomicU32::new(0);
428 pub static CONNECT_FAIL: AtomicU32 = AtomicU32::new(0);
429 pub static HANDSHAKE_FAIL: AtomicU32 = AtomicU32::new(0);
430 pub static TRUNCATED: AtomicU32 = AtomicU32::new(0);
431
432 pub fn bump(c: &AtomicU32) {
433 c.fetch_add(1, Relaxed);
434 }
435
436 pub fn report(tag: &str) {
438 let ok = OK.load(Relaxed);
439 let dns = DNS_FAIL.load(Relaxed);
440 let conn = CONNECT_FAIL.load(Relaxed);
441 let hs = HANDSHAKE_FAIL.load(Relaxed);
442 let tr = TRUNCATED.load(Relaxed);
443 let total = ok + dns + conn + hs + tr;
444 crate::warn!(
445 "[NET][STATS] {} total={} ok={} dns_fail={} connect_fail={} handshake_fail={} truncated={}",
446 tag, total, ok, dns, conn, hs, tr
447 );
448 }
449}
450
451pub fn https_get(
452 host: &str,
453 path: &str,
454) -> Result<crate::kernel::net::HttpsGetResult, &'static str> {
455 https_get_with_referer(host, path, None)
456}
457
458pub fn https_get_with_referer(
461 host: &str,
462 path: &str,
463 referer: Option<&str>,
464) -> Result<crate::kernel::net::HttpsGetResult, &'static str> {
465 let ordinal = crate::kernel::net::next_https_attempt_ordinal();
466 let (host_only, port) = crate::kernel::net::parse_host_port_with_default(host, 443);
468 let _sync = crate::kernel::sync_fetch::begin(host, path);
470
471 let referer_hdr = referer.map(|r| alloc::format!("Referer: {}\r\n", r)).unwrap_or_default();
475 let request = alloc::format!(
476 "GET {} HTTP/1.1\r\nHost: {}\r\nUser-Agent: Mozilla/5.0 (AtmOS Browser; gzip)\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Encoding: gzip\r\n{}Connection: keep-alive\r\n\r\n",
477 path, host, referer_hdr
478 );
479
480 let ex = exchange(host, host_only, port, false, None, request.as_bytes(), false)?;
481 let raw_bytes = ex.raw;
482 crate::kernel::responsiveness::add(crate::kernel::responsiveness::Qty::NetRequests, 1);
484 crate::kernel::responsiveness::add(crate::kernel::responsiveness::Qty::NetBytes, raw_bytes.len() as u64);
485
486 if raw_bytes.is_empty() {
487 crate::warn!(
488 "[NET][DIAG] https_get ordinal={} EMPTY RESPONSE (0 bytes read) host={}",
489 ordinal,
490 host
491 );
492 return Err("empty https response");
493 }
494
495 let resp_str = match alloc::string::String::from_utf8(raw_bytes.clone()) {
496 Ok(s) => s,
497 Err(e) => {
498 let valid = e.into_bytes();
499 alloc::string::String::from_utf8_lossy(&valid).into_owned()
500 }
501 };
502
503 let (status_code, reason, headers, body) = crate::kernel::net::parse_http_response_text(&raw_bytes)
507 .unwrap_or((
508 200,
509 String::from("OK"),
510 alloc::collections::BTreeMap::new(),
511 resp_str,
512 ));
513 let body_bytes = crate::kernel::net::parse_http_response_bytes(&raw_bytes)
514 .map(|(_, _, _, b)| b)
515 .unwrap_or_default();
516
517 Ok(crate::kernel::net::HttpsGetResult {
525 remote_ip: ex.remote_ip,
526 local_port: ex.local_port,
527 tls_version: String::from(if ex.tls12 { "TLS1.2" } else { "TLS1.3" }),
528 cipher_suite: String::from(if ex.tls12 {
529 "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
530 } else {
531 "TLS_AES_128_GCM_SHA256"
532 }),
533 cert_subject: alloc::format!("CN={}", host),
534 cert_issuer: String::from("Unknown Root CA"),
535 cert_not_after: String::from("Unknown"),
536 status_code,
537 reason,
538 headers,
539 body,
540 body_bytes,
541 })
542}
543
544pub fn https_request(
554 method: &str,
555 host: &str,
556 path: &str,
557 extra_headers: &[(&str, &str)],
558 content_type: &str,
559 body: Option<&[u8]>,
560) -> Result<crate::kernel::net::HttpsGetResult, &'static str> {
561 const MAX_ATTEMPTS: u32 = 3;
562 let _sync = crate::kernel::sync_fetch::begin(host, path);
564 let idempotent = matches!(method, "GET" | "HEAD" | "OPTIONS");
565 let mut partial: Option<crate::kernel::net::HttpsGetResult> = None;
566 for attempt in 1..=MAX_ATTEMPTS {
567 let (res, complete) =
568 match https_request_once(method, host, path, extra_headers, content_type, body) {
569 Ok(r) => r,
570 Err(e) if crate::kernel::sync_fetch::aborted() => return Err(e),
572 Err(e) => return partial.ok_or(e),
574 };
575 if complete || !idempotent || method == "HEAD" {
576 return Ok(res);
577 }
578 crate::warn!(
579 "[NET][DIAG] https_request 途中切れ {} {}{} attempt={}/{} body={}",
580 method, host, path, attempt, MAX_ATTEMPTS, res.body_bytes.len()
581 );
582 partial = Some(res);
583 }
584 partial.ok_or("HTTPS request failed")
585}
586
587fn https_request_once(
592 method: &str,
593 host: &str,
594 path: &str,
595 extra_headers: &[(&str, &str)],
596 content_type: &str,
597 body: Option<&[u8]>,
598) -> Result<(crate::kernel::net::HttpsGetResult, bool), &'static str> {
599 let (host_only, port) = crate::kernel::net::parse_host_port_with_default(host, 443);
600
601 let has_ua = extra_headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("user-agent"));
602 let default_ua = crate::os_lib::web_engine::site_hooks::hooks().user_agent(host).unwrap_or("AtmOS/1.0");
604 let mut header = alloc::format!("{} {} HTTP/1.1\r\nHost: {}\r\n", method, path, host);
605 if !has_ua {
606 header.push_str(&alloc::format!("User-Agent: {}\r\n", default_ua));
607 }
608 if !extra_headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("accept")) {
610 header.push_str("Accept: application/json\r\n");
611 }
612 for (k, v) in extra_headers {
613 if k.eq_ignore_ascii_case("connection") {
615 continue;
616 }
617 header.push_str(k);
618 header.push_str(": ");
619 header.push_str(v);
620 header.push_str("\r\n");
621 }
622 let body = body.unwrap_or(&[]);
623 if !content_type.is_empty() {
624 header.push_str(&alloc::format!("Content-Type: {}\r\n", content_type));
625 }
626 if !body.is_empty() || method == "POST" || method == "PUT" || method == "PATCH" {
627 header.push_str(&alloc::format!("Content-Length: {}\r\n", body.len()));
628 }
629 header.push_str("Accept-Encoding: gzip\r\n");
630 header.push_str("Connection: keep-alive\r\n\r\n");
631
632 let mut request = header.into_bytes();
633 request.extend_from_slice(body);
634
635 let ex = exchange(host, host_only, port, false, None, &request, method == "HEAD")?;
636 let raw_bytes = ex.raw;
637 crate::kernel::responsiveness::add(crate::kernel::responsiveness::Qty::XhrRequests, 1);
639 crate::kernel::responsiveness::add(crate::kernel::responsiveness::Qty::XhrBytes, raw_bytes.len() as u64);
640
641 let resp_str = match alloc::string::String::from_utf8(raw_bytes.clone()) {
642 Ok(s) => s,
643 Err(e) => alloc::string::String::from_utf8_lossy(&e.into_bytes()).into_owned(),
644 };
645 let (status_code, reason, headers, rbody) = crate::kernel::net::parse_http_response_text(&raw_bytes)
646 .unwrap_or((
647 200,
648 String::from("OK"),
649 alloc::collections::BTreeMap::new(),
650 resp_str,
651 ));
652 let body_bytes = crate::kernel::net::parse_http_response_bytes(&raw_bytes)
654 .map(|(_, _, _, b)| b)
655 .unwrap_or_default();
656 let complete = crate::kernel::http_body::is_complete_response(&raw_bytes);
657
658 Ok((crate::kernel::net::HttpsGetResult {
659 remote_ip: ex.remote_ip,
660 local_port: ex.local_port,
661 tls_version: String::from(if ex.tls12 { "TLS1.2" } else { "TLS1.3" }),
662 cipher_suite: String::from(if ex.tls12 { "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" } else { "TLS_AES_128_GCM_SHA256" }),
663 cert_subject: alloc::format!("CN={}", host),
664 cert_issuer: String::from("Unknown Root CA"),
665 cert_not_after: String::from("Unknown"),
666 status_code,
667 reason,
668 headers,
669 body: rbody,
670 body_bytes,
671 }, complete))
672}
673
674const POOL_MAX_PER_KEY: usize = 4;
683const POOL_MAX_TOTAL: usize = 8;
685const POOL_IDLE_MS: u64 = 30_000;
688
689static CONN_POOL: spin::Mutex<crate::kernel::conn_pool::Pool<PooledConn>> =
690 spin::Mutex::new(crate::kernel::conn_pool::Pool::new(POOL_MAX_PER_KEY, POOL_MAX_TOTAL, POOL_IDLE_MS));
691
692pub static POOL_REUSED: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
694pub static POOL_OPENED: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
695pub static POOL_STALE: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
696
697struct Tls13Owned {
702 conn: Option<alloc::boxed::Box<TlsConnection<'static, &'static mut TcpIoWrapper, embedded_tls::Aes128GcmSha256>>>,
705 stream: *mut TcpIoWrapper,
706 read_buf: *mut [u8],
707 write_buf: *mut [u8],
708}
709
710unsafe impl Send for Tls13Owned {}
713
714impl Tls13Owned {
715 fn new(stream: TcpIoWrapper) -> Self {
716 let stream_ptr: *mut TcpIoWrapper = alloc::boxed::Box::into_raw(alloc::boxed::Box::new(stream));
718 let read_buf: *mut [u8] = alloc::boxed::Box::into_raw(alloc::vec![0u8; 18432].into_boxed_slice());
719 let write_buf: *mut [u8] = alloc::boxed::Box::into_raw(alloc::vec![0u8; 16384].into_boxed_slice());
720 let (s, r, w): (&'static mut TcpIoWrapper, &'static mut [u8], &'static mut [u8]) =
723 unsafe { (&mut *stream_ptr, &mut *read_buf, &mut *write_buf) };
724 Self { conn: Some(alloc::boxed::Box::new(TlsConnection::new(s, r, w))), stream: stream_ptr, read_buf, write_buf }
725 }
726}
727
728impl Drop for Tls13Owned {
729 fn drop(&mut self) {
730 self.conn = None;
732 unsafe {
734 drop(alloc::boxed::Box::from_raw(self.stream));
735 drop(alloc::boxed::Box::from_raw(self.read_buf));
736 drop(alloc::boxed::Box::from_raw(self.write_buf));
737 }
738 }
739}
740
741enum Wire {
742 V13(Tls13Owned),
743 V12(alloc::boxed::Box<crate::kernel::tls12::Tls12<TcpIoWrapper>>),
744}
745
746struct PooledConn {
748 wire: Wire,
749 local_port: u16,
750 remote_ip: [u8; 4],
751 tcp_ticks: usize,
753 tls_ticks: usize,
754}
755
756impl PooledConn {
757 fn is_tls12(&self) -> bool {
758 matches!(self.wire, Wire::V12(_))
759 }
760
761 fn set_retry_write(&self, retry: bool) {
762 match &self.wire {
763 Wire::V13(o) => {
764 unsafe { (*o.stream).set_retry_write(retry) };
766 }
767 Wire::V12(c) => c.io().set_retry_write(retry),
768 }
769 }
770
771 fn write_all(&mut self, data: &[u8]) -> bool {
772 match &mut self.wire {
773 Wire::V13(o) => match o.conn.as_mut() {
774 Some(c) => {
775 let c = c.as_mut();
776 embedded_io::Write::write_all(c, data).is_ok() && embedded_io::Write::flush(c).is_ok()
777 }
778 None => false,
779 },
780 Wire::V12(c) => {
781 let c = c.as_mut();
782 embedded_io::Write::write_all(c, data).is_ok() && embedded_io::Write::flush(c).is_ok()
783 }
784 }
785 }
786
787 fn read(&mut self, buf: &mut [u8]) -> Result<usize, ()> {
789 match &mut self.wire {
790 Wire::V13(o) => match o.conn.as_mut() {
791 Some(c) => embedded_io::Read::read(c.as_mut(), buf).map_err(|e| {
792 crate::warn!("[NET][DIAG] TLS read err: {:?}", e);
793 }),
794 None => Err(()),
795 },
796 Wire::V12(c) => embedded_io::Read::read(c.as_mut(), buf).map_err(|e| {
797 crate::warn!("[NET][DIAG] TLS 1.2 read err: {:?}", e);
798 }),
799 }
800 }
801
802 fn alive(&self) -> bool {
804 !crate::kernel::net::tcp_is_socket_closed(self.local_port)
805 && !crate::kernel::net::tcp_recv_peek_nonempty(self.local_port)
806 }
807}
808
809impl Drop for PooledConn {
810 fn drop(&mut self) {
811 if let Wire::V12(c) = &mut self.wire {
812 c.close();
813 }
814 safe_tcp_close(self.local_port, "conn drop");
815 }
816}
817
818fn pool_now_ms() -> u64 {
819 (crate::kernel::timer::get_ticks() as u64).saturating_mul(10)
820}
821
822fn pool_key(host_only: &str, port: u16) -> String {
823 alloc::format!("{}:{}", host_only, port)
824}
825
826fn pool_checkout(key: &str) -> Option<PooledConn> {
828 loop {
829 let mut dropped = Vec::new();
831 let got = CONN_POOL.lock().checkout(key, pool_now_ms(), &mut dropped);
832 drop(dropped);
833 match got {
834 Some(c) if c.alive() => return Some(c),
835 Some(c) => {
836 POOL_STALE.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
837 drop(c);
838 }
839 None => return None,
840 }
841 }
842}
843
844fn pool_checkin(key: &str, conn: PooledConn) {
845 let mut dropped = Vec::new();
846 CONN_POOL.lock().checkin(key, conn, pool_now_ms(), &mut dropped);
847 drop(dropped);
848}
849
850pub fn pool_close_all() {
852 let mut dropped = Vec::new();
853 CONN_POOL.lock().drain(&mut dropped);
854 drop(dropped);
855}
856
857fn open_conn(
859 remote_ip: [u8; 4],
860 host: &str,
861 host_only: &str,
862 port: u16,
863 retry_write: bool,
864) -> Result<PooledConn, &'static str> {
865 let make_stream = |local_port: u16| {
866 if retry_write {
867 TcpIoWrapper::new_with_retry_write(local_port)
868 } else {
869 TcpIoWrapper::new(local_port)
870 }
871 };
872 POOL_OPENED.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
873 if !tls12_hosts_contains(host_only) {
874 let t_conn0 = crate::kernel::timer::get_ticks();
875 let local_port = crate::kernel::net::tcp_connect_real(remote_ip, port).inspect_err(|_| {
876 stats::bump(&stats::CONNECT_FAIL);
877 })?;
878 let t_hs0 = crate::kernel::timer::get_ticks();
879 let mut owned = Tls13Owned::new(make_stream(local_port));
880 let mut rng = OsRng::new();
881 let config = TlsConfig::new().with_server_name(host_only);
882 let mut provider =
883 embedded_tls::UnsecureProvider::new::<embedded_tls::Aes128GcmSha256>(&mut rng);
884 let _ph = crate::os_lib::web_engine::perf::start();
885 let opened = match owned.conn.as_mut() {
886 Some(c) => c
887 .open(crate::kernel::tls::TlsContext::new(&config, &mut provider))
888 .map_err(|e| {
889 crate::warn!(
890 "[NET] TLS handshake error: {:?} host={} (elapsed_ticks={})",
891 e,
892 host,
893 crate::kernel::timer::get_ticks().wrapping_sub(t_hs0)
894 );
895 })
896 .is_ok(),
897 None => false,
898 };
899 crate::os_lib::web_engine::perf::add(crate::os_lib::web_engine::perf::Slot::TlsHandshake, _ph);
900 if opened {
901 tls13_hosts_insert(host_only);
902 return Ok(PooledConn {
903 wire: Wire::V13(owned),
904 local_port,
905 remote_ip,
906 tcp_ticks: t_hs0.wrapping_sub(t_conn0),
907 tls_ticks: crate::kernel::timer::get_ticks().wrapping_sub(t_hs0),
908 });
909 }
910 drop(owned);
911 safe_tcp_close(local_port, "open_conn handshake fail");
912 if tls13_hosts_contains(host_only) {
915 stats::bump(&stats::HANDSHAKE_FAIL);
916 return Err("TLS handshake failed");
917 }
918 }
919 let t_conn0 = crate::kernel::timer::get_ticks();
920 let local_port = crate::kernel::net::tcp_connect_real(remote_ip, port).inspect_err(|_| {
921 stats::bump(&stats::CONNECT_FAIL);
922 })?;
923 let t_hs0 = crate::kernel::timer::get_ticks();
924 let mut rng = OsRng::new();
925 let _ph = crate::os_lib::web_engine::perf::start();
926 let connected = crate::kernel::tls12::Tls12::connect(make_stream(local_port), host_only, &mut rng);
927 crate::os_lib::web_engine::perf::add(crate::os_lib::web_engine::perf::Slot::TlsHandshake, _ph);
928 match connected {
929 Ok(conn) => {
930 {
932 let mut s = TLS12_HOSTS.lock();
933 if !s.contains(host_only) {
934 s.insert(String::from(host_only));
935 }
936 }
937 Ok(PooledConn {
938 wire: Wire::V12(alloc::boxed::Box::new(conn)),
939 local_port,
940 remote_ip,
941 tcp_ticks: t_hs0.wrapping_sub(t_conn0),
942 tls_ticks: crate::kernel::timer::get_ticks().wrapping_sub(t_hs0),
943 })
944 }
945 Err(e) => {
946 crate::warn!("[NET] TLS 1.2 handshake error: {:?} host={}", e, host);
947 safe_tcp_close(local_port, "open_conn tls12 handshake fail");
948 stats::bump(&stats::HANDSHAKE_FAIL);
949 Err("TLS handshake failed")
950 }
951 }
952}
953
954struct Exchanged {
956 raw: Vec<u8>,
958 remote_ip: [u8; 4],
959 local_port: u16,
960 tls12: bool,
961 reused: bool,
963 tcp_ticks: usize,
964 tls_ticks: usize,
965 http_ticks: usize,
966}
967
968fn exchange(
977 host: &str,
978 host_only: &str,
979 port: u16,
980 retry_write: bool,
981 remote_ip: Option<[u8; 4]>,
982 request: &[u8],
983 head: bool,
984) -> Result<Exchanged, &'static str> {
985 let key = pool_key(host_only, port);
986 let mut try_pool = true;
987 loop {
988 if crate::kernel::window_mgr::kill_pending_for_current() {
991 return Err("stopped app");
992 }
993 if crate::kernel::sync_fetch::aborted() {
995 return Err(crate::kernel::sync_fetch::ABORT_ERR);
996 }
997 let pooled = if try_pool { pool_checkout(&key) } else { None };
998 let reused = pooled.is_some();
999 let mut conn = match pooled {
1000 Some(c) => {
1001 c.set_retry_write(retry_write);
1002 c
1003 }
1004 None => {
1005 let ip = match remote_ip {
1006 Some(ip) => ip,
1007 None => crate::kernel::net::dns_query_a_via_udp(host_only)?,
1008 };
1009 open_conn(ip, host, host_only, port, retry_write)?
1010 }
1011 };
1012 try_pool = false;
1014
1015 let t_http0 = crate::kernel::timer::get_ticks();
1016 if !conn.write_all(request) {
1017 drop(conn);
1018 if reused {
1019 POOL_STALE.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
1020 continue;
1021 }
1022 return Err("HTTPS request failed");
1023 }
1024 crate::kernel::net::tcp::wait_for_first_byte(conn.local_port, 50);
1027
1028 let mut raw = Vec::new();
1029 let mut chunk = [0u8; 1024];
1030 let mut framed = false;
1031 let mut reserved = false;
1032 loop {
1033 match conn.read(&mut chunk) {
1034 Ok(0) => break,
1035 Ok(n) => {
1036 raw.extend_from_slice(chunk.get(..n).unwrap_or(&[]));
1037 if !reserved && crate::kernel::http_body::body_start(&raw).is_some() {
1039 reserved = true;
1040 crate::kernel::http_body::reserve_for_body(&mut raw);
1041 }
1042 if crate::kernel::http_body::is_framed_complete(&raw)
1046 || (head && crate::kernel::http_body::body_start(&raw).is_some())
1047 {
1048 framed = true;
1049 break;
1050 }
1051 }
1052 Err(()) => break,
1053 }
1054 }
1055 if !framed && crate::kernel::sync_fetch::aborted() {
1057 drop(conn);
1058 return Err(crate::kernel::sync_fetch::ABORT_ERR);
1059 }
1060 if raw.is_empty() && reused {
1061 POOL_STALE.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
1063 drop(conn);
1064 continue;
1065 }
1066 let out = Exchanged {
1067 raw,
1068 remote_ip: conn.remote_ip,
1069 local_port: conn.local_port,
1070 tls12: conn.is_tls12(),
1071 reused,
1072 tcp_ticks: if reused { 0 } else { conn.tcp_ticks },
1073 tls_ticks: if reused { 0 } else { conn.tls_ticks },
1074 http_ticks: crate::kernel::timer::get_ticks().wrapping_sub(t_http0),
1075 };
1076 if reused {
1077 POOL_REUSED.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
1078 }
1079 if request.starts_with(b"GET ") {
1081 let path = request[4..].split(|&b| b == b' ').next().and_then(|p| core::str::from_utf8(p).ok());
1082 if let Some(path) = path {
1083 let end = out.raw.len().min(8192);
1084 let rule = crate::kernel::http_cache::disk_cache_rule_from_head(&out.raw[..end]);
1085 crate::kernel::http_cache::DISK_RULES
1086 .lock()
1087 .note_response(&alloc::format!("{}{}", host, path), rule);
1088 }
1089 }
1090 if framed && crate::kernel::http_body::connection_reusable(&out.raw, head) {
1091 pool_checkin(&key, conn);
1092 } else {
1093 drop(conn);
1094 }
1095 return Ok(out);
1096 }
1097}
1098
1099pub fn https_post(
1103 host: &str,
1104 path: &str,
1105 content_type: &str,
1106 body: &[u8],
1107) -> Result<crate::kernel::net::HttpsGetResult, &'static str> {
1108 https_request("POST", host, path, &[], content_type, Some(body))
1109}
1110
1111pub fn https_get_binary_keepalive(
1134 host: &str,
1135 paths: &[String],
1136) -> Result<Vec<Option<Vec<u8>>>, &'static str> {
1137 if paths.is_empty() {
1138 return Ok(Vec::new());
1139 }
1140
1141 let (host_only, port) = crate::kernel::net::parse_host_port_with_default(host, 443);
1142 let remote_ip = crate::kernel::net::dns::dns_query_a_via_udp(host_only)?;
1143
1144 let mut out: Vec<Option<Vec<u8>>> = Vec::with_capacity(paths.len());
1147 let mut broken = false;
1148 for path in paths.iter() {
1149 if broken {
1150 out.push(None);
1151 continue;
1152 }
1153 let req = alloc::format!(
1154 "GET {} HTTP/1.1\r\nHost: {}\r\nUser-Agent: Mozilla/5.0 (AtmOS Browser; gzip)\r\nAccept: */*\r\nAccept-Encoding: gzip\r\nConnection: keep-alive\r\n\r\n",
1155 path, host
1156 );
1157 let _sync = crate::kernel::sync_fetch::begin(host, path);
1160 let res = exchange(host, host_only, port, true, Some(remote_ip), req.as_bytes(), false);
1161 if let Ok(ex) = &res {
1162 crate::kernel::responsiveness::add(crate::kernel::responsiveness::Qty::NetRequests, 1);
1164 crate::kernel::responsiveness::add(crate::kernel::responsiveness::Qty::NetBytes, ex.raw.len() as u64);
1165 }
1166 match res {
1167 Ok(ex) if !response_looks_truncated(&ex.raw) => {
1168 stats::bump(&stats::OK);
1169 out.push(Some(crate::kernel::net::extract_http_body_binary(&ex.raw)));
1170 }
1171 Ok(_) => {
1172 stats::bump(&stats::TRUNCATED);
1173 out.push(None);
1174 broken = true;
1175 }
1176 Err(_) => {
1177 out.push(None);
1178 broken = true;
1179 }
1180 }
1181 }
1182 Ok(out)
1184}
1185
1186fn response_looks_truncated(raw: &[u8]) -> bool {
1199 !crate::kernel::http_body::is_complete_response(raw)
1206}
1207
1208pub fn https_get_binary(host: &str, path: &str) -> Result<Vec<u8>, &'static str> {
1209 https_get_binary_policy(host, path, true)
1210}
1211
1212pub fn https_get_binary_complete(host: &str, path: &str) -> Result<Vec<u8>, &'static str> {
1221 https_get_binary_policy(host, path, false)
1222}
1223
1224fn https_get_binary_policy(
1225 host: &str,
1226 path: &str,
1227 accept_partial: bool,
1228) -> Result<Vec<u8>, &'static str> {
1229 let _pg = crate::os_lib::web_engine::perf::start();
1230 let r = https_get_binary_measured(host, path, accept_partial);
1231 crate::os_lib::web_engine::perf::add(
1232 crate::os_lib::web_engine::perf::Slot::HttpsGet,
1233 _pg,
1234 );
1235 r
1236}
1237
1238fn https_get_binary_measured(
1239 host: &str,
1240 path: &str,
1241 accept_partial: bool,
1242) -> Result<Vec<u8>, &'static str> {
1243 const MAX_ATTEMPTS: u32 = 3;
1244 let _sync = crate::kernel::sync_fetch::begin(host, path);
1246 let ordinal = crate::kernel::net::next_https_attempt_ordinal();
1247 let (host_only, port) = crate::kernel::net::parse_host_port_with_default(host, 443);
1254 let remote_ip = crate::kernel::net::dns_query_a_via_udp(host_only).inspect_err(|e| {
1256 crate::warn!("[NET][DIAG] https_get_binary ordinal={} DNS FAILED err={}", ordinal, e);
1257 stats::bump(&stats::DNS_FAIL);
1258 stats::report("after-dns-fail");
1259 })?;
1260 let mut best: Option<Vec<u8>> = None;
1262 for attempt in 1..=MAX_ATTEMPTS {
1263 let resume = best.as_deref().and_then(crate::kernel::http_body::resume_offset);
1266 match https_get_binary_attempt(remote_ip, host, host_only, port, path, resume) {
1267 Ok((raw, complete)) => {
1268 let (raw, complete) = match (resume, best.as_deref()) {
1269 (Some(off), Some(prev)) => {
1270 match crate::kernel::http_body::merge_range_response(prev, off, &raw) {
1271 Some(merged) => {
1272 let done = !crate::kernel::http_body::looks_truncated(&merged);
1273 (merged, done)
1278 }
1279 None => (raw, complete),
1281 }
1282 }
1283 _ => (raw, complete),
1284 };
1285 if complete {
1286 return Ok(crate::kernel::net::extract_http_body_binary(&raw));
1291 }
1292 crate::warn!(
1293 "[NET][DIAG] https_get_binary ordinal={}: truncated response on attempt {}/{} ({} bytes), retrying",
1294 ordinal, attempt, MAX_ATTEMPTS, raw.len()
1295 );
1296 if best.as_ref().is_none_or(|b: &Vec<u8>| raw.len() > b.len()) {
1297 best = Some(raw);
1298 }
1299 }
1300 Err(e) => {
1301 crate::warn!(
1302 "[NET][DIAG] https_get_binary ordinal={} attempt {}/{} FAILED err={}",
1303 ordinal, attempt, MAX_ATTEMPTS, e
1304 );
1305 if attempt == MAX_ATTEMPTS || crate::kernel::sync_fetch::aborted() {
1307 return Err(e);
1308 }
1309 }
1310 }
1311 }
1312 match best {
1315 Some(raw) if accept_partial => Ok(crate::kernel::net::extract_http_body_binary(&raw)),
1316 Some(raw) => {
1317 crate::warn!(
1318 "[NET][DIAG] https_get_binary ordinal={} 全 {} 回とも途中で切れたため不採用 (best={} bytes)",
1319 ordinal, MAX_ATTEMPTS, raw.len()
1320 );
1321 Err("HTTPS response truncated")
1322 }
1323 None => Err("HTTPS request failed"),
1324 }
1325}
1326
1327fn https_get_binary_attempt(
1336 remote_ip: [u8; 4],
1337 host: &str,
1338 host_only: &str,
1339 port: u16,
1340 path: &str,
1341 range_from: Option<usize>,
1342) -> Result<(Vec<u8>, bool), &'static str> {
1343 let range_hdr = range_from
1344 .map(|n| alloc::format!("Range: bytes={}-\r\n", n))
1345 .unwrap_or_default();
1346 let accept_encoding = if range_from.is_some() { "identity" } else { "gzip" };
1348 let request = alloc::format!("GET {} HTTP/1.1\r\nHost: {}\r\nUser-Agent: Mozilla/5.0 (AtmOS Browser; gzip)\r\nAccept: */*\r\nAccept-Encoding: {}\r\n{}Connection: keep-alive\r\n\r\n", path, host, accept_encoding, range_hdr);
1349
1350 let ex = exchange(host, host_only, port, true, Some(remote_ip), request.as_bytes(), false)?;
1351 let body_bytes = ex.raw;
1352
1353 crate::kernel::responsiveness::add(crate::kernel::responsiveness::Qty::NetRequests, 1);
1355 crate::kernel::responsiveness::add(crate::kernel::responsiveness::Qty::NetBytes, body_bytes.len() as u64);
1356 let complete = !response_looks_truncated(&body_bytes);
1368 if complete {
1371 stats::bump(&stats::OK);
1372 } else {
1373 stats::bump(&stats::TRUNCATED);
1374 crate::warn!(
1375 "[NET][DIAG] 途中切れ host={} bytes={} preview={:?}",
1376 host,
1377 body_bytes.len(),
1378 String::from_utf8_lossy(body_bytes.get(..body_bytes.len().min(80)).unwrap_or(&[]))
1379 );
1380 }
1381 Ok((body_bytes, complete))
1383}
1384
1385static TLS13_HOSTS: spin::Mutex<alloc::collections::BTreeSet<String>> =
1387 spin::Mutex::new(alloc::collections::BTreeSet::new());
1388static TLS12_HOSTS: spin::Mutex<alloc::collections::BTreeSet<String>> =
1390 spin::Mutex::new(alloc::collections::BTreeSet::new());
1391
1392fn tls13_hosts_contains(host: &str) -> bool {
1393 TLS13_HOSTS.lock().contains(host)
1394}
1395
1396fn tls13_hosts_insert(host: &str) {
1397 let mut s = TLS13_HOSTS.lock();
1398 if !s.contains(host) {
1399 s.insert(String::from(host));
1400 }
1401}
1402
1403fn tls12_hosts_contains(host: &str) -> bool {
1404 TLS12_HOSTS.lock().contains(host)
1405}