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.

15.1 KB
Raw Blame
//! Connections: DNS, TCP, proxies (HTTP CONNECT, SOCKS5) and TLS over Security.framework.
//!
//! Everything here blocks and runs on worker threads. A `Cancel` lets the main thread abort an
//! in-flight request: it shuts the socket down, which wakes any blocked read or write at once.

use std::io::{self, Read, Write};
use std::net::{Shutdown, SocketAddr, TcpStream, ToSocketAddrs};
use std::os::fd::AsRawFd;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};

use crate::proxy::{self, Proxy};

pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
/// Longest wait for the next byte of a response (Chromium has no fetch timeout; this only stops a
/// dead peer from pinning a worker thread forever).
pub const READ_TIMEOUT: Duration = Duration::from_secs(300);
/// A send that cannot make progress for this long means the peer is gone.
pub const WRITE_TIMEOUT: Duration = Duration::from_secs(30);

/// A failure, named like Chromium's net errors (`net::ERR_…`) so logs read the same.
#[derive(Debug, Clone)]
pub struct NetError {
    pub code: &'static str,
    pub detail: String,
}

impl NetError {
    pub fn new(code: &'static str, detail: impl Into<String>) -> Self {
        NetError { code, detail: detail.into() }
    }
    pub fn io(e: &io::Error) -> Self {
        use io::ErrorKind::*;
        let code = match e.kind() {
            ConnectionRefused => "ERR_CONNECTION_REFUSED",
            ConnectionReset => "ERR_CONNECTION_RESET",
            ConnectionAborted => "ERR_CONNECTION_ABORTED",
            TimedOut | WouldBlock => "ERR_TIMED_OUT",
            UnexpectedEof | BrokenPipe | NotConnected => "ERR_CONNECTION_CLOSED",
            AddrNotAvailable | NetworkUnreachable | HostUnreachable => "ERR_ADDRESS_UNREACHABLE",
            NetworkDown => "ERR_INTERNET_DISCONNECTED",
            _ => "ERR_FAILED",
        };
        NetError::new(code, e.to_string())
    }
    pub fn aborted() -> Self {
        NetError::new("ERR_ABORTED", "aborted")
    }
}

impl std::fmt::Display for NetError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.detail.is_empty() { write!(f, "net::{}", self.code) } else { write!(f, "net::{} ({})", self.code, self.detail) }
    }
}

/// Lets another thread abort a blocking request.
#[derive(Default)]
pub struct Cancel {
    flag: AtomicBool,
    sock: Mutex<Option<TcpStream>>,
}

impl Cancel {
    pub fn cancel(&self) {
        self.flag.store(true, Ordering::SeqCst);
        if let Some(s) = self.sock.lock().unwrap().take() {
            let _ = s.shutdown(Shutdown::Both);
        }
    }
    pub fn is_cancelled(&self) -> bool {
        self.flag.load(Ordering::SeqCst)
    }
    pub fn check(&self) -> Result<(), NetError> {
        if self.is_cancelled() { Err(NetError::aborted()) } else { Ok(()) }
    }
    /// Make `cancel()` shut this socket down (until `release`).
    pub fn watch(&self, tcp: &TcpStream) -> Result<(), NetError> {
        let clone = tcp.try_clone().map_err(|e| NetError::io(&e))?;
        let mut g = self.sock.lock().unwrap();
        if self.is_cancelled() {
            let _ = clone.shutdown(Shutdown::Both);
            return Err(NetError::aborted());
        }
        *g = Some(clone);
        Ok(())
    }
    /// Stop watching (the connection goes back to the pool and must not be shut down later).
    pub fn release(&self) {
        self.sock.lock().unwrap().take();
    }
}

/// A TCP socket whose reads can be switched to non-blocking while writes stay blocking: the
/// WebSocket thread waits for readability with `poll` and drains with non-blocking reads, but a
/// send always completes (bounded by `WRITE_TIMEOUT`), so the TLS layer never has to buffer a
/// partially written record.
pub struct Sock {
    pub tcp: TcpStream,
    nonblocking_reads: bool,
}

impl Sock {
    pub fn set_nonblocking_reads(&mut self, on: bool) {
        self.nonblocking_reads = on;
    }
}

