Skip to main content

atmos/kernel/net/
http.rs

1use alloc::string::String;
2use alloc::vec::Vec;
3use super::addr_util::parse_host_port;
4
5fn http_raw_request(
6    host: &str,
7    port: u16,
8    raw_request: &[u8],
9) -> Result<alloc::vec::Vec<u8>, &'static str> {
10    // アプリのスレッドの同期の取得なら全体に上限を置く(TODO R3。`kernel::sync_fetch`)。記録の URL のパスは要求の 1 行目から取る。
11    let req_path = raw_request
12        .split(|&b| b == b'\r')
13        .next()
14        .and_then(|line| core::str::from_utf8(line).ok())
15        .and_then(|line| line.split(' ').nth(1))
16        .unwrap_or("");
17    let _sync = crate::kernel::sync_fetch::begin(host, req_path);
18    let remote_ip = super::dns::dns_query_a_via_udp(host)?;
19    let local_port = super::tcp::tcp_connect_real(remote_ip, port)?;
20    super::tcp::tcp_send_real(local_port, raw_request)?;
21    // 【2026-08-05】無条件 500ms から「届いたら即抜ける」へ(上限は同じ)。
22    // 詳細は `net::tcp::wait_for_first_byte`。
23    crate::kernel::net::tcp::wait_for_first_byte(local_port, 50);
24
25    // FIN を受けるか応答が完結する(Content-Length / chunked 終端)まで読む。
26    // 【2026-10-17】従来は受信を最大 100 回で打ち切っており(1 回あたり数 KB)、約 877KB を
27    // 超える応答(動画セグメント等)が黙って途中で切れていた。進捗が止まった場合だけ抜ける。
28    let mut body_bytes = alloc::vec::Vec::new();
29    let mut idle_rounds = 0u32;
30    loop {
31        // 止めたアプリの背景のスレッドは、接続を閉じて失敗を返す(TODO R2 (c))。アプリのスレッド本人はその場で終わる。
32        if crate::kernel::window_mgr::abort_wait_if_stopped(|| {
33            let _ = super::tcp::tcp_close_real(local_port);
34        }) {
35            let _ = super::tcp::tcp_close_real(local_port);
36            return Err("stopped app");
37        }
38        let chunk = super::tcp::tcp_recv_real(local_port, 20000)?;
39        if chunk.is_empty() {
40            idle_rounds += 1;
41        } else {
42            idle_rounds = 0;
43            crate::kernel::sync_fetch::note_received(chunk.len());
44            body_bytes.extend(chunk);
45        }
46        // 全体の上限を超えた同期の取得は打ち切って失敗にする(TODO R3)。
47        if crate::kernel::sync_fetch::over_limit() {
48            let _ = super::tcp::tcp_close_real(local_port);
49            return Err(crate::kernel::sync_fetch::ABORT_ERR);
50        }
51        let fin_recvd = unsafe {
52            match super::tcp::tcp_find_socket_by_local(local_port) {
53                Some(idx) => super::TCP_SOCKETS[idx].fin_received,
54                None => true,
55            }
56        };
57        // 1 回の受信待ちは最大 5 秒なので、3 回続けて何も来なければ打ち切る。
58        if fin_recvd || idle_rounds >= 3 || crate::kernel::http_body::is_complete_response(&body_bytes) {
59            break;
60        }
61        if body_bytes.len() > 256 * 1024 * 1024 {
62            break;
63        }
64    }
65    super::tcp::tcp_close_real(local_port)?;
66    Ok(body_bytes)
67}
68
69pub fn http_get_real(host: &str, path: &str) -> Result<super::HttpGetResult, &'static str> {
70    http_get_real_with_referer(host, path, None)
71}
72
73/// `Referer` ヘッダ付きの GET(`None` なら付けない。リダイレクト先にも同じ値を送る)。
74pub fn http_get_real_with_referer(
75    host: &str,
76    path: &str,
77    referer: Option<&str>,
78) -> Result<super::HttpGetResult, &'static str> {
79    if host.is_empty() {
80        return Err("host is empty");
81    }
82    if !path.starts_with('/') {
83        return Err("path must start with '/'");
84    }
85
86    let mut current_host = alloc::string::String::from(host);
87    let mut current_path = alloc::string::String::from(path);
88    let mut redirects = 0u8;
89
90    loop {
91        let referer_hdr = referer.map(|r| alloc::format!("Referer: {}\r\n", r)).unwrap_or_default();
92        let request = alloc::format!(
93            "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: close\r\n\r\n",
94            current_path, current_host, referer_hdr
95        );
96        let (host_only, port) = parse_host_port(&current_host);
97        let remote_ip = super::dns::dns_query_a_via_udp(host_only)?;
98        let body_bytes = http_raw_request(host_only, port, request.as_bytes())?;
99        // 平文の HTTP の文書の GET も `[PERF][SUMMARY]` の GET に数える(2026-11-16)。
100        crate::kernel::responsiveness::add(crate::kernel::responsiveness::Qty::NetRequests, 1);
101        crate::kernel::responsiveness::add(crate::kernel::responsiveness::Qty::NetBytes, body_bytes.len() as u64);
102
103        let resp_str = alloc::string::String::from_utf8_lossy(&body_bytes).into_owned();
104        // バイト列のまま chunked を解いてから文字列にする(`parse_http_response_text` の doc)。
105        let (status_code, reason, headers, body) = parse_http_response_text(&body_bytes).unwrap_or((
106            200,
107            alloc::string::String::from("OK"),
108            alloc::collections::BTreeMap::new(),
109            resp_str,
110        ));
111
112        if (status_code == 301
113            || status_code == 302
114            || status_code == 303
115            || status_code == 307
116            || status_code == 308)
117            && redirects < 5
118        {
119            if let Some(location) = headers.get("location") {
120                let loc = location.trim();
121                if let Some(rest) = loc.strip_prefix("http://") {
122                    if let Some(slash) = rest.find('/') {
123                        let (h, p) = rest.split_at(slash);
124                        current_host = alloc::string::String::from(h);
125                        current_path = alloc::string::String::from(p);
126                    } else {
127                        current_host = alloc::string::String::from(rest);
128                        current_path = alloc::string::String::from("/");
129                    }
130                    redirects += 1;
131                    continue;
132                } else if loc.starts_with('/') {
133                    current_path = alloc::string::String::from(loc);
134                    redirects += 1;
135                    continue;
136                }
137            }
138        }
139
140        let raw_body = parse_http_response_bytes(&body_bytes).map(|r| r.3).unwrap_or_default();
141        return Ok(super::HttpGetResult {
142            remote_ip,
143            local_port: 80,
144            status_code,
145            reason,
146            headers,
147            body,
148            body_bytes: raw_body,
149        });
150    }
151}
152
153pub fn http_post_real(
154    host: &str,
155    path: &str,
156    content_type: &str,
157    body: &[u8],
158) -> Result<super::HttpGetResult, &'static str> {
159    http_request_real("POST", host, path, content_type, body)
160}
161
162/// 任意メソッド(GET/POST/PUT/DELETE/PATCH 等)の平文 HTTP リクエスト。
163/// body が空かつ GET/HEAD/DELETE 等の場合は Content-Type / Content-Length を付けない。
164/// メソッドは呼び出し側で検証済み(英大文字トークン)である前提。
165/// CRLF はエスケープ事故を避けるためバイト値で組み立てる。
166pub fn http_request_real(
167    method: &str,
168    host: &str,
169    path: &str,
170    content_type: &str,
171    body: &[u8],
172) -> Result<super::HttpGetResult, &'static str> {
173    if host.is_empty() {
174        return Err("host is empty");
175    }
176    if !path.starts_with('/') {
177        return Err("path must start with '/'");
178    }
179
180    const CRLF: [u8; 2] = [13, 10];
181    let mut request: Vec<u8> = Vec::new();
182    let push_line = |req: &mut Vec<u8>, s: &str| {
183        req.extend_from_slice(s.as_bytes());
184        req.extend_from_slice(&CRLF);
185    };
186    push_line(
187        &mut request,
188        &alloc::format!("{} {} HTTP/1.1", method, path),
189    );
190    push_line(&mut request, &alloc::format!("Host: {}", host));
191    push_line(&mut request, "User-Agent: Mozilla/5.0 (AtmOS Browser; gzip)");
192    push_line(&mut request, "Accept-Encoding: gzip");
193    // ボディがある、またはボディを取り得るメソッドでは Content-* を付与する。
194    let send_body = !body.is_empty() || method == "POST" || method == "PUT" || method == "PATCH";
195    if send_body {
196        push_line(
197            &mut request,
198            &alloc::format!("Content-Type: {}", content_type),
199        );
200        push_line(
201            &mut request,
202            &alloc::format!("Content-Length: {}", body.len()),
203        );
204    }
205    push_line(&mut request, "Connection: close");
206    request.extend_from_slice(&CRLF);
207    request.extend_from_slice(body);
208
209    let (host_only, port) = parse_host_port(host);
210    let remote_ip = super::dns::dns_query_a_via_udp(host_only)?;
211    let raw = http_raw_request(host_only, port, &request)?;
212    // 平文の HTTP の XHR・`fetch`・POST(`[PERF][SUMMARY]`。2026-11-16)。
213    crate::kernel::responsiveness::add(crate::kernel::responsiveness::Qty::XhrRequests, 1);
214    crate::kernel::responsiveness::add(crate::kernel::responsiveness::Qty::XhrBytes, raw.len() as u64);
215    let resp_str = alloc::string::String::from_utf8_lossy(&raw).into_owned();
216    let (status_code, reason, headers, resp_body) = parse_http_response_text(&raw).unwrap_or((
217        200,
218        alloc::string::String::from("OK"),
219        alloc::collections::BTreeMap::new(),
220        resp_str,
221    ));
222
223    let body_bytes = parse_http_response_bytes(&raw).map(|r| r.3).unwrap_or_default();
224    Ok(super::HttpGetResult {
225        remote_ip,
226        local_port: port,
227        status_code,
228        reason,
229        headers,
230        body: resp_body,
231        body_bytes,
232    })
233}
234
235pub fn extract_http_body_binary(raw: &[u8]) -> alloc::vec::Vec<u8> {
236    let mut header_end = 0usize;
237    if raw.len() >= 4 {
238        for i in 0..(raw.len() - 3) {
239            if raw[i] == b'\r' && raw[i + 1] == b'\n' && raw[i + 2] == b'\r' && raw[i + 3] == b'\n'
240            {
241                header_end = i + 4;
242                break;
243            }
244        }
245    }
246    if header_end == 0 {
247        return raw.to_vec();
248    }
249    let header = &raw[..header_end];
250    let body = &raw[header_end..];
251
252    let is_chunked = {
253        let mut found = false;
254        if let Ok(h) = core::str::from_utf8(header) {
255            let hl = h.to_ascii_lowercase();
256            if let Some(p) = hl.find("transfer-encoding:") {
257                let rest = hl.get(p..).unwrap_or("");
258                let line_end = rest.find("\r\n").unwrap_or(rest.len());
259                if rest.get(..line_end).unwrap_or("").contains("chunked") {
260                    found = true;
261                }
262            }
263        }
264        found
265    };
266
267    if !is_chunked {
268        return crate::kernel::http_body::decode_content(header, body.to_vec());
269    }
270
271    let mut out = alloc::vec::Vec::new();
272    let mut i = 0usize;
273    while i < body.len() {
274        let mut j = i;
275        while j + 1 < body.len() && !(body[j] == b'\r' && body[j + 1] == b'\n') {
276            j += 1;
277        }
278        if j + 1 >= body.len() {
279            break;
280        }
281        let size_str = core::str::from_utf8(&body[i..j]).unwrap_or("");
282        let size_hex = size_str.split(';').next().unwrap_or("").trim();
283        let size = usize::from_str_radix(size_hex, 16).unwrap_or(0);
284        let data_start = j + 2;
285        if size == 0 {
286            break;
287        }
288        let data_end = match data_start.checked_add(size) {
289            Some(end) => end,
290            None => {
291                out.extend_from_slice(&body[data_start..body.len()]);
292                break;
293            }
294        };
295        if data_end > body.len() {
296            out.extend_from_slice(&body[data_start..body.len()]);
297            break;
298        }
299        out.extend_from_slice(&body[data_start..data_end]);
300        match data_end.checked_add(2) {
301            Some(next_i) => i = next_i,
302            None => break,
303        }
304    }
305    crate::kernel::http_body::decode_content(header, out)
306}
307
308pub fn http_get_binary(host: &str, path: &str) -> Result<alloc::vec::Vec<u8>, &'static str> {
309    if host.is_empty() {
310        return Err("host is empty");
311    }
312    if !path.starts_with('/') {
313        return Err("path must start with '/'");
314    }
315
316    let (host_only, port) = parse_host_port(host);
317    let request = alloc::format!("GET {} HTTP/1.1\r\nHost: {}\r\nUser-Agent: Mozilla/5.0 (AtmOS Browser; gzip)\r\nAccept: */*\r\nAccept-Encoding: gzip\r\nConnection: close\r\n\r\n", path, host);
318    // 【2026-11-16】受信は `http_raw_request` と同じ(応答が完結する・FIN・進みが止まるまで読む)。
319    // 以前はここだけ受信を 100 回で打ち切っており、ローカルの試験ページ(数 MB の JS・CSS を平文の HTTP で
320    // 配る。TODO P9)が途中で切れるおそれがあった。
321    let body_bytes = http_raw_request(host_only, port, request.as_bytes())?;
322    // 平文の HTTP の部品の GET(`[PERF][SUMMARY]`。2026-11-16)。
323    crate::kernel::responsiveness::add(crate::kernel::responsiveness::Qty::NetRequests, 1);
324    crate::kernel::responsiveness::add(crate::kernel::responsiveness::Qty::NetBytes, body_bytes.len() as u64);
325
326    Ok(extract_http_body_binary(&body_bytes))
327}
328
329pub fn https_get_real(host: &str, path: &str) -> Result<super::HttpsGetResult, &'static str> {
330    crate::kernel::tls::https_get(host, path)
331}
332
333pub fn parse_http_response(
334    response: &str,
335) -> Result<
336    (
337        u16,
338        alloc::string::String,
339        alloc::collections::BTreeMap<alloc::string::String, alloc::string::String>,
340        alloc::string::String,
341    ),
342    &'static str,
343> {
344    let (head, body) = match response.split_once("\r\n\r\n") {
345        Some(parts) => parts,
346        None => return Err("http response malformed"),
347    };
348
349    let mut lines = head.split("\r\n");
350    let status_line = lines.next().ok_or("http status line missing")?;
351
352    let mut parts = status_line.splitn(3, ' ');
353    let version = parts.next().ok_or("http status line malformed")?;
354    if !version.starts_with("HTTP/") {
355        return Err("http version invalid");
356    }
357
358    let code_s = parts.next().ok_or("http status code missing")?;
359    let status_code = parse_decimal_u16(code_s).ok_or("http status code invalid")?;
360    let reason = alloc::string::String::from(parts.next().unwrap_or(""));
361
362    let mut headers = alloc::collections::BTreeMap::new();
363    for line in lines {
364        if let Some((k, v)) = line.split_once(':') {
365            headers.insert(
366                k.trim().to_lowercase(),
367                alloc::string::String::from(v.trim()),
368            );
369        }
370    }
371
372    if let Some(enc) = headers.get("transfer-encoding") {
373        if enc.to_lowercase().contains("chunked") {
374            let bytes = body.as_bytes();
375            let mut decoded: alloc::vec::Vec<u8> = alloc::vec::Vec::new();
376            let mut i = 0usize;
377            while i < bytes.len() {
378                let mut j = i;
379                while j + 1 < bytes.len() && !(bytes[j] == b'\r' && bytes[j + 1] == b'\n') {
380                    j += 1;
381                }
382                if j + 1 >= bytes.len() {
383                    break;
384                }
385                let size_str = core::str::from_utf8(&bytes[i..j]).unwrap_or("");
386                let size_hex = size_str.split(';').next().unwrap_or("").trim();
387                let size = usize::from_str_radix(size_hex, 16).unwrap_or(0);
388                if size == 0 {
389                    break;
390                }
391                let data_start = j + 2;
392                let data_end = data_start + size;
393                if data_end > bytes.len() {
394                    decoded.extend_from_slice(&bytes[data_start..]);
395                    break;
396                }
397                decoded.extend_from_slice(&bytes[data_start..data_end]);
398                i = data_end + 2;
399            }
400            let decoded_str = alloc::string::String::from_utf8_lossy(&decoded).into_owned();
401            return Ok((status_code, reason, headers, decoded_str));
402        }
403    }
404
405    Ok((
406        status_code,
407        reason,
408        headers,
409        alloc::string::String::from(body),
410    ))
411}
412
413fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
414    if needle.is_empty() || haystack.len() < needle.len() {
415        return None;
416    }
417    haystack.windows(needle.len()).position(|w| w == needle)
418}
419
420/// 応答の生バイト列を解析し、本文を**バイト列のまま** chunked を解いてから文字列にする。
421///
422/// 【2026-10-16】従来の経路は応答全体を先に `from_utf8_lossy` で文字列にしてから
423/// `parse_http_response` で chunked を解いていた。chunked の区切りは UTF-8 の多バイト文字の
424/// 途中にも入るため、その不正バイトが置換文字(3 バイト)に化けてバイト位置がずれ、本文が
425/// 途中で切れた(sugi-lab.net の papers.json 150,481 B → 129,615 B。区切り位置は通信ごとに
426/// 変わるので約 3 回に 1 回、jQuery の JSON 解析が黙って失敗して論文リストが出なかった)。
427/// 解析できなければ応答全体を文字列にして 200 として返す(従来の `unwrap_or` と同じ)。
428pub fn parse_http_response_text(
429    response: &[u8],
430) -> Result<
431    (
432        u16,
433        alloc::string::String,
434        alloc::collections::BTreeMap<alloc::string::String, alloc::string::String>,
435        alloc::string::String,
436    ),
437    &'static str,
438> {
439    let (status, reason, headers, body) = parse_http_response_bytes(response)?;
440    Ok((status, reason, headers, alloc::string::String::from_utf8_lossy(&body).into_owned()))
441}
442
443/// `parse_http_response` のバイト保存版。ヘッダ部分は ASCII 前提で文字列化するが、
444/// ボディは `extract_http_body_binary` の chunked 復号をそのまま使い、ロスの無い
445/// 生バイト列で返す(画像/zip 等のバイナリダウンロード向け)。
446/// 戻り値: (status_code, reason, headers, body_bytes)
447pub fn parse_http_response_bytes(
448    response: &[u8],
449) -> Result<
450    (
451        u16,
452        alloc::string::String,
453        alloc::collections::BTreeMap<alloc::string::String, alloc::string::String>,
454        alloc::vec::Vec<u8>,
455    ),
456    &'static str,
457> {
458    let split_at = find_subslice(response, b"\r\n\r\n").ok_or("http response malformed")?;
459    let head = &response[..split_at];
460
461    let head_str = core::str::from_utf8(head).map_err(|_| "http header not utf8")?;
462    let mut lines = head_str.split("\r\n");
463    let status_line = lines.next().ok_or("http status line missing")?;
464
465    let mut parts = status_line.splitn(3, ' ');
466    let version = parts.next().ok_or("http status line malformed")?;
467    if !version.starts_with("HTTP/") {
468        return Err("http version invalid");
469    }
470
471    let code_s = parts.next().ok_or("http status code missing")?;
472    let status_code = parse_decimal_u16(code_s).ok_or("http status code invalid")?;
473    let reason = alloc::string::String::from(parts.next().unwrap_or(""));
474
475    let mut headers = alloc::collections::BTreeMap::new();
476    for line in lines {
477        if let Some((k, v)) = line.split_once(':') {
478            headers.insert(
479                k.trim().to_lowercase(),
480                alloc::string::String::from(v.trim()),
481            );
482        }
483    }
484
485    // ボディ(chunked なら復号済み)の抽出は既存のバイナリ安全ヘルパーに委譲。
486    let body = extract_http_body_binary(response);
487
488    Ok((status_code, reason, headers, body))
489}
490
491
492
493fn build_http_get_request(host: &str, path: &str) -> Result<String, &'static str> {
494    if host.is_empty() {
495        return Err("host is empty");
496    }
497    if !path.starts_with('/') {
498        return Err("path must start with '/'");
499    }
500
501    Ok(alloc::format!(
502        "GET {} HTTP/1.1\r\nHost: {}\r\nUser-Agent: AtmOS/0.1\r\nAccept-Encoding: identity\r\nConnection: close\r\n\r\n",
503        path,
504        host
505    ))
506}
507
508
509
510fn parse_decimal_u16(s: &str) -> Option<u16> {
511    let mut val: u16 = 0;
512    if s.is_empty() {
513        return None;
514    }
515
516    for ch in s.chars() {
517        if !ch.is_ascii_digit() {
518            return None;
519        }
520        val = val
521            .checked_mul(10)?
522            .checked_add((ch as u16) - ('0' as u16))?;
523    }
524
525    Some(val)
526}
527
528
529// pub(super) wrappers for self_test() in mod.rs
530pub(crate) fn build_http_get_request_pub(host: &str, path: &str) -> Result<String, &'static str> {
531    build_http_get_request(host, path)
532}
533
534