Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

23.3 KB
Raw Blame
//! A small blocking HTTP/1.1 client for `fetch`: keep-alive pool, redirects with the Fetch
//! standard's rules, chunked bodies and content decoding. Runs on worker threads.

use std::io::{Read, Write};
use std::sync::Mutex;
use std::time::{Duration, Instant};

use crate::conn::{self, Cancel, Conn, Endpoint, NetError, Purpose, Stream};

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum RedirectMode {
    Follow,
    Error,
    Manual,
}

pub struct Request {
    pub method: String,
    pub url: String,
    /// Header names and values as Latin-1 byte strings, in the page's order.
    pub headers: Vec<(String, String)>,
    pub body: Option<Vec<u8>>,
    pub redirect: RedirectMode,
}

pub struct Head {
    pub status: u16,
    pub status_text: String,
    /// Lower-case names, in arrival order (`set-cookie` removed, as in browsers).
    pub headers: Vec<(String, String)>,
    pub url: String,
    pub redirected: bool,
    /// `redirect: "manual"` met a redirect: an opaque-redirect response.
    pub opaque_redirect: bool,
}

/// A parsed absolute http(s) URL (the page already normalised it with its URL class).
#[derive(Clone, Debug)]
pub struct Url {
    pub ep: Endpoint,
    /// path + query, never empty, no fragment
    pub target: String,
}

impl Url {
    pub fn parse(s: &str) -> Result<Url, NetError> {
        let bad = || NetError::new("ERR_INVALID_URL", s.to_string());
        let (scheme, rest) = s.split_once("://").ok_or_else(bad)?;
        let tls = match scheme.to_ascii_lowercase().as_str() {
            "http" | "ws" => false,
            "https" | "wss" => true,
            _ => return Err(NetError::new("ERR_UNKNOWN_URL_SCHEME", s.to_string())),
        };
        let rest = rest.split('#').next().unwrap_or("");
        let end = rest.find(['/', '?']).unwrap_or(rest.len());
        let authority = rest[..end].rsplit('@').next().unwrap_or("");
        let mut target = rest[end..].to_string();
        if !target.starts_with('/') {
            target.insert(0, '/');
        }
        let (host, port) = if let Some(h) = authority.strip_prefix('[') {
            let (h, p) = h.split_once(']').ok_or_else(bad)?;
            (h.to_string(), p.strip_prefix(':').unwrap_or(""))
        } else {
            match authority.rsplit_once(':') {
                Some((h, p)) => (h.to_string(), p),
                None => (authority.to_string(), ""),
            }
        };
        if host.is_empty() {
            return Err(bad());
        }
        let port = if port.is_empty() { if tls { 443 } else { 80 } } else { port.parse().map_err(|_| bad())? };
        Ok(Url { ep: Endpoint { tls, host: host.to_ascii_lowercase(), port }, target })
    }

    pub fn origin(&self) -> String {
        format!("{}://{}", if self.ep.tls { "https" } else { "http" }, self.ep.authority(false))
    }

    pub fn href(&self) -> String {
        format!("{}{}", self.origin(), self.target)
    }

    /// Resolve a `Location` header against this URL.
    pub fn join(&self, loc: &str) -> Option<String> {
        let loc = loc.trim();
        let loc = loc.split('#').next().unwrap_or("");
        let has_scheme = loc.find(':').is_some_and(|i| {
            i > 0 && loc[..i].bytes().all(|b| b.is_ascii_alphanumeric() || b == b'+' || b == b'-' || b == b'.') && loc.as_bytes()[0].is_ascii_alphabetic()
        });
        let abs = if has_scheme {
            loc.to_string()
        } else if loc.starts_with("//") {
            format!("{}:{loc}", if self.ep.tls { "https" } else { "http" })
        } else if loc.starts_with('/') {
            format!("{}{}", self.origin(), normalize(loc))
        } else if loc.starts_with('?') {
            let path = self.target.split('?').next().unwrap_or("/");
            format!("{}{path}{loc}", self.origin())
        } else if loc.is_empty() {
            self.href()
        } else {
            let path = self.target.split('?').next().unwrap_or("/");
            let dir = &path[..path.rfind('/').map(|i| i + 1).unwrap_or(0)];
            format!("{}{}", self.origin(), normalize(&format!("{dir}{loc}")))
        };
        Some(percent_encode_non_ascii(&abs))
    }
}

