Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: browser panel follows the system proxy on macOS, Windows and Linux (#14029)

Long Yixingb4a4855e49c6
diff --git a/studio/backend/core/inference/browser_agent.py b/studio/backend/core/inference/browser_agent.py
index f33e6b3d91e..f561c86a7b3 100644
--- a/studio/backend/core/inference/browser_agent.py
+++ b/studio/backend/core/inference/browser_agent.py
@@ -326,7 +326,16 @@ _HIDDEN_TAIL_RE = re.compile(r"(?:[ \t]*\r?\n){4,}|[ \t]{200,}")
_MAX_POINT = 100_000
_MAX_MODEL_CHARS = 24000
_REF_RE = re.compile(r"^\[?r?(\d{1,9})\]?$", re.IGNORECASE)
-_LOCAL_SUFFIXES = (".local", ".localhost", ".internal", ".lan", ".home", ".home.arpa", ".corp")
+_LOCAL_SUFFIXES = (
+ ".local",
+ ".localhost",
+ ".internal",
+ ".lan",
+ ".home",
+ ".home.arpa",
+ ".corp",
+ ".intranet",
+)
_FENCE = "untrusted_web_content"
@@ -385,7 +394,7 @@ def _host_problem(hostname: str) -> Optional[str]:
ip = None
if ip is not None:
return None if ip.is_global else f"{host} is not a public address"
- if host == "localhost" or "." not in host or host.endswith(_LOCAL_SUFFIXES):
+ if host == "localhost" or "." not in host or f".{host}".endswith(_LOCAL_SUFFIXES):
return f"{host} is a local name"
return None
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 4f0b2dabcaf..b8ee09696cf 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -114,6 +114,8 @@ _RAG_SEARCH_SLOT = threading.BoundedSemaphore(1)
# Candidate multiplier when a website policy will filter the results after the search.
_POLICY_OVERFETCH = 4
_DISABLE_DNS_PINNING_ENV = "UNSLOTH_STUDIO_DISABLE_DNS_PINNING"
+# How a lookup that found no address starts, as opposed to a refused one.
+_RESOLVE_FAILED = "Failed to resolve host"
# Splits the UI source-map from the result; loops strip it (like __IMAGES__).
RAG_SOURCES_SENTINEL = "\n__RAG_SOURCES__:"
@@ -15898,12 +15900,13 @@ _PINNED_DIAL_TIMEOUT = 1.0
_PINNED_PROBE_BUDGET = 0.25
-def _pinned_create_connection(addresses):
+def _pinned_create_connection(addresses, origin = None):
"""``socket.create_connection`` that walks *addresses* instead of resolving.
Pinning to one validated address dropped the walk every other client gets. Walking
here rather than around ``opener.open`` keeps the caller's timeout covering one
- whole response.
+ whole response. A direct dial of *origin*, a name sent on for a proxy, walks them
+ too: the opener reads the proxy settings again, and must not look the name up afresh.
"""
import socket
@@ -15915,8 +15918,10 @@ def _pinned_create_connection(addresses):
if timeout is socket._GLOBAL_DEFAULT_TIMEOUT:
timeout = socket.getdefaulttimeout()
# A proxy dial is not an origin dial, and callers withhold the addresses for it.
- if address[0] not in addresses:
+ if address[0] not in addresses and address[0] != origin:
return socket.create_connection(address, timeout, source_address)
+ if not addresses:
+ raise OSError(f"{origin} did not resolve here and no proxy took it")
port = address[1]
expiry = None if timeout is None else time.monotonic() + timeout
@@ -15972,12 +15977,13 @@ class _PinnedHTTPSConnection(http.client.HTTPSConnection):
*,
sni_hostname: str,
addresses = (),
+ origin = None,
**kwargs,
):
super().__init__(host, **kwargs)
self._sni_hostname = sni_hostname
- if addresses:
- self._create_connection = _pinned_create_connection(tuple(addresses))
+ if addresses or origin:
+ self._create_connection = _pinned_create_connection(tuple(addresses), origin)
def connect(self):
http.client.HTTPConnection.connect(self)
@@ -16001,10 +16007,12 @@ class _SNIHTTPSHandler(urllib.request.HTTPSHandler):
self,
hostname: str,
addresses = (),
+ origin = None,
):
super().__init__(context = _tls_ctx)
self._sni_hostname = hostname
self._addresses = tuple(addresses)
+ self._origin = origin
def https_open(self, req):
return self.do_open(self._sni_connection, req)
@@ -16015,22 +16023,28 @@ class _SNIHTTPSHandler(urllib.request.HTTPSHandler):
host,
sni_hostname = self._sni_hostname,
addresses = self._addresses,
+ origin = self._origin,
**kwargs,
)
class _PinnedHTTPHandler(urllib.request.HTTPHandler):
- def __init__(self, addresses = ()):
+ def __init__(
+ self,
+ addresses = (),
+ origin = None,
+ ):
super().__init__()
self._addresses = tuple(addresses)
+ self._origin = origin
def http_open(self, req):
return self.do_open(self._pinned_connection, req)
def _pinned_connection(self, host, **kwargs):
conn = http.client.HTTPConnection(host, **kwargs)
- if self._addresses:
- conn._create_connection = _pinned_create_connection(self._addresses)
+ if self._addresses or self._origin:
+ conn._create_connection = _pinned_create_connection(self._addresses, self._origin)
return conn
@@ -16072,10 +16086,10 @@ def _validate_and_resolve_host(hostname: str, port: int) -> tuple[bool, str, lis
infos = socket.getaddrinfo(hostname, port, type = socket.SOCK_STREAM)
except (OSError, UnicodeError) as e:
# IDNA encoding rejects a hostname with UnicodeError, not OSError.
- return False, f"Failed to resolve host: {e}", []
+ return False, f"{_RESOLVE_FAILED}: {e}", []
if not infos:
- return False, f"Failed to resolve host: no addresses for {hostname!r}", []
+ return False, f"{_RESOLVE_FAILED}: no addresses for {hostname!r}", []
resolved = []
for *_, sockaddr in infos:
@@ -16253,7 +16267,7 @@ def _resolve_with_budget(hostname, port, deadline, cancel_event):
try:
result.put(_validate_and_resolve_host(hostname, port))
except Exception as exc: # prevent the resolver thread from failing silently
- result.put((False, f"Failed to resolve host: {exc}", []))
+ result.put((False, f"{_RESOLVE_FAILED}: {exc}", []))
threading.Thread(target = _resolve, name = "web-fetch-dns", daemon = True).start()
while True:
@@ -16622,19 +16636,13 @@ def _pinned_netloc(ip: str, port: int | None) -> str:
return f"{host}:{port}" if port else host
-def _redirect_hop(url: str, website_policy, deadline, cancel_event) -> tuple[str | None, str, list]:
- from urllib.parse import urlparse
+def _redirect_hop(url: str, website_policy) -> tuple[str | None, str]:
from .web_access_policy import check_url_access
allowed, reason, host = check_url_access(url, website_policy)
if not allowed:
- return reason, "", []
- parsed = urlparse(url)
- port = parsed.port or (443 if parsed.scheme == "https" else 80)
- ok, reason, pinned_ips = _resolve_with_budget(host, port, deadline, cancel_event)
- if not ok:
- return reason, "", []
- return None, host, pinned_ips
+ return reason, ""
+ return None, host
def _is_bot_check(status: int, headers) -> bool:
@@ -16670,10 +16678,12 @@ def _fetch_url_raw(
method: str | None = None,
any_status: bool = False,
on_redirect = None,
+ proxy_hostname: bool | None = None,
) -> tuple[str | None, "str | bytes", str]:
"""fetch with SSRF protection; binary reads stay capped, HTML error pages require binary mode, per-hop headers do not cross redirects, and deadlines cover redirects and body reads.
``method`` replaces the GET/POST chosen from ``post_data``; with ``any_status`` (binary mode) every status returns its body, and ``meta_out`` gets the status and headers.
- ``on_redirect(url, method, has_body, headers)`` runs before a redirect is followed, with the redirect's headers; a string it returns is the error, and the hop is never sent."""
+ ``on_redirect(url, method, has_body, headers)`` runs before a redirect is followed, with the redirect's headers; a string it returns is the error, and the hop is never sent.
+ ``proxy_hostname`` sends a system proxy the hostname instead of the validated IP, and lets a proxied hop whose name doesn't resolve here go on; ``None`` follows ``--disable-dns-pinning``."""
from urllib.parse import urlparse
from .web_access_policy import check_url_access
@@ -16683,17 +16693,8 @@ def _fetch_url_raw(
if not allowed:
return reason, "", ""
- # check_url_access already parsed this and read .port, so this cannot raise.
- parsed = urlparse(url)
- port = parsed.port or (443 if parsed.scheme == "https" else 80)
- ok, reason, pinned_ips = _resolve_with_budget(
- canonical_host,
- port,
- deadline,
- cancel_event,
- )
- if not ok:
- return reason, "", ""
+ if proxy_hostname is None:
+ proxy_hostname = os.environ.get(_DISABLE_DNS_PINNING_ENV) == "1"
try:
from urllib.error import HTTPError as _HTTPError
@@ -16725,7 +16726,24 @@ def _fetch_url_raw(
# Decide routing once, on the netloc urllib tests: a pinned request carries an IP, which no NO_PROXY entry
# matches, so the opener below has to carry the decision rather than re-derive it.
proxied = _explicit_proxy_applies(cp.scheme, validated_netloc)
- if os.environ.get(_DISABLE_DNS_PINNING_ENV) == "1" and proxied:
+ # Resolved after routing: a name that reaches the proxy may resolve only there (proxy-only networks),
+ # and a poisoned answer here never gets used. Non-public answers are refused either way.
+ ok, reason, pinned_ips = _resolve_with_budget(
+ current_host,
+ cp.port or (443 if cp.scheme == "https" else 80),
+ deadline,
+ cancel_event,
+ )
+ named = proxied and proxy_hostname
+ if not ok and not (named and reason.startswith(_RESOLVE_FAILED)):
+ return reason, "", ""
+ if named:
+ from .browser_agent import _host_problem
+
+ # The proxy resolves what it gets, so a local name must not reach it, as in the desktop's page proxy.
+ local = _host_problem(current_host)
+ if local:
+ return f"Blocked: {local}.", "", ""
# Enterprise proxies need the hostname in CONNECT for policy and TLS interception, and they resolve
# it, so nothing rebinds behind us.
request_url = urlunparse(cp._replace(netloc = validated_netloc))
@@ -16734,11 +16752,12 @@ def _fetch_url_raw(
request_url = urlunparse(cp._replace(netloc = _pinned_netloc(pinned_ips[0], cp.port)))
# The proxy makes the origin connection, to the one address the URL pins.
- walk = () if proxied else pinned_ips
+ walk = () if proxied and not named else pinned_ips
+ origin = current_host if named else None
handlers = [
_NoRedirect,
- _SNIHTTPSHandler(current_host, walk),
- _PinnedHTTPHandler(walk),
+ _SNIHTTPSHandler(current_host, walk, origin),
+ _PinnedHTTPHandler(walk, origin),
]
if not proxied:
# An empty ProxyHandler is the documented way to opt a request out.
@@ -16799,12 +16818,7 @@ def _fetch_url_raw(
)
if refused:
return refused, "", ""
- hop_error, current_host, pinned_ips = _redirect_hop(
- current_url,
- website_policy,
- deadline,
- cancel_event,
- )
+ hop_error, current_host = _redirect_hop(current_url, website_policy)
if hop_error is not None:
return hop_error, "", ""
continue
@@ -16882,12 +16896,7 @@ def _fetch_url_raw(
current_url = refresh_url
# a refresh starts a new GET like a browser.
pending_post = None
- hop_error, current_host, pinned_ips = _redirect_hop(
- current_url,
- website_policy,
- deadline,
- cancel_event,
- )
+ hop_error, current_host = _redirect_hop(current_url, website_policy)
if hop_error is not None:
return hop_error, "", ""
else:
diff --git a/studio/backend/routes/browser.py b/studio/backend/routes/browser.py
index e65c5032274..c132aa0e7cd 100644
--- a/studio/backend/routes/browser.py
+++ b/studio/backend/routes/browser.py
@@ -1582,6 +1582,7 @@ def _fetch_module(
meta_out = meta,
cancel_event = cancel_event,
host_headers = _studio_headers,
+ proxy_hostname = True,
)
except Exception as exc:
logger.warning("browser_module_fetch_failed", error = type(exc).__name__)
@@ -1732,6 +1733,7 @@ def _fetch(
cancel_event = cancel_event,
host_headers = _studio_headers,
error_page = request.error_page,
+ proxy_hostname = True,
)
return error, body if isinstance(body, bytes) else b"", content_type, meta
@@ -2002,6 +2004,7 @@ def _page_request(request: BrowserPageRequest, cancel_event: threading.Event) ->
method = method,
any_status = True,
on_redirect = on_redirect,
+ proxy_hostname = True,
)
# "manual" gets an opaque redirect: no status, headers or body reach the page.
if hops["stopped"] and request.redirect == "manual":
diff --git a/studio/backend/run.py b/studio/backend/run.py
index 9996dd45797..e6f553521b7 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -3217,7 +3217,8 @@ def _build_arg_parser():
action = "store_true",
help = "Send the hostname (not the validated IP) in web fetches that go through an "
"explicitly configured HTTP(S)_PROXY, so the proxy can apply hostname policy and "
- "TLS interception. Direct fetches stay pinned to the validated IP.",
+ "TLS interception, and let them go on when the name doesn't resolve locally. The "
+ "browser panel's fetches always do. Direct fetches stay pinned to the validated IP.",
)
parser.add_argument(
"--parallel",
diff --git a/studio/backend/tests/test_browser_routes.py b/studio/backend/tests/test_browser_routes.py
index 9e22d12aa46..d4cdb152274 100644
--- a/studio/backend/tests/test_browser_routes.py
+++ b/studio/backend/tests/test_browser_routes.py
@@ -885,6 +885,7 @@ def _serve(
monkeypatch.setattr(
tools, "_validate_and_resolve_host", lambda host, port: (True, "", ["127.0.0.1"])
)
+ monkeypatch.setattr(tools, "_explicit_proxy_applies", lambda scheme, host: False)
return f"http://example.com:{server.getsockname()[1]}/missing"
diff --git a/studio/backend/tests/test_web_fetch_extraction.py b/studio/backend/tests/test_web_fetch_extraction.py
index 4bc9c68206e..85ce2ff5599 100644
--- a/studio/backend/tests/test_web_fetch_extraction.py
+++ b/studio/backend/tests/test_web_fetch_extraction.py
@@ -2014,6 +2014,13 @@ def test_pinned_https_connection_walks_a_bracketed_ipv6_host(monkeypatch):
assert sock.address == (addresses[1], 443)
assert [ip for ip, _timeout in calls] == list(addresses)
+ name = "example.com"
+ for conn in (
+ tools_mod._SNIHTTPSHandler(name, (), name)._sni_connection(name),
+ tools_mod._PinnedHTTPHandler((), name)._pinned_connection(name),
+ ):
+ with pytest.raises(OSError, match = "no proxy took it"):
+ conn._create_connection((name, 443), 30, None)
def test_pinned_http_handler_walks_through_a_real_opener(monkeypatch):
@@ -2123,8 +2130,10 @@ def test_fetch_url_raw_pins_one_address_and_hands_urllib_every_address(monkeypat
(True, True, "https://example.com:8443/page?q=1"),
],
)
[email protected]("proxy_hostname", [None, True])
[email protected]("failure", [None, "Failed to resolve host: x", "Blocked: x"])
def test_fetch_url_raw_dns_pinning_proxy_opt_out(
- monkeypatch, disable_dns_pinning, proxied, expected_url
+ monkeypatch, disable_dns_pinning, proxied, expected_url, proxy_hostname, failure
):
import email
import urllib.request
@@ -2156,7 +2165,7 @@ def test_fetch_url_raw_dns_pinning_proxy_opt_out(
def resolve(host, port):
resolved.append((host, port))
- return True, "", ["203.0.113.7"]
+ return (False, failure, []) if failure else (True, "", ["203.0.113.7"])
monkeypatch.setenv("UNSLOTH_STUDIO_DISABLE_DNS_PINNING", "1" if disable_dns_pinning else "0")
built = []
@@ -2178,16 +2187,74 @@ def test_fetch_url_raw_dns_pinning_proxy_opt_out(
# No embedded credentials: the web access policy rejects those outright
# (see test_fetch_url_raw_rejects_embedded_credentials).
- err, body, _content_type = tools_mod._fetch_url_raw("https://example.com:8443/page?q=1")
+ url = "https://example.com:8443/page?q=1"
+ err, body, _content_type = tools_mod._fetch_url_raw(url, proxy_hostname = proxy_hostname)
+ named = proxied and (proxy_hostname or disable_dns_pinning)
+ if failure and not (named and failure.startswith("Failed to resolve")):
+ assert err == failure and not requested
+ return
assert err is None
assert body == "ok"
assert resolved == [("example.com", 8443)]
- assert [req.full_url for req in requested] == [expected_url]
+ assert [req.full_url for req in requested] == [url if named else expected_url]
assert requested[0].get_header("Host") == "example.com:8443"
for handler_type in (tools_mod._SNIHTTPSHandler, tools_mod._PinnedHTTPHandler):
handler = next(h for h in built[0] if isinstance(h, handler_type))
- assert handler._addresses == (() if proxied else ("203.0.113.7",))
+ assert handler._addresses == (
+ () if (proxied and not named) or failure else ("203.0.113.7",)
+ )
+ assert handler._origin == ("example.com" if named else None)
+
+
+ "host",
+ ["intranet", "printer.local", "nas.lan", "router.home.arpa", "home.arpa", "wiki.intranet"],
+)
+def test_fetch_url_raw_named_proxy_fetch_refuses_local_names(monkeypatch, host):
+ import socket
+ import threading
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+ import core.inference.tools as tools_mod
+
+ seen = []
+
+ class Proxy(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def do_GET(self):
+ seen.append(self.path)
+ self.send_response(200)
+ self.send_header("Content-Length", "2")
+ self.end_headers()
+ self.wfile.write(b"ok")
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Proxy)
+ threading.Thread(target = server.serve_forever, daemon = True).start()
+ for name in ("NO_PROXY", "no_proxy", "ALL_PROXY", "all_proxy", "HTTPS_PROXY", "https_proxy"):
+ monkeypatch.delenv(name, raising = False)
+ monkeypatch.setenv("HTTP_PROXY", f"http://127.0.0.1:{server.server_address[1]}")
+ monkeypatch.setenv("http_proxy", f"http://127.0.0.1:{server.server_address[1]}")
+ real_getaddrinfo = socket.getaddrinfo
+
+ def nxdomain(name, *args, **kwargs):
+ if name == host:
+ raise socket.gaierror(socket.EAI_NONAME, "Name or service not known")
+ return real_getaddrinfo(name, *args, **kwargs)
+
+ monkeypatch.setattr(socket, "getaddrinfo", nxdomain)
+ try:
+ err, _, _ = tools_mod._fetch_url_raw(
+ f"http://{host}/page",
+ deadline = time.monotonic() + 4,
+ proxy_hostname = True,
+ )
+ finally:
+ server.shutdown()
+ assert err == f"Blocked: {host} is a local name."
+ assert seen == []
def test_fetch_url_raw_proxy_scheme_key_case_insensitive(monkeypatch):
diff --git a/studio/src-tauri/Cargo.lock b/studio/src-tauri/Cargo.lock
index f7579a18d3b..c107a48ff1e 100644
--- a/studio/src-tauri/Cargo.lock
+++ b/studio/src-tauri/Cargo.lock
@@ -5687,9 +5687,12 @@ dependencies = [
"elevated-command",
"gdk",
"gdk-pixbuf",
+ "gio",
"glib",
"gtk",
"hmac",
+ "http",
+ "hyper-util",
"libc",
"log",
"minisign-verify 0.3.0",
@@ -5709,6 +5712,7 @@ dependencies = [
"signal-hook",
"simplelog",
"strip-ansi-escapes",
+ "system-configuration",
"tauri",
"tauri-build",
"tauri-plugin-autostart",
diff --git a/studio/src-tauri/Cargo.toml b/studio/src-tauri/Cargo.toml
index 3ae00cd06a4..acfed3bf8ab 100644
--- a/studio/src-tauri/Cargo.toml
+++ b/studio/src-tauri/Cargo.toml
@@ -29,6 +29,9 @@ semver = "1"
hmac = "0.13"
sha2 = "0.11"
reqwest = { version = "0.13", features = ["json"] }
+# The system proxy browser-panel pages go through (browser_proxy.rs); reqwest already builds both.
+hyper-util = { version = "0.1.20", features = ["client-proxy", "client-proxy-system"] }
+http = "1"
tokio = { version = "1", features = ["full"] }
log = "0.4"
simplelog = "0.12"
@@ -67,12 +70,16 @@ objc2-foundation = { version = "0.3.2", default-features = false, features = ["s
# builds this crate.
objc2-web-kit = { version = "0.3.2", default-features = false, features = ["std", "block2", "WKContentRuleList", "WKContentRuleListStore", "WKDownload", "WKDownloadDelegate", "WKNavigationDelegate", "WKUserContentController", "WKWebView", "WKWebViewConfiguration", "WKWebsiteDataStore", "WKSnapshotConfiguration", "objc2-app-kit", "objc2-core-foundation"] }
block2 = "0.6"
+# macOS' SOCKS proxy setting, which hyper-util does not read (browser_proxy.rs); already built.
+system-configuration = "0.7"
[target.'cfg(target_os = "linux")'.dependencies]
# PNG output for the browser panel's screenshots (browser_capture.rs); gtk already builds it.
cairo-rs = { version = "0.18", features = ["png"] }
gdk = "0.18"
gdk-pixbuf = "0.18"
+# The desktop's proxy resolver for browser panel pages (browser_proxy.rs); gtk already builds it.
+gio = "0.18"
glib = "0.18"
gtk = "0.18"
elevated-command = "1.1.2"
@@ -85,7 +92,7 @@ webview2-com = "0.39.1"
winreg = "0.55"
windows = { version = "0.62.2", features = ["Win32_System_Threading"] }
windows-core = "0.62.2"
-windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Com", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell"] }
+windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Com", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_Networking_WinHttp"] }
[build-dependencies]
tauri-build = { version = "~2.7.0", features = [] }
diff --git a/studio/src-tauri/src/browser_proxy.rs b/studio/src-tauri/src/browser_proxy.rs
index e817d65eb17..b067207d75b 100644
--- a/studio/src-tauri/src/browser_proxy.rs
+++ b/studio/src-tauri/src/browser_proxy.rs
@@ -2,9 +2,11 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
//! Loopback proxy for browser-panel pages: resolves hosts itself, refuses private answers and
-//! connects to the checked address, defeating DNS rebinding.
+//! connects to the checked address, defeating DNS rebinding. Hosts the system proxy covers go to it
+//! by name instead, after the same check, so a poisoned public answer or none at all doesn't matter.
use crate::browser_webview::{host_is_private, ip_is_private};
+use hyper_util::client::proxy::matcher::Matcher;
use std::net::{IpAddr, SocketAddr};
use std::sync::OnceLock;
use std::time::Duration;
@@ -16,6 +18,7 @@ const MAX_HEAD: usize = 16 * 1024;
const TIMEOUT: Duration = Duration::from_secs(30);
// One address's share of it, so a dead first answer leaves time for the next.
const ADDRESS_TIMEOUT: Duration = Duration::from_secs(10);
+const ESTABLISHED: &[u8] = b"HTTP/1.1 200 Connection Established\r\n\r\n";
static ADDRESS: OnceLock<Result<SocketAddr, String>> = OnceLock::new();
@@ -33,7 +36,10 @@ pub fn address() -> Result<SocketAddr, String> {
loop {
match listener.accept().await {
Ok((client, _)) => {
- tauri::async_runtime::spawn(serve(client));
+ // Read per connection, so a proxy switched on or off applies at once.
+ tauri::async_runtime::spawn(async move {
+ serve(client, system_proxies()).await
+ });
}
// Out of descriptors, say: don't spin.
Err(_) => tokio::time::sleep(Duration::from_millis(100)).await,
@@ -49,13 +55,62 @@ pub fn address() -> Result<SocketAddr, String> {
struct Request {
host: String,
port: u16,
- forward: Option<String>,
+ forward: Option<Forward>,
+ /// A tunnel seen to carry cleartext (a `ws://` socket), not TLS.
+ cleartext: bool,
+}
+
+/// A plain-HTTP request, without the proxy's own headers.
+#[derive(Debug, PartialEq)]
+struct Forward {
+ method: String,
+ url: Url,
+ version: String,
+ headers: String,
+}
+
+impl Forward {
+ /// One request per connection: absolute-form to an HTTP proxy, origin-form otherwise.
+ fn head(&self, upstream: Option<&Upstream>) -> String {
+ let (target, auth) = match upstream {
+ Some(Upstream::Http { auth, .. }) => (self.url.as_str(), auth.as_deref()),
+ _ => (&self.url[Position::BeforePath..], None),
+ };
+ let mut head = format!(
+ "{} {target} {}\r\n{}",
+ self.method, self.version, self.headers
+ );
+ if let Some(auth) = auth {
+ head.push_str(&format!("Proxy-Authorization: {auth}\r\n"));
+ }
+ head.push_str("Connection: close\r\n\r\n");
+ head
+ }
+}
+
+/// The system proxy a request goes through.
+#[derive(Debug, PartialEq)]
+enum Upstream {
+ Http {
+ address: String,
+ auth: Option<String>,
+ },
+ Socks {
+ address: String,
+ auth: Option<(String, String)>,
+ },
+ /// What a Windows PAC script's `SOCKS` names, as WinINet and Chromium read it, or a Linux
+ /// desktop's `socks4(a)` proxy.
+ #[cfg(any(windows, target_os = "linux", test))]
+ Socks4 { address: String },
}
#[derive(Debug, PartialEq)]
enum Refusal {
Private,
Unreachable,
+ /// The proxy itself can't be reached, so the next route may be tried.
+ ProxyDown,
}
fn parse(head: &str) -> Option<Request> {
@@ -68,14 +123,14 @@ fn parse(head: &str) -> Option<Request> {
host: url.host_str()?.to_string(),
port: url.port_or_known_default()?,
forward: None,
+ cleartext: false,
});
}
let url = Url::parse(target).ok()?;
if url.scheme() != "http" {
return None;
}
- // One request per connection, without the proxy's own headers.
- let mut forward = format!("{method} {} {version}\r\n", &url[Position::BeforePath..]);
+ let mut headers = String::new();
for line in lines.filter(|line| !line.is_empty()) {
let name = line
.split(':')
@@ -87,27 +142,334 @@ fn parse(head: &str) -> Option<Request> {
name.as_str(),
"connection" | "keep-alive" | "proxy-connection" | "proxy-authorization"
) {
- forward.push_str(line);
- forward.push_str("\r\n");
+ headers.push_str(line);
+ headers.push_str("\r\n");
}
}
- forward.push_str("Connection: close\r\n\r\n");
Some(Request {
host: url.host_str()?.to_string(),
port: url.port_or_known_default()?,
- forward: Some(forward),
+ forward: Some(Forward {
+ method: method.to_string(),
+ url,
+ version: version.to_string(),
+ headers,
+ }),
+ cleartext: false,
})
}
-/// Connect to a public address of `host`, refusing it if any answer is private. One deadline covers
-/// the lookup and every address, so a host with many dead answers can't hold a task for long.
-async fn connect(host: &str, port: u16) -> Result<TcpStream, Refusal> {
- tokio::time::timeout(TIMEOUT, connect_within(host, port))
- .await
- .unwrap_or(Err(Refusal::Unreachable))
+/// How the system routes pages.
+#[derive(Default)]
+struct Proxies {
+ /// A PAC script (on Linux, the desktop's settings), which decides before `fixed` unless it
+ /// can't be found or run.
+ #[cfg(any(target_os = "macos", windows, target_os = "linux"))]
+ pac: Option<pac::Pac>,
+ /// Fixed settings, in order: proxy variables, else macOS or Windows settings.
+ fixed: Vec<Matcher>,
}
-async fn connect_within(host: &str, port: u16) -> Result<TcpStream, Refusal> {
+fn system_proxies() -> Proxies {
+ #[cfg(target_os = "macos")]
+ let proxies = macos_proxies(|name| std::env::var(name).ok());
+ #[cfg(windows)]
+ let proxies = Proxies {
+ pac: pac::configured()
+ .map(|source| pac::Pac::new(source, &|name: &str| std::env::var(name).ok())),
+ fixed: vec![windows_per_protocol().unwrap_or_else(Matcher::from_system)],
+ };
+ #[cfg(target_os = "linux")]
+ let proxies = linux_proxies(|name| std::env::var(name).ok());
+ #[cfg(not(any(target_os = "macos", windows, target_os = "linux")))]
+ let proxies = Proxies {
+ fixed: vec![Matcher::from_system()],
+ };
+ proxies
+}
+
+/// Proxy settings by protocol, as macOS and Windows store them.
+#[cfg(any(target_os = "macos", windows, test))]
+#[derive(Default)]
+struct Settings {
+ http: String,
+ https: String,
+ bypass: String,
+}
+
+/// Proxies for `settings`. As in hyper-util, each proxy variable that is set and not empty
+/// overrides its own setting.
+#[cfg(any(target_os = "macos", windows, test))]
+fn with_variables(settings: Settings, env: &impl Fn(&str) -> Option<String>) -> Matcher {
+ let variable = |names| variable(env, names);
+ Matcher::builder()
+ .all(variable(["ALL_PROXY", "all_proxy"]).unwrap_or_default())
+ .http(variable(["HTTP_PROXY", "http_proxy"]).unwrap_or(settings.http))
+ .https(variable(["HTTPS_PROXY", "https_proxy"]).unwrap_or(settings.https))
+ .no(variable(["NO_PROXY", "no_proxy"]).unwrap_or(settings.bypass))
+ .build()
+}
+
+#[cfg(any(target_os = "macos", windows, target_os = "linux", test))]
+fn variable(env: &impl Fn(&str) -> Option<String>, names: [&str; 2]) -> Option<String> {
+ names
+ .into_iter()
+ .filter_map(env)
+ .find(|value| !value.is_empty())
+}
+
+/// The desktop's settings, unless proxy variables (Linux's own way to set a proxy) are.
+#[cfg(target_os = "linux")]
+fn linux_proxies(env: impl Fn(&str) -> Option<String>) -> Proxies {
+ let names = [
+ ["ALL_PROXY", "all_proxy"],
+ ["HTTP_PROXY", "http_proxy"],
+ ["HTTPS_PROXY", "https_proxy"],
+ ];
+ let variables = names
+ .into_iter()
+ .any(|names| variable(&env, names).is_some());
+ Proxies {
+ pac: (!variables).then(|| pac::Pac::new(pac::Source::Desktop, &env)),
+ fixed: vec![Matcher::from_system()],
+ }
+}
+
+/// macOS' proxy settings, read here rather than by hyper-util, which skips PAC, the SOCKS proxy and
+/// the exceptions and can't parse an IPv6 host. The SOCKS proxy serves what HTTP(S) ones don't cover.
+#[cfg(target_os = "macos")]
+fn macos_proxies(env: impl Fn(&str) -> Option<String>) -> Proxies {
+ use system_configuration::core_foundation::array::CFArray;
+ use system_configuration::core_foundation::base::{CFType, TCFType};
+ use system_configuration::core_foundation::number::CFNumber;
+ use system_configuration::core_foundation::string::{CFString, CFStringRef};
+ use system_configuration::dynamic_store::SCDynamicStoreBuilder;
+ use system_configuration::sys::schema_definitions::*;
+
+ let Some(proxies) = SCDynamicStoreBuilder::new("unsloth-browser")
+ .build()
+ .and_then(|store| store.get_proxies())
+ else {
+ return Proxies {
+ pac: None,
+ fixed: vec![with_variables(Settings::default(), &env)],
+ };
+ };
+ let number = |key| {
+ proxies
+ .find(key)
+ .and_then(|value| value.downcast::<CFNumber>())
+ .and_then(|value| value.to_i32())
+ };
+ let text = |key| {
+ proxies
+ .find(key)
+ .and_then(|value| value.downcast::<CFString>())
+ .map(|value| value.to_string())
+ };
+ let proxy = |enable: CFStringRef, host: CFStringRef, port: CFStringRef| {
+ if number(enable) != Some(1) {
+ return None;
+ }
+ Some(authority(&text(host)?, number(port)))
+ };
+ let pac = unsafe {
+ if number(kSCPropNetProxiesProxyAutoConfigEnable) != Some(1) {
+ None
+ } else {
+ text(kSCPropNetProxiesProxyAutoConfigJavaScript)
+ .map(|script| pac::Source::Script(script.into()))
+ .or_else(|| text(kSCPropNetProxiesProxyAutoConfigURLString).map(pac::Source::Url))
+ }
+ };
+ let pac = pac.map(|source| pac::Pac::new(source, &env));
+ let exceptions = proxies
+ .find(unsafe { kSCPropNetProxiesExceptionsList })
+ .and_then(|value| value.downcast::<CFArray>())
+ .map(|list| {
+ list.iter()
+ .filter_map(|item| {
+ unsafe { CFType::wrap_under_get_rule(*item as _) }.downcast::<CFString>()
+ })
+ .map(|entry| entry.to_string())
+ .collect::<Vec<_>>()
+ })
+ .unwrap_or_default();
+ let settings = unsafe {
+ Settings {
+ http: proxy(
+ kSCPropNetProxiesHTTPEnable,
+ kSCPropNetProxiesHTTPProxy,
+ kSCPropNetProxiesHTTPPort,
+ )
+ .unwrap_or_default(),
+ https: proxy(
+ kSCPropNetProxiesHTTPSEnable,
+ kSCPropNetProxiesHTTPSProxy,
+ kSCPropNetProxiesHTTPSPort,
+ )
+ .unwrap_or_default(),
+ bypass: bypass_list(exceptions.iter().map(String::as_str)),
+ }
+ };
+ let socks = unsafe {
+ proxy(
+ kSCPropNetProxiesSOCKSEnable,
+ kSCPropNetProxiesSOCKSProxy,
+ kSCPropNetProxiesSOCKSPort,
+ )
+ };
+ let no = variable(&env, ["NO_PROXY", "no_proxy"]).unwrap_or_else(|| settings.bypass.clone());
+ let mut fixed = vec![with_variables(settings, &env)];
+ fixed.extend(socks.map(|address| socks_fallback(&address, &no)));
+ Proxies { pac, fixed }
+}
+
+/// `host[:port]`, with an IPv6 host bracketed as a URI needs.
+#[cfg(any(target_os = "macos", windows, target_os = "linux", test))]
+fn authority(host: &str, port: Option<i32>) -> String {
+ let host = match host.parse::<std::net::Ipv6Addr>() {
+ Ok(_) => format!("[{host}]"),
+ Err(_) => host.to_string(),
+ };
+ match port {
+ Some(port) => format!("{host}:{port}"),
+ None => host,
+ }
+}
+
+/// A NO_PROXY list from bypass entries, `*.` wildcards as suffixes as hyper-util reads them.
+#[cfg(any(target_os = "macos", windows, test))]
+fn bypass_list<'a>(entries: impl Iterator<Item = &'a str>) -> String {
+ entries
+ .map(str::trim)
+ .collect::<Vec<_>>()
+ .join(",")
+ .replace("*.", "")
+}
+
+/// Every destination through the SOCKS proxy at `address`, minus the `no` list.
+#[cfg(any(target_os = "macos", test))]
+fn socks_fallback(address: &str, no: &str) -> Matcher {
+ Matcher::builder()
+ .all(format!("socks5h://{address}"))
+ .no(no)
+ .build()
+}
+
+/// hyper-util reads Windows' `ProxyServer` as one address, so its per-protocol form
+/// (`http=a:80;https=b:443`) is split here.
+#[cfg(windows)]
+fn windows_per_protocol() -> Option<Matcher> {
+ use winreg::enums::{HKEY_CURRENT_USER, KEY_QUERY_VALUE};
+ use winreg::RegKey;
+
+ let settings = RegKey::predef(HKEY_CURRENT_USER)
+ .open_subkey_with_flags(
+ r"Software\Microsoft\Windows\CurrentVersion\Internet Settings",
+ KEY_QUERY_VALUE,
+ )
+ .ok()?;
+ if settings.get_value::<u32, _>("ProxyEnable").unwrap_or(0) == 0 {
+ return None;
+ }
+ let server = settings.get_value::<String, _>("ProxyServer").ok()?;
+ let proxy_override = settings
+ .get_value::<String, _>("ProxyOverride")
+ .unwrap_or_default();
+ per_protocol(&server, &proxy_override, |name| std::env::var(name).ok())
+}
+
+/// Proxies for a per-protocol `ProxyServer` value (`None` for a single address).
+#[cfg(any(windows, test))]
+fn per_protocol(
+ server: &str,
+ proxy_override: &str,
+ env: impl Fn(&str) -> Option<String>,
+) -> Option<Matcher> {
+ if !server.contains('=') {
+ return None;
+ }
+ let setting = |wanted: &str| {
+ server
+ .split(';')
+ .filter_map(|entry| entry.split_once('='))
+ .find(|(scheme, _)| scheme.trim().eq_ignore_ascii_case(wanted))
+ .map(|(_, address)| address.trim().to_string())
+ .unwrap_or_default()
+ };
+ let settings = Settings {
+ http: setting("http"),
+ https: setting("https"),
+ bypass: bypass_list(proxy_override.split(';')),
+ };
+ Some(with_variables(settings, &env))
+}
+
+/// Where `request` may go, in order: through a system proxy, or direct (`None`).
+async fn routes(proxies: &Proxies, request: &Request) -> Vec<Option<Upstream>> {
+ let destination: Option<http::Uri> = match &request.forward {
+ Some(forward) => forward.url.as_str().parse().ok(),
+ None if request.cleartext => format!("http://{}:{}/", request.host, request.port)
+ .parse()
+ .ok(),
+ // Tunnels carry TLS, so they take the HTTPS proxy.
+ None => format!("https://{}:{}/", request.host, request.port)
+ .parse()
+ .ok(),
+ };
+ let Some(destination) = destination else {
+ return vec![None];
+ };
+ #[cfg(any(target_os = "macos", windows, target_os = "linux"))]
+ if let Some(pac) = proxies.pac.as_ref().filter(|pac| pac.decides(&destination)) {
+ // As browsers ask, without a default port.
+ let url = Url::parse(&destination.to_string())
+ .map_or_else(|_| destination.to_string(), String::from);
+ if let Some(routes) = pac::routes(pac, &url).await {
+ return routes;
+ }
+ }
+ vec![system_proxy(&proxies.fixed, &destination)]
+}
+
+/// The first fixed setting that covers `destination`. HTTP and SOCKS5 proxies are chained.
+fn system_proxy(proxies: &[Matcher], destination: &http::Uri) -> Option<Upstream> {
+ let intercept = proxies
+ .iter()
+ .find_map(|proxies| proxies.intercept(destination))?;
+ let uri = intercept.uri();
+ let address = |default| {
+ format!(
+ "{}:{}",
+ uri.host().unwrap_or(""),
+ uri.port_u16().unwrap_or(default)
+ )
+ };
+ match uri.scheme_str() {
+ Some("http") => Some(Upstream::Http {
+ address: address(80),
+ auth: intercept
+ .basic_auth()
+ .and_then(|value| value.to_str().ok())
+ .map(str::to_owned),
+ }),
+ // Either way the proxy gets the name, as with HTTP proxies.
+ Some("socks5" | "socks5h") => Some(Upstream::Socks {
+ address: address(1080),
+ auth: intercept
+ .raw_auth()
+ .map(|(user, pass)| (user.to_owned(), pass.to_owned())),
+ }),
+ scheme => {
+ log::info!("browser proxy can't chain to a {scheme:?} proxy");
+ None
+ }
+ }
+}
+
+/// Parse `host`, refusing it if it names a private address.
+fn public_host(host: &str) -> Result<Host<String>, Refusal> {
let parsed = Host::parse(host).map_err(|_| Refusal::Unreachable)?;
let borrowed = match &parsed {
Host::Domain(name) => Host::Domain(name.as_str()),
@@ -117,7 +479,19 @@ async fn connect_within(host: &str, port: u16) -> Result<TcpStream, Refusal> {
if host_is_private(&borrowed) {
return Err(Refusal::Private);
}
- let addresses: Vec<SocketAddr> = match parsed {
+ Ok(parsed)
+}
+
+/// Connect to a public address of `host`, refusing it if any answer is private. One deadline covers
+/// the lookup and every address, so a host with many dead answers can't hold a task for long.
+async fn connect(host: &str, port: u16) -> Result<TcpStream, Refusal> {
+ tokio::time::timeout(TIMEOUT, connect_within(host, port))
+ .await
+ .unwrap_or(Err(Refusal::Unreachable))
+}
+
+async fn connect_within(host: &str, port: u16) -> Result<TcpStream, Refusal> {
+ let addresses: Vec<SocketAddr> = match public_host(host)? {
Host::Ipv4(ip) => vec![SocketAddr::new(IpAddr::V4(ip), port)],
Host::Ipv6(ip) => vec![SocketAddr::new(IpAddr::V6(ip), port)],
Host::Domain(name) => tokio::net::lookup_host((name.as_str(), port))
@@ -128,6 +502,10 @@ async fn connect_within(host: &str, port: u16) -> Result<TcpStream, Refusal> {
if addresses.iter().any(|address| ip_is_private(address.ip())) {
return Err(Refusal::Private);
}
+ dial(addresses).await
+}
+
+async fn dial(addresses: impl IntoIterator<Item = SocketAddr>) -> Result<TcpStream, Refusal> {
for address in addresses {
if let Ok(Ok(stream)) =
tokio::time::timeout(ADDRESS_TIMEOUT, TcpStream::connect(address)).await
@@ -138,6 +516,234 @@ async fn connect_within(host: &str, port: u16) -> Result<TcpStream, Refusal> {
Err(Refusal::Unreachable)
}
+/// Open `request` through the system proxy, which gets the name. Never falls back to a direct
+/// connection. Returns what the proxy sent past its answer.
+async fn connect_via(
+ upstream: &Upstream,
+ request: &Request,
+) -> Result<(TcpStream, Vec<u8>), Refusal> {
+ let host = public_host(&request.host)?;
+ let (address, http_auth) = match upstream {
+ Upstream::Http { address, auth } => (address, auth),
+ Upstream::Socks { address, .. } => (address, &None),
+ #[cfg(any(windows, target_os = "linux", test))]
+ Upstream::Socks4 { address } => (address, &None),
+ };
+ let deadline = tokio::time::Instant::now() + TIMEOUT;
+ // Running out of time before the proxy answers the dial means it's down: the next route may go.
+ let mut stream = tokio::time::timeout_at(deadline, async {
+ refuse_private_answers(&host, request.port).await?;
+ let addresses = tokio::net::lookup_host(address.as_str())
+ .await
+ .map_err(|_| Refusal::ProxyDown)?;
+ dial(addresses).await.map_err(|_| Refusal::ProxyDown)
+ })
+ .await
+ .unwrap_or(Err(Refusal::ProxyDown))?;
+ tokio::time::timeout_at(deadline, async {
+ let socks = match upstream {
+ Upstream::Http { .. } => None,
+ Upstream::Socks { auth, .. } => {
+ Some(socks_connect(&mut stream, &host, request.port, auth.as_ref()).await)
+ }
+ #[cfg(any(windows, target_os = "linux", test))]
+ Upstream::Socks4 { .. } => Some(socks4_connect(&mut stream, &host, request.port).await),
+ };
+ if let Some(connected) = socks {
+ connected.ok_or(Refusal::Unreachable)?;
+ return Ok((stream, Vec::new()));
+ }
+ if request.forward.is_some() {
+ return Ok((stream, Vec::new()));
+ }
+ let target = format!("{}:{}", request.host, request.port);
+ let mut head = format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n");
+ if let Some(auth) = http_auth {
+ head.push_str(&format!("Proxy-Authorization: {auth}\r\n"));
+ }
+ head.push_str("\r\n");
+ stream
+ .write_all(head.as_bytes())
+ .await
+ .map_err(|_| Refusal::Unreachable)?;
+ let (answer, early) = read_head(&mut stream).await.ok_or(Refusal::Unreachable)?;
+ let status = answer.split_ascii_whitespace().nth(1).unwrap_or("");
+ if !status.starts_with('2') {
+ log::info!("system proxy answered {status} for {target}");
+ return Err(Refusal::Unreachable);
+ }
+ Ok((stream, early))
+ })
+ .await
+ .unwrap_or(Err(Refusal::Unreachable))
+}
+
+/// Refuse a name local DNS answers privately, as the direct path does. One it can't answer in time
+/// (a proxy-only network) is left to the proxy.
+async fn refuse_private_answers(host: &Host<String>, port: u16) -> Result<(), Refusal> {
+ let Host::Domain(name) = host else {
+ return Ok(());
+ };
+ // Its own share of the deadline, so a resolver dropping queries leaves time for the proxy.
+ let answers = tokio::time::timeout(
+ ADDRESS_TIMEOUT,
+ tokio::net::lookup_host((name.as_str(), port)),
+ );
+ let private = answers.await.is_ok_and(|answers| {
+ answers.is_ok_and(|mut answers| answers.any(|answer| ip_is_private(answer.ip())))
+ });
+ if private {
+ return Err(Refusal::Private);
+ }
+ Ok(())
+}
+
+/// A SOCKS5 CONNECT (RFC 1928, password auth RFC 1929) that names `host`, so the proxy resolves it.
+async fn socks_connect(
+ stream: &mut TcpStream,
+ host: &Host<String>,
+ port: u16,
+ auth: Option<&(String, String)>,
+) -> Option<()> {
+ let methods: &[u8] = if auth.is_some() { &[0, 2] } else { &[0] };
+ let mut greeting = vec![5, methods.len() as u8];
+ greeting.extend_from_slice(methods);
+ stream.write_all(&greeting).await.ok()?;
+ let mut chosen = [0u8; 2];
+ stream.read_exact(&mut chosen).await.ok()?;
+ match (chosen, auth) {
+ ([5, 0], _) => {}
+ ([5, 2], Some((user, pass))) => {
+ let (user, pass) = (user.as_bytes(), pass.as_bytes());
+ let mut login = vec![1, u8::try_from(user.len()).ok()?];
+ login.extend_from_slice(user);
+ login.push(u8::try_from(pass.len()).ok()?);
+ login.extend_from_slice(pass);
+ stream.write_all(&login).await.ok()?;
+ let mut status = [0u8; 2];
+ stream.read_exact(&mut status).await.ok()?;
+ if status[1] != 0 {
+ return None;
+ }
+ }
+ _ => return None,
+ }
+ let mut connect = vec![5, 1, 0];
+ match host {
+ Host::Domain(name) => {
+ connect.push(3);
+ connect.push(u8::try_from(name.len()).ok()?);
+ connect.extend_from_slice(name.as_bytes());
+ }
+ Host::Ipv4(ip) => {
+ connect.push(1);
+ connect.extend_from_slice(&ip.octets());
+ }
+ Host::Ipv6(ip) => {
+ connect.push(4);
+ connect.extend_from_slice(&ip.octets());
+ }
+ }
+ connect.extend_from_slice(&port.to_be_bytes());
+ stream.write_all(&connect).await.ok()?;
+ let mut reply = [0u8; 4];
+ stream.read_exact(&mut reply).await.ok()?;
+ if reply[..2] != [5, 0] {
+ log::info!("SOCKS proxy answered {} for {host}:{port}", reply[1]);
+ return None;
+ }
+ // Skip the bound address the reply carries.
+ let bound = match reply[3] {
+ 1 => 4,
+ 4 => 16,
+ 3 => {
+ let mut length = [0u8; 1];
+ stream.read_exact(&mut length).await.ok()?;
+ usize::from(length[0])
+ }
+ _ => return None,
+ };
+ let mut rest = vec![0u8; bound + 2];
+ stream.read_exact(&mut rest).await.ok()?;
+ Some(())
+}
+
+/// A SOCKS4a CONNECT that names `host`, so the proxy resolves it. SOCKS4 has no IPv6.
+#[cfg(any(windows, target_os = "linux", test))]
+async fn socks4_connect(stream: &mut TcpStream, host: &Host<String>, port: u16) -> Option<()> {
+ let mut connect = vec![4, 1];
+ connect.extend_from_slice(&port.to_be_bytes());
+ match host {
+ Host::Ipv4(ip) => {
+ connect.extend_from_slice(&ip.octets());
+ connect.push(0);
+ }
+ Host::Domain(name) => {
+ connect.extend_from_slice(&[0, 0, 0, 1, 0]);
+ connect.extend_from_slice(name.as_bytes());
+ connect.push(0);
+ }
+ Host::Ipv6(_) => return None,
+ }
+ stream.write_all(&connect).await.ok()?;
+ let mut reply = [0u8; 8];
+ stream.read_exact(&mut reply).await.ok()?;
+ if reply[1] != 0x5a {
+ log::info!("SOCKS4 proxy answered {} for {host}:{port}", reply[1]);
+ return None;
+ }
+ Some(())
+}
+
+/// The plain-HTTP request a tunnel carries, made absolute so it is routed and forwarded as one,
+/// with the body read past its head; or no request (a WebSocket upgrade, TLS), with every byte read.
+async fn untunnel(client: &mut TcpStream, tunnel: &Request) -> Option<(Option<Request>, Vec<u8>)> {
+ let mut buffer = Vec::new();
+ let mut chunk = [0u8; 4096];
+ loop {
+ let read = client.read(&mut chunk).await.ok()?;
+ if read == 0 {
+ return None;
+ }
+ buffer.extend_from_slice(&chunk[..read]);
+ let method = buffer
+ .iter()
+ .take_while(|byte| byte.is_ascii_uppercase())
+ .count();
+ if method == buffer.len() && method < 16 {
+ continue;
+ }
+ if method == 0 || buffer.get(method..method + 2) != Some(b" /") {
+ return Some((None, buffer));
+ }
+ let Some(end) = buffer.windows(4).position(|window| window == b"\r\n\r\n") else {
+ if buffer.len() > MAX_HEAD {
+ return None;
+ }
+ continue;
+ };
+ let request = std::str::from_utf8(&buffer[..end + 4])
+ .ok()
+ .filter(|head| {
+ !head
+ .split("\r\n")
+ .any(|line| line.to_ascii_lowercase().starts_with("upgrade:"))
+ })
+ .and_then(|head| {
+ let (method, rest) = head.split_once(' ')?;
+ parse(&format!(
+ "{method} http://{}:{}{rest}",
+ tunnel.host, tunnel.port
+ ))
+ })
+ .filter(|request| request.host == tunnel.host && request.port == tunnel.port);
+ return Some(match request {
+ Some(request) => (Some(request), buffer.split_off(end + 4)),
+ None => (None, buffer),
+ });
+ }
+}
+
async fn read_head(client: &mut TcpStream) -> Option<(String, Vec<u8>)> {
let mut buffer = Vec::new();
let mut chunk = [0u8; 4096];
@@ -157,35 +763,76 @@ async fn read_head(client: &mut TcpStream) -> Option<(String, Vec<u8>)> {
}
}
-async fn serve(mut client: TcpStream) {
+async fn serve(mut client: TcpStream, proxies: Proxies) {
let Ok(Some((head, rest))) = tokio::time::timeout(TIMEOUT, read_head(&mut client)).await else {
return;
};
- let Some(request) = parse(&head) else {
+ let Some(mut request) = parse(&head) else {
let _ = reply(&mut client, "400 Bad Request").await;
return;
};
- let mut upstream = match connect(&request.host, request.port).await {
- Ok(stream) => stream,
+ let (mut rest, mut established) = (rest, false);
+ // WebKit on macOS 14+ tunnels plain-HTTP pages too; routed as tunnels they'd count as HTTPS,
+ // and a nested CONNECT to port 80 is refused by many HTTP proxies.
+ if request.forward.is_none()
+ && request.port == 80
+ && rest.is_empty()
+ && public_host(&request.host).is_ok()
+ {
+ if client.write_all(ESTABLISHED).await.is_err() {
+ return;
+ }
+ established = true;
+ let Ok(Some((inner, read))) =
+ tokio::time::timeout(TIMEOUT, untunnel(&mut client, &request)).await
+ else {
+ return;
+ };
+ match inner {
+ Some(inner) => request = inner,
+ // A TLS handshake starts with a 0x16 record.
+ None => request.cleartext = read.first() != Some(&0x16),
+ }
+ rest = read;
+ }
+ let (mut via, mut opened) = (None, Err(Refusal::Unreachable));
+ for route in routes(&proxies, &request).await {
+ opened = match &route {
+ Some(route) => connect_via(route, &request).await,
+ None => connect(&request.host, request.port)
+ .await
+ .map(|stream| (stream, Vec::new())),
+ };
+ via = route;
+ if !matches!(opened, Err(Refusal::ProxyDown)) {
+ break;
+ }
+ }
+ let (mut upstream, early) = match opened {
+ Ok(opened) => opened,
Err(Refusal::Private) => {
log::info!("browser proxy refused private host {}", request.host);
let _ = reply(&mut client, "403 Forbidden").await;
return;
}
- Err(Refusal::Unreachable) => {
+ Err(Refusal::Unreachable | Refusal::ProxyDown) => {
let _ = reply(&mut client, "502 Bad Gateway").await;
return;
}
};
let opened = match &request.forward {
- Some(forward) => upstream.write_all(forward.as_bytes()).await,
- None => {
- client
- .write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n")
+ Some(forward) => {
+ upstream
+ .write_all(forward.head(via.as_ref()).as_bytes())
.await
}
+ None if established => Ok(()),
+ None => client.write_all(ESTABLISHED).await,
};
- if opened.is_ok() && upstream.write_all(&rest).await.is_ok() {
+ if opened.is_ok()
+ && client.write_all(&early).await.is_ok()
+ && upstream.write_all(&rest).await.is_ok()
+ {
let _ = tokio::io::copy_bidirectional(&mut client, &mut upstream).await;
}
}
@@ -195,9 +842,540 @@ async fn reply(client: &mut TcpStream, status: &str) -> std::io::Result<()> {
client.write_all(response.as_bytes()).await
}
+/// PAC scripts, run as the system's own browser runs them: on macOS fetched here (directly, since a
+/// local proxy app or the intranet often serves them) and run by CFNetwork; on Windows found and
+/// run by WinHTTP, which also discovers them (WPAD). On Linux GIO's resolver, which WebKitGTK uses,
+/// answers from the desktop's settings: GNOME's, else libproxy's (KDE, PAC, WPAD).
+#[cfg(any(target_os = "macos", windows, target_os = "linux"))]
+mod pac {
+ use super::{variable, Upstream, ADDRESS_TIMEOUT};
+ use hyper_util::client::proxy::matcher::Matcher;
+ #[cfg(windows)]
+ pub(super) use winhttp::configured;
+ #[cfg(target_os = "macos")]
+ use {
+ super::authority,
+ std::sync::Arc,
+ std::time::{Duration, Instant},
+ system_configuration::core_foundation::array::{CFArray, CFArrayRef},
+ system_configuration::core_foundation::base::{CFType, TCFType},
+ system_configuration::core_foundation::dictionary::CFDictionary,
+ system_configuration::core_foundation::error::{CFError, CFErrorRef},
+ system_configuration::core_foundation::number::CFNumber,
+ system_configuration::core_foundation::string::{CFString, CFStringRef},
+ system_configuration::core_foundation::url::{CFURLCreateWithString, CFURLRef, CFURL},
+ tokio::sync::Mutex,
+ };
+
+ #[cfg(target_os = "macos")]
+ const SCRIPT_TTL: Duration = Duration::from_secs(60);
+
+ #[cfg(target_os = "macos")]
+ #[link(name = "CFNetwork", kind = "framework")]
+ extern "C" {
+ fn CFNetworkCopyProxiesForAutoConfigurationScript(
+ script: CFStringRef,
+ url: CFURLRef,
+ error: *mut CFErrorRef,
+ ) -> CFArrayRef;
+ static kCFProxyTypeKey: CFStringRef;
+ static kCFProxyHostNameKey: CFStringRef;
+ static kCFProxyPortNumberKey: CFStringRef;
+ static kCFProxyTypeNone: CFStringRef;
+ static kCFProxyTypeHTTP: CFStringRef;
+ static kCFProxyTypeHTTPS: CFStringRef;
+ static kCFProxyTypeSOCKS: CFStringRef;
+ }
+
+ pub(super) enum Source {
+ #[cfg(target_os = "macos")]
+ Url(String),
+ #[cfg(target_os = "macos")]
+ Script(Arc<str>),
+ /// Windows' automatic configuration: discovery when `detect`, then the script at `url`.
+ #[cfg(windows)]
+ Automatic { detect: bool, url: Option<String> },
+ #[cfg(target_os = "linux")]
+ Desktop,
+ }
+
+ pub(super) struct Pac {
+ source: Source,
+ /// Proxy variables, which override the script for their protocols.
+ variables: Matcher,
+ /// NO_PROXY, which keeps its hosts from the script: a stand-in proxy minus the list.
+ bypass: Matcher,
+ }
+
+ impl Pac {
+ pub(super) fn new(source: Source, env: &impl Fn(&str) -> Option<String>) -> Pac {
+ let variable = |names| variable(env, names).unwrap_or_default();
+ Pac {
+ source,
+ variables: Matcher::builder()
+ .all(variable(["ALL_PROXY", "all_proxy"]))
+ .http(variable(["HTTP_PROXY", "http_proxy"]))
+ .https(variable(["HTTPS_PROXY", "https_proxy"]))
+ .build(),
+ bypass: Matcher::builder()
+ .all("http://pac.invalid")
+ .no(variable(["NO_PROXY", "no_proxy"]))
+ .build(),
+ }
+ }
+
+ /// Whether the script routes `destination`, which the fixed settings route otherwise.
+ pub(super) fn decides(&self, destination: &http::Uri) -> bool {
+ self.variables.intercept(destination).is_none()
+ && self.bypass.intercept(destination).is_some()
+ }
+ }
+
+ /// The script's routes for `url`, `None` meaning direct; nothing if it can't be had or run.
+ pub(super) async fn routes(pac: &Pac, url: &str) -> Option<Vec<Option<Upstream>>> {
+ let url = url.to_string();
+ #[cfg(target_os = "macos")]
+ let run = {
+ let script = match &pac.source {
+ Source::Url(location) => script(location).await?,
+ Source::Script(script) => script.clone(),
+ };
+ move || evaluate(&script, &url)
+ };
+ #[cfg(windows)]
+ let run = {
+ let Source::Automatic {
+ detect,
+ url: script,
+ } = &pac.source;
+ let (detect, script) = (*detect, script.clone());
+ move || winhttp::evaluate(detect, script.as_deref(), &url)
+ };
+ #[cfg(target_os = "linux")]
+ let run = {
+ let Source::Desktop = pac.source;
+ move || desktop::evaluate(&gio::ProxyResolver::default(), &url)
+ };
+ tokio::time::timeout(ADDRESS_TIMEOUT, tokio::task::spawn_blocking(run))
+ .await
+ .ok()?
+ .ok()?
+ }
+
+ #[cfg(target_os = "macos")]
+ struct Fetched {
+ location: String,
+ at: Instant,
+ script: Option<Arc<str>>,
+ }
+
+ #[cfg(target_os = "macos")]
+ async fn script(location: &str) -> Option<Arc<str>> {
+ // Held across the fetch, so a page's many connections fetch the script once.
+ static CACHE: Mutex<Option<Fetched>> = Mutex::const_new(None);
+ let mut cache = CACHE.lock().await;
+ if let Some(fetched) = &*cache {
+ if fetched.location == location && fetched.at.elapsed() < SCRIPT_TTL {
+ return fetched.script.clone();
+ }
+ }
+ let script = fetch(location).await.map(Arc::from);
+ if script.is_none() {
+ log::info!("browser proxy couldn't fetch the PAC script at {location}");
+ }
+ *cache = Some(Fetched {
+ location: location.to_string(),
+ at: Instant::now(),
+ script: script.clone(),
+ });
+ script
+ }
+
+ #[cfg(target_os = "macos")]
+ async fn fetch(location: &str) -> Option<String> {
+ let client = crate::loopback_http::client(ADDRESS_TIMEOUT).ok()?;
+ let response = client.get(location).send().await.ok()?;
+ response.error_for_status().ok()?.text().await.ok()
+ }
+
+ /// The entries that are DIRECT or a proxy this one can chain to, in order.
+ #[cfg(target_os = "macos")]
+ fn evaluate(script: &str, url: &str) -> Option<Vec<Option<Upstream>>> {
+ let (script, url) = (CFString::new(script), CFString::new(url));
+ unsafe {
+ let url = CFURLCreateWithString(
+ std::ptr::null(),
+ url.as_concrete_TypeRef(),
+ std::ptr::null(),
+ );
+ if url.is_null() {
+ return None;
+ }
+ let url = CFURL::wrap_under_create_rule(url);
+ let mut error: CFErrorRef = std::ptr::null_mut();
+ let proxies = CFNetworkCopyProxiesForAutoConfigurationScript(
+ script.as_concrete_TypeRef(),
+ url.as_concrete_TypeRef(),
+ &mut error,
+ );
+ if proxies.is_null() {
+ if !error.is_null() {
+ let error = CFError::wrap_under_create_rule(error);
+ log::info!("browser proxy couldn't run the PAC script: {error}");
+ }
+ return None;
+ }
+ let proxies: CFArray<CFDictionary<CFString, CFType>> =
+ CFArray::wrap_under_create_rule(proxies);
+ let mut routes = Vec::new();
+ for proxy in proxies.iter() {
+ let text = |key| proxy.find(key).and_then(|v| v.downcast::<CFString>());
+ let Some(kind) = text(kCFProxyTypeKey) else {
+ continue;
+ };
+ let is = |other| kind == CFString::wrap_under_get_rule(other);
+ if is(kCFProxyTypeNone) {
+ routes.push(None);
+ continue;
+ }
+ let (socks, default_port) = if is(kCFProxyTypeSOCKS) {
+ (true, 1080)
+ } else if is(kCFProxyTypeHTTP) || is(kCFProxyTypeHTTPS) {
+ (false, 80)
+ } else {
+ continue;
+ };
+ let Some(host) = text(kCFProxyHostNameKey) else {
+ continue;
+ };
+ let port = proxy
+ .find(kCFProxyPortNumberKey)
+ .and_then(|v| v.downcast::<CFNumber>())
+ .and_then(|v| v.to_i32());
+ let address = authority(&host.to_string(), Some(port.unwrap_or(default_port)));
+ routes.push(Some(match socks {
+ true => Upstream::Socks {
+ address,
+ auth: None,
+ },
+ false => Upstream::Http {
+ address,
+ auth: None,
+ },
+ }));
+ }
+ // An empty answer means direct, as browsers read one.
+ if routes.is_empty() {
+ routes.push(None);
+ }
+ Some(routes)
+ }
+ }
+
+ #[cfg(target_os = "linux")]
+ pub(super) mod desktop {
+ use super::super::{authority, system_proxy, Upstream};
+ use gio::prelude::*;
+ use hyper_util::client::proxy::matcher::Matcher;
+ use url::Url;
+
+ pub(in crate::browser_proxy) fn evaluate(
+ resolver: &gio::ProxyResolver,
+ url: &str,
+ ) -> Option<Vec<Option<Upstream>>> {
+ let destination: http::Uri = url.parse().ok()?;
+ let entries = resolver
+ .lookup(url, gio::Cancellable::NONE)
+ .map_err(|error| log::info!("browser proxy couldn't ask the desktop: {error}"))
+ .ok()?;
+ Some(from_entries(&entries, &destination))
+ }
+
+ /// The entries that are DIRECT or a proxy this one can chain to, in order.
+ pub(in crate::browser_proxy) fn from_entries(
+ entries: &[impl AsRef<str>],
+ destination: &http::Uri,
+ ) -> Vec<Option<Upstream>> {
+ let mut routes: Vec<_> = entries
+ .iter()
+ .filter_map(|entry| route(entry.as_ref(), destination))
+ .collect();
+ // GLib lists a `socks` proxy once per version; the first that connects is the one used.
+ routes.dedup_by(|later, earlier| match (earlier, later) {
+ (
+ Some(Upstream::Socks { address, .. }),
+ Some(Upstream::Socks4 { address: same }),
+ ) => address == same,
+ (earlier, later) => earlier == later,
+ });
+ if routes.is_empty() {
+ routes.push(None);
+ }
+ routes
+ }
+
+ fn route(entry: &str, destination: &http::Uri) -> Option<Option<Upstream>> {
+ let proxy = Url::parse(entry).ok()?;
+ let chained = |entry: String| {
+ system_proxy(&[Matcher::builder().all(entry).build()], destination).map(Some)
+ };
+ match proxy.scheme() {
+ "direct" => Some(None),
+ "http" => chained(entry.to_string()),
+ // GLib tries SOCKS5 first for a plain `socks` proxy.
+ "socks" | "socks5" => chained(entry.replacen(proxy.scheme(), "socks5", 1)),
+ "socks4" | "socks4a" => Some(Some(Upstream::Socks4 {
+ address: authority(
+ proxy.host_str()?,
+ Some(i32::from(proxy.port().unwrap_or(1080))),
+ ),
+ })),
+ _ => None,
+ }
+ }
+ }
+
+ #[cfg(windows)]
+ mod winhttp {
+ use super::super::{authority, Upstream, ADDRESS_TIMEOUT};
+ use super::Source;
+ use std::ffi::c_void;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ use std::sync::mpsc::{sync_channel, SyncSender};
+ use std::sync::{Mutex, OnceLock};
+ use std::time::{Duration, Instant};
+ use windows_sys::Win32::Foundation::GlobalFree;
+ use windows_sys::Win32::Networking::WinHttp::*;
+
+ // Discovery that found nothing is remembered, so pages don't each wait on it again.
+ const FAILURE_TTL: Duration = Duration::from_secs(300);
+ const ERROR_IO_PENDING: u32 = 997;
+ const ERROR_TIMEOUT: u32 = 1460;
+ const ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT: u32 = 12167;
+
+ /// Lookups in flight, by the context their callback gets; one that timed out is gone.
+ static PENDING: Mutex<Vec<(usize, SyncSender<u32>)>> = Mutex::new(Vec::new());
+
+ struct Handle(*mut c_void);
+ // WinHTTP handles may be used from any thread.
+ unsafe impl Send for Handle {}
+ unsafe impl Sync for Handle {}
+
+ impl Drop for Handle {
+ fn drop(&mut self) {
+ unsafe { WinHttpCloseHandle(self.0) };
+ }
+ }
+
+ /// Internet Options' automatic configuration for this user, if any is on.
+ pub(in crate::browser_proxy) fn configured() -> Option<Source> {
+ let mut config: WINHTTP_CURRENT_USER_IE_PROXY_CONFIG = unsafe { std::mem::zeroed() };
+ if unsafe { WinHttpGetIEProxyConfigForCurrentUser(&mut config) } == 0 {
+ return None;
+ }
+ let url = unsafe { text(config.lpszAutoConfigUrl) };
+ for owned in [
+ config.lpszAutoConfigUrl,
+ config.lpszProxy,
+ config.lpszProxyBypass,
+ ] {
+ if !owned.is_null() {
+ unsafe { GlobalFree(owned.cast()) };
+ }
+ }
+ let detect = config.fAutoDetect != 0;
+ (detect || url.is_some()).then_some(Source::Automatic { detect, url })
+ }
+
+ /// One asynchronous session, fetching scripts directly; WinHTTP caches what it finds in it.
+ fn session() -> Option<&'static Handle> {
+ static SESSION: OnceLock<Option<Handle>> = OnceLock::new();
+ SESSION
+ .get_or_init(|| unsafe {
+ let agent = wide("Unsloth");
+ let flags = WINHTTP_FLAG_ASYNC;
+ let handle = WinHttpOpen(
+ agent.as_ptr(),
+ WINHTTP_ACCESS_TYPE_NO_PROXY,
+ std::ptr::null(),
+ std::ptr::null(),
+ flags,
+ );
+ if handle.is_null() {
+ return None;
+ }
+ let events = WINHTTP_CALLBACK_FLAG_GETPROXYFORURL_COMPLETE
+ | WINHTTP_CALLBACK_FLAG_REQUEST_ERROR;
+ WinHttpSetStatusCallback(handle, Some(completed), events, 0);
+ Some(Handle(handle))
+ })
+ .as_ref()
+ }
+
+ unsafe extern "system" fn completed(
+ _handle: *mut c_void,
+ context: usize,
+ status: u32,
+ info: *mut c_void,
+ _length: u32,
+ ) {
+ let error = match status {
+ WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE => 0,
+ WINHTTP_CALLBACK_STATUS_REQUEST_ERROR if !info.is_null() => unsafe {
+ (*info.cast::<WINHTTP_ASYNC_RESULT>()).dwError
+ },
+ _ => return,
+ };
+ let Ok(mut pending) = PENDING.lock() else {
+ return;
+ };
+ if let Some(index) = pending.iter().position(|(id, _)| *id == context) {
+ let _ = pending.swap_remove(index).1.send(error);
+ }
+ }
+
+ /// The entries that are DIRECT or a proxy this one can chain to, in order.
+ pub(super) fn evaluate(
+ detect: bool,
+ script: Option<&str>,
+ url: &str,
+ ) -> Option<Vec<Option<Upstream>>> {
+ static FAILED: Mutex<Option<(String, Instant)>> = Mutex::new(None);
+ let key = format!("{detect} {script:?}");
+ let failed = FAILED.lock().ok()?;
+ if failed
+ .as_ref()
+ .is_some_and(|(failed, at)| *failed == key && at.elapsed() < FAILURE_TTL)
+ {
+ return None;
+ }
+ drop(failed);
+ match resolve(detect, script, url) {
+ Ok(routes) => Some(routes),
+ Err(error) => {
+ log::info!("browser proxy couldn't use the automatic proxy setup: {error}");
+ let missing = [
+ ERROR_WINHTTP_AUTODETECTION_FAILED,
+ ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT,
+ ];
+ if missing.contains(&error) {
+ *FAILED.lock().ok()? = Some((key, Instant::now()));
+ }
+ None
+ }
+ }
+ }
+
+ fn resolve(
+ detect: bool,
+ script: Option<&str>,
+ url: &str,
+ ) -> Result<Vec<Option<Upstream>>, u32> {
+ let (url, script) = (wide(url), script.map(wide));
+ let session = session().ok_or(0u32)?;
+ let mut resolver = std::ptr::null_mut();
+ let error = unsafe { WinHttpCreateProxyResolver(session.0, &mut resolver) };
+ if error != 0 {
+ return Err(error);
+ }
+ let resolver = Handle(resolver);
+ let mut flags = 0;
+ if detect {
+ flags |= WINHTTP_AUTOPROXY_AUTO_DETECT;
+ }
+ if script.is_some() {
+ flags |= WINHTTP_AUTOPROXY_CONFIG_URL;
+ }
+ let options = WINHTTP_AUTOPROXY_OPTIONS {
+ dwFlags: flags,
+ dwAutoDetectFlags: if detect {
+ WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A
+ } else {
+ 0
+ },
+ lpszAutoConfigUrl: script
+ .as_ref()
+ .map_or(std::ptr::null(), |script| script.as_ptr()),
+ lpvReserved: std::ptr::null_mut(),
+ dwReserved: 0,
+ fAutoLogonIfChallenged: 1,
+ };
+ static NEXT: AtomicUsize = AtomicUsize::new(1);
+ let context = NEXT.fetch_add(1, Ordering::Relaxed);
+ let (sender, done) = sync_channel(1);
+ PENDING.lock().map_err(|_| 0u32)?.push((context, sender));
+ let started =
+ unsafe { WinHttpGetProxyForUrlEx(resolver.0, url.as_ptr(), &options, context) };
+ let error = match started {
+ ERROR_IO_PENDING => done.recv_timeout(ADDRESS_TIMEOUT).unwrap_or(ERROR_TIMEOUT),
+ error => error,
+ };
+ if let Ok(mut pending) = PENDING.lock() {
+ pending.retain(|(id, _)| *id != context);
+ }
+ if error != 0 {
+ return Err(error);
+ }
+ let mut result = WINHTTP_PROXY_RESULT {
+ cEntries: 0,
+ pEntries: std::ptr::null_mut(),
+ };
+ let error = unsafe { WinHttpGetProxyResult(resolver.0, &mut result) };
+ if error != 0 {
+ return Err(error);
+ }
+ let entries = match result.pEntries.is_null() {
+ true => &[][..],
+ false => unsafe {
+ std::slice::from_raw_parts(result.pEntries, result.cEntries as usize)
+ },
+ };
+ let mut routes: Vec<_> = entries.iter().filter_map(route).collect();
+ unsafe { WinHttpFreeProxyResult(&mut result) };
+ // An empty answer means direct, as browsers read one.
+ if routes.is_empty() {
+ routes.push(None);
+ }
+ Ok(routes)
+ }
+
+ fn route(entry: &WINHTTP_PROXY_RESULT_ENTRY) -> Option<Option<Upstream>> {
+ if entry.fProxy == 0 {
+ return Some(None);
+ }
+ let host = unsafe { text(entry.pwszProxy) }?;
+ let address = authority(&host, Some(i32::from(entry.ProxyPort)));
+ match entry.ProxyScheme {
+ WINHTTP_INTERNET_SCHEME_HTTP => Some(Some(Upstream::Http {
+ address,
+ auth: None,
+ })),
+ WINHTTP_INTERNET_SCHEME_SOCKS => Some(Some(Upstream::Socks4 { address })),
+ // An HTTPS proxy wants TLS to the proxy itself, which this one doesn't speak.
+ _ => None,
+ }
+ }
+
+ fn wide(text: &str) -> Vec<u16> {
+ text.encode_utf16().chain(Some(0)).collect()
+ }
+
+ unsafe fn text(pointer: *const u16) -> Option<String> {
+ if pointer.is_null() {
+ return None;
+ }
+ let length = (0..)
+ .take_while(|&i| unsafe { *pointer.add(i) } != 0)
+ .count();
+ String::from_utf16(unsafe { std::slice::from_raw_parts(pointer, length) }).ok()
+ }
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ use tokio::task::JoinHandle;
#[test]
fn parses_tunnels_and_plain_requests() {
@@ -206,7 +1384,8 @@ mod tests {
Some(Request {
host: "example.com".into(),
port: 443,
- forward: None
+ forward: None,
+ cleartext: false,
})
);
assert_eq!(
@@ -218,10 +1397,19 @@ mod tests {
)
.unwrap();
assert_eq!((plain.host.as_str(), plain.port), ("example.com", 80));
+ let forward = plain.forward.unwrap();
assert_eq!(
- plain.forward.unwrap(),
+ forward.head(None),
"GET /a?b=1 HTTP/1.1\r\nHost: example.com\r\nAccept: */*\r\nConnection: close\r\n\r\n"
);
+ let proxy = Upstream::Http {
+ address: "127.0.0.1:9".into(),
+ auth: Some("Basic dTpw".into()),
+ };
+ assert_eq!(
+ forward.head(Some(&proxy)),
+ "GET http://example.com/a?b=1 HTTP/1.1\r\nHost: example.com\r\nAccept: */*\r\nProxy-Authorization: Basic dTpw\r\nConnection: close\r\n\r\n"
+ );
assert_eq!(parse("GET /relative HTTP/1.1\r\n\r\n"), None);
assert_eq!(parse("GET https://example.com/ HTTP/1.1\r\n\r\n"), None);
}
@@ -236,6 +1424,8 @@ mod tests {
"[::ffff:7f00:1]",
"10.0.0.1",
"printer.local",
+ "wiki.corp",
+ "router.home",
] {
assert_eq!(
connect(host, 80).await.err(),
@@ -257,4 +1447,505 @@ mod tests {
client.read_to_string(&mut response).await.unwrap();
assert!(response.starts_with("HTTP/1.1 403"), "{response}");
}
+
+ /// The port of the proxy `per_protocol` picks for `url`, given proxy variables `env`.
+ fn port_for(server: &str, bypass: &str, env: &[(&str, &str)], url: &str) -> Option<u16> {
+ let env = |name: &str| {
+ env.iter()
+ .find(|(key, _)| *key == name)
+ .map(|(_, v)| v.to_string())
+ };
+ let intercept = per_protocol(server, bypass, env)?.intercept(&url.parse().unwrap())?;
+ intercept.uri().port_u16()
+ }
+
+ #[test]
+ fn windows_per_protocol_proxies_are_split() {
+ let both = "http=127.0.0.1:1; HTTPS=127.0.0.1:2;socks=127.0.0.1:3";
+ let corp = "*.corp.example;<local>";
+ let (http, https) = ("http://a.example/", "https://a.example/");
+ assert!(per_protocol("127.0.0.1:7890", "", |_| None).is_none());
+ let (wiki, http_wiki) = ("https://wiki.corp.example/", "http://wiki.corp.example/");
+ for (url, port) in [(http, Some(1)), (https, Some(2)), (wiki, None)] {
+ assert_eq!(port_for(both, corp, &[], url), port, "{url}");
+ }
+ // Each variable overrides only its own setting, and only when not empty.
+ let http_var = [("HTTP_PROXY", "http://127.0.0.1:9"), ("HTTPS_PROXY", "")];
+ assert_eq!(port_for(both, "", &http_var, http), Some(9));
+ assert_eq!(port_for(both, "", &http_var, https), Some(2));
+ let https_var = [
+ ("HTTPS_PROXY", "http://127.0.0.1:8"),
+ ("NO_PROXY", "a.example"),
+ ];
+ for (url, port) in [(https, None), (wiki, Some(8)), (http_wiki, Some(1))] {
+ assert_eq!(port_for(both, corp, &https_var, url), port, "{url}");
+ }
+ let all_var = [("ALL_PROXY", "http://127.0.0.1:7")];
+ assert_eq!(port_for("http=127.0.0.1:1", "", &all_var, https), Some(7));
+ }
+
+ // A name local DNS can't answer, so only a request sent on by name gets through.
+ const UNRESOLVABLE: &str = "studio-proxy-test.invalid";
+
+ fn tunnel(target: &str) -> String {
+ format!("CONNECT {target} HTTP/1.1\r\n\r\n")
+ }
+
+ /// A system proxy that records the request head it gets and sends `answer`.
+ async fn system_proxy_answering(answer: &'static str) -> (Matcher, JoinHandle<Option<String>>) {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = format!("http://u:p@{}", listener.local_addr().unwrap());
+ let seen = tokio::spawn(async move {
+ let (mut stream, _) = listener.accept().await.ok()?;
+ let (head, _) = read_head(&mut stream).await?;
+ stream.write_all(answer.as_bytes()).await.ok()?;
+ Some(head)
+ });
+ let proxies = Matcher::builder().http(&address).https(&address).build();
+ (proxies, seen)
+ }
+
+ /// As `system_proxy_answering`, with a proxy set for `scheme` only, as with System Settings'
+ /// "Web Proxy (HTTP)" or "Secure Web Proxy (HTTPS)" alone.
+ async fn proxy_answering_for(
+ scheme: &str,
+ answer: &'static str,
+ ) -> (Matcher, JoinHandle<Option<String>>) {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = format!("http://u:p@{}", listener.local_addr().unwrap());
+ let seen = tokio::spawn(async move {
+ let (mut stream, _) = listener.accept().await.ok()?;
+ let (head, _) = read_head(&mut stream).await?;
+ stream.write_all(answer.as_bytes()).await.ok()?;
+ Some(head)
+ });
+ let proxies = match scheme {
+ "http" => Matcher::builder().http(&address),
+ _ => Matcher::builder().https(&address),
+ };
+ (proxies.build(), seen)
+ }
+
+ async fn exchange(proxies: Matcher, request: &str) -> String {
+ exchange_all(vec![proxies], request).await
+ }
+
+ async fn exchange_all(fixed: Vec<Matcher>, request: &str) -> String {
+ let proxies = Proxies {
+ fixed,
+ ..Default::default()
+ };
+ exchange_via(proxies, request).await
+ }
+
+ async fn exchange_via(proxies: Proxies, request: &str) -> String {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let mut client = TcpStream::connect(listener.local_addr().unwrap())
+ .await
+ .unwrap();
+ tokio::spawn(serve(listener.accept().await.unwrap().0, proxies));
+ client.write_all(request.as_bytes()).await.unwrap();
+ let mut response = String::new();
+ client.read_to_string(&mut response).await.unwrap();
+ response
+ }
+
+ #[tokio::test]
+ async fn requests_go_through_the_system_proxy_by_name() {
+ let target = format!("{UNRESOLVABLE}:443");
+ let auth = "Proxy-Authorization: Basic dTpw";
+ let (proxies, seen) = system_proxy_answering("HTTP/1.1 200 OK\r\n\r\nhello").await;
+ let response = exchange(proxies, &tunnel(&target)).await;
+ assert_eq!(response, "HTTP/1.1 200 Connection Established\r\n\r\nhello");
+ let expected = format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n{auth}\r\n\r\n");
+ assert_eq!(seen.await.unwrap().as_deref(), Some(expected.as_str()));
+ let (proxies, seen) = system_proxy_answering("HTTP/1.1 200 OK\r\n\r\nhello").await;
+ let url = format!("http://{UNRESOLVABLE}/a");
+ let response = exchange(proxies, &format!("GET {url} HTTP/1.1\r\n\r\n")).await;
+ assert_eq!(response, "HTTP/1.1 200 OK\r\n\r\nhello");
+ let expected = format!("GET {url} HTTP/1.1\r\n{auth}\r\nConnection: close\r\n\r\n");
+ assert_eq!(seen.await.unwrap().as_deref(), Some(expected.as_str()));
+ }
+
+ /// Opens a tunnel to `target`, then sends `inner` through it once the tunnel is up.
+ async fn exchange_in_tunnel(proxies: Matcher, target: &str, inner: &str) -> String {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let mut client = TcpStream::connect(listener.local_addr().unwrap())
+ .await
+ .unwrap();
+ let proxies = Proxies {
+ fixed: vec![proxies],
+ ..Default::default()
+ };
+ tokio::spawn(serve(listener.accept().await.unwrap().0, proxies));
+ client.write_all(tunnel(target).as_bytes()).await.unwrap();
+ let mut established = vec![0u8; ESTABLISHED.len()];
+ client.read_exact(&mut established).await.unwrap();
+ assert_eq!(established, ESTABLISHED);
+ client.write_all(inner.as_bytes()).await.unwrap();
+ let mut response = String::new();
+ client.read_to_string(&mut response).await.unwrap();
+ response
+ }
+
+ #[tokio::test]
+ async fn plain_http_tunnels_are_forwarded_as_http_requests() {
+ let (proxies, seen) = proxy_answering_for("http", "HTTP/1.1 200 OK\r\n\r\nhello").await;
+ let host = format!("Host: {UNRESOLVABLE}\r\n");
+ let inner = format!("GET /a?q=1 HTTP/1.1\r\n{host}Connection: keep-alive\r\n\r\n");
+ let response = exchange_in_tunnel(proxies, &format!("{UNRESOLVABLE}:80"), &inner).await;
+ assert_eq!(response, "HTTP/1.1 200 OK\r\n\r\nhello");
+ let auth = "Proxy-Authorization: Basic dTpw";
+ let expected = format!(
+ "GET http://{UNRESOLVABLE}/a?q=1 HTTP/1.1\r\n{host}{auth}\r\nConnection: close\r\n\r\n"
+ );
+ assert_eq!(seen.await.unwrap().as_deref(), Some(expected.as_str()));
+ }
+
+ #[tokio::test]
+ async fn websocket_tunnels_to_port_80_stay_tunnels() {
+ // A `ws://` socket takes the HTTP proxy, which is all that is set here.
+ let (proxies, seen) = proxy_answering_for("http", "HTTP/1.1 200 OK\r\n\r\n").await;
+ let inner = "GET /ws HTTP/1.1\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n";
+ let target = format!("{UNRESOLVABLE}:80");
+ // The proxy took the tunnel, so no refusal comes back.
+ assert_eq!(exchange_in_tunnel(proxies, &target, inner).await, "");
+ let auth = "Proxy-Authorization: Basic dTpw";
+ let expected = format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n{auth}\r\n\r\n");
+ assert_eq!(seen.await.unwrap().as_deref(), Some(expected.as_str()));
+ }
+
+ #[tokio::test]
+ async fn tls_tunnels_to_port_80_take_the_https_proxy() {
+ let (proxies, seen) = proxy_answering_for("https", "HTTP/1.1 200 OK\r\n\r\n").await;
+ let target = format!("{UNRESOLVABLE}:80");
+ let hello = "\u{16}\u{3}\u{1}\u{0}\u{5}hello";
+ assert_eq!(exchange_in_tunnel(proxies, &target, hello).await, "");
+ let auth = "Proxy-Authorization: Basic dTpw";
+ let expected = format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n{auth}\r\n\r\n");
+ assert_eq!(seen.await.unwrap().as_deref(), Some(expected.as_str()));
+ }
+
+ #[tokio::test]
+ async fn private_hosts_and_refused_tunnels_fail_through_the_system_proxy() {
+ let (proxies, _) = system_proxy_answering("HTTP/1.1 200 OK\r\n\r\n").await;
+ let response = exchange(proxies, "CONNECT printer.local:80 HTTP/1.1\r\n\r\n").await;
+ assert!(response.starts_with("HTTP/1.1 403"), "{response}");
+ let (proxies, _) = system_proxy_answering("HTTP/1.1 407 Proxy Auth\r\n\r\n").await;
+ let response = exchange(proxies, &tunnel(&format!("{UNRESOLVABLE}:443"))).await;
+ assert!(response.starts_with("HTTP/1.1 502"), "{response}");
+ }
+
+ /// A SOCKS5 proxy that wants `u`/`p`, records the CONNECT it gets, answers with a domain-typed
+ /// bound address, sends "hello", then (with `request`) records the request head sent next.
+ async fn socks_proxy(request: bool) -> (String, JoinHandle<(String, u16, String)>) {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap().to_string();
+ let seen = tokio::spawn(async move {
+ let (mut stream, _) = listener.accept().await.unwrap();
+ let mut greeting = [0u8; 4];
+ stream.read_exact(&mut greeting).await.unwrap();
+ assert_eq!(greeting, [5, 2, 0, 2]);
+ stream.write_all(&[5, 2]).await.unwrap();
+ let mut login = [0u8; 5];
+ stream.read_exact(&mut login).await.unwrap();
+ assert_eq!(login, [1, 1, b'u', 1, b'p']);
+ stream.write_all(&[1, 0]).await.unwrap();
+ let mut connect = [0u8; 5];
+ stream.read_exact(&mut connect).await.unwrap();
+ assert_eq!(connect[..4], [5, 1, 0, 3]);
+ let mut name = vec![0u8; usize::from(connect[4])];
+ stream.read_exact(&mut name).await.unwrap();
+ let mut port = [0u8; 2];
+ stream.read_exact(&mut port).await.unwrap();
+ stream
+ .write_all(&[5, 0, 0, 3, 4, b'b', b'o', b'u', b'n', 0, 80])
+ .await
+ .unwrap();
+ stream.write_all(b"hello").await.unwrap();
+ let sent = if request {
+ tokio::time::timeout(Duration::from_secs(5), read_head(&mut stream))
+ .await
+ .unwrap()
+ .unwrap()
+ .0
+ } else {
+ String::new()
+ };
+ (
+ String::from_utf8(name).unwrap(),
+ u16::from_be_bytes(port),
+ sent,
+ )
+ });
+ (address, seen)
+ }
+
+ #[test]
+ fn proxy_settings_bracket_ipv6_hosts() {
+ assert_eq!(authority("::1", Some(1080)), "[::1]:1080");
+ assert_eq!(authority("::1", None), "[::1]");
+ assert_eq!(authority("proxy.example", Some(1080)), "proxy.example:1080");
+ let proxies = socks_fallback(&authority("::1", Some(1080)), "");
+ assert!(proxies
+ .intercept(&"https://example.com/".parse().unwrap())
+ .is_some());
+ }
+
+ #[tokio::test]
+ async fn socks4_tunnels_name_the_host() {
+ for (answer, opened) in [(0x5a, true), (0x5b, false)] {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap().to_string();
+ let seen = tokio::spawn(async move {
+ let (mut stream, _) = listener.accept().await.unwrap();
+ let mut connect = vec![0u8; 10 + UNRESOLVABLE.len()];
+ stream.read_exact(&mut connect).await.unwrap();
+ stream
+ .write_all(&[0, answer, 0, 0, 0, 0, 0, 0])
+ .await
+ .unwrap();
+ connect
+ });
+ let request = parse(&tunnel(&format!("{UNRESOLVABLE}:443"))).unwrap();
+ let result = connect_via(&Upstream::Socks4 { address }, &request).await;
+ assert_eq!(result.is_ok(), opened, "{answer}");
+ let mut expected = vec![4, 1, 1, 187, 0, 0, 0, 1, 0];
+ expected.extend_from_slice(UNRESOLVABLE.as_bytes());
+ expected.push(0);
+ assert_eq!(seen.await.unwrap(), expected);
+ }
+ }
+
+ #[tokio::test]
+ async fn tunnels_go_through_a_socks_proxy_by_name() {
+ let (address, seen) = socks_proxy(false).await;
+ let proxies = Matcher::builder()
+ .all(format!("socks5://u:p@{address}"))
+ .build();
+ let response = exchange(proxies, &tunnel(&format!("{UNRESOLVABLE}:443"))).await;
+ assert_eq!(response, "HTTP/1.1 200 Connection Established\r\n\r\nhello");
+ let (name, port, _) = seen.await.unwrap();
+ assert_eq!((name.as_str(), port), (UNRESOLVABLE, 443));
+ }
+
+ #[tokio::test]
+ async fn plain_requests_through_socks_stay_origin_form() {
+ let (address, seen) = socks_proxy(true).await;
+ // The SOCKS fallback covers what the first settings leave out.
+ let proxies = vec![
+ Matcher::builder().build(),
+ socks_fallback(&format!("u:p@{address}"), ""),
+ ];
+ let response = exchange_all(
+ proxies,
+ &format!("GET http://{UNRESOLVABLE}/a HTTP/1.1\r\nHost: {UNRESOLVABLE}\r\n\r\n"),
+ )
+ .await;
+ assert_eq!(response, "hello");
+ let (name, port, sent) = seen.await.unwrap();
+ assert_eq!((name.as_str(), port), (UNRESOLVABLE, 80));
+ assert!(sent.starts_with("GET /a HTTP/1.1\r\n"), "{sent}");
+ }
+
+ #[cfg(target_os = "macos")]
+ #[tokio::test]
+ async fn pac_scripts_decide_before_fixed_settings() {
+ let script = r#"function FindProxyForURL(url, host) {
+ if (host == "h.example") return "PROXY 127.0.0.1:1; DIRECT";
+ if (host == "s.example") return "SOCKS 127.0.0.1:2";
+ return "DIRECT";
+ }"#;
+ let server = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let location = format!("http://{}/proxy.pac", server.local_addr().unwrap());
+ // Answers once, so only a cached script serves the later pages.
+ tokio::spawn(async move {
+ let (mut stream, _) = server.accept().await.unwrap();
+ read_head(&mut stream).await;
+ let head = format!(
+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n",
+ script.len()
+ );
+ stream.write_all((head + script).as_bytes()).await.unwrap();
+ });
+ let env = |name: &str| match name {
+ "HTTP_PROXY" => Some("http://127.0.0.1:8".to_string()),
+ "NO_PROXY" => Some("n.example".to_string()),
+ _ => None,
+ };
+ let pac = |source| Some(pac::Pac::new(source, &env));
+ let fixed = || vec![Matcher::builder().all("http://127.0.0.1:9").build()];
+ let proxies = Proxies {
+ pac: pac(pac::Source::Url(location)),
+ fixed: fixed(),
+ };
+ let to = |host| parse(&tunnel(&format!("{host}:443"))).unwrap();
+ let http = |address: &str| {
+ Some(Upstream::Http {
+ address: address.into(),
+ auth: None,
+ })
+ };
+ assert_eq!(
+ routes(&proxies, &to("h.example")).await,
+ [http("127.0.0.1:1"), None]
+ );
+ let socks = Upstream::Socks {
+ address: "127.0.0.1:2".into(),
+ auth: None,
+ };
+ assert_eq!(routes(&proxies, &to("s.example")).await, [Some(socks)]);
+ assert_eq!(routes(&proxies, &to("d.example")).await, [None]);
+ // Proxy variables and NO_PROXY take precedence, as over the other settings.
+ let plain = parse("GET http://h.example/ HTTP/1.1\r\n\r\n").unwrap();
+ assert_eq!(routes(&proxies, &plain).await, [http("127.0.0.1:9")]);
+ assert_eq!(
+ routes(&proxies, &to("n.example")).await,
+ [http("127.0.0.1:9")]
+ );
+ let broken = Proxies {
+ pac: pac(pac::Source::Script("not a script(".into())),
+ fixed: fixed(),
+ };
+ assert_eq!(
+ routes(&broken, &to("h.example")).await,
+ [http("127.0.0.1:9")]
+ );
+ // The script sees the URL Safari would give it.
+ let by_url = "function FindProxyForURL(url) { return url == 'https://h.example/' ? 'PROXY 127.0.0.1:3' : 'DIRECT'; }";
+ let no_env = |_: &str| None;
+ let proxies = Proxies {
+ pac: Some(pac::Pac::new(pac::Source::Script(by_url.into()), &no_env)),
+ fixed: vec![],
+ };
+ assert_eq!(
+ routes(&proxies, &to("h.example")).await,
+ [http("127.0.0.1:3")]
+ );
+ // A proxy that can't be reached gives way to the next route; one that refuses doesn't.
+ let address = |(proxies, _): (Matcher, JoinHandle<_>)| {
+ let proxy = proxies
+ .intercept(&"https://a.example/".parse().unwrap())
+ .unwrap();
+ format!(
+ "{}:{}",
+ proxy.uri().host().unwrap(),
+ proxy.uri().port_u16().unwrap()
+ )
+ };
+ let working = address(system_proxy_answering("HTTP/1.1 200 OK\r\n\r\nhello").await);
+ let refusing = address(system_proxy_answering("HTTP/1.1 407 Proxy Auth\r\n\r\n").await);
+ for (first, expected) in [
+ (refusing.as_str(), "HTTP/1.1 502"),
+ ("127.0.0.1:1", "HTTP/1.1 200"),
+ ] {
+ let script = format!(
+ "function FindProxyForURL() {{ return 'PROXY {first}; PROXY {working}'; }}"
+ );
+ let proxies = Proxies {
+ pac: pac(pac::Source::Script(script.into())),
+ fixed: vec![],
+ };
+ let response = exchange_via(proxies, &tunnel(&format!("{UNRESOLVABLE}:443"))).await;
+ assert!(response.starts_with(expected), "{first}: {response}");
+ }
+ }
+
+ #[cfg(windows)]
+ #[tokio::test]
+ async fn windows_automatic_setup_decides_before_fixed_settings() {
+ let script = r#"function FindProxyForURL(url, host) {
+ if (host == "h.example") return "PROXY 127.0.0.1:1; DIRECT";
+ if (host == "s.example") return "SOCKS 127.0.0.1:2";
+ if (url == "https://u.example/") return "PROXY 127.0.0.1:3";
+ return "DIRECT";
+ }"#;
+ let server = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let location = format!("http://{}/proxy.pac", server.local_addr().unwrap());
+ tokio::spawn(async move {
+ while let Ok((mut stream, _)) = server.accept().await {
+ read_head(&mut stream).await;
+ let head = format!(
+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n",
+ script.len()
+ );
+ let _ = stream.write_all((head + script).as_bytes()).await;
+ }
+ });
+ let proxies = |url: &str| Proxies {
+ pac: Some(pac::Pac::new(
+ pac::Source::Automatic {
+ detect: false,
+ url: Some(url.into()),
+ },
+ &|_: &str| None,
+ )),
+ fixed: vec![Matcher::builder().all("http://127.0.0.1:9").build()],
+ };
+ let to = |host| parse(&tunnel(&format!("{host}:443"))).unwrap();
+ let http = |address: &str| {
+ Some(Upstream::Http {
+ address: address.into(),
+ auth: None,
+ })
+ };
+ let socks = Upstream::Socks4 {
+ address: "127.0.0.1:2".into(),
+ };
+ let found = proxies(&location);
+ for (host, expected) in [
+ ("h.example", vec![http("127.0.0.1:1"), None]),
+ ("s.example", vec![Some(socks)]),
+ ("u.example", vec![http("127.0.0.1:3")]),
+ ("d.example", vec![None]),
+ ] {
+ assert_eq!(routes(&found, &to(host)).await, expected, "{host}");
+ }
+ let missing = proxies("http://127.0.0.1:1/proxy.pac");
+ assert_eq!(
+ routes(&missing, &to("h.example")).await,
+ [http("127.0.0.1:9")]
+ );
+ }
+
+ #[cfg(target_os = "linux")]
+ #[test]
+ fn linux_desktop_proxies_map_to_routes() {
+ let routes = |proxy: &str, host: &str| {
+ let resolver = gio::SimpleProxyResolver::new(Some(proxy), &["n.example"][..]);
+ pac::desktop::evaluate(&resolver, &format!("https://{host}/")).unwrap()
+ };
+ assert_eq!(routes("http://127.0.0.1:1", "n.example"), [None]);
+ let socks4 = Upstream::Socks4 {
+ address: "127.0.0.1:3".into(),
+ };
+ assert_eq!(routes("socks4a://127.0.0.1:3", "h.example"), [Some(socks4)]);
+ // In order: GLib's expanded `socks`, libproxy's unexpanded one, then a DIRECT fallback.
+ let entries = [
+ "http://u:[email protected]:1",
+ "socks5://127.0.0.1:2",
+ "socks4a://127.0.0.1:2",
+ "socks://127.0.0.1:4",
+ "direct://",
+ ];
+ let http = Upstream::Http {
+ address: "127.0.0.1:1".into(),
+ auth: Some("Basic dTpw".into()),
+ };
+ let socks = |address: &str| {
+ Some(Upstream::Socks {
+ address: address.into(),
+ auth: None,
+ })
+ };
+ let to = "https://h.example/".parse().unwrap();
+ assert_eq!(
+ pac::desktop::from_entries(&entries, &to),
+ [Some(http), socks("127.0.0.1:2"), socks("127.0.0.1:4"), None]
+ );
+ // Proxy variables replace the desktop's settings rather than mixing with them.
+ let env = |name: &str| (name == "https_proxy").then(|| "http://127.0.0.1:8".to_string());
+ assert!(linux_proxies(env).pac.is_none());
+ assert!(linux_proxies(|_: &str| None).pac.is_some());
+ }
}
diff --git a/studio/src-tauri/src/browser_webview.rs b/studio/src-tauri/src/browser_webview.rs
index aacf1dd6f1d..34e32d44c00 100644
--- a/studio/src-tauri/src/browser_webview.rs
+++ b/studio/src-tauri/src/browser_webview.rs
@@ -303,7 +303,9 @@ pub(crate) fn host_is_private(host: &url::Host<&str>) -> bool {
let domain = domain.trim_end_matches('.').to_ascii_lowercase();
// A dotless name only resolves locally.
!domain.contains('.')
- || ["localhost", "local", "internal", "lan", "home.arpa", "intranet"]
+ || [
+ "localhost", "local", "internal", "lan", "home", "home.arpa", "corp", "intranet",
+ ]
.iter()
.any(|suffix| domain == *suffix || domain.ends_with(&format!(".{suffix}")))
// Written as a number the URL parser didn't normalise.