impl Read for Sock {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if !self.nonblocking_reads {
            return self.tcp.read(buf);
        }
        loop {
            let n = unsafe { libc::recv(self.tcp.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len(), libc::MSG_DONTWAIT) };
            if n >= 0 {
                return Ok(n as usize);
            }
            let e = io::Error::last_os_error();
            if e.kind() != io::ErrorKind::Interrupted {
                return Err(e);
            }
        }
    }
}

impl Write for Sock {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.tcp.write(buf)
    }
    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

pub enum Stream {
    Plain(Sock),
    Tls(Box<native_tls::TlsStream<Sock>>),
}

impl Stream {
    pub fn sock(&self) -> &Sock {
        match self {
            Stream::Plain(s) => s,
            Stream::Tls(t) => t.get_ref(),
        }
    }
    pub fn sock_mut(&mut self) -> &mut Sock {
        match self {
            Stream::Plain(s) => s,
            Stream::Tls(t) => t.get_mut(),
        }
    }
    pub fn tcp(&self) -> &TcpStream {
        &self.sock().tcp
    }
}

impl Read for Stream {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self {
            Stream::Plain(s) => s.read(buf),
            Stream::Tls(t) => t.read(buf),
        }
    }
}

impl Write for Stream {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match self {
            Stream::Plain(s) => s.write(buf),
            Stream::Tls(t) => t.write(buf),
        }
    }
    fn flush(&mut self) -> io::Result<()> {
        match self {
            Stream::Plain(s) => s.flush(),
            Stream::Tls(t) => t.flush(),
        }
    }
}

/// Where a request goes: scheme security, host (IPv6 literals without brackets) and port.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Endpoint {
    pub tls: bool,
    pub host: String,
    pub port: u16,
}

impl Endpoint {
    /// `host[:port]` as written in a Host header / CONNECT line.
    pub fn authority(&self, always_port: bool) -> String {
        let h = if self.host.contains(':') { format!("[{}]", self.host) } else { self.host.clone() };
        let default = if self.tls { 443 } else { 80 };
        if always_port || self.port != default { format!("{h}:{}", self.port) } else { h }
    }
    pub fn is_loopback(&self) -> bool {
        let h = self.host.to_ascii_lowercase();
        h == "localhost" || h.ends_with(".localhost") || h == "::1" || h.starts_with("127.")
    }
}

/// An open connection and how it reaches the endpoint.
pub struct Conn {
    pub stream: Stream,
    /// Plain HTTP through an HTTP proxy: requests use the absolute URL as the target.
    pub absolute_form: bool,
    /// Pool key: endpoint + route.
    pub key: String,
}

/// What the connection is for: WebSockets always tunnel through HTTP proxies (as Chromium does).
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Purpose {
    Http,
    WebSocket,
}

pub fn connect(ep: &Endpoint, purpose: Purpose, cancel: &Cancel) -> Result<Conn, NetError> {
    let proxies = if ep.is_loopback() { vec![Proxy::Direct] } else { proxy::for_endpoint(ep) };
    let mut last = NetError::new("ERR_FAILED", "no route");
    for p in &proxies {
        cancel.check()?;
        match connect_via(ep, p, purpose, cancel) {
            Ok(c) => return Ok(c),
            Err(e) if e.code == "ERR_ABORTED" => return Err(e),
            // TLS and HTTP errors from the origin are final; only proxy failures fall back.
            Err(e) if matches!(p, Proxy::Direct) || !e.code.contains("PROXY") && !e.code.contains("TUNNEL") => return Err(e),
            Err(e) => last = e,
        }
    }
    Err(last)
}

