Merge pull request #2059 from zhykowo/feat/launcher-proxy

🤖 Agent: Gate check by Ludovic's AI agent (Claude). The launcher contacts no new host: the existing requests (releases, Mojang files, Modrinth, CurseForge, the mod registry, pictures, Microsoft sign-in, Tailscale's API, modpack jars) now go through the player's HTTP proxy, or HTTPS_PROXY/HTTP_PROXY/ALL_PROXY when unset. Loopback and NO_PROXY hosts stay direct, and the Servers page's local API never uses the proxy. Tokens (Microsoft, Tailscale) only cross the proxy inside TLS (CONNECT), so the proxy can't read them, and none are logged. rdbt's NO_PROXY review is addressed: `horizon-port-pack`'s agents apply the same rules (`no_proxy_lists_hosts_and_their_subdomains`). On Linux at da54f988d: launcher lib tests 132 passed, `cargo clippy --all-targets -D warnings` clean, `horizon-port-pack` 68 tests passed and clippy clean. Labelled feature. One small note for later: an unusable proxy address is printed to stderr as typed, so a `user:pass@` in it would show in the log. Thanks @zhykowo!
This commit is contained in:
Ludovic Marie
2026-10-26 16:10:03 +01:00
committed by GitHub
19 changed files with 712 additions and 56 deletions
+5 -2
View File
@@ -143,7 +143,9 @@ pub fn fetch(
if let Some((dest, url)) = crate::worldgen::loader_jar(work, &pack.loader, &pack.loader_version)
.filter(|(dest, _)| !dest.exists())
{
let sha1 = ureq::get(&format!("{url}.sha1"))
let checksum = format!("{url}.sha1");
let sha1 = crate::net::agent(&checksum)
.get(&checksum)
.set("User-Agent", modrinth::AGENT)
.call()
.ok()
@@ -201,7 +203,8 @@ pub fn url_of(file: &PackFile, cache: &Cache) -> Option<String> {
/// Downloads `url` to `dest`, kept only if its SHA-1 is `sha1`.
fn download(url: &str, sha1: Option<&str>, dest: &Path) -> Result<(), String> {
let response = ureq::get(url)
let response = crate::net::agent(url)
.get(url)
.set("User-Agent", modrinth::AGENT)
.call()
.map_err(|e| format!("{url}: {e}"))?;
+1
View File
@@ -16,6 +16,7 @@ pub mod jar;
pub(crate) mod legacy_structure_mods;
mod lithostitched;
pub mod modrinth;
pub mod net;
pub mod oracle;
pub mod pipeline;
pub mod processors;
+4 -2
View File
@@ -79,7 +79,8 @@ impl Cache {
}
fn post(url: &str, body: &Value) -> Result<Value, String> {
let response = ureq::post(url)
let response = crate::net::agent(url)
.post(url)
.set("User-Agent", AGENT)
.set("Content-Type", "application/json")
.send_string(&body.to_string())
@@ -88,7 +89,8 @@ fn post(url: &str, body: &Value) -> Result<Value, String> {
}
fn get(url: &str) -> Result<Value, String> {
let response = ureq::get(url)
let response = crate::net::agent(url)
.get(url)
.set("User-Agent", AGENT)
.call()
.map_err(|e| format!("{url}: {e}"))?;
+352
View File
@@ -0,0 +1,352 @@
//! The agents port-pack's downloads go through: the jars of an imported modpack come from the same
//! places as everything else, so they take the same proxy — and leave the same hosts alone.
//!
//! The launcher hands its own setting over (`set_proxy`, from `proxy.rs`); a run of the
//! `horizon-port-pack` command reads `HTTPS_PROXY`, `HTTP_PROXY` and `ALL_PROXY` instead (`env_for`),
//! taking the one that matches the address's scheme the way the launcher does. Either way a host in
//! `NO_PROXY`, or on this computer, is reached directly: a host that only answers without the proxy
//! would otherwise fail here while the launcher's own downloads worked.
//!
//! Which hosts those are is decided here and nowhere else. The launcher asks `direct`, `env_for`,
//! `host_of`, `scheme_of`, `socks` and `parse` for its own traffic, and keeps its agents here too
//! (`keep`), so the two agree whatever the player set — and there is one copy of the rules to
//! change when they need it.
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, MutexGuard};
/// What the launcher set, when it did.
static PROXY: Mutex<Option<String>> = Mutex::new(None);
/// Agents kept for reuse, named by the part that asked and the proxy they use: a fresh `Agent`
/// starts a new connection pool, so building one per request costs a handshake per file.
static KEPT: Mutex<Option<HashMap<String, ureq::Agent>>> = Mutex::new(None);
/// The proxy to use from now on: the launcher's setting, or None to fall back to the environment.
/// The agents built so far are dropped when it changes, since they hold the address it replaces.
pub fn set_proxy(spec: Option<String>) {
let spec = spec.map(|s| s.trim().to_owned()).filter(|s| !s.is_empty());
let mut proxy = lock(&PROXY);
if *proxy == spec {
return;
}
*proxy = spec;
drop(proxy);
*lock(&KEPT) = None;
}
/// The proxy address `url` is fetched through: what the launcher set, else the environment's for
/// its scheme, unless `url` is a host that must be reached directly.
fn spec_for(url: &str) -> Option<String> {
if direct(url) {
return None;
}
lock(&PROXY)
.clone()
.or_else(|| env_for(scheme_of(url).unwrap_or("https")))
}
/// An agent for downloading `url`: through the proxy when one is set, unless `url` is a host that
/// must be reached directly.
pub fn agent(url: &str) -> ureq::Agent {
keep("port-pack", spec_for(url).as_deref(), |proxy| {
let builder = ureq::AgentBuilder::new();
match proxy {
Some(proxy) => builder.proxy(proxy).build(),
None => builder.build(),
}
})
}
/// The agent `url` is fetched with, built by `build` and then kept for the next request that names
/// the same `slot` and proxy: a fresh `Agent` starts a new connection pool, so building one per
/// request is a handshake per file, and a modpack's jars are fetched one after another.
pub fn keep(
slot: &str,
spec: Option<&str>,
build: impl FnOnce(Option<ureq::Proxy>) -> ureq::Agent,
) -> ureq::Agent {
let proxy = spec.and_then(parse);
// An address that isn't a proxy is used as none, and remembered as none.
let key = format!(
"{slot} {}",
if proxy.is_some() {
spec.unwrap_or_default()
} else {
""
}
);
if let Some(agent) = lock(&KEPT).as_ref().and_then(|kept| kept.get(&key)) {
return agent.clone();
}
let agent = build(proxy);
lock(&KEPT)
.get_or_insert_with(HashMap::new)
.insert(key, agent.clone());
agent
}
/// `spec` as a proxy, when it is one. An address that can't be used is said once: a download left
/// to go direct would otherwise fail with nothing pointing at the proxy.
pub fn parse(spec: &str) -> Option<ureq::Proxy> {
if socks(spec) {
say(&format!(
"{spec} is a SOCKS proxy; downloads go without one. Write the http:// address your \
proxy app listens on as well."
));
return None;
}
match ureq::Proxy::new(spec) {
Ok(proxy) => Some(proxy),
Err(e) => {
say(&format!(
"The proxy address {spec} can't be used ({e}); downloads go without one."
));
None
}
}
}
/// Whether `spec` names a SOCKS proxy, which these downloads don't go through: `ureq` reads a
/// SOCKS address happily and only fails when it connects through it.
pub fn socks(spec: &str) -> bool {
matches!(
spec.split_once("://")
.map(|(s, _)| s.to_ascii_lowercase())
.as_deref(),
Some("socks" | "socks4" | "socks4a" | "socks5" | "socks5h")
)
}
/// Whether `url` is reached without the proxy: a local address, or a host `NO_PROXY` names. The
/// launcher asks this of its own requests, so both reach the same hosts directly.
pub fn direct(url: &str) -> bool {
host_of(url).is_some_and(|host| local(host) || excluded(host, &no_proxy()))
}
/// `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.
pub fn env_for(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`).
pub 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.
pub 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()
}
/// Said once, however many downloads follow: a wrong address is one thing to report, not one
/// report per file.
fn say(what: &str) {
static SAID: AtomicBool = AtomicBool::new(false);
if !SAID.swap(true, Ordering::Relaxed) {
eprintln!("{what}");
}
}
/// The lock, even after a thread panicked while holding it: an address lost to a panic is worse
/// than an old one kept.
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
#[cfg(test)]
mod tests {
use super::*;
/// What the tests below share, since the address and the agents are one of each for the whole
/// process: they take it in turn.
fn alone() -> MutexGuard<'static, ()> {
static TURN: Mutex<()> = Mutex::new(());
lock(&TURN)
}
#[test]
fn a_proxy_the_launcher_sets_is_trimmed_and_kept() {
let _turn = alone();
set_proxy(Some(" http://127.0.0.1:7890 ".into()));
assert_eq!(
PROXY.lock().unwrap().as_deref(),
Some("http://127.0.0.1:7890")
);
set_proxy(Some(" ".into()));
assert!(PROXY.lock().unwrap().is_none());
}
/// An address on this computer is reached directly whatever `NO_PROXY` says: what an import
/// needs when the launcher's own requests to it go direct.
#[test]
fn a_local_address_is_reached_directly() {
assert!(direct("http://127.0.0.1:8130/api/v1/status"));
assert!(direct("http://localhost/api/v1/status"));
assert!(direct("https://[::1]:25565/"));
}
#[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"));
}
#[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}");
}
}
/// What an import with `NO_PROXY=modrinth.com` needs: the launcher's own requests to it go
/// direct, so the jars fetched for it must too.
#[test]
fn no_proxy_lists_hosts_and_their_subdomains() {
assert!(excluded("anything.at.all", "*"));
assert!(excluded("cdn.modrinth.com", "modrinth.com"));
assert!(excluded("api.modrinth.com", "modrinth.com"));
assert!(excluded("piston-meta.mojang.com", "mojang.com"));
assert!(excluded(
"wiki.corp.example",
" .corp.example , other.host "
));
assert!(excluded("github.com", "github.com:443"));
assert!(!excluded("notmodrinth.com", "modrinth.com"));
assert!(!excluded("modrinth.com", " .corp.example , mojang.com "));
assert!(!excluded("edge.forgecdn.net", "modrinth.com"));
assert!(!excluded("modrinth.com", ""));
}
#[test]
fn an_address_that_cant_be_used_becomes_no_proxy() {
assert!(parse("http://127.0.0.1:7890").is_some());
assert!(parse("127.0.0.1:7890").is_some());
// `ureq` reads a SOCKS address and only fails once it connects through it.
assert!(socks("socks5://127.0.0.1:7891"));
assert!(parse("socks5://127.0.0.1:7891").is_none());
assert!(!socks("http://127.0.0.1:7890"));
}
/// The agent a second request gets is the one the first built: one connection pool, not one
/// handshake per jar.
#[test]
fn an_agent_is_kept_for_the_next_request() {
let _turn = alone();
set_proxy(None);
let mut built = 0;
for _ in 0..3 {
keep("kept", None, |_| {
built += 1;
ureq::AgentBuilder::new().build()
});
}
assert_eq!(built, 1, "three requests, one agent");
// Another address is another agent, and a new setting drops the ones before it.
keep("kept", Some("http://127.0.0.1:7890"), |proxy| {
assert!(proxy.is_some());
built += 1;
ureq::AgentBuilder::new().build()
});
assert_eq!(built, 2, "a second address needs a second agent");
set_proxy(Some("http://127.0.0.1:7891".into()));
keep("kept", Some("http://127.0.0.1:7891"), |_| {
built += 1;
ureq::AgentBuilder::new().build()
});
assert_eq!(built, 3, "a new setting drops the agents kept before it");
set_proxy(None);
}
}
+2 -2
View File
@@ -132,11 +132,11 @@ MCP: `account_offline`.
## `horizon-launcher settings`
Show the launcher's settings, or set one (the Settings page): selected-version TAG, minecraft-dir PATH, server-dir PATH ("default" resets a folder), install-new-versions on|off, opening-animation on|off.
Show the launcher's settings, or set one (the Settings page): selected-version TAG, minecraft-dir PATH, server-dir PATH ("default" resets a folder), install-new-versions on|off, opening-animation on|off, proxy http://host:port ("default" removes it).
horizon-launcher settings [KEY] [VALUE]
- `KEY` (selected-version, minecraft-dir, server-dir, install-new-versions, opening-animation)
- `KEY` (selected-version, minecraft-dir, server-dir, install-new-versions, opening-animation, proxy)
- `VALUE`: The new value (with KEY)
MCP: `settings`.
+11 -1
View File
@@ -79,7 +79,8 @@ page `servers.json` (the list), `servers/<name>/` (the servers created there) an
- **Settings**: install new Horizon versions automatically (on unless you turn it off; the
selected version only moves to the new one if you were on the newest), the opening animation,
the game's extra command-line arguments, and the launcher's own version and update state.
the game's extra command-line arguments, an HTTP proxy for downloads, and the launcher's own
version and update state.
- **Updates**: there is one channel. Every release is published as the release, GitHub's latest,
once its smoke test passed (docs/release-flow.md), and the launcher installs it. The game
pre-releases of the old Alpha channel (v0.2.1 on) stay on the Versions page to install
@@ -90,6 +91,15 @@ page `servers.json` (the list), `servers/<name>/` (the servers created there) an
launcher's own arguments, kept as `game_args` in `settings.json`, and apply the next time the
game starts. `horizon-launcher game-args "<line>"` sets them too, and `play --arg <ARG>` passes
one for a single run.
- **Proxy**: when the internet here needs one (a school's, an office's, a country where a host is
unreachable), Settings' Proxy takes the `http://host:port` address your proxy app listens on, and
every download goes through it: Horizon's releases and the launcher's own update, Minecraft's
files and Java from Mojang, Modrinth, CurseForge, Horizon's mod registry, pictures, Microsoft
sign-in, and the jars a modpack import fetches. It is kept as `proxy` in `settings.json`, and
`horizon-launcher settings proxy http://127.0.0.1:7890` sets it too ("default" removes it).
Without one, `HTTPS_PROXY` and `HTTP_PROXY` are used when the launcher is started with them, and
`NO_PROXY` names the hosts to reach directly, a modpack import's jars included. A server on this
computer never goes through it.
- **Links**: the Discord invite, the Sponsors page and the website come from `launcher/links.json` on main
(`{"discord": "...", "sponsor": "...", "website": "..."}`), so they change without a launcher release. Offline,
the launcher uses the same values built in; an empty address hides its button.
+22 -13
View File
@@ -60,11 +60,17 @@ impl Endpoints {
}
}
fn agent() -> ureq::Agent {
ureq::AgentBuilder::new()
.timeout(Duration::from_secs(20))
.user_agent(&format!("horizon-launcher/{}", crate::backend::VERSION))
.build()
/// A request to `url`: the launcher's user agent, a 20 s timeout, and the player's proxy when one
/// is set (`proxy`), since a sign-in has to get out the way downloads do.
fn request_to(method: &str, url: &str) -> ureq::Request {
crate::proxy::agent(
ureq::AgentBuilder::new()
.timeout(Duration::from_secs(20))
.user_agent(&format!("horizon-launcher/{}", crate::backend::VERSION)),
url,
)
.build()
.request(method, url)
}
/// One request's result: the status and the JSON body (empty when there is none). Transport
@@ -147,7 +153,7 @@ pub enum Poll {
pub fn device_code(ep: &Endpoints, client_id: &str) -> Result<DeviceCode, String> {
let (status, v) = send(
agent().post(&format!("{}/devicecode", ep.microsoft)),
request_to("POST", &format!("{}/devicecode", ep.microsoft)),
Some(Body::Form(vec![("client_id", client_id), ("scope", SCOPE)])),
"Microsoft",
)?;
@@ -190,7 +196,7 @@ fn oauth_error(v: &Value) -> String {
/// One poll of the token endpoint while the player signs in.
pub fn poll(ep: &Endpoints, client_id: &str, code: &DeviceCode) -> Result<Poll, String> {
let (status, v) = send(
agent().post(&format!("{}/token", ep.microsoft)),
request_to("POST", &format!("{}/token", ep.microsoft)),
Some(Body::Form(vec![
("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
("client_id", client_id),
@@ -247,7 +253,7 @@ pub fn wait_for_sign_in(
fn refresh_ms(ep: &Endpoints, client_id: &str, refresh: &str) -> Result<MsTokens, String> {
let (status, v) = send(
agent().post(&format!("{}/token", ep.microsoft)),
request_to("POST", &format!("{}/token", ep.microsoft)),
Some(Body::Form(vec![
("grant_type", "refresh_token"),
("client_id", client_id),
@@ -281,7 +287,7 @@ struct Minecraft {
fn minecraft_login(ep: &Endpoints, ms_access: &str) -> Result<Minecraft, String> {
let (status, xbl) = send(
agent().post(&ep.xbox_user),
request_to("POST", &ep.xbox_user),
Some(Body::Json(json!({
"Properties": {
"AuthMethod": "RPS",
@@ -297,7 +303,7 @@ fn minecraft_login(ep: &Endpoints, ms_access: &str) -> Result<Minecraft, String>
.filter(|_| status == 200)
.ok_or("Xbox Live refused the sign-in.")?;
let (status, xsts) = send(
agent().post(&ep.xsts),
request_to("POST", &ep.xsts),
Some(Body::Json(json!({
"Properties": { "SandboxId": "RETAIL", "UserTokens": [xbl_token] },
"RelyingParty": "rp://api.minecraftservices.com/",
@@ -317,7 +323,10 @@ fn minecraft_login(ep: &Endpoints, ms_access: &str) -> Result<Minecraft, String>
};
let xuid = claims.and_then(|c| str_field(c, "xid"));
let (status, mc) = send(
agent().post(&format!("{}/authentication/login_with_xbox", ep.minecraft)),
request_to(
"POST",
&format!("{}/authentication/login_with_xbox", ep.minecraft),
),
Some(Body::Json(
json!({ "identityToken": format!("XBL3.0 x={uhs};{xsts_token}") }),
)),
@@ -350,7 +359,7 @@ fn bearer(request: ureq::Request, token: &str) -> ureq::Request {
fn owns_game(ep: &Endpoints, token: &str) -> Result<bool, String> {
let (status, v) = send(
bearer(
agent().get(&format!("{}/entitlements/mcstore", ep.minecraft)),
request_to("GET", &format!("{}/entitlements/mcstore", ep.minecraft)),
token,
),
None,
@@ -387,7 +396,7 @@ pub struct Account {
fn profile(ep: &Endpoints, token: &str) -> Result<Account, String> {
let (status, v) = send(
bearer(
agent().get(&format!("{}/minecraft/profile", ep.minecraft)),
request_to("GET", &format!("{}/minecraft/profile", ep.minecraft)),
token,
),
None,
+13 -5
View File
@@ -80,14 +80,18 @@ const CLIENT: &str = if cfg!(windows) {
"horizon-client"
};
fn agent() -> ureq::Agent {
ureq::AgentBuilder::new()
.user_agent(&format!("horizon-launcher/{VERSION}"))
.build()
/// The agent `url` is fetched with: the launcher's own user agent, through the player's proxy when
/// one is set (`proxy`).
fn agent(url: &str) -> ureq::Agent {
crate::proxy::agent(
ureq::AgentBuilder::new().user_agent(&format!("horizon-launcher/{VERSION}")),
url,
)
.build()
}
fn get(url: &str) -> Result<ureq::Response, String> {
let mut request = agent().get(url);
let mut request = agent(url).get(url);
// CI runners share addresses and hit GitHub's anonymous rate limit; they pass their own token.
if let Some(token) = std::env::var("HORIZON_GITHUB_TOKEN")
.ok()
@@ -2530,6 +2534,10 @@ pub struct Settings {
/// default. Appended after the launcher's own arguments, so they can add to or override them.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub game_args: String,
/// The HTTP proxy every download goes through (`proxy`), such as `http://127.0.0.1:7890`.
/// Unset means none: the environment's `HTTPS_PROXY` and `HTTP_PROXY` apply instead.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub proxy: Option<String>,
/// Dark, Light, or the system's: the launcher's look. Dark by default.
#[serde(default)]
pub appearance: Appearance,
+1 -1
View File
@@ -55,7 +55,7 @@ impl CurseForge {
}
fn get(&self, url: &str) -> Result<Value, String> {
let response = super::download::agent()
let response = super::download::agent(url)
.get(url)
.set("x-api-key", &self.key)
.set("Accept", "application/json")
+27 -14
View File
@@ -17,16 +17,26 @@ const HOSTS: [&str; 4] = [
/// Bigger than any pack these sources serve (Modrinth caps uploads at 500 MiB).
const MAX: u64 = 1 << 30;
/// The HTTP agent the sources share. Modrinth asks for a user agent that names the project.
pub(super) fn agent() -> ureq::Agent {
ureq::AgentBuilder::new()
.user_agent(&format!(
"ludovic111/horizon horizon-launcher/{} (github.com/ludovic111/horizon)",
crate::backend::VERSION
))
.timeout_connect(std::time::Duration::from_secs(15))
.timeout_read(std::time::Duration::from_secs(60))
.build()
/// The HTTP agent the sources share, reaching `url` through the player's proxy when one is set
/// (`proxy`). Modrinth asks for a user agent that names the project.
///
/// It is kept between downloads: a fresh agent starts a new connection pool, so one per file would
/// be a handshake per file, and a modpack brings hundreds.
pub(super) fn agent(url: &str) -> ureq::Agent {
let spec = crate::proxy::spec_for(url);
horizon_port_pack::net::keep("browser", spec.as_deref(), |proxy| {
let builder = ureq::AgentBuilder::new()
.user_agent(&format!(
"ludovic111/horizon horizon-launcher/{} (github.com/ludovic111/horizon)",
crate::backend::VERSION
))
.timeout_connect(std::time::Duration::from_secs(15))
.timeout_read(std::time::Duration::from_secs(60));
match proxy {
Some(proxy) => builder.proxy(proxy).build(),
None => builder.build(),
}
})
}
/// Why a file can't be downloaded at all, before any byte is read.
@@ -159,9 +169,12 @@ pub fn fetch(file: &FileRef, folder: &Path, progress: &dyn Fn(f32)) -> Result<Pa
if let Some(why) = refuse(file) {
return Err(why);
}
let response = agent().get(&file.url).call().map_err(|e| match e {
ureq::Error::Status(code, _) => format!("{} answered {code}.", file.url),
ureq::Error::Transport(t) => format!("No connection: {t}"),
})?;
let response = agent(&file.url)
.get(&file.url)
.call()
.map_err(|e| match e {
ureq::Error::Status(code, _) => format!("{} answered {code}.", file.url),
ureq::Error::Transport(t) => format!("No connection: {t}"),
})?;
save(file, response.into_reader(), folder, progress)
}
+1 -1
View File
@@ -95,7 +95,7 @@ fn fetch_index() -> Result<(Index, String), String> {
use std::io::Read;
let at = location();
let text = if at.starts_with("https://") {
let response = download::agent().get(&at).call().map_err(|e| match e {
let response = download::agent(&at).get(&at).call().map_err(|e| match e {
ureq::Error::Status(code, _) => format!("The mod registry answered {code}."),
ureq::Error::Transport(t) => format!("The mod registry can't be reached: {t}"),
})?;
+1 -1
View File
@@ -63,7 +63,7 @@ pub fn fetch(home: &Path, url: &str, size: u32) -> Result<PathBuf, String> {
if let Some(why) = refuse(url) {
return Err(format!("{url}: {why}"));
}
let response = super::download::agent()
let response = super::download::agent(url)
.get(url)
.call()
.map_err(|e| format!("{url}: {e}"))?;
+1 -1
View File
@@ -227,7 +227,7 @@ impl Source for Modrinth {
}
fn get(url: &str) -> Result<Value, String> {
let response = super::download::agent()
let response = super::download::agent(url)
.get(url)
.call()
.map_err(|e| match e {
+14 -2
View File
@@ -297,7 +297,7 @@ enum Cmd {
},
/// Show the launcher's settings, or set one (the Settings page): selected-version TAG,
/// minecraft-dir PATH, server-dir PATH ("default" resets a folder), install-new-versions
/// on|off, opening-animation on|off
/// on|off, opening-animation on|off, proxy http://host:port ("default" removes it)
Settings {
#[arg(value_parser = SETTING_KEYS)]
key: Option<String>,
@@ -399,12 +399,13 @@ pub fn command() -> clap::Command {
pub const AI_COMMANDS: [&str; 2] = ["mcp", "agent-config"];
/// The keys `settings` sets.
const SETTING_KEYS: [&str; 5] = [
const SETTING_KEYS: [&str; 6] = [
"selected-version",
"minecraft-dir",
"server-dir",
"install-new-versions",
"opening-animation",
"proxy",
];
fn on_off(value: &str) -> Result<bool, String> {
@@ -423,6 +424,15 @@ fn set_setting(s: &mut backend::Settings, key: &str, value: &str) -> Result<(),
"server-dir" => s.server_dir = folder(value),
"install-new-versions" => s.install_new_versions = Some(on_off(value)?),
"opening-animation" => s.skip_opening = !on_off(value)?,
"proxy" => {
if value == "default" || value.is_empty() {
s.proxy = None;
} else if let Some(why) = horizon_launcher::proxy::refuse(value) {
return Err(why);
} else {
s.proxy = Some(value.trim().to_string());
}
}
_ => return Err(format!("No setting {key}.")),
}
Ok(())
@@ -437,6 +447,7 @@ fn settings_json(s: &backend::Settings) -> serde_json::Value {
"install_new_versions": s.install_new_versions.unwrap_or(true),
"opening_animation": !s.skip_opening,
"game_args": s.game_args,
"proxy": s.proxy,
"desktop_entry": s.desktop_entry.unwrap_or(true),
"no_ai": backend::no_ai(),
})
@@ -722,6 +733,7 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
let value = value.ok_or("settings KEY VALUE: the value is missing")?;
set_setting(&mut settings, &key, &value)?;
settings.save();
horizon_launcher::proxy::announce(settings.proxy.clone());
}
let all = settings_json(&settings);
if as_json {
+1
View File
@@ -10,6 +10,7 @@ pub mod heads;
pub mod modpacks;
pub mod mojang;
pub mod process;
pub mod proxy;
pub mod servers;
pub mod signed;
pub mod sources;
+107 -7
View File
@@ -186,6 +186,10 @@ struct Launcher {
args_input: String,
args_focused: bool,
args_focus: FocusHandle,
/// Settings' Proxy field, the same way (`proxy`).
proxy_input: String,
proxy_focused: bool,
proxy_focus: FocusHandle,
/// Opt-in data collection: the player's answer and Settings' section (`collection`).
collection: collection::Collection,
/// Settings' "Connect an AI agent" (`agents_page`).
@@ -301,6 +305,9 @@ impl Launcher {
args_input: settings.game_args.clone(),
args_focused: false,
args_focus: cx.focus_handle(),
proxy_input: settings.proxy.clone().unwrap_or_default(),
proxy_focused: false,
proxy_focus: cx.focus_handle(),
settings,
links: backend::Links::default(),
preparing: false,
@@ -2539,28 +2546,30 @@ impl Launcher {
Some(opening.into_any_element()),
&t,
))
.child(group("Network", "globe"))
.child(self.proxy_row(n + 4, cx))
.child(group("Game", "gamepad"))
.child(self.game_args_row(n + 4, cx))
.child(self.game_args_row(n + 5, cx))
.child(group("AI", "terminal"))
.child(self.no_ai_row(n + 4, cx))
.child(self.no_ai_row(n + 6, cx))
.child(group("About", "info-box"))
.child(index_row(n + 5, "Horizon", Some(plain(&horizon)), horizon_action, &t))
.child(index_row(n + 7, "Horizon", Some(plain(&horizon)), horizon_action, &t))
.child(index_row(
n + 6,
n + 8,
"Launcher",
Some(plain(&launcher)),
launcher_action,
&t,
))
.child(index_row(
n + 7,
n + 9,
"Data folder",
Some(mono(short(&backend::data_dir()))),
None,
&t,
))
.child(index_row(
n + 8,
n + 10,
"Logs",
Some(mono(format!(
"{} · crash reports beside it",
@@ -2579,7 +2588,7 @@ impl Launcher {
))
.when(cfg!(target_os = "linux"), |d| {
d.child(index_row(
n + 9,
n + 11,
"Applications menu",
Some(plain(if self.settings.desktop_entry() {
"Horizon and its icon are in your desktop's menu."
@@ -2668,6 +2677,93 @@ impl Launcher {
)
}
/// Settings' Proxy row: the HTTP proxy every download and sign-in goes through, kept in
/// `settings.json` and read back by `proxy.rs` on each request.
fn proxy_row(&self, n: usize, cx: &mut Context<Self>) -> Div {
let t = self.theme;
let focused = self.proxy_focused;
let field = div()
.id("proxy")
.track_focus(&self.proxy_focus)
.flex()
.items_center()
.w(px(300.))
.h(px(30.))
.px(px(12.))
.overflow_hidden()
.border_2()
.border_color(if focused { t.accent } else { t.outline })
.bg(t.well)
.font_family(theme::MONO)
.text_size(px(12.))
.cursor_text()
.child(if self.proxy_input.is_empty() && !focused {
div()
.text_color(t.muted)
.child("For example http://127.0.0.1:7890")
} else {
// The end of a long line stays in view while typing.
let chars: Vec<char> = self.proxy_input.chars().collect();
let shown: String = chars[chars.len().saturating_sub(44)..].iter().collect();
div().text_color(t.ink).child(shown)
})
.when(focused, |d| d.child(div().w(px(1.)).h(px(14.)).bg(t.ink)))
.on_click(cx.listener(|this, _: &ClickEvent, window, cx| {
window.focus(&this.proxy_focus);
cx.notify();
}))
.on_key_down(cx.listener(|this, ev: &KeyDownEvent, _, cx| {
let k = &ev.keystroke;
let paste = k.key == "v" && (k.modifiers.control || k.modifiers.platform);
match k.key.as_str() {
"backspace" => {
this.proxy_input.pop();
}
_ if paste => {
if let Some(text) = cx.read_from_clipboard().and_then(|c| c.text()) {
// A copied line, not a copied page: the field takes one address.
let line = text.lines().next().unwrap_or(&text);
this.proxy_input.push_str(line.trim());
}
}
_ if !k.modifiers.control && !k.modifiers.platform => {
if let Some(ch) = &k.key_char {
this.proxy_input.push_str(ch);
}
}
_ => return,
}
// `truncate` counts bytes, and a cut inside a character panics: count characters.
if this.proxy_input.chars().count() > 256 {
this.proxy_input = this.proxy_input.chars().take(256).collect();
}
this.save_proxy();
cx.stop_propagation();
cx.notify();
}));
// A half-typed address is no reason to complain; one left behind is.
let detail = match (focused, horizon_launcher::proxy::refuse(&self.proxy_input)) {
(false, Some(why)) => div().text_color(t.danger).child(why).into_any_element(),
_ => div()
.child(
"Downloads, sign-ins and updates go through this HTTP proxy \
(http://host:port). Empty means none: HTTPS_PROXY is used instead when the \
launcher was started with one.",
)
.into_any_element(),
};
index_row(n, "Proxy", Some(detail), Some(field.into_any_element()), &t)
}
/// Keeps the Proxy field in `settings.json`, and tells the parts that build their own agents
/// (`horizon-port-pack`) which proxy to use.
fn save_proxy(&mut self) {
let value = self.proxy_input.trim().to_owned();
self.settings.proxy = (!value.is_empty()).then_some(value);
self.settings.save();
horizon_launcher::proxy::announce(self.settings.proxy.clone());
}
/// Settings' Microsoft accounts: who is signed in and plays, the sign-in with its code. The
/// rows are numbered from 01; returns them and how many there are.
fn account_rows(&mut self, cx: &mut Context<Self>) -> (Div, usize) {
@@ -3317,6 +3413,7 @@ impl Render for Launcher {
self.friend_focused = self.friend_focus.is_focused(window);
self.mods.note_focus(window);
self.args_focused = self.args_focus.is_focused(window);
self.proxy_focused = self.proxy_focus.is_focused(window);
let size = window.viewport_size();
let banner_width = f32::from(size.width) - theme::SIDEBAR - scrollbar::GUTTER;
let content = match self.page {
@@ -3578,6 +3675,9 @@ fn main() {
}
perf::process_started();
backend::exe_path();
// What the launcher downloads goes through the player's proxy, if they set one: the parts
// that build their own agents (`horizon-port-pack`) are told before anything starts.
horizon_launcher::proxy::announce(horizon_launcher::backend::Settings::load().proxy);
if let Some(code) = cli::run() {
std::process::exit(code);
}
+140
View File
@@ -0,0 +1,140 @@
//! The proxy every download and request goes through, when the player needs one: a school's or an
//! office's, or a country where a host is unreachable. The Settings page's Proxy row (kept as
//! `proxy` in `settings.json`) wins; without it the usual `HTTPS_PROXY`, `HTTP_PROXY`, `ALL_PROXY`
//! and `NO_PROXY` variables apply, so a launcher started from a shell that has them needs nothing.
//!
//! What goes through it: Horizon's releases and the launcher's own update, Minecraft's files and
//! Java from Mojang, Modrinth, CurseForge, Horizon's mod registry, pictures, Microsoft sign-in,
//! Tailscale's API, and the jars a modpack import downloads. A local address never does, and the
//! 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.
//!
//! 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 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 spec_for(url: &str) -> Option<String> {
let scheme = horizon_port_pack::net::scheme_of(url)?;
if horizon_port_pack::net::direct(url) {
return None;
}
setting().or_else(|| horizon_port_pack::net::env_for(scheme))
}
/// 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),
None => builder,
}
}
/// Why `spec` can't be used as a proxy, or None when it can (empty means none).
pub fn refuse(spec: &str) -> Option<String> {
let spec = spec.trim();
if spec.is_empty() {
return None;
}
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."
));
}
// `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."
));
}
None
}
/// 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 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())
}
/// 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)]
mod tests {
use super::*;
#[test]
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 a_relative_address_has_no_scheme_to_read_a_proxy_for() {
assert_eq!(spec_for("data/a.jar"), None);
}
#[test]
fn a_proxy_address_is_checked_before_it_is_kept() {
assert_eq!(refuse(""), None);
assert_eq!(refuse(" "), None);
assert_eq!(refuse("http://127.0.0.1:7890"), None);
assert_eq!(refuse("127.0.0.1:7890"), None);
assert_eq!(refuse("http://user:pass@proxy.local:3128"), None);
assert!(refuse("http://").is_some());
assert!(refuse("socks5://127.0.0.1:7891").is_some());
}
}
+2
View File
@@ -813,6 +813,8 @@ impl Api {
}
pub fn call(&self, method: &str, path: &str, body: Option<Value>) -> Result<Value, String> {
// No proxy here on purpose: the server is on this computer, and this is asked every
// second (`proxy` never sends a loopback address through one either).
let agent = ureq::AgentBuilder::new()
.timeout(Duration::from_secs(10))
.build();
+7 -4
View File
@@ -260,11 +260,14 @@ impl Api {
body: Option<&Value>,
if_match: Option<&str>,
) -> Result<(Value, Option<String>), String> {
let agent = ureq::AgentBuilder::new()
.timeout(Duration::from_secs(20))
.build();
let url = format!("{}/api/v2{path}", self.base);
let agent = crate::proxy::agent(
ureq::AgentBuilder::new().timeout(Duration::from_secs(20)),
&url,
)
.build();
let mut request = agent
.request(method, &format!("{}/api/v2{path}", self.base))
.request(method, &url)
.set("Authorization", &format!("Bearer {}", self.token))
.set("Accept", "application/json");
if let Some(etag) = if_match {