Proxy: one copy of the rules, none of it per request
Co-Authored-By: WorkBuddy AI (DeepSeek-V4.1-Flash) <noreply@workbuddy.cn>
This commit is contained in:
+66
-150
@@ -9,23 +9,35 @@
|
||||
//! Servers page's calls to a game server's API (`servers.rs`) build their agent without it: they
|
||||
//! are on loopback and asked every second.
|
||||
//!
|
||||
//! The jars an import downloads are fetched by `horizon-port-pack`, which builds its own agents and
|
||||
//! keeps these same `NO_PROXY` rules (`crates/horizon-port-pack/src/net.rs`). The two crates share
|
||||
//! no code, so a change to them here belongs there too.
|
||||
//! Which hosts are reached directly, and how an address is read, are `horizon-port-pack`'s rules
|
||||
//! (`crates/horizon-port-pack/src/net.rs`): the jars an import fetches are downloaded there, and
|
||||
//! the same hosts have to be left alone on both sides. This module adds what is the launcher's
|
||||
//! own — the setting in `settings.json`, kept in memory so a request doesn't read the file — and
|
||||
//! hands the address to the parts that build their agents.
|
||||
use crate::backend::Settings;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// The proxy to reach `url` through: the one set for the launcher or in the environment, unless
|
||||
/// The launcher's setting, as `announce` last read it, or None before it has: a request shouldn't
|
||||
/// read `settings.json` every time, and an import fetches hundreds of jars.
|
||||
static SET: Mutex<Option<Option<String>>> = Mutex::new(None);
|
||||
|
||||
/// The proxy address to reach `url` through: the launcher's setting, else the environment's, unless
|
||||
/// `url` is a local address or `NO_PROXY` names its host.
|
||||
pub fn for_url(url: &str) -> Option<ureq::Proxy> {
|
||||
let scheme = scheme_of(url)?;
|
||||
let host = host_of(url)?;
|
||||
if local(host) || excluded(host, &no_proxy()) {
|
||||
pub fn spec_for(url: &str) -> Option<String> {
|
||||
let scheme = horizon_port_pack::net::scheme_of(url)?;
|
||||
if horizon_port_pack::net::direct(url) {
|
||||
return None;
|
||||
}
|
||||
ureq::Proxy::new(written(scheme)?).ok()
|
||||
setting().or_else(|| horizon_port_pack::net::env_for(scheme))
|
||||
}
|
||||
|
||||
/// `builder`, reaching `url` through the proxy when one is set.
|
||||
/// The proxy to reach `url` through: `spec_for`'s address, read as one.
|
||||
pub fn for_url(url: &str) -> Option<ureq::Proxy> {
|
||||
spec_for(url).and_then(|spec| horizon_port_pack::net::parse(&spec))
|
||||
}
|
||||
|
||||
/// `builder`, reaching `url` through the proxy when one is set. For the parts that ask for a few
|
||||
/// addresses; the ones that fetch file after file keep their agent instead (`keep`).
|
||||
pub fn agent(builder: ureq::AgentBuilder, url: &str) -> ureq::AgentBuilder {
|
||||
match for_url(url) {
|
||||
Some(proxy) => builder.proxy(proxy),
|
||||
@@ -39,19 +51,17 @@ pub fn refuse(spec: &str) -> Option<String> {
|
||||
if spec.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let scheme = spec.split_once("://").map(|(s, _)| s.to_ascii_lowercase());
|
||||
if matches!(
|
||||
scheme.as_deref(),
|
||||
Some("socks" | "socks4" | "socks4a" | "socks5" | "socks5h")
|
||||
) {
|
||||
if horizon_port_pack::net::socks(spec) {
|
||||
return Some(format!(
|
||||
"{spec} is a SOCKS proxy; Horizon downloads through an HTTP proxy, such as the \
|
||||
http:// address your proxy app also listens on."
|
||||
));
|
||||
}
|
||||
// `Proxy::new` takes `http://` without a host, which would leave a download failing with
|
||||
// nothing said about the proxy.
|
||||
if ureq::Proxy::new(spec).is_err() || host_of(spec).is_none_or(str::is_empty) {
|
||||
// `ureq` takes `http://` without a host, which would leave a download failing with nothing
|
||||
// said about the proxy.
|
||||
if horizon_port_pack::net::parse(spec).is_none()
|
||||
|| horizon_port_pack::net::host_of(spec).is_none_or(str::is_empty)
|
||||
{
|
||||
return Some(format!(
|
||||
"{spec} isn't a proxy address. Write it as http://host:port."
|
||||
));
|
||||
@@ -59,97 +69,46 @@ pub fn refuse(spec: &str) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Tells the parts that build their own agents (`horizon-port-pack`) which proxy to use. Called at
|
||||
/// start and whenever the player changes the setting; the hosts `NO_PROXY` names stay direct there
|
||||
/// too, since it reads the same list.
|
||||
pub fn announce() {
|
||||
horizon_port_pack::net::set_proxy(written("https"));
|
||||
/// Tells the parts that build their own agents (`horizon-port-pack`) which proxy to use, and keeps
|
||||
/// the setting for the launcher's own requests. Called with what `settings.json` holds: at start,
|
||||
/// and whenever the player changes the setting.
|
||||
///
|
||||
/// The environment's is left to them: they read it per address (`HTTPS_PROXY` for an https jar,
|
||||
/// `HTTP_PROXY` for an http one), the way the launcher does for its own.
|
||||
pub fn announce(setting: Option<String>) {
|
||||
let spec = setting
|
||||
.map(|p| p.trim().to_owned())
|
||||
.filter(|p| !p.is_empty());
|
||||
*held() = Some(spec.clone());
|
||||
horizon_port_pack::net::set_proxy(spec);
|
||||
}
|
||||
|
||||
/// The proxy as it is written down: the launcher's, else the environment's for `scheme`.
|
||||
fn written(scheme: &str) -> Option<String> {
|
||||
/// The launcher's setting: read from `settings.json` the first time it is needed and kept after
|
||||
/// that, so a download doesn't read the file once per file.
|
||||
fn setting() -> Option<String> {
|
||||
let mut set = held();
|
||||
match set.clone() {
|
||||
Some(kept) => kept,
|
||||
None => {
|
||||
let read = written();
|
||||
*set = Some(read.clone());
|
||||
read
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The launcher's setting as it is written down, or None when there is none.
|
||||
fn written() -> Option<String> {
|
||||
Settings::load()
|
||||
.proxy
|
||||
.map(|p| p.trim().to_owned())
|
||||
.filter(|p| !p.is_empty())
|
||||
.or_else(|| from_env(scheme))
|
||||
}
|
||||
|
||||
/// `HTTPS_PROXY` (`HTTP_PROXY` for an http address), then `ALL_PROXY`, in the upper-case spelling
|
||||
/// first and the lower-case one after, as the tools that write them do.
|
||||
fn from_env(scheme: &str) -> Option<String> {
|
||||
let names: &[&str] = if scheme.eq_ignore_ascii_case("http") {
|
||||
&["HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"]
|
||||
} else {
|
||||
&["HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"]
|
||||
};
|
||||
names.iter().find_map(|name| {
|
||||
std::env::var(name)
|
||||
.ok()
|
||||
.map(|v| v.trim().to_owned())
|
||||
.filter(|v| !v.is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
/// `NO_PROXY`'s list: the hosts reached directly whatever the proxy is.
|
||||
fn no_proxy() -> String {
|
||||
["NO_PROXY", "no_proxy"]
|
||||
.iter()
|
||||
.find_map(|name| std::env::var(name).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The host part of a URL (`https://user@host:port/path` is `host`).
|
||||
fn host_of(url: &str) -> Option<&str> {
|
||||
let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
|
||||
let rest = rest.split(['/', '?', '#']).next()?;
|
||||
let rest = rest.rsplit_once('@').map_or(rest, |(_, host)| host);
|
||||
Some(match rest.rfind(':') {
|
||||
// A port follows the last colon; an IPv6 literal keeps the colons inside its brackets.
|
||||
Some(at) if !rest[at..].contains(']') => &rest[..at],
|
||||
_ => rest,
|
||||
})
|
||||
}
|
||||
|
||||
/// `https` in `https://…`, or None for anything that isn't an absolute address.
|
||||
fn scheme_of(url: &str) -> Option<&str> {
|
||||
url.split_once("://").map(|(scheme, _)| scheme)
|
||||
}
|
||||
|
||||
/// Whether `host` is this computer: the game's own API and a server on the same machine.
|
||||
fn local(host: &str) -> bool {
|
||||
let host = bare(host);
|
||||
host == "localhost"
|
||||
|| host.ends_with(".localhost")
|
||||
|| host == "::1"
|
||||
|| host == "0.0.0.0"
|
||||
|| host.starts_with("127.")
|
||||
}
|
||||
|
||||
/// Whether `host` is in `NO_PROXY`: `*`, `host`, `.domain`, `*.domain` and `host:port` entries.
|
||||
fn excluded(host: &str, no_proxy: &str) -> bool {
|
||||
let host = bare(host);
|
||||
no_proxy
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|e| !e.is_empty())
|
||||
.any(|entry| {
|
||||
if entry == "*" {
|
||||
return true;
|
||||
}
|
||||
let entry = entry.trim_start_matches('*').trim_start_matches('.');
|
||||
let entry = match entry.rfind(':') {
|
||||
Some(at) if !entry[at..].contains(']') => &entry[..at],
|
||||
_ => entry,
|
||||
};
|
||||
let entry = bare(entry);
|
||||
!entry.is_empty() && (host == entry || host.ends_with(&format!(".{entry}")))
|
||||
})
|
||||
}
|
||||
|
||||
/// A host without the brackets an IPv6 literal wears, lower case.
|
||||
fn bare(host: &str) -> String {
|
||||
host.trim().trim_matches(['[', ']']).to_ascii_lowercase()
|
||||
/// The setting's lock, even after a thread panicked while holding it: an address lost to a panic
|
||||
/// is worse than an old one kept.
|
||||
fn held() -> std::sync::MutexGuard<'static, Option<Option<String>>> {
|
||||
SET.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -157,58 +116,15 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_host_is_read_out_of_the_address() {
|
||||
assert_eq!(
|
||||
host_of("https://cdn.modrinth.com/v2/x.jar"),
|
||||
Some("cdn.modrinth.com")
|
||||
);
|
||||
assert_eq!(
|
||||
host_of("https://user:pass@piston-meta.mojang.com:8443/a"),
|
||||
Some("piston-meta.mojang.com")
|
||||
);
|
||||
assert_eq!(
|
||||
host_of("http://127.0.0.1:8130/api/v1/status"),
|
||||
Some("127.0.0.1")
|
||||
);
|
||||
assert_eq!(host_of("https://[::1]:25565/"), Some("[::1]"));
|
||||
assert_eq!(host_of("https://example.com?x=1"), Some("example.com"));
|
||||
assert_eq!(host_of("https://example.com#top"), Some("example.com"));
|
||||
fn a_local_address_takes_no_proxy() {
|
||||
assert_eq!(spec_for("http://127.0.0.1:8130/api/v1/status"), None);
|
||||
assert_eq!(spec_for("http://localhost/api/v1/status"), None);
|
||||
}
|
||||
|
||||
/// An address the launcher knows nothing about is one nothing is written for either.
|
||||
#[test]
|
||||
fn only_absolute_addresses_have_a_scheme() {
|
||||
assert_eq!(scheme_of("https://a.b"), Some("https"));
|
||||
assert_eq!(scheme_of("http://a.b"), Some("http"));
|
||||
assert_eq!(scheme_of("a.b/c"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn this_computer_is_never_proxied() {
|
||||
for host in [
|
||||
"localhost",
|
||||
"LOCALHOST",
|
||||
"[::1]",
|
||||
"::1",
|
||||
"127.0.0.1",
|
||||
"127.1.2.3",
|
||||
] {
|
||||
assert!(local(host), "{host}");
|
||||
}
|
||||
for host in ["playhorizon.dev", "api.minecraftservices.com", "10.0.0.1"] {
|
||||
assert!(!local(host), "{host}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_proxy_lists_hosts_and_their_subdomains() {
|
||||
let list = "*.internal, .corp.example, mojang.com, github.com:443, *";
|
||||
assert!(excluded("anything.at.all", list));
|
||||
assert!(excluded("wiki.corp.example", "corp.example"));
|
||||
assert!(excluded("piston-meta.mojang.com", "mojang.com"));
|
||||
assert!(excluded("github.com", "github.com:443"));
|
||||
assert!(!excluded("notmojang.com", "mojang.com"));
|
||||
assert!(!excluded("modrinth.com", " .corp.example , mojang.com "));
|
||||
assert!(!excluded("modrinth.com", ""));
|
||||
fn a_relative_address_has_no_scheme_to_read_a_proxy_for() {
|
||||
assert_eq!(spec_for("data/a.jar"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user