/// Resolve `.` and `..` segments in the path part.
fn normalize(path_and_query: &str) -> String {
    let (path, query) = match path_and_query.find('?') {
        Some(i) => path_and_query.split_at(i),
        None => (path_and_query, ""),
    };
    let mut out: Vec<&str> = Vec::new();
    let segs: Vec<&str> = path.split('/').skip(1).collect();
    for (i, seg) in segs.iter().enumerate() {
        let last = i + 1 == segs.len();
        match *seg {
            "." => {
                if last {
                    out.push("");
                }
            }
            ".." => {
                out.pop();
                if last {
                    out.push("");
                }
            }
            s => out.push(s),
        }
    }
    format!("/{}{query}", out.join("/"))
}

fn percent_encode_non_ascii(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        if b >= 0x80 || b == b' ' || b < 0x20 {
            out.push_str(&format!("%{b:02X}"));
        } else {
            out.push(b as char);
        }
    }
    out
}

// ---------------------------------------------------------------- keep-alive pool

struct Idle {
    key: String,
    stream: Stream,
    since: Instant,
}

static POOL: Mutex<Vec<Idle>> = Mutex::new(Vec::new());
const IDLE_TTL: Duration = Duration::from_secs(30);
const POOL_MAX: usize = 16;

/// The most recently used idle connection for `prefix` (an origin; any proxy route).
fn pool_take(prefix: &str) -> Option<(String, Stream)> {
    let mut pool = POOL.lock().unwrap();
    pool.retain(|c| c.since.elapsed() < IDLE_TTL);
    let matches = |k: &str| k == prefix || k.strip_prefix(prefix).is_some_and(|r| r.starts_with('|'));
    while let Some(i) = pool.iter().rposition(|c| matches(&c.key)) {
        let c = pool.remove(i);
        if conn::idle_socket_alive(c.stream.tcp()) {
            return Some((c.key, c.stream));
        }
    }
    None
}

/// Drop idle connections (the network changed under them).
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub fn clear_pool() {
    POOL.lock().unwrap().clear();
}

fn pool_put(key: String, stream: Stream) {
    let mut pool = POOL.lock().unwrap();
    if pool.len() >= POOL_MAX {
        pool.remove(0);
    }
    pool.push(Idle { key, stream, since: Instant::now() });
}

// ---------------------------------------------------------------- one exchange

enum Framing {
    None,
    Length(u64),
    Chunked,
    UntilClose,
}

struct Response {
    status: u16,
    reason: String,
    headers: Vec<(String, String)>,
    stream: Stream,
    key: String,
    /// bytes read past the head
    buf: Vec<u8>,
    framing: Framing,
    keep_alive: bool,
}

fn latin1(b: &[u8]) -> String {
    b.iter().map(|&c| c as char).collect()
}

fn to_bytes(s: &str) -> Vec<u8> {
    s.chars().map(|c| if (c as u32) < 256 { c as u8 } else { b'?' }).collect()
}

fn header<'a>(h: &'a [(String, String)], name: &str) -> Option<&'a str> {
    h.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str())
}

