Skip to content

Commit 75bec21

Browse files
fix: route plain HTTP proxy requests direct in google_only mode (#256)
1 parent a028df8 commit 75bec21

1 file changed

Lines changed: 238 additions & 17 deletions

File tree

‎src/proxy_server.rs‎

Lines changed: 238 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -461,25 +461,21 @@ async fn handle_http_client(
461461
sock.flush().await?;
462462
dispatch_tunnel(sock, host, port, fronter, mitm, rewrite_ctx, tunnel_mux).await
463463
} else {
464-
// Plain HTTP proxy request (e.g. `GET http://…`). The Apps Script
465-
// relay is the only code path that can fulfil this, so in google_only
466-
// bootstrap mode we return a clear 502 instead.
464+
// Plain HTTP proxy request (e.g. `GET http://…`).
465+
//
466+
// apps_script mode: relay through the Apps Script fronter (which
467+
// is the whole point of the relay).
468+
//
469+
// google_only bootstrap mode: no fronter exists, so passthrough as
470+
// direct TCP. Same contract as `dispatch_tunnel` honors for CONNECT
471+
// in google_only — anything not on the Google edge is forwarded
472+
// direct (or via `upstream_socks5`) so the user's browser still
473+
// works while they finish setting up Apps Script. Issue: typing a
474+
// bare `http://example.com` URL used to return a 502 here even
475+
// though `https://example.com` (CONNECT) worked fine.
467476
match fronter {
468477
Some(f) => do_plain_http(sock, &head, &leftover, f).await,
469-
None => {
470-
let _ = sock
471-
.write_all(
472-
b"HTTP/1.1 502 Bad Gateway\r\n\
473-
Content-Type: text/plain; charset=utf-8\r\n\
474-
Content-Length: 120\r\n\
475-
Connection: close\r\n\r\n\
476-
google_only mode: plain HTTP proxy requests are not supported. \
477-
Browse https over CONNECT, or switch to apps_script mode.",
478-
)
479-
.await;
480-
let _ = sock.flush().await;
481-
Ok(())
482-
}
478+
None => do_plain_http_passthrough(sock, &head, &leftover, &rewrite_ctx).await,
483479
}
484480
}
485481
}
@@ -2203,6 +2199,174 @@ async fn do_plain_http(
22032199
Ok(())
22042200
}
22052201