fn connect_via(ep: &Endpoint, p: &Proxy, purpose: Purpose, cancel: &Cancel) -> Result<Conn, NetError> {
    let (tcp, absolute_form, route) = match p {
        Proxy::Direct => (tcp_connect(&ep.host, ep.port, cancel, false)?, false, String::new()),
        Proxy::Http(h, port) => {
            let tcp = tcp_connect(h, *port, cancel, true)?;
            if ep.tls || purpose == Purpose::WebSocket {
                http_tunnel(&tcp, ep)?;
                (tcp, false, format!("|http-tunnel:{h}:{port}"))
            } else {
                (tcp, true, format!("|http-proxy:{h}:{port}"))
            }
        }
        Proxy::Socks(h, port) => {
            let tcp = tcp_connect(h, *port, cancel, true)?;
            socks5(&tcp, ep)?;
            (tcp, false, format!("|socks:{h}:{port}"))
        }
    };
    let key = format!("{}://{}{}", if ep.tls { "https" } else { "http" }, ep.authority(true), route);
    let sock = Sock { tcp, nonblocking_reads: false };
    let stream = if ep.tls {
        Stream::Tls(Box::new(tls_handshake(&ep.host, sock)?))
    } else {
        Stream::Plain(sock)
    };
    cancel.check()?;
    Ok(Conn { stream, absolute_form, key })
}

fn tcp_connect(host: &str, port: u16, cancel: &Cancel, is_proxy: bool) -> Result<TcpStream, NetError> {
    let addrs: Vec<SocketAddr> = match (host, port).to_socket_addrs() {
        Ok(a) => a.collect(),
        Err(e) => {
            let code = if is_proxy { "ERR_PROXY_CONNECTION_FAILED" } else { "ERR_NAME_NOT_RESOLVED" };
            return Err(NetError::new(code, format!("{host}: {e}")));
        }
    };
    if addrs.is_empty() {
        return Err(NetError::new("ERR_NAME_NOT_RESOLVED", host.to_string()));
    }
    cancel.check()?;
    let deadline = Instant::now() + CONNECT_TIMEOUT;
    let mut last = NetError::new("ERR_CONNECTION_FAILED", host.to_string());
    for (i, addr) in addrs.iter().enumerate() {
        let left = deadline.saturating_duration_since(Instant::now());
        if left.is_zero() {
            break;
        }
        // Leave time for the other addresses when the first family is unreachable.
        let budget = if i + 1 < addrs.len() { left.min(Duration::from_secs(5)) } else { left };
        match TcpStream::connect_timeout(addr, budget) {
            Ok(tcp) => {
                configure(&tcp);
                cancel.watch(&tcp)?;
                return Ok(tcp);
            }
            Err(e) => {
                last = NetError::io(&e);
                if is_proxy {
                    last.code = "ERR_PROXY_CONNECTION_FAILED";
                }
            }
        }
        cancel.check()?;
    }
    Err(last)
}

fn configure(tcp: &TcpStream) {
    let _ = tcp.set_nodelay(true);
    let _ = tcp.set_read_timeout(Some(READ_TIMEOUT));
    let _ = tcp.set_write_timeout(Some(WRITE_TIMEOUT));
    // A write to a socket the peer closed must return EPIPE, not kill the process.
    #[cfg(target_os = "macos")]
    unsafe {
        let one: libc::c_int = 1;
        libc::setsockopt(tcp.as_raw_fd(), libc::SOL_SOCKET, libc::SO_NOSIGPIPE, (&one as *const libc::c_int).cast(), 4);
    }
    #[cfg(all(unix, not(target_os = "macos")))]
    {
        static IGNORE_SIGPIPE: std::sync::Once = std::sync::Once::new();
        IGNORE_SIGPIPE.call_once(|| unsafe {
            libc::signal(libc::SIGPIPE, libc::SIG_IGN);
        });
    }
}

fn tls_connector() -> Result<&'static native_tls::TlsConnector, NetError> {
    static C: OnceLock<Result<native_tls::TlsConnector, String>> = OnceLock::new();
    C.get_or_init(|| native_tls::TlsConnector::new().map_err(|e| e.to_string()))
        .as_ref()
        .map_err(|e| NetError::new("ERR_SSL_PROTOCOL_ERROR", e.clone()))
}

fn tls_handshake(host: &str, sock: Sock) -> Result<native_tls::TlsStream<Sock>, NetError> {
    let _ = sock.tcp.set_read_timeout(Some(CONNECT_TIMEOUT));
    match tls_connector()?.connect(host, sock) {
        Ok(s) => {
            let _ = s.get_ref().tcp.set_read_timeout(Some(READ_TIMEOUT));
            Ok(s)
        }
        Err(native_tls::HandshakeError::Failure(e)) => {
            let msg = e.to_string();
            let code = if msg.contains("certificate") || msg.contains("trust") { "ERR_CERT_INVALID" } else { "ERR_SSL_PROTOCOL_ERROR" };
            Err(NetError::new(code, msg))
        }
        Err(native_tls::HandshakeError::WouldBlock(_)) => Err(NetError::new("ERR_TIMED_OUT", "TLS handshake timed out")),
    }
}