fn send_request(conn: &mut Conn, url: &Url, method: &str, headers: &[(String, String)], body: Option<&[u8]>) -> std::io::Result<()> {
    let target = if conn.absolute_form { url.href() } else { url.target.clone() };
    let mut head = Vec::with_capacity(512);
    head.extend_from_slice(format!("{method} {target} HTTP/1.1\r\nHost: {}\r\n", url.ep.authority(false)).as_bytes());
    let has = |name: &str| headers.iter().any(|(k, _)| k.eq_ignore_ascii_case(name));
    let (has_ua, has_accept) = (has("user-agent"), has("accept"));
    head.extend_from_slice(b"Connection: keep-alive\r\n");
    if !has_ua {
        head.extend_from_slice(format!("User-Agent: {}\r\n", crate::user_agent()).as_bytes());
    }
    if !has_accept {
        head.extend_from_slice(b"Accept: */*\r\n");
    }
    head.extend_from_slice(b"Accept-Encoding: gzip, deflate, br\r\n");
    for (k, v) in headers {
        head.extend_from_slice(&to_bytes(k));
        head.extend_from_slice(b": ");
        head.extend_from_slice(&to_bytes(v));
        head.extend_from_slice(b"\r\n");
    }
    // Chromium sends a length for every body, and `0` for bodiless POST/PUT/PATCH.
    let needs_len = body.is_some() || matches!(method, "POST" | "PUT" | "PATCH");
    if needs_len {
        head.extend_from_slice(format!("Content-Length: {}\r\n", body.map_or(0, |b| b.len())).as_bytes());
    }
    head.extend_from_slice(b"\r\n");
    let s = &mut conn.stream;
    match body {
        Some(b) if b.len() <= 64 * 1024 => {
            head.extend_from_slice(b);
            s.write_all(&head)?;
        }
        Some(b) => {
            s.write_all(&head)?;
            s.write_all(b)?;
        }
        None => s.write_all(&head)?,
    }
    s.flush()
}

fn read_head(stream: &mut Stream, cancel: &Cancel) -> Result<(u16, String, Vec<(String, String)>, u8, Vec<u8>), NetError> {
    let mut buf: Vec<u8> = Vec::with_capacity(8192);
    let mut chunk = [0u8; 16 * 1024];
    loop {
        let mut hs = [httparse::EMPTY_HEADER; 128];
        let mut r = httparse::Response::new(&mut hs);
        match r.parse(&buf) {
            Ok(httparse::Status::Complete(n)) => {
                let headers = r.headers.iter().map(|h| (h.name.to_ascii_lowercase(), latin1(h.value).trim().to_string())).collect();
                let rest = buf[n..].to_vec();
                return Ok((r.code.unwrap_or(0), r.reason.unwrap_or("").to_string(), headers, r.version.unwrap_or(1), rest));
            }
            Ok(httparse::Status::Partial) => {}
            Err(e) => return Err(NetError::new("ERR_INVALID_HTTP_RESPONSE", e.to_string())),
        }
        if buf.len() > 256 * 1024 {
            return Err(NetError::new("ERR_RESPONSE_HEADERS_TOO_BIG", ""));
        }
        let n = stream.read(&mut chunk).map_err(|e| if cancel.is_cancelled() { NetError::aborted() } else { NetError::io(&e) })?;
        if n == 0 {
            let code = if buf.is_empty() { "ERR_EMPTY_RESPONSE" } else { "ERR_CONNECTION_CLOSED" };
            return Err(NetError::new(code, ""));
        }
        buf.extend_from_slice(&chunk[..n]);
    }
}