2202+
/// google_only mode plain-HTTP passthrough. The CONNECT path already
2203+
/// falls through to direct TCP for non-Google-edge hosts in google_only;
2204+
/// this is the same idea for the `GET http://…` proxy form so a bare
2205+
/// `http://example.com` typed in the address bar doesn't 502.
2206+
///
2207+
/// We rewrite the absolute-form request URI (`GET http://host/path`) to
2208+
/// origin form (`GET /path`), strip hop-by-hop headers, force
2209+
/// `Connection: close` so a keep-alive client can't pipeline a request
2210+
/// to a different host onto our spliced socket, then dial the origin
2211+
/// (honoring `upstream_socks5` if set) and splice both directions.
2212+
async fn do_plain_http_passthrough(
2213+
mut sock: TcpStream,
2214+
head: &[u8],
2215+
leftover: &[u8],
2216+
rewrite_ctx: &RewriteCtx,
2217+
) -> std::io::Result<()> {
2218+
let (method, target, version, headers) = match parse_request_head(head) {
2219+
Some(v) => v,
2220+
None => return Ok(()),
2221+
};
2222+
2223+
let (host, port, path) = match resolve_plain_http_target(&target, &headers) {
2224+
Some(v) => v,
2225+
None => {
2226+
tracing::debug!("plain-http passthrough: cannot parse target {}", target);
2227+
return Ok(());
2228+
}
2229+
};
2230+
2231+
tracing::info!(
2232+
"dispatch http {}:{} -> raw-tcp ({}) (google_only: no relay)",
2233+
host,
2234+
port,
2235+
rewrite_ctx.upstream_socks5.as_deref().unwrap_or("direct"),
2236+
);
2237+
2238+
// Rewrite request line to origin form and drop hop-by-hop headers.
2239+
let mut rewritten = Vec::with_capacity(head.len());
2240+
rewritten.extend_from_slice(method.as_bytes());
2241+
rewritten.push(b' ');
2242+
rewritten.extend_from_slice(path.as_bytes());
2243+
rewritten.push(b' ');
2244+
rewritten.extend_from_slice(version.as_bytes());
2245+
rewritten.extend_from_slice(b"\r\n");
2246+
for (k, v) in &headers {
2247+
let kl = k.to_ascii_lowercase();
2248+
if kl == "proxy-connection" || kl == "connection" || kl == "keep-alive" {
2249+
continue;
2250+
}
2251+
rewritten.extend_from_slice(k.as_bytes());
2252+
rewritten.extend_from_slice(b": ");
2253+
rewritten.extend_from_slice(v.as_bytes());
2254+
rewritten.extend_from_slice(b"\r\n");
2255+
}
2256+
rewritten.extend_from_slice(b"Connection: close\r\n\r\n");
2257+
2258+
let target_host = host.trim_start_matches('[').trim_end_matches(']');
2259+
let connect_timeout = if looks_like_ip(target_host) {
2260+
std::time::Duration::from_secs(4)
2261+
} else {
2262+
std::time::Duration::from_secs(10)
2263+
};
2264+
let upstream = if let Some(proxy) = rewrite_ctx.upstream_socks5.as_deref() {
2265+
match socks5_connect_via(proxy, target_host, port).await {
2266+
Ok(s) => s,
2267+
Err(e) => {
2268+
tracing::warn!(
2269+
"upstream-socks5 {} -> {}:{} failed: {} (falling back to direct)",
2270+
proxy,
2271+
host,
2272+
port,
2273+
e
2274+
);
2275+
match tokio::time::timeout(
2276+
connect_timeout,
2277+
TcpStream::connect((target_host, port)),
2278+
)
2279+
.await
2280+
{
2281+
Ok(Ok(s)) => s,
2282+
_ => return Ok(()),
2283+
}
2284+
}
2285+
}
2286+
} else {
2287+
match tokio::time::timeout(connect_timeout, TcpStream::connect((target_host, port))).await {
2288+
Ok(Ok(s)) => s,
2289+
Ok(Err(e)) => {
2290+
tracing::debug!("plain-http connect {}:{} failed: {}", host, port, e);
2291+
return Ok(());
2292+
}
2293+
Err(_) => {
2294+
tracing::debug!("plain-http connect {}:{} timeout", host, port);
2295+
return Ok(());
2296+
}
2297+
}
2298+
};
2299+
let _ = upstream.set_nodelay(true);
2300+
2301+
let (mut ar, mut aw) = sock.split();
2302+
let (mut br, mut bw) = upstream.into_split();
2303+
bw.write_all(&rewritten).await?;
2304+
if !leftover.is_empty() {
2305+
bw.write_all(leftover).await?;
2306+
}
2307+
let t1 = tokio::io::copy(&mut ar, &mut bw);
2308+
let t2 = tokio::io::copy(&mut br, &mut aw);
2309+
tokio::select! {
2310+
_ = t1 => {}
2311+
_ = t2 => {}
2312+
}
2313+
Ok(())
2314+
}
2315+
2316+
/// Parse the target of a plain-HTTP proxy request line into
2317+
/// `(host, port, origin-form-path)`. Browsers send absolute form
2318+
/// (`http://host[:port]/path`); we also accept the origin-form
2319+
/// fallback (`/path` with a `Host:` header) for transparent-proxy
2320+
/// clients. `https://` is accepted defensively, though browsers route
2321+
/// HTTPS through CONNECT and shouldn't hit this path.
2322+
fn resolve_plain_http_target(
2323+
target: &str,
2324+
headers: &[(String, String)],
2325+
) -> Option<(String, u16, String)> {
2326+
let (rest, default_port) = if let Some(r) = target.strip_prefix("http://") {
2327+
(r, 80u16)
2328+
} else if let Some(r) = target.strip_prefix("https://") {
2329+
(r, 443u16)
2330+
} else if target.starts_with('/') {
2331+
let host_header = headers
2332+
.iter()
2333+
.find(|(k, _)| k.eq_ignore_ascii_case("host"))
2334+
.map(|(_, v)| v.as_str())?;
2335+
let (host, port) = split_authority(host_header, 80);
2336+
return Some((host, port, target.to_string()));
2337+
} else {
2338+
return None;
2339+
};
2340+
2341+
let (authority, path) = match rest.find('/') {
2342+
Some(i) => (&rest[..i], &rest[i..]),
2343+
None => (rest, "/"),
2344+
};
2345+
if authority.is_empty() {
2346+
return None;
2347+
}
2348+
let (host, port) = split_authority(authority, default_port);
2349+
Some((host, port, path.to_string()))
2350+
}
2351+
2352+
/// Split an `authority` (`host[:port]`, with optional IPv6 brackets)
2353+
/// into a `(host, port)` pair, defaulting the port when absent.
2354+
fn split_authority(authority: &str, default_port: u16) -> (String, u16) {
2355+
// Bare IPv6 (multiple colons, no brackets) — `rsplit_once(':')`
2356+
// would otherwise mangle `::1` into `(":", 1)`. Take the whole
2357+
// string as the host and use the default port.
2358+
let colons = authority.bytes().filter(|&b| b == b':').count();
2359+
if colons > 1 && !authority.starts_with('[') {
2360+
return (authority.to_string(), default_port);
2361+
}
2362+
if let Some((h, p)) = authority.rsplit_once(':') {
2363+
if let Ok(port) = p.parse::<u16>() {
2364+
return (h.to_string(), port);
2365+
}
2366+
}
2367+
(authority.to_string(), default_port)
2368+
}
2369+
22062370
#[cfg(test)]
22072371
mod tests {
22082372
use super::*;
@@ -2215,6 +2379,63 @@ mod tests {
22152379
.collect()
22162380
}
22172381

2382+
#[test]
2383+
fn resolve_plain_http_target_parses_absolute_form() {
2384+
let h = headers(&[]);
2385+
let (host, port, path) =
2386+
resolve_plain_http_target("http://example.com/", &h).unwrap();
2387+
assert_eq!(host, "example.com");
2388+
assert_eq!(port, 80);
2389+
assert_eq!(path, "/");
2390+
2391+
let (host, port, path) =
2392+
resolve_plain_http_target("http://example.com:8080/foo?x=1", &h).unwrap();
2393+
assert_eq!(host, "example.com");
2394+
assert_eq!(port, 8080);
2395+
assert_eq!(path, "/foo?x=1");
2396+
2397+
let (host, port, path) =
2398+
resolve_plain_http_target("http://example.com", &h).unwrap();
2399+
assert_eq!(host, "example.com");
2400+
assert_eq!(port, 80);
2401+
assert_eq!(path, "/");
2402+
}
2403+
2404+
#[test]
2405+
fn resolve_plain_http_target_falls_back_to_host_header() {
2406+
let h = headers(&[("Host", "example.com:8080")]);
2407+
let (host, port, path) = resolve_plain_http_target("/foo", &h).unwrap();
2408+
assert_eq!(host, "example.com");
2409+
assert_eq!(port, 8080);
2410+
assert_eq!(path, "/foo");
2411+
}
2412+
2413+
#[test]
2414+
fn resolve_plain_http_target_rejects_bare_authority() {
2415+
// No scheme, doesn't start with `/` — not something we can route.
2416+
assert!(resolve_plain_http_target("example.com", &headers(&[])).is_none());
2417+
assert!(resolve_plain_http_target("http://", &headers(&[])).is_none());
2418+
}
2419+
2420+
#[test]
2421+
fn split_authority_handles_ports_and_ipv6() {
2422+
assert_eq!(
2423+
split_authority("example.com", 80),
2424+
("example.com".to_string(), 80)
2425+
);
2426+
assert_eq!(
2427+
split_authority("example.com:8080", 80),
2428+
("example.com".to_string(), 8080)
2429+
);
2430+
assert_eq!(
2431+
split_authority("[::1]:8080", 80),
2432+
("[::1]".to_string(), 8080)
2433+
);
2434+
// Bare IPv6 without brackets — keep the whole string as the host
2435+
// and use the default port instead of mis-splitting on a colon.
2436+
assert_eq!(split_authority("::1", 80), ("::1".to_string(), 80));
2437+
}
2438+
22182439
#[test]
22192440
fn socks5_udp_domain_packet_round_trips() {
22202441
let mut raw = vec![0, 0, 0, 0x03, 11];

0 commit comments

Comments
 (0)