Launcher downloads go through the proxy the player sets

Everything the launcher fetches now goes through one HTTP proxy when there is
one: Horizon's releases and the launcher's own update, Minecraft's files and
Java from Mojang, Modrinth, CurseForge, the mod registry, pictures, Microsoft
sign-in, Tailscale's API, and the jars a modpack import downloads. It is
Settings' Proxy row (`proxy` in settings.json), or `horizon-launcher settings
proxy http://host:port`; without one, HTTPS_PROXY, HTTP_PROXY and ALL_PROXY
apply, with NO_PROXY naming the hosts to reach directly.

A local address never goes through it, and the Servers page's calls to a game
server's API stay direct: they are on loopback and asked every second.

horizon-port-pack builds its own agents, so the launcher hands it the address
(net.rs); run on its own, it reads the same variables.

Co-Authored-By: WorkBuddy AI (DeepSeek-V4.1-Flash) <noreply@workbuddy.cn>
This commit is contained in:
zhykowo
2026-10-26 16:21:24 +08:00
parent 57c5f81299
commit 3e79b22c43
18 changed files with 489 additions and 54 deletions
+4 -2
View File
@@ -143,7 +143,8 @@ 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 sha1 = crate::net::agent()
.get(&format!("{url}.sha1"))
.set("User-Agent", modrinth::AGENT)
.call()
.ok()
@@ -201,7 +202,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()
.get(url)
.set("User-Agent", modrinth::AGENT)
.call()
.map_err(|e| format!("{url}: {e}"))?;
+1
View File
@@ -15,6 +15,7 @@ pub mod inventory;
pub mod jar;
pub(crate) mod legacy_structure_mods;
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()
.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()
.get(url)
.set("User-Agent", AGENT)
.call()
.map_err(|e| format!("{url}: {e}"))?;
+65
View File
@@ -0,0 +1,65 @@
//! The agents port-pack's downloads go through, since the jars of an imported modpack come from
//! the same places as everything else and may need the same proxy.
//!
//! 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. A
//! `NO_PROXY` list is the launcher's business: it decides per address, and nothing here is local.
use std::sync::Mutex;
/// What the launcher set, when it did.
static PROXY: Mutex<Option<String>> = Mutex::new(None);
/// The proxy to use from now on: the launcher's setting, or None to fall back to the environment.
pub fn set_proxy(spec: Option<String>) {
let spec = spec.map(|s| s.trim().to_owned()).filter(|s| !s.is_empty());
if let Ok(mut proxy) = PROXY.lock() {
*proxy = spec;
}
}
/// The proxy address to use: the launcher's, else the environment's.
fn spec() -> Option<String> {
let set = PROXY.lock().ok().and_then(|proxy| proxy.clone());
set.or_else(|| {
[
"HTTPS_PROXY",
"https_proxy",
"HTTP_PROXY",
"http_proxy",
"ALL_PROXY",
"all_proxy",
]
.iter()
.find_map(|name| {
std::env::var(name)
.ok()
.map(|v| v.trim().to_owned())
.filter(|v| !v.is_empty())
})
})
}
/// An agent for a download, through the proxy when one is set.
pub fn agent() -> ureq::Agent {
let mut builder = ureq::AgentBuilder::new();
if let Some(proxy) = spec().and_then(|s| ureq::Proxy::new(s).ok()) {
builder = builder.proxy(proxy);
}
builder.build()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_proxy_the_launcher_sets_is_trimmed_and_kept() {
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());
}
}
+10 -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,14 @@ 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 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()
@@ -2499,6 +2503,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
@@ -50,7 +50,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")
+21 -14
View File
@@ -17,16 +17,20 @@ 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.
pub(super) fn agent(url: &str) -> ureq::Agent {
crate::proxy::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)),
url,
)
.build()
}
/// Why a file can't be downloaded at all, before any byte is read.
@@ -159,9 +163,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
@@ -89,7 +89,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
@@ -221,7 +221,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
@@ -295,7 +295,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>,
@@ -397,12 +397,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> {
@@ -421,6 +422,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(())
@@ -435,6 +445,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(),
})
@@ -720,6 +731,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();
}
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;
+102 -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,88 @@ 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()) {
this.proxy_input.push_str(text.trim());
}
}
_ if !k.modifiers.control && !k.modifiers.platform => {
if let Some(ch) = &k.key_char {
this.proxy_input.push_str(ch);
}
}
_ => return,
}
this.proxy_input.truncate(256);
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();
}
/// 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 +3408,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 +3670,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();
if let Some(code) = cli::run() {
std::process::exit(code);
}
+219
View File
@@ -0,0 +1,219 @@
//! 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.
use crate::backend::Settings;
/// The proxy to reach `url` through: the one set for the launcher or in the environment, 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()) {
return None;
}
ureq::Proxy::new(written(scheme)?).ok()
}
/// `builder`, reaching `url` through the proxy when one is set.
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;
}
let scheme = spec.split_once("://").map(|(s, _)| s.to_ascii_lowercase());
if matches!(
scheme.as_deref(),
Some("socks" | "socks4" | "socks4a" | "socks5" | "socks5h")
) {
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) {
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`) what to use. Called at start
/// and whenever the player changes the setting.
pub fn announce() {
horizon_port_pack::net::set_proxy(written("https"));
}
/// The proxy as it is written down: the launcher's, else the environment's for `scheme`.
fn written(scheme: &str) -> 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()
}
#[cfg(test)]
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"));
}
#[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", ""));
}
#[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 {