/// Send one request and read the response head (1xx responses skipped). A reused connection
/// that fails before any response byte is retried once on a fresh one, as Chromium does.
fn exchange(url: &Url, method: &str, headers: &[(String, String)], body: Option<&[u8]>, cancel: &Cancel) -> Result<Response, NetError> {
    let mut attempt = 0;
    loop {
        attempt += 1;
        cancel.check()?;
        // The pool key includes the proxy route chosen by `connect`; match any route.
        let prefix = format!("{}://{}", if url.ep.tls { "https" } else { "http" }, url.ep.authority(true));
        let pooled = if attempt == 1 { pool_take(&prefix) } else { None };
        let reused = pooled.is_some();
        let mut conn = match pooled {
            Some((key, stream)) => {
                cancel.watch(stream.tcp())?;
                let absolute_form = key.contains("|http-proxy:");
                Conn { stream, absolute_form, key }
            }
            None => conn::connect(&url.ep, Purpose::Http, cancel)?,
        };
        let sent = send_request(&mut conn, url, method, headers, body);
        let head = match sent {
            Ok(()) => read_head(&mut conn.stream, cancel),
            Err(e) => Err(if cancel.is_cancelled() { NetError::aborted() } else { NetError::io(&e) }),
        };
        let (mut status, mut reason, mut hdrs, mut version, mut rest) = match head {
            Ok(h) => h,
            Err(e) if reused && attempt == 1 && e.code != "ERR_ABORTED" => continue,
            Err(e) => return Err(e),
        };
        // 1xx (100 Continue, 103 Early Hints): another head follows.
        while (100..200).contains(&status) && status != 101 {
            let mut more = rest.clone();
            let mut hs = [httparse::EMPTY_HEADER; 128];
            let mut r = httparse::Response::new(&mut hs);
            if let Ok(httparse::Status::Complete(n)) = r.parse(&more) {
                status = r.code.unwrap_or(0);
                reason = r.reason.unwrap_or("").to_string();
                hdrs = r.headers.iter().map(|h| (h.name.to_ascii_lowercase(), latin1(h.value).trim().to_string())).collect();
                version = r.version.unwrap_or(1);
                rest = more.split_off(n);
            } else {
                let (s, rs, h, v, r2) = read_head_more(&mut conn.stream, more, cancel)?;
                (status, reason, hdrs, version, rest) = (s, rs, h, v, r2);
            }
        }
        let conn_hdr = header(&hdrs, "connection").unwrap_or("").to_ascii_lowercase();
        let mut keep_alive = if version == 0 { conn_hdr.contains("keep-alive") } else { !conn_hdr.contains("close") };
        let te = header(&hdrs, "transfer-encoding").unwrap_or("").to_ascii_lowercase();
        let framing = if method == "HEAD" || status == 204 || status == 304 {
            Framing::None
        } else if te.contains("chunked") {
            Framing::Chunked
        } else if let Some(len) = header(&hdrs, "content-length") {
            let first = len.split(',').next().unwrap_or("").trim();
            Framing::Length(first.parse().map_err(|_| NetError::new("ERR_INVALID_HTTP_RESPONSE", "bad content-length"))?)
        } else {
            keep_alive = false;
            Framing::UntilClose
        };
        let key = conn.key.clone();
        return Ok(Response { status, reason, headers: hdrs, stream: conn.stream, key, buf: rest, framing, keep_alive });
    }
}

type HeadParts = (u16, String, Vec<(String, String)>, u8, Vec<u8>);

fn read_head_more(stream: &mut Stream, mut buf: Vec<u8>, cancel: &Cancel) -> Result<HeadParts, NetError> {
    let mut chunk = [0u8; 8192];
    loop {
        let n = stream.read(&mut chunk).map_err(|e| if cancel.is_cancelled() { NetError::aborted() } else { NetError::io(&e) })?;
        if n == 0 {
            return Err(NetError::new("ERR_CONNECTION_CLOSED", ""));
        }
        buf.extend_from_slice(&chunk[..n]);
        let mut hs = [httparse::EMPTY_HEADER; 128];
        let mut r = httparse::Response::new(&mut hs);
        if let Ok(httparse::Status::Complete(n)) = r.parse(&buf) {
            let h = r.headers.iter().map(|h| (h.name.to_ascii_lowercase(), latin1(h.value).trim().to_string())).collect();
            return Ok((r.code.unwrap_or(0), r.reason.unwrap_or("").to_string(), h, r.version.unwrap_or(1), buf[n..].to_vec()));
        }
    }
}

impl Response {
    fn fill(&mut self, cancel: &Cancel) -> Result<usize, NetError> {
        let mut chunk = [0u8; 64 * 1024];
        let n = self.stream.read(&mut chunk).map_err(|e| if cancel.is_cancelled() { NetError::aborted() } else { NetError::io(&e) })?;
        self.buf.extend_from_slice(&chunk[..n]);
        Ok(n)
    }

