forge
Explore
Log in

Don't you dare go Hollow

kur

Clone
★ 0

0 watching0 forksRustAGPL-3.073.7 KiB6ae6238Tahinli21 days ago5 commits

forge.rs146 lines, 4.9 KiBHistoryRawDownload
1//! Forge release API and streaming, hashed asset download.
2
3use crate::Res;
4use crate::config::{App, Config};
5use serde::Deserialize;
6use sha2::{Digest, Sha256};
7use std::fs::{self, File};
8use std::io::{Read, Write};
9use std::os::unix::fs::PermissionsExt;
10use std::path::Path;
11use std::time::Duration;
12use ureq::http::Response;
13use ureq::{Agent, Body};
14
15const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
16const API_TIMEOUT: Duration = Duration::from_secs(30);
17const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(600);
18const MAX_DOWNLOAD: u64 = 1 << 30;
19const MAX_API_BODY: u64 = 16 << 20;
20
21#[derive(Deserialize)]
22struct Release {
23 tag: String,
24 draft: bool,
25 prerelease: bool,
26 assets: Vec<Asset>,
27}
28
29/// A downloadable file attached to a release.
30#[derive(Deserialize)]
31pub struct Asset {
32 name: String,
33 size: u64,
34 pub sha256: String,
35 download_url: String,
36}
37
38/// Client for one forge. The token is attached only to URLs under the forge base.
39pub struct Forge {
40 agent: Agent,
41 /// Forge base URL plus a trailing slash, for the token host check.
42 prefix: String,
43 token: Option<String>,
44}
45
46impl Forge {
47 pub fn new(cfg: &Config) -> Forge {
48 let agent = Agent::config_builder()
49 .timeout_connect(Some(CONNECT_TIMEOUT))
50 .http_status_as_error(false)
51 .build()
52 .into();
53 Forge {
54 agent,
55 prefix: format!("{}/", cfg.forge),
56 token: cfg.token.clone(),
57 }
58 }
59
60 /// GET `url` with an overall timeout, adding the token if `url` is on the forge host.
61 fn get(&self, url: &str, timeout: Duration) -> Res<Response<Body>> {
62 let mut req = self
63 .agent
64 .get(url)
65 .config()
66 .timeout_global(Some(timeout))
67 .build();
68 if let Some(token) = self
69 .token
70 .as_deref()
71 .filter(|_| url.starts_with(&self.prefix))
72 {
73 req = req.header("Authorization", format!("token {token}"));
74 }
75 req.call().map_err(|e| format!("request failed: {e}"))
76 }
77
78 /// Newest eligible release of the app's repo and its asset for this host, as `(tag, asset)`.
79 pub fn latest(&self, app: &App) -> Res<(String, Asset)> {
80 let url = format!("{}api/v1/repos/{}/releases", self.prefix, app.repo);
81 let mut resp = self.get(&url, API_TIMEOUT)?;
82 if !resp.status().is_success() {
83 return Err(format!("releases API returned {}", resp.status()));
84 }
85 let releases: Vec<Release> =
86 serde_json::from_reader(resp.body_mut().with_config().limit(MAX_API_BODY).reader())
87 .map_err(|e| format!("bad releases JSON: {e}"))?;
88
89 let Release { tag, assets, .. } = releases
90 .into_iter()
91 .find(|r| !r.draft && (app.prerelease || !r.prerelease))
92 .ok_or("no release")?;
93 let want = app.asset_name();
94 let asset = assets
95 .into_iter()
96 .find(|a| a.name == want)
97 .ok_or_else(|| format!("release {tag} has no asset {want}"))?;
98 if asset.sha256.len() != 64
99 || !asset
100 .sha256
101 .bytes()
102 .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
103 {
104 return Err(format!("asset {want} has a malformed sha256"));
105 }
106 Ok((tag, asset))
107 }
108
109 /// Streams `asset` to `dest` (mode 0755, fsynced), failing on a hash mismatch or the size cap.
110 /// On error the caller removes `dest`.
111 pub fn download(&self, asset: &Asset, dest: &Path) -> Res<()> {
112 if asset.size > MAX_DOWNLOAD {
113 return Err(format!("asset {} is larger than 1 GiB", asset.name));
114 }
115 let mut resp = self.get(&asset.download_url, DOWNLOAD_TIMEOUT)?;
116 if !resp.status().is_success() {
117 return Err(format!("download returned {}", resp.status()));
118 }
119 let mut body = resp.body_mut().with_config().limit(MAX_DOWNLOAD).reader();
120 let mut file = File::create(dest).map_err(|e| format!("create {}: {e}", dest.display()))?;
121 let mut hasher = Sha256::new();
122 let mut buf = vec![0u8; 64 * 1024];
123 loop {
124 let n = body
125 .read(&mut buf)
126 .map_err(|e| format!("download failed: {e}"))?;
127 if n == 0 {
128 break;
129 }
130 hasher.update(&buf[..n]);
131 file.write_all(&buf[..n])
132 .map_err(|e| format!("write {}: {e}", dest.display()))?;
133 }
134 file.set_permissions(fs::Permissions::from_mode(0o755))
135 .and_then(|()| file.sync_all())
136 .map_err(|e| format!("finalize {}: {e}", dest.display()))?;
137 let got = hex::encode(hasher.finalize());
138 if got != asset.sha256 {
139 return Err(format!(
140 "sha256 mismatch for {} (expected {}, got {got})",
141 asset.name, asset.sha256
142 ));
143 }
144 Ok(())
145 }
146}