diff --git a/crates-proxy/yaak-proxy-lib/tests/flow.rs b/crates-proxy/yaak-proxy-lib/tests/flow.rs index 6a7be5f5b..41b60d117 100644 --- a/crates-proxy/yaak-proxy-lib/tests/flow.rs +++ b/crates-proxy/yaak-proxy-lib/tests/flow.rs @@ -708,3 +708,46 @@ async fn times_capture_through_the_engine() { FLOWS as f64 / capture.as_secs_f64() ); } + +/// A plain request whose server can't be reached resets the client's connection, and is one +/// row: its request as sent, ended as an error with the reason in plain words and no status. +#[tokio::test(flavor = "multi_thread")] +async fn an_unreachable_plain_request_is_one_error_row() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let dir = tempfile::tempdir().unwrap(); + let settings = ProxySettings { port: 0, system_proxy_at_launch: false, ..Default::default() }; + settings.save(&dir.path().join("settings.json")).unwrap(); + let (events, _event_rx) = RpcEventEmitter::new(); + let ctx = ProxyCtx::new(dir.path(), events, MasterKeySource::memory()).unwrap(); + ctx.start().unwrap(); + + let closed = TcpListener::bind("127.0.0.1:0").await.unwrap().local_addr().unwrap(); + let url = format!("http://{closed}/missing?q=1"); + let mut tcp = tokio::net::TcpStream::connect(("127.0.0.1", ctx.port().unwrap())).await.unwrap(); + let request = format!("GET {url} HTTP/1.1\r\nHost: {closed}\r\nUser-Agent: yaak-test\r\n\r\n"); + tcp.write_all(request.as_bytes()).await.unwrap(); + let mut received = Vec::new(); + let read = tcp.read_to_end(&mut received).await; + assert!(received.is_empty(), "{}", String::from_utf8_lossy(&received)); + assert_eq!(read.unwrap_err().kind(), std::io::ErrorKind::ConnectionReset); + + let flow = wait_for_flow(&ctx, &url).await; + assert_eq!(flow.method, "GET"); + assert!(flow.error.as_deref().unwrap().starts_with("Connection refused: "), "{flow:?}"); + assert_eq!(flow.status, None); + assert!(!flow.cancelled); + assert!(flow.elapsed_ms.is_some(), "ended, not pending"); + assert!( + flow.request_headers + .iter() + .any(|h| h.name.eq_ignore_ascii_case("user-agent") && h.value == "yaak-test") + ); + tokio::time::sleep(Duration::from_millis(200)).await; + let flows = ctx.db().unwrap().with_conn(|db| db.find_all::().unwrap()); + assert_eq!(flows.len(), 1, "one row: {flows:?}"); + + let errors = rpc(&ctx, "list_flows", json!({"query": "@is:error"})).await.unwrap(); + let ids: Vec = + errors["flows"].as_array().unwrap().iter().map(|f| f["id"].clone()).collect(); + assert_eq!(ids, vec![json!(flow.id)]); +} diff --git a/crates/yaak-proxy/Cargo.toml b/crates/yaak-proxy/Cargo.toml index efeaf1178..0c074077e 100644 --- a/crates/yaak-proxy/Cargo.toml +++ b/crates/yaak-proxy/Cargo.toml @@ -27,12 +27,12 @@ rustls-native-certs = "0.8" tokio-rustls = "0.26" pem = "3" time = "0.3" +tower-service = "0.3" [target.'cfg(target_os = "macos")'.dependencies] block2 = "0.6" dispatch2 = "0.3" libc = "0.2" -tower-service = "0.3" [dev-dependencies] futures-util = "0.3" diff --git a/crates/yaak-proxy/src/connection.rs b/crates/yaak-proxy/src/connection.rs index 6498c72ee..64b2e6aba 100644 --- a/crates/yaak-proxy/src/connection.rs +++ b/crates/yaak-proxy/src/connection.rs @@ -1,10 +1,17 @@ +use std::error::Error; +use std::io; +use std::pin::Pin; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::task::{Context, Poll}; use hyper::server::conn::http1; use hyper::service::service_fn; use hyper_util::rt::{TokioExecutor, TokioIo}; use hyper_util::server::conn::auto; -use tokio::io::{AsyncRead, AsyncWrite}; +use log::debug; +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; +use tokio::net::TcpStream; use crate::request::handle_request; use crate::{ClientConn, Engine}; @@ -25,7 +32,7 @@ pub(crate) async fn serve_tls( io: S, http2: bool, handler: F, -) -> Result<(), Box> +) -> Result<(), Box> where S: AsyncRead + AsyncWrite + Unpin + Send + 'static, F: Fn(hyper::Request) -> Fut + Send + Sync + 'static, @@ -47,17 +54,107 @@ where /// Serves a connection to the listener, in HTTP/1.1 only: HTTP/2 is offered inside TLS alone. pub(crate) async fn handle_connection( - stream: tokio::net::TcpStream, + stream: TcpStream, client: ClientConn, engine: Arc, ) -> Result<(), hyper::Error> { - http1::Builder::new() + let reset = ResetHandle::default(); + let io = ClientIo { tcp: stream, reset: reset.clone() }; + let served = http1::Builder::new() .preserve_header_case(true) .title_case_headers(true) .serve_connection( - TokioIo::new(stream), - service_fn(move |req| handle_request(req, client, engine.clone())), + TokioIo::new(io), + service_fn(move |req| handle_request(req, client, engine.clone(), reset.clone())), ) .with_upgrades() - .await + .await; + match served { + // Reset as the request service asked, which said why. + Err(e) if e.source().is_some_and(|e| e.is::()) => Ok(()), + served => served, + } +} + +/// Lets a request service reset the client connection it serves, so the client reports a +/// connection error of its own rather than a response. +#[derive(Clone, Default)] +pub(crate) struct ResetHandle(Arc); + +impl ResetHandle { + /// Marks the connection to be reset as it closes. The service returns the [`Reset`], which + /// makes hyper close the connection at once, unanswered. + pub(crate) fn reset(&self) -> Reset { + self.0.store(true, Ordering::Relaxed); + Reset + } +} + +/// A request service's error for a connection reset by [`ResetHandle::reset`]. +#[derive(Debug)] +pub(crate) struct Reset; + +impl std::fmt::Display for Reset { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("client connection reset") + } +} + +impl Error for Reset {} + +/// A client connection from the listener, closed with a reset (`SO_LINGER` 0) once its +/// [`ResetHandle`] is tripped. +struct ClientIo { + tcp: TcpStream, + reset: ResetHandle, +} + +impl Drop for ClientIo { + fn drop(&mut self) { + if self.reset.0.load(Ordering::Relaxed) + && let Err(e) = self.tcp.set_zero_linger() + { + debug!("Could not reset the client connection: {e}"); + } + } +} + +impl AsyncRead for ClientIo { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.get_mut().tcp).poll_read(cx, buf) + } +} + +impl AsyncWrite for ClientIo { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + Pin::new(&mut self.get_mut().tcp).poll_write(cx, buf) + } + + fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[io::IoSlice<'_>], + ) -> Poll> { + Pin::new(&mut self.get_mut().tcp).poll_write_vectored(cx, bufs) + } + + fn is_write_vectored(&self) -> bool { + self.tcp.is_write_vectored() + } + + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.get_mut().tcp).poll_flush(cx) + } + + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.get_mut().tcp).poll_shutdown(cx) + } } diff --git a/crates/yaak-proxy/src/dial.rs b/crates/yaak-proxy/src/dial.rs index ad0b275b7..852249f92 100644 --- a/crates/yaak-proxy/src/dial.rs +++ b/crates/yaak-proxy/src/dial.rs @@ -1,23 +1,30 @@ -//! The connection to the server of a CONNECT, opened before the CONNECT is answered, so a server +//! The connection to a server: for a CONNECT, opened before the CONNECT is answered, so a server //! that can't be reached fails the CONNECT itself and the client reports its own connection -//! error, as it would without the proxy. +//! error, as it would without the proxy; and for plain HTTP, the connections of +//! `Engine::http_client`, through [`Connector`], whose failures are told apart the same way. +use std::error::Error; use std::io; use std::net::SocketAddr; use std::pin::Pin; use std::task::{Context, Poll}; use std::time::{Duration, Instant}; -use hyper::StatusCode; +use hyper::http::uri::Scheme; +use hyper::{StatusCode, Uri}; +use hyper_util::client::legacy::connect::{Connected, Connection}; +use hyper_util::rt::TokioIo; +#[cfg(target_os = "macos")] +use log::debug; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use tokio::net::TcpStream; -/// The longest the dial before answering a CONNECT may take, name lookup included. The system's +/// The longest opening a connection to a server may take, name lookup included. The system's /// own limit is over a minute. pub(crate) const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); -/// A TCP connection to a server: a socket, or on macOS for port 80 a Network.framework -/// connection, which skips the system proxy as [`crate::tunnel::tunnel`] does there. +/// A TCP connection to a server: a socket, or on macOS a Network.framework connection, which +/// skips the system proxy as [`crate::tunnel::tunnel`] does there. pub(crate) enum UpstreamIo { Tcp(TcpStream), #[cfg(target_os = "macos")] @@ -41,36 +48,61 @@ pub(crate) struct Dialled { } /// Opens the connection to `host:port` for a CONNECT, within [`CONNECT_TIMEOUT`]. `host` is as -/// the CONNECT named it, an IPv6 address in brackets. +/// the CONNECT named it, an IPv6 address in brackets. On macOS, port 80 goes through +/// Network.framework. pub(crate) async fn dial(host: &str, port: u16) -> Result { + let through_nw = cfg!(target_os = "macos") && port == 80; + dial_within(host, port, through_nw, CONNECT_TIMEOUT).await +} + +/// [`dial`], through Network.framework when `through_nw` is set (on macOS only), within +/// `timeout`. +async fn dial_within( + host: &str, + port: u16, + through_nw: bool, + timeout: Duration, +) -> Result { let start = Instant::now(); - let deadline = tokio::time::Instant::now() + CONNECT_TIMEOUT; - let io = match tokio::time::timeout_at(deadline, open(host, port, deadline)).await { + let deadline = tokio::time::Instant::now() + timeout; + let io = match tokio::time::timeout_at(deadline, open(host, port, through_nw, deadline)).await { Ok(io) => io?, - Err(_) => return Err(Unreachable::of(&timed_out(), false)), + Err(_) => return Err(Unreachable::of(&timed_out(timeout), false)), }; Ok(Dialled { io, took: start.elapsed() }) } -fn timed_out() -> io::Error { - let message = format!("no connection after {} seconds", CONNECT_TIMEOUT.as_secs()); +fn timed_out(timeout: Duration) -> io::Error { + let message = format!("no connection after {} seconds", timeout.as_secs_f32()); io::Error::new(io::ErrorKind::TimedOut, message) } async fn open( host: &str, port: u16, + through_nw: bool, deadline: tokio::time::Instant, ) -> Result { #[cfg(target_os = "macos")] - if port == 80 { - let host = host.trim_start_matches('[').trim_end_matches(']'); - return crate::nw::connect(host, port) - .await - .map(UpstreamIo::Nw) - .map_err(|e| Unreachable::of(&e, crate::nw::is_lookup_failure(&e))); + if through_nw { + let bare = host.trim_start_matches('[').trim_end_matches(']'); + return match crate::nw::connect(bare, port).await { + Ok(nw) => Ok(UpstreamIo::Nw(nw)), + Err(e) if crate::nw::is_local_proxy_fallback(&e) => { + debug!("{e}"); + Err(no_direct_route(host, port).await) + } + Err(e) => Err(Unreachable::of(&e, crate::nw::is_lookup_failure(&e))), + }; } - // Looked up apart from connecting, so a failure is known to be the lookup's. + let _ = through_nw; + let addrs = lookup(host, port).await?; + connect_any(&addrs, deadline).await.map(UpstreamIo::Tcp).map_err(|e| Unreachable::of(&e, false)) +} + +/// The addresses of `host`, looked up apart from connecting, so a failure is known to be the +/// lookup's. +async fn lookup(host: &str, port: u16) -> Result, Unreachable> { let addrs: Vec = tokio::net::lookup_host(format!("{host}:{port}")) .await .map_err(|e| Unreachable::of(&e, true))? @@ -79,7 +111,22 @@ async fn open( let e = io::Error::new(io::ErrorKind::NotFound, "no address for the host"); return Err(Unreachable::of(&e, true)); } - connect_any(&addrs, deadline).await.map(UpstreamIo::Tcp).map_err(|e| Unreachable::of(&e, false)) + Ok(addrs) +} + +/// Why Network.framework found no direct route to `host:port`, falling back to a proxy on this +/// Mac, which may be the engine, and so was refused: the name not resolving, found by looking it +/// up apart, or else the host unreachable. Its own error, which names the system proxy, is +/// only logged. +#[cfg(target_os = "macos")] +async fn no_direct_route(host: &str, port: u16) -> Unreachable { + match lookup(host, port).await { + Err(unreachable) => unreachable, + Ok(_) => Unreachable { + kind: UnreachableKind::HostUnreachable, + error: format!("no direct route to {host}:{port}"), + }, + } } /// Connects to the first of `addrs` that answers, in turn, each given an even share of the time @@ -96,10 +143,114 @@ async fn connect_any( match tokio::time::timeout(share, TcpStream::connect(addr)).await { Ok(Ok(tcp)) => return Ok(tcp), Ok(Err(e)) => last = Some(e), - Err(_) => last = Some(timed_out()), + Err(_) => { + let message = format!("no answer from {addr}"); + last = Some(io::Error::new(io::ErrorKind::TimedOut, message)); + } } } - Err(last.unwrap_or_else(timed_out)) + Err(last.unwrap_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no address for the host"))) +} + +/// Connects `Engine::http_client` to plain HTTP servers as [`dial`] does, within +/// [`CONNECT_TIMEOUT`], and on macOS through Network.framework whatever the port, as the plain +/// HTTP client always has. A server that can't be reached fails with an [`Unreachable`], which +/// [`unreachable_of`] finds in the client's error. +#[derive(Clone, Copy, Default)] +pub(crate) struct Connector; + +impl tower_service::Service for Connector { + type Response = PlainIo; + type Error = Box; + type Future = Pin> + Send>>; + + fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn call(&mut self, uri: Uri) -> Self::Future { + Box::pin(async move { + let invalid = |message| io::Error::new(io::ErrorKind::InvalidInput, message); + if uri.scheme() != Some(&Scheme::HTTP) { + return Err(invalid("invalid URL, scheme is not http").into()); + } + let host = uri.host().ok_or_else(|| invalid("invalid URL, host is missing"))?; + let port = uri.port_u16().unwrap_or(80); + let through_nw = cfg!(target_os = "macos"); + let dialled = dial_within(host, port, through_nw, CONNECT_TIMEOUT).await?; + Ok(PlainIo(TokioIo::new(dialled.io))) + }) + } +} + +/// The [`Unreachable`] [`Connector`] failed with, somewhere in `e`'s sources: why the request's +/// server could not be reached. None when it was, and the request failed after. +pub(crate) fn unreachable_of<'a>(e: &'a (dyn Error + 'static)) -> Option<&'a Unreachable> { + let mut source = Some(e); + while let Some(e) = source { + if let Some(unreachable) = e.downcast_ref::() { + return Some(unreachable); + } + source = e.source(); + } + None +} + +/// A connection from [`Connector`], as hyper's IO, reporting where it connected. +pub(crate) struct PlainIo(TokioIo); + +/// The address a plain HTTP response came from, in its extensions. +#[derive(Clone, Copy, Debug)] +pub(crate) struct RemoteAddr(pub(crate) SocketAddr); + +impl Connection for PlainIo { + fn connected(&self) -> Connected { + let connected = Connected::new(); + match self.0.inner().remote_addr() { + Some(addr) => connected.extra(RemoteAddr(addr)), + None => connected, + } + } +} + +impl hyper::rt::Read for PlainIo { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: hyper::rt::ReadBufCursor<'_>, + ) -> Poll> { + Pin::new(&mut self.0).poll_read(cx, buf) + } +} + +impl hyper::rt::Write for PlainIo { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + Pin::new(&mut self.0).poll_write(cx, buf) + } + + fn poll_write_vectored( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[io::IoSlice<'_>], + ) -> Poll> { + Pin::new(&mut self.0).poll_write_vectored(cx, bufs) + } + + fn is_write_vectored(&self) -> bool { + hyper::rt::Write::is_write_vectored(&self.0) + } + + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.0).poll_flush(cx) + } + + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.0).poll_shutdown(cx) + } } /// Whether a CONNECT to `host:port` may be one of the engine's own connections coming back @@ -116,7 +267,7 @@ pub(crate) fn may_be_own_connection(host: &str, port: u16) -> bool { false } -/// Why a CONNECT's server could not be reached: what is said of it, and the system's error. +/// Why a server could not be reached: what is said of it, and the system's error. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct Unreachable { pub(crate) kind: UnreachableKind, @@ -179,6 +330,8 @@ impl std::fmt::Display for Unreachable { } } +impl Error for Unreachable {} + impl AsyncRead for UpstreamIo { fn poll_read( self: Pin<&mut Self>, @@ -318,6 +471,53 @@ mod tests { assert!(dialled.io.is_write_vectored()); } + /// A server that never answers fails within the limit as a timeout. The plain HTTP client's + /// connections are opened the same way, within [`CONNECT_TIMEOUT`]. + #[tokio::test] + async fn a_server_that_never_answers_times_out() { + let limit = Duration::from_millis(200); + let started = Instant::now(); + // Reserved for documentation (RFC 5737), so nothing answers there. + let Err(unreachable) = dial_within("192.0.2.1", 9, false, limit).await else { + panic!("connected to an address that never answers"); + }; + assert_eq!( + (unreachable.kind, unreachable.reason()), + (UnreachableKind::TimedOut, "Timed out") + ); + assert!(started.elapsed() < limit * 5, "{:?}", started.elapsed()); + } + + /// With no direct route, Network.framework falls back to the system proxy, which the engine + /// refuses as it may be itself. The reason is found apart: the name not resolving, or else + /// the host unreachable, never the fallback. + #[cfg(target_os = "macos")] + #[tokio::test] + async fn no_direct_route_says_why() { + let lookup = no_direct_route("yaak-proxy-dial.invalid", 80).await; + assert_eq!(lookup.kind, UnreachableKind::Lookup, "{lookup}"); + let route = no_direct_route("127.0.0.1", 80).await; + assert_eq!(route.to_string(), "Host unreachable: no direct route to 127.0.0.1:80"); + } + + /// The plain HTTP client's failure to connect carries the reason, found in its sources. + #[tokio::test] + async fn the_connectors_failure_is_found_in_the_clients_error() { + let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = closed.local_addr().unwrap(); + drop(closed); + let client = + hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new()) + .build::<_, http_body_util::Empty>(Connector); + let uri: Uri = format!("http://{addr}/").parse().unwrap(); + let e = client.get(uri).await.unwrap_err(); + let unreachable = unreachable_of(&e).expect("no reason in the client's error"); + assert_eq!(unreachable.kind, UnreachableKind::Refused, "{unreachable}"); + + let e = client.get("https://127.0.0.1/".parse().unwrap()).await.unwrap_err(); + assert!(unreachable_of(&e).is_none(), "{e:?}"); + } + #[tokio::test] async fn a_closed_port_is_refused() { let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); diff --git a/crates/yaak-proxy/src/lib.rs b/crates/yaak-proxy/src/lib.rs index 844bd5de4..cf81a1f5d 100644 --- a/crates/yaak-proxy/src/lib.rs +++ b/crates/yaak-proxy/src/lib.rs @@ -25,8 +25,6 @@ use std::time::SystemTime; use bytes::Bytes; use http::HeaderValue; use hyper_util::client::legacy::Client; -#[cfg(not(target_os = "macos"))] -use hyper_util::client::legacy::connect::HttpConnector; use hyper_util::rt::TokioExecutor; use rustls::ClientConfig; use rustls::pki_types::CertificateDer; @@ -201,9 +199,11 @@ pub enum ProxyEvent { /// connection. Not an error of the engine's or the server's. cancelled: bool, }, - /// No response: connecting to or requesting from upstream failed, and the client got a 502, - /// or the engine refused the request (no host to send it to, or it looped back to the engine) - /// with a 4xx or 5xx of its own. + /// No response. The server could not be reached, so the client's connection was dropped + /// unanswered, as it would have failed without the proxy: `error` is then the reason in plain + /// words and the system's error, as a `ConnectFailed`'s. Or the request failed once it was + /// on its way, and the client got a 502. Or the engine refused the request (no host to send + /// it to) with a 4xx of its own. Error { id: u64, error: String, @@ -519,19 +519,13 @@ fn upstream_tls_config( Ok(Arc::new(config)) } -/// Sends plain HTTP upstream. On macOS it connects through Network.framework, so Private Relay -/// can't route the engine's own port-80 connections back into the engine (see [`nw`]). -#[cfg(target_os = "macos")] -type HttpClient = Client; -#[cfg(not(target_os = "macos"))] -type HttpClient = Client; +/// Sends plain HTTP upstream, connecting as a CONNECT's dial does (see [`dial::Connector`]). On +/// macOS it connects through Network.framework, so Private Relay can't route the engine's own +/// port-80 connections back into the engine (see [`nw`]). +type HttpClient = Client; fn http_client() -> HttpClient { - let builder = Client::builder(TokioExecutor::new()); - #[cfg(target_os = "macos")] - return builder.build(nw::Connector); - #[cfg(not(target_os = "macos"))] - builder.build_http() + Client::builder(TokioExecutor::new()).build(dial::Connector) } fn via_marker() -> HeaderValue { diff --git a/crates/yaak-proxy/src/nw.rs b/crates/yaak-proxy/src/nw.rs index f8e7e003c..475e3fde0 100644 --- a/crates/yaak-proxy/src/nw.rs +++ b/crates/yaak-proxy/src/nw.rs @@ -9,7 +9,6 @@ use std::collections::HashMap; use std::ffi::{CStr, CString, c_char, c_void}; -use std::future::Future; use std::io; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV6}; use std::pin::Pin; @@ -22,9 +21,6 @@ use block2::{Block, RcBlock}; use bytes::Bytes; use dispatch2::{DispatchData, DispatchQueue, DispatchRetained}; use hyper::Uri; -use hyper::http::uri::Scheme; -use hyper_util::client::legacy::connect::{Connected, Connection as HyperConnection}; -use hyper_util::rt::TokioIo; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use tokio::sync::{oneshot, watch}; @@ -150,6 +146,32 @@ pub(crate) fn is_lookup_failure(e: &io::Error) -> bool { e.get_ref().is_some_and(|inner| inner.is::()) } +/// A connection refused by [`connect`] for going through a proxy on this Mac, which may be the +/// engine. It says nothing of why there was no direct route. +#[derive(Debug)] +struct LocalProxyFallback { + host: String, + port: u16, +} + +impl std::fmt::Display for LocalProxyFallback { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let Self { host, port } = self; + write!( + f, + "could not connect to {host}:{port} without the system proxy, which may be Yaak Proxy" + ) + } +} + +impl std::error::Error for LocalProxyFallback {} + +/// Whether `e`, from [`connect`], is the connection refused for going through a proxy on this +/// Mac, as it does when there is no direct route. +pub(crate) fn is_local_proxy_fallback(e: &io::Error) -> bool { + e.get_ref().is_some_and(|inner| inner.is::()) +} + /// An `nw_connection_t`, cancelled when dropped. struct Connection(NwObject); @@ -635,9 +657,7 @@ async fn open(host: &str, port: u16, configure: impl FnOnce(NwObject)) -> io::Re let via_local_proxy = conn.used_local_proxy().await; attempt.finish(via_local_proxy); if via_local_proxy { - return Err(io::Error::other(format!( - "could not connect to {host}:{port} without the system proxy, which may be Yaak Proxy" - ))); + return Err(io::Error::other(LocalProxyFallback { host: host.to_string(), port })); } Ok(NwStream { remote_addr: conn.remote_addr(), @@ -681,78 +701,6 @@ unsafe fn is_local_endpoint(endpoint: NwObject) -> bool { } } -/// The address a plain-HTTP response came from, in its extensions. -#[derive(Clone, Copy, Debug)] -pub(crate) struct RemoteAddr(pub(crate) SocketAddr); - -/// Connects hyper-util's client to plain-HTTP origins through [`connect`]. -#[derive(Clone, Copy, Default)] -pub(crate) struct Connector; - -impl tower_service::Service for Connector { - type Response = NwIo; - type Error = io::Error; - type Future = Pin> + Send>>; - - fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { - Poll::Ready(Ok(())) - } - - fn call(&mut self, uri: Uri) -> Self::Future { - Box::pin(async move { - let invalid = |message| io::Error::new(io::ErrorKind::InvalidInput, message); - if uri.scheme() != Some(&Scheme::HTTP) { - return Err(invalid("invalid URL, scheme is not http")); - } - let host = uri.host().ok_or_else(|| invalid("invalid URL, host is missing"))?; - let host = host.trim_start_matches('[').trim_end_matches(']'); - let stream = connect(host, uri.port_u16().unwrap_or(80)).await?; - Ok(NwIo(TokioIo::new(stream))) - }) - } -} - -/// [`NwStream`] as hyper's IO, reporting where it connected. -pub(crate) struct NwIo(TokioIo); - -impl HyperConnection for NwIo { - fn connected(&self) -> Connected { - let connected = Connected::new(); - match self.0.inner().remote_addr() { - Some(addr) => connected.extra(RemoteAddr(addr)), - None => connected, - } - } -} - -impl hyper::rt::Read for NwIo { - fn poll_read( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - buf: hyper::rt::ReadBufCursor<'_>, - ) -> Poll> { - Pin::new(&mut self.0).poll_read(cx, buf) - } -} - -impl hyper::rt::Write for NwIo { - fn poll_write( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - buf: &[u8], - ) -> Poll> { - Pin::new(&mut self.0).poll_write(cx, buf) - } - - fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - Pin::new(&mut self.0).poll_flush(cx) - } - - fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - Pin::new(&mut self.0).poll_shutdown(cx) - } -} - #[cfg(test)] mod tests { use std::time::Duration; @@ -1007,6 +955,7 @@ mod tests { .expect("the connection kept waiting") .err() .expect("connected through the local proxy"); + assert!(is_local_proxy_fallback(&err), "{err}"); assert!(err.to_string().contains("without the system proxy"), "{err}"); let (head, own, after) = tokio::time::timeout(WAIT, seen_rx).await.unwrap().unwrap(); diff --git a/crates/yaak-proxy/src/request.rs b/crates/yaak-proxy/src/request.rs index bb3cd0345..bd8720da8 100644 --- a/crates/yaak-proxy/src/request.rs +++ b/crates/yaak-proxy/src/request.rs @@ -17,8 +17,6 @@ use hyper::http::request::Parts; use hyper::http::uri::{Authority, PathAndQuery, Scheme}; use hyper::upgrade::OnUpgrade; use hyper::{Method, Request, Response, StatusCode, Uri}; -#[cfg(not(target_os = "macos"))] -use hyper_util::client::legacy::connect::HttpInfo; use hyper_util::rt::{TokioExecutor, TokioIo}; use log::{debug, info, warn}; use rustls::pki_types::ServerName; @@ -27,7 +25,7 @@ use tokio::net::TcpStream; use tokio_rustls::{LazyConfigAcceptor, TlsConnector}; use crate::body::{BodyParser, CaptureBody, Direction}; -use crate::connection::serve_tls; +use crate::connection::{Reset, ResetHandle, serve_tls}; use crate::decrypt::Verdict; use crate::dial::{self, Dialled, UpstreamIo}; use crate::grpc::{self, GrpcParser}; @@ -279,6 +277,21 @@ impl Flow { .unwrap() } + /// Ends the flow as an error, its server unreachable, and resets the client's connection + /// unanswered, so the client reports a connection error of its own, as it would without the + /// proxy. A response of the engine's would look the server's. + fn unreachable(mut self, unreachable: &dial::Unreachable, conn: &ResetHandle) -> Reset { + self.answered = true; + let error = unreachable.to_string(); + debug!("Flow {} could not reach the server: {error}", self.id); + self.engine.emit(ProxyEvent::Error { + id: self.id, + error, + elapsed_ms: self.start.elapsed().as_millis() as u64, + }); + conn.reset() + } + fn fail(mut self, error: String) -> Response { // The request failed because the client stopped sending its body: it cancelled. The // answer goes nowhere, and dropping the flow unanswered says so. @@ -316,11 +329,14 @@ fn bad_gateway(body: String) -> Response { Response::builder().status(StatusCode::BAD_GATEWAY).body(text_body(body)).unwrap() } +/// Serves a request to the listener. A plain HTTP request whose server can't be reached resets +/// the client's connection through `conn`, failing with the [`Reset`]. pub(crate) async fn handle_request( mut req: Request, client: ClientConn, engine: Arc, -) -> Result, Infallible> { + conn: ResetHandle, +) -> Result, Reset> { if req.method() == Method::CONNECT { return Ok(handle_connect(req, client, engine).await); } @@ -348,21 +364,16 @@ pub(crate) async fn handle_request( let (parts, body) = req.into_parts(); let outgoing = Request::from_parts(parts, flow.capture_request(body)); - Ok(match engine.http_client.request(outgoing).await { + match engine.http_client.request(outgoing).await { Ok(resp) => { - let remote_addr = plain_remote_addr(&resp); - flow.respond(resp, remote_addr) + let remote_addr = resp.extensions().get::().map(|a| a.0); + Ok(flow.respond(resp, remote_addr)) } - Err(e) => flow.fail(error_chain(&e)), - }) -} - -/// The address `Engine::http_client` connected to for `resp`. -fn plain_remote_addr(resp: &Response) -> Option { - #[cfg(target_os = "macos")] - return resp.extensions().get::().map(|a| a.0); - #[cfg(not(target_os = "macos"))] - resp.extensions().get::().map(|i| i.remote_addr()) + Err(e) => match dial::unreachable_of(&e) { + Some(unreachable) => Err(flow.unreachable(unreachable, &conn)), + None => Ok(flow.fail(error_chain(&e))), + }, + } } /// Whether `req` carries this engine's `Via` mark, which it adds to every plain-HTTP request it diff --git a/crates/yaak-proxy/tests/own_fallback.rs b/crates/yaak-proxy/tests/own_fallback.rs index b481a0ba2..ee00fb4d8 100644 --- a/crates/yaak-proxy/tests/own_fallback.rs +++ b/crates/yaak-proxy/tests/own_fallback.rs @@ -10,7 +10,7 @@ use std::time::Duration; use tempfile::TempDir; use tokio::io::{AsyncReadExt, AsyncWriteExt, copy_bidirectional}; use tokio::net::{TcpListener, TcpStream}; -use yaak_proxy::{CaStore, ProxyConfig, start_proxy}; +use yaak_proxy::{CaStore, ProxyConfig, ProxyEvent, start_proxy}; type NwObject = *mut c_void; @@ -52,14 +52,16 @@ async fn read_head(stream: &mut (impl AsyncReadExt + Unpin)) -> String { /// through Network.framework, which falls back to the system proxy, the engine, when there is no /// direct route. That fallback is a CONNECT of the engine's own, which dialling again would /// repeat without end, so it is answered before any dial and refused once it is known to be the -/// engine's own. One `CONNECT` each, then the client gets a 502: for its CONNECT, and for a plain -/// request. +/// engine's own. One `CONNECT` each, then the client's CONNECT gets a 502 and its plain request a +/// reset connection, each recorded with the real reason, the name not resolving, and never the +/// fallback. #[tokio::test(flavor = "multi_thread")] async fn own_fallback_stops() { const TARGET: &str = "yaak-proxy-own-fallback.invalid"; let dir = TempDir::new().unwrap(); let ca = Arc::new(CaStore::load_or_create(dir.path()).unwrap()); - let proxy = start_proxy(ProxyConfig::new(0, ca)).unwrap(); + let mut proxy = start_proxy(ProxyConfig::new(0, ca)).unwrap(); + let events = proxy.take_event_rx().unwrap(); let engine_port = proxy.port; // Counts the CONNECTs on their way from Network.framework to the engine. @@ -98,10 +100,38 @@ async fn own_fallback_stops() { let mut client = TcpStream::connect(("127.0.0.1", engine_port)).await.unwrap(); let request = format!("GET http://{TARGET}/ HTTP/1.1\r\nHost: {TARGET}\r\n\r\n"); client.write_all(request.as_bytes()).await.unwrap(); - let head = tokio::time::timeout(Duration::from_secs(10), read_head(&mut client)) + let mut received = Vec::new(); + let read = tokio::time::timeout(Duration::from_secs(10), client.read_to_end(&mut received)) .await - .expect("no response"); - assert!(head.starts_with("HTTP/1.1 502"), "{head}"); + .expect("the connection stayed open"); + assert!(received.is_empty(), "{}", String::from_utf8_lossy(&received)); + let err = read.expect_err("the connection closed cleanly"); + assert_eq!(err.kind(), std::io::ErrorKind::ConnectionReset, "{err}"); tokio::time::sleep(Duration::from_secs(1)).await; assert_eq!(connects.load(Ordering::SeqCst), 2); + + let events: Vec = events.try_iter().collect(); + let connect_failed = events.iter().find_map(|e| match e { + ProxyEvent::ConnectFailed { authority, error, .. } + if authority == &format!("{TARGET}:80") => + { + Some(error.clone()) + } + _ => None, + }); + let request_id = events.iter().find_map(|e| match e { + ProxyEvent::RequestStart { id, url, .. } if url == &format!("http://{TARGET}/") => { + Some(*id) + } + _ => None, + }); + let request_failed = events.iter().find_map(|e| match e { + ProxyEvent::Error { id, error, .. } if Some(*id) == request_id => Some(error.clone()), + _ => None, + }); + for error in [connect_failed, request_failed] { + let error = error.unwrap_or_else(|| panic!("no failure recorded in {events:#?}")); + assert!(error.starts_with("DNS lookup failed: "), "{error}"); + assert!(!error.contains("system proxy"), "{error}"); + } } diff --git a/crates/yaak-proxy/tests/proxy.rs b/crates/yaak-proxy/tests/proxy.rs index 895029544..fccbcbd80 100644 --- a/crates/yaak-proxy/tests/proxy.rs +++ b/crates/yaak-proxy/tests/proxy.rs @@ -1867,19 +1867,150 @@ async fn plain_http_get() { assert_eq!((status, remote_addr), (200, Some(upstream))); } -#[tokio::test(flavor = "multi_thread")] -async fn unreachable_upstream_is_an_error() { - let h = Harness::start(1024); - let closed = TcpListener::bind("127.0.0.1:0").await.unwrap().local_addr().unwrap(); - let url = format!("http://{closed}/"); +/// Sends `request` on `tcp`, a client's connection to the proxy, and reads what comes back until +/// the connection ends: the bytes, and how it ended. +async fn send_raw(tcp: &mut TcpStream, request: &str) -> (Vec, std::io::Result) { + tcp.write_all(request.as_bytes()).await.unwrap(); + let mut received = Vec::new(); + let read = tokio::time::timeout(Duration::from_secs(15), tcp.read_to_end(&mut received)).await; + (received, read.expect("the connection stayed open")) +} - let resp = h.client().get(&url).send().await.unwrap(); - assert_eq!(resp.status(), 502); +fn get(url: &str, host: &str) -> String { + format!("GET {url} HTTP/1.1\r\nHost: {host}\r\nUser-Agent: yaak-test\r\n\r\n") +} +/// Asserts the client's connection was reset with no response, as a client would see it fail +/// without the proxy, not answered with a response of the engine's that would look the server's. +fn assert_reset((received, read): (Vec, std::io::Result)) { + assert!(received.is_empty(), "{}", String::from_utf8_lossy(&received)); + let err = read.expect_err("the connection closed cleanly"); + assert_eq!(err.kind(), std::io::ErrorKind::ConnectionReset, "{err}"); +} + +/// The one flow of a plain request whose server could not be reached: its request, ended as an +/// error with no response. Returns the error. +fn unreachable_flow(h: &Harness, url: &str) -> String { let events = h.flow_events(); + let starts: Vec<_> = events + .iter() + .filter_map(|e| match e { + ProxyEvent::RequestStart { method, url, .. } => Some((method.clone(), url.clone())), + _ => None, + }) + .collect(); + assert_eq!(starts, [("GET".to_string(), url.to_string())], "{events:#?}"); + assert!(headers(&events, true).contains(&("user-agent".into(), "yaak-test".into()))); + assert!(!events.iter().any(|e| matches!(e, ProxyEvent::ResponseStart { .. })), "{events:#?}"); let error = find!(events, ProxyEvent::Error { error, .. } => error.clone()); - assert!(error.to_lowercase().contains("connect"), "{error}"); - assert!(!events.iter().any(|e| matches!(e, ProxyEvent::ResponseStart { .. }))); + assert!(!error.contains("system proxy"), "{error}"); + error +} + +/// A server that can't be reached resets the client's connection, as connecting to it without +/// the proxy would have failed, and the flow ends as an error with the reason in plain words. +#[tokio::test(flavor = "multi_thread")] +async fn a_name_that_does_not_resolve_resets_the_plain_request() { + within(async { + let h = Harness::start(1024); + let url = "http://yaak-proxy-test.invalid/"; + let mut tcp = TcpStream::connect(("127.0.0.1", h.proxy.port)).await.unwrap(); + assert_reset(send_raw(&mut tcp, &get(url, "yaak-proxy-test.invalid")).await); + let error = unreachable_flow(&h, url); + assert!(error.starts_with("DNS lookup failed: "), "{error}"); + }) + .await +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_closed_port_resets_the_plain_request() { + within(async { + let h = Harness::start(1024); + let closed = TcpListener::bind("127.0.0.1:0").await.unwrap().local_addr().unwrap(); + let url = format!("http://{closed}/"); + let mut tcp = TcpStream::connect(("127.0.0.1", h.proxy.port)).await.unwrap(); + assert_reset(send_raw(&mut tcp, &get(&url, &closed.to_string())).await); + let error = unreachable_flow(&h, &url); + assert!(error.starts_with("Connection refused: "), "{error}"); + }) + .await +} + +/// A client sees the failure as its own connection error. +#[tokio::test(flavor = "multi_thread")] +async fn an_unreachable_server_is_a_connection_error_to_the_client() { + within(async { + let h = Harness::start(1024); + let closed = TcpListener::bind("127.0.0.1:0").await.unwrap().local_addr().unwrap(); + let err = h.client().get(format!("http://{closed}/")).send().await.unwrap_err(); + assert!(err.status().is_none(), "{err:?}"); + let error = find!(h.flow_events(), ProxyEvent::Error { error, .. } => error.clone()); + assert!(error.starts_with("Connection refused: "), "{error}"); + }) + .await +} + +/// Only the connection the failed request came on is reset: the request before it on that +/// connection was answered, and a new connection works. +#[tokio::test(flavor = "multi_thread")] +async fn a_failed_request_resets_its_keep_alive_connection_alone() { + within(async { + let h = Harness::start(1024); + let upstream = spawn_upstream(None).await; + let hello = format!("http://{upstream}/hello"); + let closed = TcpListener::bind("127.0.0.1:0").await.unwrap().local_addr().unwrap(); + let unreachable = format!("http://{closed}/"); + + let mut tcp = TcpStream::connect(("127.0.0.1", h.proxy.port)).await.unwrap(); + tcp.write_all(get(&hello, &upstream.to_string()).as_bytes()).await.unwrap(); + let mut head = Vec::new(); + while !head.ends_with(b"\r\n\r\n") { + head.push(tcp.read_u8().await.unwrap()); + } + let head = String::from_utf8(head).unwrap(); + assert!(head.starts_with("HTTP/1.1 200"), "{head}"); + assert!(head.to_ascii_lowercase().contains("content-length: 5\r\n"), "{head}"); + let mut body = [0u8; 5]; + tcp.read_exact(&mut body).await.unwrap(); + assert_eq!(&body, b"hello"); + assert_reset(send_raw(&mut tcp, &get(&unreachable, &closed.to_string())).await); + + assert_eq!(h.client().get(&hello).send().await.unwrap().text().await.unwrap(), "hello"); + + let flows = h.flows_events(3); + let mut ends: Vec<_> = flows + .values() + .map(|events| { + let url = find!(events, ProxyEvent::RequestStart { url, .. } => url.clone()); + let status = events.iter().find_map(|e| match e { + ProxyEvent::ResponseStart { status, .. } => Some(*status), + _ => None, + }); + let error = events.iter().find_map(|e| match e { + ProxyEvent::Error { error, .. } => Some(error.clone()), + _ => None, + }); + ( + flow_id(&events[0]), + url, + status, + error.is_some_and(|e| e.starts_with("Connection refused: ")), + ) + }) + .collect(); + ends.sort(); + let ends: Vec<_> = + ends.into_iter().map(|(_, url, status, refused)| (url, status, refused)).collect(); + assert_eq!( + ends, + [ + (hello.clone(), Some(200), false), + (unreachable, None, true), + (hello, Some(200), false) + ] + ); + }) + .await } /// Telegram's HTTP transport request, `POST /api` with only `Host` to say where it goes, from the