    /// Read the whole body (still content-encoded) and, when the connection can be reused,
    /// return it to the pool. `limit` caps memory for bodies we only drain.
    fn read_body(mut self, cancel: &Cancel, limit: usize) -> Result<Vec<u8>, NetError> {
        let too_big = || NetError::new("ERR_FILE_TOO_BIG", "");
        let body = match self.framing {
            Framing::None => Vec::new(),
            Framing::Length(n) => {
                let n = usize::try_from(n).map_err(|_| too_big())?;
                if n > limit {
                    return Err(too_big());
                }
                self.buf.reserve(n.saturating_sub(self.buf.len()));
                while self.buf.len() < n {
                    if self.fill(cancel)? == 0 {
                        return Err(NetError::new("ERR_CONTENT_LENGTH_MISMATCH", ""));
                    }
                }
                let extra = self.buf.split_off(n);
                if !extra.is_empty() {
                    self.keep_alive = false;
                }
                std::mem::take(&mut self.buf)
            }
            Framing::UntilClose => {
                while self.fill(cancel)? > 0 {
                    if self.buf.len() > limit {
                        return Err(too_big());
                    }
                }
                std::mem::take(&mut self.buf)
            }
            Framing::Chunked => {
                let mut out = Vec::new();
                let mut pos = 0;
                loop {
                    // chunk-size [; ext] CRLF
                    let line_end = loop {
                        if let Some(i) = self.buf[pos..].windows(2).position(|w| w == b"\r\n") {
                            break pos + i;
                        }
                        if self.fill(cancel)? == 0 {
                            return Err(NetError::new("ERR_INCOMPLETE_CHUNKED_ENCODING", ""));
                        }
                    };
                    let line = latin1(&self.buf[pos..line_end]);
                    let size = usize::from_str_radix(line.split(';').next().unwrap_or("").trim(), 16)
                        .map_err(|_| NetError::new("ERR_INVALID_CHUNKED_ENCODING", line.clone()))?;
                    pos = line_end + 2;
                    if size == 0 {
                        // trailers, then a blank line
                        loop {
                            if let Some(i) = self.buf[pos..].windows(2).position(|w| w == b"\r\n") {
                                let blank = i == 0;
                                pos += i + 2;
                                if blank {
                                    break;
                                }
                            } else if self.fill(cancel)? == 0 {
                                break;
                            }
                        }
                        if pos < self.buf.len() {
                            self.keep_alive = false;
                        }
                        break;
                    }
                    if out.len() + size > limit {
                        return Err(too_big());
                    }
                    while self.buf.len() < pos + size + 2 {
                        if self.fill(cancel)? == 0 {
                            return Err(NetError::new("ERR_INCOMPLETE_CHUNKED_ENCODING", ""));
                        }
                    }
                    out.extend_from_slice(&self.buf[pos..pos + size]);
                    pos += size + 2;
                    // Keep the buffer small for long streams.
                    if pos > 1 << 20 {
                        self.buf.drain(..pos);
                        pos = 0;
                    }
                }
                out
            }
        };
        cancel.release();
        if self.keep_alive {
            pool_put(self.key, self.stream);
        }
        Ok(body)
    }
}

// ---------------------------------------------------------------- fetch

const MAX_REDIRECTS: usize = 20;
const MAX_BODY: usize = 1 << 30;