/// Read an HTTP head (through the blank line) byte by byte, so nothing after it is consumed.
fn read_head_exact(mut r: impl Read, limit: usize) -> io::Result<Vec<u8>> {
    let mut head = Vec::with_capacity(256);
    let mut b = [0u8; 1];
    while !head.ends_with(b"\r\n\r\n") {
        if r.read(&mut b)? == 0 {
            return Err(io::ErrorKind::UnexpectedEof.into());
        }
        head.push(b[0]);
        if head.len() > limit {
            return Err(io::Error::other("response head too large"));
        }
    }
    Ok(head)
}

fn http_tunnel(mut tcp: &TcpStream, ep: &Endpoint) -> Result<(), NetError> {
    let target = ep.authority(true);
    let req = format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\nProxy-Connection: keep-alive\r\nUser-Agent: {}\r\n\r\n", crate::user_agent());
    let fail = |d: String| NetError::new("ERR_TUNNEL_CONNECTION_FAILED", d);
    tcp.write_all(req.as_bytes()).map_err(|e| fail(e.to_string()))?;
    let head = read_head_exact(tcp, 64 * 1024).map_err(|e| fail(e.to_string()))?;
    let mut hs = [httparse::EMPTY_HEADER; 64];
    let mut resp = httparse::Response::new(&mut hs);
    match resp.parse(&head) {
        Ok(httparse::Status::Complete(_)) if resp.code == Some(200) => Ok(()),
        Ok(_) if resp.code == Some(407) => Err(NetError::new("ERR_PROXY_AUTH_UNSUPPORTED", "proxy requires authentication")),
        Ok(_) => Err(fail(format!("proxy answered {}", resp.code.unwrap_or(0)))),
        Err(e) => Err(fail(e.to_string())),
    }
}

fn socks5(mut tcp: &TcpStream, ep: &Endpoint) -> Result<(), NetError> {
    let fail = |d: &str| NetError::new("ERR_SOCKS_CONNECTION_FAILED", d.to_string());
    let io = |e: io::Error| NetError::new("ERR_SOCKS_CONNECTION_FAILED", e.to_string());
    tcp.write_all(&[5, 1, 0]).map_err(io)?;
    let mut r = [0u8; 2];
    tcp.read_exact(&mut r).map_err(io)?;
    if r != [5, 0] {
        return Err(fail("no acceptable authentication method"));
    }
    let host = ep.host.as_bytes();
    if host.len() > 255 {
        return Err(fail("host name too long"));
    }
    // Domain names go to the proxy unresolved (remote DNS, like Chromium's socks5).
    let mut req = vec![5, 1, 0, 3, host.len() as u8];
    req.extend_from_slice(host);
    req.extend_from_slice(&ep.port.to_be_bytes());
    tcp.write_all(&req).map_err(io)?;
    let mut rep = [0u8; 4];
    tcp.read_exact(&mut rep).map_err(io)?;
    if rep[1] != 0 {
        return Err(fail(&format!("proxy replied {}", rep[1])));
    }
    let skip = match rep[3] {
        1 => 4 + 2,
        4 => 16 + 2,
        3 => {
            let mut n = [0u8; 1];
            tcp.read_exact(&mut n).map_err(io)?;
            n[0] as usize + 2
        }
        _ => return Err(fail("bad address type")),
    };
    let mut rest = vec![0u8; skip];
    tcp.read_exact(&mut rest).map_err(io)?;
    Ok(())
}

/// Is a pooled socket still usable? A readable idle socket means EOF, a TLS close alert or
/// stray bytes; any of them makes it unusable.
pub fn idle_socket_alive(tcp: &TcpStream) -> bool {
    let mut p = libc::pollfd { fd: tcp.as_raw_fd(), events: libc::POLLIN, revents: 0 };
    let n = unsafe { libc::poll(&mut p, 1, 0) };
    n == 0
}