1use crate::netguard;
9use std::time::Duration;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum Reach {
14 Public,
17 Anywhere,
20}
21
22pub async fn get(
27 url: &reqwest::Url,
28 timeout: Duration,
29 reach: Reach,
30 headers: &[(&str, &str)],
31) -> Result<reqwest::Response, String> {
32 if !matches!(url.scheme(), "http" | "https") {
33 return Err("only http(s) URLs are allowed".into());
34 }
35 let mut builder = reqwest::Client::builder()
36 .timeout(timeout)
37 .redirect(reqwest::redirect::Policy::none());
38 if reach == Reach::Public {
39 let host = netguard::check_url_host(url)?;
42 let port = url.port_or_known_default().unwrap_or(80);
43 let addrs = netguard::resolve_public(&host, port, timeout).await?;
44 builder = builder.resolve_to_addrs(&host, &addrs);
45 if let Some(named) = url.host_str() {
49 if named != host {
50 builder = builder.resolve_to_addrs(named, &addrs);
51 }
52 }
53 builder = builder.no_proxy();
55 }
56 let client = builder.build().map_err(|e| e.to_string())?;
57 let mut request = client.get(url.clone());
58 for (name, value) in headers {
59 request = request.header(*name, *value);
60 }
61 request.send().await.map_err(|e| e.to_string())
62}
63
64pub async fn download(
71 raw: &str,
72 timeout: Duration,
73 cap: u64,
74 path: &std::path::Path,
75) -> Result<u64, String> {
76 use tokio::io::AsyncWriteExt;
77 let url = reqwest::Url::parse(raw).map_err(|e| format!("{raw:?}: {e}"))?;
78 if !matches!(url.scheme(), "http" | "https") {
79 return Err("only http(s) URLs are allowed".into());
80 }
81 let client = reqwest::Client::builder()
82 .timeout(timeout)
83 .redirect(reqwest::redirect::Policy::limited(5))
84 .build()
85 .map_err(|e| e.to_string())?;
86 let user_agent = format!("eclipse/{}", env!("CARGO_PKG_VERSION"));
87 let mut resp = client
88 .get(url.clone())
89 .header("User-Agent", user_agent)
90 .send()
91 .await
92 .map_err(|e| e.to_string())?;
93 if !resp.status().is_success() {
94 return Err(format!("{url} answered {}", resp.status()));
95 }
96 let mut file = tokio::fs::File::create(path)
97 .await
98 .map_err(|e| format!("{}: {e}", path.display()))?;
99 let mut written = 0u64;
100 while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? {
101 written += chunk.len() as u64;
102 if written > cap {
103 return Err(format!(
104 "{url} sent more than the {cap} bytes a release can weigh"
105 ));
106 }
107 file.write_all(&chunk)
108 .await
109 .map_err(|e| format!("{}: {e}", path.display()))?;
110 }
111 file.flush()
112 .await
113 .map_err(|e| format!("{}: {e}", path.display()))?;
114 Ok(written)
115}