/// Run a request to completion: `on_head` gets the final response head (before the body is
/// read, so the page's `fetch()` resolves as soon as headers arrive), then the decoded body is
/// returned.
pub fn fetch(req: Request, cancel: &Cancel, on_head: impl FnOnce(Head)) -> Result<Vec<u8>, NetError> {
    let mut url = Url::parse(&req.url)?;
    let mut method = req.method.clone();
    let mut headers = req.headers.clone();
    let mut body = req.body.clone();
    let mut redirected = false;
    for hop in 0..=MAX_REDIRECTS {
        let resp = exchange(&url, &method, &headers, body.as_deref(), cancel)?;
        let status = resp.status;
        let location = header(&resp.headers, "location").map(|s| s.to_string());
        if matches!(status, 301 | 302 | 303 | 307 | 308) && location.is_some() {
            let next = url.join(location.as_deref().unwrap_or("")).ok_or_else(|| NetError::new("ERR_INVALID_REDIRECT", ""))?;
            if req.redirect == RedirectMode::Manual {
                let head = Head { status: 0, status_text: String::new(), headers: Vec::new(), url: url.href(), redirected, opaque_redirect: true };
                let _ = resp.read_body(cancel, 64 * 1024);
                on_head(head);
                return Ok(Vec::new());
            }
            if req.redirect == RedirectMode::Error {
                return Err(NetError::new("ERR_UNSAFE_REDIRECT", "redirect mode is \"error\""));
            }
            if hop == MAX_REDIRECTS {
                return Err(NetError::new("ERR_TOO_MANY_REDIRECTS", ""));
            }
            let next_url = Url::parse(&next).map_err(|_| NetError::new("ERR_UNSAFE_REDIRECT", next.clone()))?;
            // Drain small bodies so the connection can be reused; drop it otherwise.
            let _ = resp.read_body(cancel, 64 * 1024);
            if (matches!(status, 301 | 302) && method == "POST") || (status == 303 && method != "GET" && method != "HEAD") {
                method = "GET".into();
                body = None;
                headers.retain(|(k, _)| {
                    !matches!(k.to_ascii_lowercase().as_str(), "content-type" | "content-encoding" | "content-language" | "content-location")
                });
            }
            if next_url.origin() != url.origin() {
                headers.retain(|(k, _)| !k.eq_ignore_ascii_case("authorization"));
            }
            url = next_url;
            redirected = true;
            continue;
        }
        let encoding = header(&resp.headers, "content-encoding").map(|s| s.to_string());
        let head = Head {
            status,
            status_text: resp.reason.clone(),
            headers: resp.headers.iter().filter(|(k, _)| k != "set-cookie" && k != "set-cookie2").cloned().collect(),
            url: url.href(),
            redirected,
            opaque_redirect: false,
        };
        on_head(head);
        let raw = resp.read_body(cancel, MAX_BODY)?;
        return match encoding {
            Some(enc) if !raw.is_empty() => crate::decode::decode(&enc, raw).map_err(|e| NetError::new("ERR_CONTENT_DECODING_FAILED", e)),
            _ => Ok(raw),
        };
    }
    Err(NetError::new("ERR_TOO_MANY_REDIRECTS", ""))
}

/// Blocking GET for other crates' worker threads (images, resources): the decoded body of a
/// 2xx response, following redirects.
pub fn get(url: &str) -> Result<Vec<u8>, String> {
    let cancel = Cancel::default();
    let mut status = 0;
    let req = Request { method: "GET".into(), url: url.to_string(), headers: Vec::new(), body: None, redirect: RedirectMode::Follow };
    let body = fetch(req, &cancel, |h| status = h.status).map_err(|e| e.to_string())?;
    if (200..300).contains(&status) { Ok(body) } else { Err(format!("HTTP {status}")) }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn urls() {
        let u = Url::parse("http://127.0.0.1:8787/api/a/b?x=1#frag").unwrap();
        assert_eq!(u.ep, Endpoint { tls: false, host: "127.0.0.1".into(), port: 8787 });
        assert_eq!(u.target, "/api/a/b?x=1");
        assert_eq!(u.join("/c").unwrap(), "http://127.0.0.1:8787/c");
        assert_eq!(u.join("c?y").unwrap(), "http://127.0.0.1:8787/api/a/c?y");
        assert_eq!(u.join("../d").unwrap(), "http://127.0.0.1:8787/api/d");
        assert_eq!(u.join("//example.com/x").unwrap(), "http://example.com/x");
        assert_eq!(u.join("https://example.com").unwrap(), "https://example.com");
        assert_eq!(u.join("?q=2").unwrap(), "http://127.0.0.1:8787/api/a/b?q=2");
        let v = Url::parse("https://[::1]/").unwrap();
        assert_eq!((v.ep.host.as_str(), v.ep.port, v.ep.authority(false)), ("::1", 443, "[::1]".to_string()));
        assert_eq!(Url::parse("https://example.com?a").unwrap().target, "/?a");
    }
}