1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
//! The one place an unauthenticated HTTP `GET` leaves this process.
//!
//! Model calls have their own client in `provider`; everything else that reads a URL goes
//! through [`get`]: the `fetch` tool, and the update notice (`update`). Having one function
//! means one SSRF policy, one rule about redirects, and one thing to read when asking "what
//! does this tool send to the network?".
use crate::netguard;
use std::time::Duration;
/// Which hosts a request may reach.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reach {
/// Public hosts only: no IP literals, no `localhost`, every resolved address public.
/// For anything a *model* can choose, which is what makes an internal address a hazard.
Public,
/// Any host. For a URL the *user* wrote into their own config: pointing the update
/// notice at a mirror on the LAN is their call, not a model's.
Anywhere,
}
/// Send one `GET` and return the response head and body reader. Redirects are not followed:
/// whoever approved or configured this URL did not approve its redirect target.
///
/// Errors are plain sentences naming the host or the cause.
pub async fn get(
url: &reqwest::Url,
timeout: Duration,
reach: Reach,
headers: &[(&str, &str)],
) -> Result<reqwest::Response, String> {
if !matches!(url.scheme(), "http" | "https") {
return Err("only http(s) URLs are allowed".into());
}
let mut builder = reqwest::Client::builder()
.timeout(timeout)
.redirect(reqwest::redirect::Policy::none());
if reach == Reach::Public {
// The vetted addresses are pinned so a second, different DNS answer cannot swap an
// internal address in after the check.
let host = netguard::check_url_host(url)?;
let port = url.port_or_known_default().unwrap_or(80);
let addrs = netguard::resolve_public(&host, port, timeout).await?;
builder = builder.resolve_to_addrs(&host, &addrs);
// A resolver override is keyed by the host reqwest is about to look up, which is the
// string in the URL — and `check_url_host` trims a trailing dot, so `example.com.` was
// vetted under one name and pinned under another. Pin both (`#422`).
if let Some(named) = url.host_str() {
if named != host {
builder = builder.resolve_to_addrs(named, &addrs);
}
}
// A proxy decides where the bytes go; vetting a name locally says nothing about it.
builder = builder.no_proxy();
}
let client = builder.build().map_err(|e| e.to_string())?;
let mut request = client.get(url.clone());
for (name, value) in headers {
request = request.header(*name, *value);
}
request.send().await.map_err(|e| e.to_string())
}
/// Stream one `GET` into a file, refusing anything over `cap` bytes.
///
/// This is the only request here that follows redirects, and the reason is narrow: a release
/// asset URL on GitHub answers `302` to a signed CDN address by design, so refusing the hop
/// would refuse every download. What vouches for the bytes is not the host that served them —
/// it is the SHA256 the release published, checked after this returns.
pub async fn download(
raw: &str,
timeout: Duration,
cap: u64,
path: &std::path::Path,
) -> Result<u64, String> {
use tokio::io::AsyncWriteExt;
let url = reqwest::Url::parse(raw).map_err(|e| format!("{raw:?}: {e}"))?;
if !matches!(url.scheme(), "http" | "https") {
return Err("only http(s) URLs are allowed".into());
}
let client = reqwest::Client::builder()
.timeout(timeout)
.redirect(reqwest::redirect::Policy::limited(5))
.build()
.map_err(|e| e.to_string())?;
let user_agent = format!("eclipse/{}", env!("CARGO_PKG_VERSION"));
let mut resp = client
.get(url.clone())
.header("User-Agent", user_agent)
.send()
.await
.map_err(|e| e.to_string())?;
if !resp.status().is_success() {
return Err(format!("{url} answered {}", resp.status()));
}
let mut file = tokio::fs::File::create(path)
.await
.map_err(|e| format!("{}: {e}", path.display()))?;
let mut written = 0u64;
while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? {
written += chunk.len() as u64;
if written > cap {
return Err(format!(
"{url} sent more than the {cap} bytes a release can weigh"
));
}
file.write_all(&chunk)
.await
.map_err(|e| format!("{}: {e}", path.display()))?;
}
file.flush()
.await
.map_err(|e| format!("{}: {e}", path.display()))?;
Ok(written)
}