use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime};
use base64::Engine;
use base64::prelude::BASE64_STANDARD;
use eyre::{Report, Result, WrapErr, bail, ensure, eyre};
use regex::Regex;
use reqwest::StatusCode;
use reqwest::header::{
ACCEPT_ENCODING, AUTHORIZATION, CONTENT_RANGE, CONTENT_TYPE, COOKIE, DATE, ETAG, HeaderMap,
HeaderName, HeaderValue, IF_MODIFIED_SINCE, IF_NONE_MATCH, IF_RANGE, LAST_MODIFIED,
PROXY_AUTHORIZATION, RANGE,
};
use reqwest::{ClientBuilder, IntoUrl, Method, Response, ResponseBuilderExt};
use serde::{Deserialize, Serialize};
use std::sync::LazyLock as Lazy;
use tokio::io::AsyncWriteExt;
use tokio::sync::OnceCell;
use url::Url;
use crate::file::display_path;
use crate::netrc;
use crate::progress::SingleReport;
use crate::redactions::redact_url_userinfo;
use crate::time::format_duration;
use crate::{env, file};
use mise_settings::Settings;
mod cas;
pub static HTTP: Lazy<Client> = Lazy::new(|| {
Client::new_shared(
crate::network::http_timeout(&Settings::get()),
ClientKind::Http,
)
});
pub static HTTP_UPLOAD: Lazy<Client> = Lazy::new(|| {
Client::new_shared_without_read_timeout(
crate::network::http_timeout(&Settings::get()),
ClientKind::Http,
)
});
pub static HTTP_FETCH: Lazy<Client> = Lazy::new(|| {
Client::new_shared(
crate::network::configured_fetch_remote_versions_timeout(&Settings::get()),
ClientKind::Fetch,
)
});
#[cfg(unix)]
static HTTP_CHECKSUM_PINNED: Lazy<Client> = Lazy::new(|| {
Client::new_shared_with(
crate::network::http_timeout(&Settings::get()),
ClientKind::Http,
Downgrade::FollowChecksumPinned,
)
});
type CachedResult = Arc<OnceCell<Result<String, CachedFailure>>>;
static HTTP_CACHE: Lazy<Mutex<HashMap<String, CachedResult>>> =
Lazy::new(|| Mutex::new(HashMap::new()));
static UNAVAILABLE_HTTP_HOSTS: Lazy<Mutex<HashMap<String, String>>> =
Lazy::new(|| Mutex::new(HashMap::new()));
type RetryStateHandle = Arc<Mutex<RetryState>>;
#[derive(Clone, Debug)]
struct CachedFailure {
message: String,
unreachable: bool,
}
impl std::fmt::Display for CachedFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for CachedFailure {}
#[derive(Debug)]
struct UnavailableHttpHost {
origin: String,
cause: String,
}
impl std::fmt::Display for UnavailableHttpHost {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"HTTP host {} is unavailable after an earlier connection failure: {}",
self.origin, self.cause
)
}
}
impl std::error::Error for UnavailableHttpHost {}
struct RetryState {
headers: HeaderMap,
use_netrc: bool,
netrc_replacement_only: bool,
}
fn new_retry_state(headers: &HeaderMap, netrc_replacement_only: bool) -> RetryStateHandle {
Arc::new(Mutex::new(RetryState {
headers: headers.clone(),
use_netrc: true,
netrc_replacement_only,
}))
}
fn with_saved_authorization(headers: &HeaderMap, retry_state: &RetryStateHandle) -> HeaderMap {
let mut headers = headers.clone();
match retry_state.lock().unwrap().headers.get(AUTHORIZATION) {
Some(value) => {
headers.insert(AUTHORIZATION, value.clone());
}
None => {
headers.remove(AUTHORIZATION);
}
}
headers
}
fn attempt_options(
retry_state: &RetryStateHandle,
error_for_status: bool,
) -> (HeaderMap, SendOnceOptions) {
let (headers, use_netrc, netrc_replacement_only) = {
let state = retry_state.lock().unwrap();
(
state.headers.clone(),
state.use_netrc,
state.netrc_replacement_only,
)
};
let mut options = SendOnceOptions::new(Some(retry_state.clone()), use_netrc);
options.netrc_replacement_only = netrc_replacement_only;
let options = if error_for_status {
options
} else {
options.allow_error_status()
};
(headers, options)
}
struct RetryableRequest<'a> {
method: Method,
url: Url,
headers: &'a HeaderMap,
verb_label: &'a str,
retries: i64,
error_for_status: bool,
}
#[derive(Clone)]
struct SendOnceOptions {
use_netrc: bool,
netrc_replacement_only: bool,
retry_github_oauth_401: bool,
error_for_status: bool,
allow_range_not_satisfiable: bool,
retry_state: Option<RetryStateHandle>,
}
impl SendOnceOptions {
fn check_response(&self, response: Response) -> Result<Response> {
if self.error_for_status
&& !(self.allow_range_not_satisfiable
&& response.status() == StatusCode::RANGE_NOT_SATISFIABLE)
&& let Err(err) = response.error_for_status_ref().map_err(redact_error_url)
{
return Err(match retry_after(&response) {
Some(wait) => {
let message = err.to_string();
Report::new(err).wrap_err(RetryAfter { wait, message })
}
None => err.into(),
});
}
Ok(response)
}
fn new(retry_state: Option<RetryStateHandle>, use_netrc: bool) -> Self {
Self {
use_netrc,
netrc_replacement_only: false,
retry_github_oauth_401: true,
error_for_status: true,
allow_range_not_satisfiable: false,
retry_state,
}
}
fn allow_error_status(mut self) -> Self {
self.error_for_status = false;
self
}
fn allow_range_not_satisfiable(mut self) -> Self {
self.allow_range_not_satisfiable = true;
self
}
fn recursive_retry(&self) -> Self {
Self {
use_netrc: false,
netrc_replacement_only: false,
retry_github_oauth_401: false,
error_for_status: self.error_for_status,
allow_range_not_satisfiable: self.allow_range_not_satisfiable,
retry_state: self.retry_state.clone(),
}
}
}
const PARTIAL_DOWNLOAD_STATE_VERSION: u8 = 3;
const PARTIAL_DOWNLOAD_MAX_AGE: Duration = Duration::from_secs(30 * 24 * 60 * 60);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind", content = "value")]
enum DownloadValidator {
Etag(String),
LastModified {
value: String,
response_date: String,
},
}
impl DownloadValidator {
fn as_header_value(&self) -> &str {
match self {
Self::Etag(value) | Self::LastModified { value, .. } => value,
}
}
fn matches(&self, other: &Self) -> bool {
match (self, other) {
(Self::Etag(a), Self::Etag(b)) => a == b,
(Self::LastModified { value: a, .. }, Self::LastModified { value: b, .. }) => a == b,
_ => false,
}
}
fn is_valid(&self) -> bool {
match self {
Self::Etag(value) => !value.is_empty() && !value.starts_with("W/"),
Self::LastModified {
value,
response_date,
} => is_strong_last_modified(value, response_date),
}
}
}
fn cache_allowed(pin: Option<&str>) -> bool {
let settings = Settings::get();
settings.download_cache
&& (pin.is_some() || !(settings.locked || settings.paranoid.provenance()))
}
#[derive(Clone, Copy)]
struct CacheMode<'a> {
pin: Option<&'a str>,
enabled: bool,
}
struct Fetched {
metadata: DownloadFileMetadata,
stored: Option<PathBuf>,
validator: Option<DownloadValidator>,
request_hash: String,
url: String,
}
#[derive(Clone)]
struct DownloadLimits {
time: Duration,
bytes: Option<u64>,
netrc: RetryStateHandle,
}
impl DownloadLimits {
fn new(bytes: Option<u64>, headers: &HeaderMap) -> Self {
Self {
time: crate::network::http_download_timeout(&Settings::get()),
bytes,
netrc: new_retry_state(headers, false),
}
}
}
#[derive(Default)]
struct AttemptOutcome {
max_bytes: Option<u64>,
cond: Option<DownloadValidator>,
not_modified: std::sync::atomic::AtomicBool,
validator: Mutex<Option<DownloadValidator>>,
netrc: Option<RetryStateHandle>,
}
#[derive(Debug)]
struct DownloadSizeMismatch {
expected: u64,
actual: u64,
}
impl std::fmt::Display for DownloadSizeMismatch {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"downloaded file size mismatch: expected {} bytes, got {}",
self.expected, self.actual
)
}
}
impl std::error::Error for DownloadSizeMismatch {}
#[derive(Debug)]
struct GithubRateLimited(String);
impl std::fmt::Display for GithubRateLimited {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for GithubRateLimited {}
const MAX_RETRY_AFTER: Duration = Duration::from_secs(30);
#[derive(Debug)]
struct RetryAfter {
wait: Duration,
message: String,
}
impl std::fmt::Display for RetryAfter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{} (retry-after: {}s)",
self.message,
self.wait.as_secs()
)
}
}
fn retry_delay(backoff: Duration, err: &Report) -> Duration {
err.downcast_ref::<RetryAfter>()
.map_or(backoff, |retry_after| backoff.max(retry_after.wait))
}
fn retry_after(response: &Response) -> Option<Duration> {
if response.status() != StatusCode::TOO_MANY_REQUESTS {
return None;
}
response
.headers()
.get(reqwest::header::RETRY_AFTER)?
.to_str()
.ok()?
.trim()
.parse::<u64>()
.ok()
.map(Duration::from_secs)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct PartialDownloadState {
version: u8,
request_hash: String,
validator: DownloadValidator,
total_size: Option<u64>,
effective_filename: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DownloadFileMetadata {
pub effective_filename: Option<String>,
}
type SharedDownload =
std::sync::Arc<tokio::sync::OnceCell<(tempfile::TempDir, DownloadFileMetadata)>>;
static INVOCATION_DOWNLOADS: std::sync::LazyLock<
std::sync::Mutex<std::collections::HashMap<String, SharedDownload>>,
> = std::sync::LazyLock::new(Default::default);
fn prune_shared_downloads(
downloads: &mut std::collections::HashMap<String, SharedDownload>,
max_bytes: u64,
max_entries: usize,
) {
let size = |entry: &SharedDownload| {
entry
.get()
.and_then(|(directory, _)| {
std::fs::metadata(directory.path().join("artifact"))
.ok()
.map(|m| m.len())
})
.unwrap_or(0)
};
let mut bytes: u64 = downloads.values().map(size).sum();
let mut count = downloads.len();
downloads.retain(|_, entry| {
if (bytes > max_bytes || count > max_entries) && Arc::strong_count(entry) == 1 {
bytes = bytes.saturating_sub(size(entry));
count -= 1;
false
} else {
true
}
});
}
pub struct InvocationDownloads;
impl Drop for InvocationDownloads {
fn drop(&mut self) {
INVOCATION_DOWNLOADS.lock().unwrap().clear();
}
}
fn download_filename_hint(url: &Url) -> Option<String> {
let segment = url.path_segments()?.next_back()?;
let filename = urlencoding::decode(segment).ok()?.into_owned();
if filename.is_empty()
|| filename == "."
|| filename == ".."
|| filename.ends_with([' ', '.'])
|| filename.chars().any(|c| {
c.is_control() || matches!(c, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*')
})
{
None
} else {
Some(filename)
}
}
#[derive(Debug, Clone)]
struct PartialDownload {
path: PathBuf,
state_path: PathBuf,
request_hash: String,
}
const DOWNLOAD_STATE_PREFIX: &str = ".mise-download-state.";
fn io_error(err: std::io::Error, doing: &str, path: &Path) -> eyre::Report {
let msg = file::with_io_hint(format!("{doing}: {}", display_path(path)), path, &err);
eyre::Report::new(err).wrap_err(msg)
}
impl PartialDownload {
fn new(destination: &Path, request_hash: String) -> Result<Self> {
let parent = destination.parent().ok_or_else(|| {
eyre!(
"download destination has no parent: {}",
destination.display()
)
})?;
let filename = destination
.file_name()
.ok_or_else(|| {
eyre!(
"download destination has no filename: {}",
destination.display()
)
})?
.to_string_lossy();
let partial_name = format!(".{filename}.mise-part");
Ok(Self {
path: parent.join(&partial_name),
state_path: parent.join(format!("{partial_name}.json")),
request_hash,
})
}
fn load(&self) -> Result<Option<(PartialDownloadState, u64)>> {
let state_bytes = match std::fs::read(&self.state_path) {
Ok(bytes) => bytes,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
self.remove_partial_if_exists()?;
return Ok(None);
}
Err(err) => return Err(err.into()),
};
let state: PartialDownloadState = match serde_json::from_slice(&state_bytes) {
Ok(state) => state,
Err(_) => {
self.clear()?;
return Ok(None);
}
};
let partial_size = match std::fs::metadata(&self.path) {
Ok(metadata) => metadata.len(),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
self.remove_state_if_exists()?;
return Ok(None);
}
Err(err) => return Err(err.into()),
};
if state.version != PARTIAL_DOWNLOAD_STATE_VERSION
|| state.request_hash != self.request_hash
|| !state.validator.is_valid()
|| partial_size == 0
|| state.total_size.is_some_and(|total| partial_size > total)
{
self.clear()?;
return Ok(None);
}
Ok(Some((state, partial_size)))
}
fn write_state(&self, state: &PartialDownloadState) -> Result<()> {
let parent = self.state_path.parent().unwrap();
let temp_name = parent.join(format!("{DOWNLOAD_STATE_PREFIX}XXXXXX"));
let mut temp = tempfile::NamedTempFile::with_prefix_in(DOWNLOAD_STATE_PREFIX, parent)
.map_err(|err| io_error(err, "failed to create the download state file", &temp_name))?;
serde_json::to_writer(&mut temp, state)?;
temp.as_file_mut().sync_all()?;
temp.persist(&self.state_path).map_err(|err| {
io_error(
err.error,
"failed to write the download state file",
&self.state_path,
)
})?;
Ok(())
}
fn clear(&self) -> Result<()> {
self.remove_partial_if_exists()?;
self.remove_state_if_exists()?;
Ok(())
}
fn remove_partial_if_exists(&self) -> Result<()> {
remove_file_if_exists(&self.path)
}
fn remove_state_if_exists(&self) -> Result<()> {
remove_file_if_exists(&self.state_path)
}
fn persist(&self, destination: &Path) -> Result<()> {
let temp_path = tempfile::TempPath::try_from_path(&self.path)?;
if let Err(err) = temp_path.persist(destination) {
let error = err.error;
let _ = err.path.keep();
return Err(io_error(
error,
"failed to move the downloaded file into place",
destination,
));
}
self.remove_state_if_exists()?;
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ParsedContentRange {
Bytes { start: u64, end: u64, total: u64 },
Unsatisfied { total: u64 },
}
fn remove_file_if_exists(path: &Path) -> Result<()> {
match std::fs::remove_file(path) {
Ok(()) => Ok(()),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(err) => Err(err.into()),
}
}
pub fn cleanup_download_dir(path: &Path) -> Result<()> {
let entries = match std::fs::read_dir(path) {
Ok(entries) => entries,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(err) => return Err(err.into()),
};
for entry in entries {
let entry = entry?;
let name = entry.file_name();
let name = name.to_string_lossy();
let pair_path = name
.strip_suffix(".mise-part.json")
.map(|stem| path.join(format!("{stem}.mise-part")))
.or_else(|| {
name.strip_suffix(".mise-part")
.map(|_| path.join(format!("{name}.json")))
});
if name.starts_with('.')
&& pair_path.is_some_and(|pair_path| {
pair_path.is_file()
&& partial_file_is_recent(&entry.path())
&& partial_file_is_recent(&pair_path)
})
{
continue;
}
let path = entry.path();
if entry.file_type()?.is_dir() {
file::remove_all(&path)?;
} else {
remove_file_if_exists(&path)?;
}
}
if std::fs::read_dir(path)?.next().is_none() {
std::fs::remove_dir(path)?;
}
Ok(())
}
fn partial_file_is_recent(path: &Path) -> bool {
let Ok(modified) = std::fs::metadata(path).and_then(|metadata| metadata.modified()) else {
return false;
};
SystemTime::now()
.duration_since(modified)
.map_or(true, |age| age <= PARTIAL_DOWNLOAD_MAX_AGE)
}
fn update_download_hash(hasher: &mut blake3::Hasher, value: &[u8]) {
hasher.update(&(value.len() as u64).to_le_bytes());
hasher.update(value);
}
fn header_digest(headers: &HeaderMap) -> String {
let mut hasher = blake3::Hasher::new();
hash_headers(&mut hasher, headers);
hasher.finalize().to_hex().to_string()
}
fn hash_headers(hasher: &mut blake3::Hasher, headers: &HeaderMap) {
let mut header_values = headers
.keys()
.flat_map(|name| {
headers
.get_all(name)
.iter()
.map(move |value| (name.as_str().as_bytes(), value.as_bytes()))
})
.collect::<Vec<_>>();
header_values.sort_unstable();
for (name, value) in header_values {
update_download_hash(hasher, name);
update_download_hash(hasher, value);
}
}
fn download_request_hash(url: &Url, headers: &HeaderMap) -> String {
let mut hasher = blake3::Hasher::new();
update_download_hash(&mut hasher, url.as_str().as_bytes());
hash_headers(&mut hasher, headers);
if let Some(replacements) = &Settings::get().url_replacements {
for (pattern, replacement) in replacements {
update_download_hash(&mut hasher, pattern.as_bytes());
update_download_hash(&mut hasher, replacement.as_bytes());
}
}
hasher.finalize().to_hex().to_string()
}
fn response_validator(headers: &HeaderMap) -> Option<DownloadValidator> {
headers
.get(ETAG)
.and_then(|value| value.to_str().ok())
.filter(|value| !value.is_empty() && !value.starts_with("W/"))
.map(|value| DownloadValidator::Etag(value.to_string()))
.or_else(|| {
let value = headers
.get(LAST_MODIFIED)
.and_then(|value| value.to_str().ok())
.filter(|value| !value.is_empty())?;
let response_date = headers.get(DATE)?.to_str().ok()?;
is_strong_last_modified(value, response_date).then(|| DownloadValidator::LastModified {
value: value.to_string(),
response_date: response_date.to_string(),
})
})
}
fn is_strong_last_modified(value: &str, response_date: &str) -> bool {
let Ok(last_modified) = chrono::DateTime::parse_from_rfc2822(value) else {
return false;
};
let Ok(response_date) = chrono::DateTime::parse_from_rfc2822(response_date) else {
return false;
};
response_date.signed_duration_since(last_modified) >= chrono::Duration::seconds(60)
}
fn parse_content_range(value: &str) -> Option<ParsedContentRange> {
let value = value.strip_prefix("bytes ")?;
let (range, total) = value.split_once('/')?;
let total = total.parse::<u64>().ok()?;
if range == "*" {
return Some(ParsedContentRange::Unsatisfied { total });
}
let (start, end) = range.split_once('-')?;
let start = start.parse::<u64>().ok()?;
let end = end.parse::<u64>().ok()?;
if start > end || end >= total {
return None;
}
Some(ParsedContentRange::Bytes { start, end, total })
}
#[cfg(unix)]
pub async fn download_file_checksum_pinned<U: IntoUrl>(
url: U,
path: &Path,
sha256: &str,
pr: Option<&dyn SingleReport>,
) -> Result<()> {
let pin = format!("sha256:{sha256}");
HTTP_CHECKSUM_PINNED
.download_file_pinned(url, path, Some(&pin), pr)
.await?;
verify_sha256_or_remove(path, sha256, pr)
}
#[cfg(unix)]
fn verify_sha256_or_remove(path: &Path, sha256: &str, pr: Option<&dyn SingleReport>) -> Result<()> {
if let Err(err) = crate::hash::ensure_checksum(path, sha256, pr, "sha256") {
let _ = file::remove_file(path);
return Err(err);
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Downgrade {
Refuse,
#[cfg(unix)]
FollowChecksumPinned,
}
fn https_downgrade_policy(what: &'static str) -> reqwest::redirect::Policy {
use reqwest::redirect::Policy;
Policy::custom(move |attempt| {
if is_https_downgrade(attempt.previous(), attempt.url()) {
attempt.error(std::io::Error::other(format!(
"refusing to redirect {what} from HTTPS to HTTP"
)))
} else {
Policy::default().redirect(attempt)
}
})
}
pub fn is_https_downgrade(previous: &[Url], next: &Url) -> bool {
previous
.last()
.is_some_and(|url| url.scheme() == "https" && next.scheme() != "https")
}
#[derive(Debug)]
pub struct Client {
reqwest: Result<reqwest::Client, String>,
manual_redirects: std::sync::OnceLock<Result<reqwest::Client, String>>,
undecoded: std::sync::OnceLock<Result<reqwest::Client, String>>,
undecoded_manual_redirects: std::sync::OnceLock<Result<reqwest::Client, String>>,
timeout: Duration,
read_timeout: Option<Duration>,
downgrade: Downgrade,
kind: ClientKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClientKind {
Http,
Fetch,
}
impl ClientKind {
fn redirect_subject(self) -> &'static str {
match self {
Self::Http => "a download",
Self::Fetch => "a remote version request",
}
}
}
impl Client {
#[doc(hidden)]
pub fn new(timeout: Duration, kind: ClientKind) -> Result<Self> {
Ok(Self {
reqwest: Ok(Self::build(
timeout,
kind,
Downgrade::Refuse,
Some(timeout),
true,
)?),
manual_redirects: Default::default(),
undecoded: Default::default(),
undecoded_manual_redirects: Default::default(),
timeout,
read_timeout: Some(timeout),
downgrade: Downgrade::Refuse,
kind,
})
}
fn new_shared(timeout: Duration, kind: ClientKind) -> Self {
Self::new_shared_with(timeout, kind, Downgrade::Refuse)
}
fn new_shared_without_read_timeout(timeout: Duration, kind: ClientKind) -> Self {
Self {
reqwest: Self::build(timeout, kind, Downgrade::Refuse, None, true)
.map_err(|err| format!("{err:#}")),
manual_redirects: Default::default(),
undecoded: Default::default(),
undecoded_manual_redirects: Default::default(),
timeout,
read_timeout: None,
downgrade: Downgrade::Refuse,
kind,
}
}
fn new_shared_with(timeout: Duration, kind: ClientKind, downgrade: Downgrade) -> Self {
Self {
reqwest: Self::build(timeout, kind, downgrade, Some(timeout), true)
.map_err(|err| format!("{err:#}")),
manual_redirects: Default::default(),
undecoded: Default::default(),
undecoded_manual_redirects: Default::default(),
timeout,
read_timeout: Some(timeout),
downgrade,
kind,
}
}
fn build(
timeout: Duration,
kind: ClientKind,
downgrade: Downgrade,
read_timeout: Option<Duration>,
decode: bool,
) -> Result<reqwest::Client> {
Ok(mise_tls::build_client(|| {
let builder = Self::_new_with(decode).connect_timeout(timeout);
let builder = match read_timeout {
Some(read_timeout) => builder.read_timeout(read_timeout),
None => builder,
};
let policy = match downgrade {
Downgrade::Refuse => https_downgrade_policy(kind.redirect_subject()),
#[cfg(unix)]
Downgrade::FollowChecksumPinned => reqwest::redirect::Policy::default(),
};
builder.redirect(policy)
})?)
}
#[doc(hidden)]
pub fn with_init_error(error: impl Into<String>) -> Self {
Self {
reqwest: Err(error.into()),
manual_redirects: Default::default(),
undecoded: Default::default(),
undecoded_manual_redirects: Default::default(),
timeout: Duration::from_secs(1),
read_timeout: Some(Duration::from_secs(1)),
downgrade: Downgrade::Refuse,
kind: ClientKind::Http,
}
}
pub fn reqwest(&self) -> Result<&reqwest::Client> {
self.reqwest
.as_ref()
.map_err(|err| eyre!("Could not initialize the HTTP client: {err}"))
}
fn undecoded(&self) -> Result<&reqwest::Client> {
self.reqwest()?;
self.undecoded
.get_or_init(|| {
Self::build(
self.timeout,
self.kind,
self.downgrade,
self.read_timeout,
false,
)
.map_err(|err| format!("{err:#}"))
})
.as_ref()
.map_err(|err| eyre!("Could not initialize the HTTP client: {err}"))
}
async fn send_scoped(
&self,
method: &Method,
url: &Url,
headers: &HeaderMap,
forward: &ForwardRules,
timeout: Option<Duration>,
) -> std::result::Result<Response, SendError> {
let decode = headers
.get(ACCEPT_ENCODING)
.is_none_or(|encoding| encoding != "identity");
if !has_unscoped_credential(headers) && !forward.applies_to(headers) {
let client = if decode {
self.reqwest()
} else {
self.undecoded()
};
let mut req = client
.map_err(|err| SendError::Refused(format!("{err:#}")))?
.request(method.clone(), url.clone());
if let Some(timeout) = timeout {
req = req.timeout(timeout);
}
return req
.headers(headers.clone())
.send()
.await
.map_err(Into::into);
}
let manual_redirects = if decode {
&self.manual_redirects
} else {
&self.undecoded_manual_redirects
};
let client = manual_redirects
.get_or_init(|| {
mise_tls::build_client(|| {
Self::_new_with(decode)
.read_timeout(self.timeout)
.connect_timeout(self.timeout)
.redirect(reqwest::redirect::Policy::none())
})
.map_err(|err| format!("{err:#}"))
})
.as_ref()
.map_err(|err| {
SendError::Refused(format!("Could not initialize the HTTP client: {err}"))
})?;
let mut method = method.clone();
let mut url = url.clone();
let mut headers = headers.clone();
for _ in 0..MAX_MANUAL_REDIRECTS {
let mut req = client.request(method.clone(), url.clone());
if let Some(timeout) = timeout {
req = req.timeout(timeout);
}
let resp = req.headers(headers.clone()).send().await?;
if !resp.status().is_redirection() {
return Ok(resp);
}
let Some(location) = resp
.headers()
.get(reqwest::header::LOCATION)
.and_then(|value| value.to_str().ok())
else {
return Ok(resp);
};
let Ok(mut next) = url.join(location) else {
return Ok(resp);
};
if is_https_downgrade(std::slice::from_ref(&url), &next) {
return Err(SendError::Refused(
"refusing to redirect a request with credentials from HTTPS to HTTP"
.to_string(),
));
}
if next.host() != url.host()
|| next.port_or_known_default() != url.port_or_known_default()
|| next.scheme() != url.scheme()
{
forward.retain_for(&mut headers, &url, &next);
let _ = next.set_username("");
let _ = next.set_password(None);
}
if matches!(
resp.status(),
StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND | StatusCode::SEE_OTHER
) && method != Method::HEAD
{
method = Method::GET;
}
url = next;
}
Err(SendError::Refused(format!(
"too many redirects (more than {MAX_MANUAL_REDIRECTS})"
)))
}
fn _new() -> ClientBuilder {
Self::_new_with(true)
}
fn _new_with(decode: bool) -> ClientBuilder {
let builder = ClientBuilder::new().user_agent(crate::user_agent::get());
if decode {
builder.gzip(true).zstd(true)
} else {
builder.no_gzip().no_zstd().no_brotli().no_deflate()
}
}
fn request_timeout(&self) -> Duration {
match self.kind {
ClientKind::Fetch if crate::network::bound_remote_version_lookups(&Settings::get()) => {
self.timeout.min(Duration::from_secs(3))
}
_ => self.timeout,
}
}
pub async fn get_bytes<U: IntoUrl>(&self, url: U) -> Result<impl AsRef<[u8]>> {
self.get_bytes_with_headers(url, HeaderMap::new()).await
}
pub async fn get_bytes_with_headers<U: IntoUrl>(
&self,
url: U,
headers: HeaderMap,
) -> Result<impl AsRef<[u8]>> {
ensure!(
!crate::network::offline(&Settings::get()),
"offline mode is enabled"
);
let url = url.into_url()?;
let headers = with_host_auth(&url, &headers)?;
self.send_with_retries(
RetryableRequest {
method: Method::GET,
url,
headers: &headers,
verb_label: "GET",
retries: crate::network::http_retries(&Settings::get()),
error_for_status: true,
},
|resp| async move {
Ok(buffer_body(resp)
.await?
.bytes()
.await
.map_err(redact_error_url)?)
},
)
.await
}
pub async fn get_async<U: IntoUrl>(&self, url: U) -> Result<Response> {
let url = url.into_url()?;
let headers = host_auth_headers(&url)?;
self.get_async_with_headers(url, &headers).await
}
pub async fn get_async_with_headers<U: IntoUrl>(
&self,
url: U,
headers: &HeaderMap,
) -> Result<Response> {
ensure!(
!crate::network::offline(&Settings::get()),
"offline mode is enabled"
);
let url = url.into_url()?;
let resp = self
.send_with_https_fallback(Method::GET, url, headers, "GET")
.await?;
resp.error_for_status_ref().map_err(redact_error_url)?;
Ok(resp)
}
pub async fn get_async_with_headers_allow_error_status<U: IntoUrl>(
&self,
url: U,
headers: &HeaderMap,
) -> Result<Response> {
ensure!(
!crate::network::offline(&Settings::get()),
"offline mode is enabled"
);
let url = url.into_url()?;
self.send_with_https_fallback_allow_error_status(Method::GET, url, headers, "GET")
.await
}
pub async fn head<U: IntoUrl>(&self, url: U) -> Result<Response> {
let url = url.into_url()?;
let headers = host_auth_headers(&url)?;
self.head_async_with_headers(url, &headers).await
}
pub async fn head_without_netrc<U: IntoUrl>(
&self,
url: U,
max_retries: i64,
) -> Result<Response> {
ensure!(
!crate::network::offline(&Settings::get()),
"offline mode is enabled"
);
let url = url.into_url()?;
let headers = host_auth_headers(&url)?;
let retry_state = new_retry_state(&headers, true);
let resp = retry_async_with_retries(
"HEAD",
&url,
crate::network::http_retries(&Settings::get()).min(max_retries),
|| async {
let (headers, options) = attempt_options(&retry_state, true);
self.send_once_with_https_fallback_with_retry_headers(
Method::HEAD,
url.clone(),
&headers,
"HEAD",
options,
)
.await
},
)
.await?;
resp.error_for_status_ref().map_err(redact_error_url)?;
Ok(resp)
}
pub async fn head_async_with_headers<U: IntoUrl>(
&self,
url: U,
headers: &HeaderMap,
) -> Result<Response> {
ensure!(
!crate::network::offline(&Settings::get()),
"offline mode is enabled"
);
let url = url.into_url()?;
let resp = self
.send_with_https_fallback(Method::HEAD, url, headers, "HEAD")
.await?;
resp.error_for_status_ref().map_err(redact_error_url)?;
Ok(resp)
}
pub async fn get_text<U: IntoUrl>(&self, url: U) -> Result<String> {
self.get_text_request(url).send().await
}
pub fn get_text_request<U: IntoUrl>(&self, url: U) -> TextRequest<'_> {
TextRequest {
client: self,
url: url.into_url().map_err(|e| e.to_string()),
extra_headers: HeaderMap::new(),
retries: crate::network::http_retries(&Settings::get()),
allow_html: false,
}
}
pub async fn get_text_cached<U: IntoUrl>(&self, url: U) -> Result<String> {
self.get_text_cached_with_headers(url, &HeaderMap::new())
.await
}
pub async fn get_text_cached_with_headers<U: IntoUrl>(
&self,
url: U,
headers: &HeaderMap,
) -> Result<String> {
let url = url.into_url()?;
let key = if headers.is_empty() {
url.to_string()
} else {
format!("{url}\n{}", header_digest(headers))
};
let cell = {
let mut cache = HTTP_CACHE.lock().unwrap();
cache.entry(key).or_default().clone()
};
let result = cell
.get_or_init(|| {
let url = url.clone();
async move {
match self.get_text_request(url).headers(headers).send().await {
Ok(text) => Ok(text),
Err(err) => Err(CachedFailure {
message: err.to_string(),
unreachable: is_unreachable(&err),
}),
}
}
})
.await;
match result {
Ok(text) => Ok(text.clone()),
Err(err) => Err(err.clone().into()),
}
}
pub async fn get_html<U: IntoUrl>(&self, url: U) -> Result<String> {
let url = url.into_url()?;
let headers = host_auth_headers(&url)?;
self.get_html_with_headers(url, &headers).await
}
pub async fn get_html_with_headers<U: IntoUrl>(
&self,
url: U,
headers: &HeaderMap,
) -> Result<String> {
let url = url.into_url()?;
let resp = self.get_async_with_headers(url.clone(), headers).await?;
let is_html = resp
.headers()
.get(CONTENT_TYPE)
.and_then(|content_type| content_type.to_str().ok())
.is_some_and(|content_type| {
let media_type = content_type
.split_once(';')
.map_or(content_type, |(media_type, _)| media_type)
.trim()
.to_ascii_lowercase();
media_type == "text/html" || media_type.ends_with("+html")
});
if !is_html {
bail!("Got non-HTML text from {}", log_url(&url));
}
let read = async {
Ok(buffer_body(resp)
.await?
.text()
.await
.map_err(redact_error_url)?)
};
read_body_within(
crate::network::http_download_timeout(&Settings::get()),
&url,
read,
)
.await
}
pub async fn json_headers<T, U: IntoUrl>(&self, url: U) -> Result<(T, HeaderMap)>
where
T: serde::de::DeserializeOwned,
{
let url = url.into_url()?;
let headers = host_auth_headers(&url)?;
self.json_headers_with_headers(url, &headers).await
}
pub async fn json_headers_with_headers<T, U: IntoUrl>(
&self,
url: U,
headers: &HeaderMap,
) -> Result<(T, HeaderMap)>
where
T: serde::de::DeserializeOwned,
{
ensure!(
!crate::network::offline(&Settings::get()),
"offline mode is enabled"
);
let url = url.into_url()?;
self.send_with_retries(
RetryableRequest {
method: Method::GET,
url,
headers,
verb_label: "GET",
retries: crate::network::http_retries(&Settings::get()),
error_for_status: true,
},
|resp| async move {
let headers = resp.headers().clone();
Ok((
buffer_body(resp)
.await?
.json()
.await
.map_err(redact_error_url)?,
headers,
))
},
)
.await
}
pub async fn json<T, U: IntoUrl>(&self, url: U) -> Result<T>
where
T: serde::de::DeserializeOwned,
{
self.json_headers(url).await.map(|(json, _)| json)
}
pub async fn json_cached<T, U: IntoUrl>(&self, url: U) -> Result<T>
where
T: serde::de::DeserializeOwned,
{
let text = self.get_text_cached(url).await?;
Ok(serde_json::from_str(&text)?)
}
pub async fn json_with_headers<T, U: IntoUrl>(&self, url: U, headers: &HeaderMap) -> Result<T>
where
T: serde::de::DeserializeOwned,
{
self.json_headers_with_headers(url, headers)
.await
.map(|(json, _)| json)
}
pub async fn download_file<U: IntoUrl>(
&self,
url: U,
path: &Path,
pr: Option<&dyn SingleReport>,
) -> Result<()> {
self.download_file_with_metadata(url, path, pr)
.await
.map(|_| ())
}
pub async fn download_file_limited<U: IntoUrl>(
&self,
url: U,
path: &Path,
max_bytes: u64,
pr: Option<&dyn SingleReport>,
) -> Result<()> {
let url = url.into_url()?;
let headers = host_auth_headers(&url)?;
self.download_file_with_pin_limited(url.clone(), path, &headers, None, pr, Some(max_bytes))
.await?;
ensure_download_within(path, &url, max_bytes)
}
pub async fn download_file_with_metadata<U: IntoUrl>(
&self,
url: U,
path: &Path,
pr: Option<&dyn SingleReport>,
) -> Result<DownloadFileMetadata> {
let url = url.into_url()?;
let headers = host_auth_headers(&url)?;
self.download_file_with_headers_metadata(url, path, &headers, pr)
.await
}
pub async fn download_file_with_headers<U: IntoUrl>(
&self,
url: U,
path: &Path,
headers: &HeaderMap,
pr: Option<&dyn SingleReport>,
) -> Result<()> {
self.download_file_with_headers_metadata(url, path, headers, pr)
.await
.map(|_| ())
}
pub async fn download_file_with_headers_metadata<U: IntoUrl>(
&self,
url: U,
path: &Path,
headers: &HeaderMap,
pr: Option<&dyn SingleReport>,
) -> Result<DownloadFileMetadata> {
self.download_file_with_pin(url, path, headers, None, pr)
.await
}
pub async fn download_file_pinned<U: IntoUrl>(
&self,
url: U,
path: &Path,
pin: Option<&str>,
pr: Option<&dyn SingleReport>,
) -> Result<DownloadFileMetadata> {
let url = url.into_url()?;
let headers = host_auth_headers(&url)?;
self.download_file_with_pin(url, path, &headers, pin, pr)
.await
}
pub async fn download_file_with_pin<U: IntoUrl>(
&self,
url: U,
path: &Path,
headers: &HeaderMap,
pin: Option<&str>,
pr: Option<&dyn SingleReport>,
) -> Result<DownloadFileMetadata> {
self.download_file_with_pin_limited(url, path, headers, pin, pr, None)
.await
}
async fn download_file_with_pin_limited<U: IntoUrl>(
&self,
url: U,
path: &Path,
headers: &HeaderMap,
pin: Option<&str>,
pr: Option<&dyn SingleReport>,
max_bytes: Option<u64>,
) -> Result<DownloadFileMetadata> {
let url = url.into_url()?;
if Settings::get().generate_lockfiles() {
let key = format!(
"{:p}:{}:{max_bytes:?}",
self,
download_request_hash(&url, headers)
);
let shared = INVOCATION_DOWNLOADS
.lock()
.unwrap()
.entry(key)
.or_default()
.clone();
let (directory, metadata) = shared
.get_or_try_init(|| async {
let scratch = crate::dirs::CACHE.join("invocation-downloads");
file::create_dir_all(&scratch)?;
let directory = tempfile::tempdir_in(&scratch)?;
let metadata = self
.download_file_with_headers_timeout(
url.clone(),
&directory.path().join("artifact"),
headers,
pin,
pr,
DownloadLimits::new(max_bytes, headers),
)
.await?;
Ok::<_, eyre::Report>((directory, metadata))
})
.await?;
if let Some(parent) = path.parent() {
file::create_dir_all(parent)?;
}
let partial = PartialDownload::new(path, download_request_hash(&url, headers))?;
let lock_path = partial.path.clone();
let _download_lock = tokio::task::spawn_blocking(move || {
crate::lock_file::LockFile::new(&lock_path).lock()
})
.await??;
partial.clear()?;
file::copy(directory.path().join("artifact"), &partial.path)?;
partial.persist(path)?;
let metadata = metadata.clone();
drop(shared);
prune_shared_downloads(
&mut INVOCATION_DOWNLOADS.lock().unwrap(),
512 * 1024 * 1024,
64,
);
return Ok(metadata);
}
self.download_file_with_headers_timeout(
url,
path,
headers,
pin,
pr,
DownloadLimits::new(max_bytes, headers),
)
.await
}
async fn download_file_with_headers_timeout<U: IntoUrl>(
&self,
url: U,
path: &Path,
headers: &HeaderMap,
pin: Option<&str>,
pr: Option<&dyn SingleReport>,
limits: DownloadLimits,
) -> Result<DownloadFileMetadata> {
let use_cache = cache_allowed(pin);
let cache = CacheMode {
pin,
enabled: use_cache,
};
let fetched = self
.download_file_inner(url, path, headers, cache, pr, limits)
.await?;
if let Some(blob) = fetched.stored {
let dest = path.to_path_buf();
tokio::task::spawn_blocking(move || cas::place(&blob, &dest, false)).await??;
return Ok(fetched.metadata);
}
if use_cache {
let path = path.to_path_buf();
let pin = pin.map(str::to_string);
let effective_filename = fetched.metadata.effective_filename.clone();
let kept = tokio::task::spawn_blocking(move || {
cas::store(
&path,
cas::Keep {
request_hash: &fetched.request_hash,
url: &fetched.url,
pin: pin.as_deref(),
validator: fetched.validator.as_ref(),
effective_filename,
},
)
})
.await;
if let Ok(Err(err)) | Err(err) = kept.map_err(Report::from) {
debug!("could not keep the download: {err:#}");
}
}
Ok(fetched.metadata)
}
pub async fn download_file_stored<U: IntoUrl>(
&self,
url: U,
dest: &Path,
pin: Option<&str>,
pr: Option<&dyn SingleReport>,
) -> Result<DownloadFileMetadata> {
let url = url.into_url()?;
let headers = host_auth_headers(&url)?;
self.download_file_linked(url, dest, &headers, pin, pr)
.await
}
pub async fn download_file_linked<U: IntoUrl>(
&self,
url: U,
dest: &Path,
headers: &HeaderMap,
pin: Option<&str>,
pr: Option<&dyn SingleReport>,
) -> Result<DownloadFileMetadata> {
self.download_file_linked_limited(url, dest, headers, pin, pr, None)
.await
}
pub async fn download_file_linked_limited<U: IntoUrl>(
&self,
url: U,
dest: &Path,
headers: &HeaderMap,
pin: Option<&str>,
pr: Option<&dyn SingleReport>,
max_bytes: Option<u64>,
) -> Result<DownloadFileMetadata> {
let url = url.into_url()?;
let metadata = self
.download_file_linked_inner(url.clone(), dest, headers, pin, pr, max_bytes)
.await?;
if let Some(max_bytes) = max_bytes {
ensure_download_within(dest, &url, max_bytes)?;
}
Ok(metadata)
}
async fn download_file_linked_inner(
&self,
url: Url,
dest: &Path,
headers: &HeaderMap,
pin: Option<&str>,
pr: Option<&dyn SingleReport>,
max_bytes: Option<u64>,
) -> Result<DownloadFileMetadata> {
let name = dest
.file_name()
.ok_or_else(|| eyre!("download destination has no filename: {}", dest.display()))?
.to_string_lossy()
.to_string();
let request_hash = download_request_hash(&url, headers);
let staging = (cache_allowed(pin) && !Settings::get().generate_lockfiles())
.then(|| cas::staging_path(&request_hash, &name))
.flatten();
let Some(staging) = staging else {
return self
.download_file_with_pin_limited(url, dest, headers, pin, pr, max_bytes)
.await;
};
let cache = CacheMode { pin, enabled: true };
let fetched = self
.download_file_inner(
url,
&staging,
headers,
cache,
pr,
DownloadLimits::new(max_bytes, headers),
)
.await?;
let blob = match fetched.stored {
Some(blob) => Some(blob),
None => {
let staged = staging.clone();
let pin = pin.map(str::to_string);
let effective_filename = fetched.metadata.effective_filename.clone();
let validator = fetched.validator.clone();
let hash = fetched.request_hash.clone();
let fetched_url = fetched.url.clone();
tokio::task::spawn_blocking(move || {
cas::ingest(
&staged,
cas::Keep {
request_hash: &hash,
url: &fetched_url,
pin: pin.as_deref(),
validator: validator.as_ref(),
effective_filename,
},
)
})
.await??
}
};
let dest = dest.to_path_buf();
let (source, link) = match &blob {
Some(blob) => (blob.clone(), true),
None => (staging.clone(), false),
};
tokio::task::spawn_blocking(move || cas::place(&source, &dest, link)).await??;
if blob.is_none() {
let _ = file::remove_file(&staging);
}
Ok(fetched.metadata)
}
async fn download_file_inner<U: IntoUrl>(
&self,
url: U,
path: &Path,
headers: &HeaderMap,
cache: CacheMode<'_>,
pr: Option<&dyn SingleReport>,
limits: DownloadLimits,
) -> Result<Fetched> {
let total_timeout = limits.time;
let CacheMode {
pin,
enabled: use_cache,
} = cache;
let started = Instant::now();
let url = url.into_url()?;
let request_hash = download_request_hash(&url, headers);
if use_cache && let Some(hit) = pin.and_then(|pin| cas::lookup_pin(pin, url.as_str())) {
let effective_filename = hit.effective_filename.clone();
if let Some(blob) = tokio::task::spawn_blocking(move || hit.verified()).await? {
return Ok(Fetched {
metadata: DownloadFileMetadata { effective_filename },
stored: Some(blob),
validator: None,
request_hash,
url: url.to_string(),
});
}
}
ensure!(
!crate::network::offline(&Settings::get()),
"offline mode is enabled"
);
debug!(
"GET Downloading {} to {}",
log_url(&url),
display_path(path)
);
let parent = path.parent().unwrap();
file::create_dir_all(parent)?;
let partial = PartialDownload::new(path, download_request_hash(&url, headers))?;
let lock_path = partial.path.clone();
let _download_lock =
tokio::task::spawn_blocking(move || crate::lock_file::LockFile::new(&lock_path).lock())
.await??;
let attempt = Arc::new(AtomicUsize::new(0));
let progress = Arc::new(DownloadProgress::default());
let cached = if use_cache {
cas::lookup_url(&request_hash, pin)
} else {
None
};
let outcome = Arc::new(AttemptOutcome {
max_bytes: limits.bytes,
netrc: Some(limits.netrc.clone()),
cond: cached.as_ref().map(|c| c.validator.clone()),
..Default::default()
});
let download = retry_async("GET", &url, || {
let attempt = attempt.clone();
let progress = progress.clone();
let request_url = url.clone();
let partial = partial.clone();
let outcome = outcome.clone();
async move {
attempt.fetch_add(1, Ordering::Relaxed);
progress.start_attempt();
Box::pin(self.download_file_attempt(
request_url,
headers,
&partial,
pr,
&progress,
&outcome,
))
.await
}
});
let download = async {
tokio::select! {
result = download => result,
never = warn_when_download_is_slow(&url, &progress) => match never {},
}
};
let metadata = match tokio::time::timeout(total_timeout, download).await {
Ok(result) => result?,
Err(_) => {
if let Err(err) = partial.load() {
debug!("failed to validate partial download after timeout: {err:#}");
}
bail!(
"HTTP download timed out after {} for {} (attempt {}, {} bytes received; change with `http_download_timeout` or env `MISE_HTTP_DOWNLOAD_TIMEOUT`)",
format_duration(total_timeout),
log_url(&url),
attempt.load(Ordering::Relaxed),
progress.attempt.load(Ordering::Relaxed),
)
}
};
let path = path.to_path_buf();
if outcome.not_modified.load(Ordering::Relaxed)
&& let Some(cached) = cached
{
let effective_filename = cached.effective_filename();
let hit = cached.into_hit();
if let Some(blob) = tokio::task::spawn_blocking(move || hit.verified()).await? {
return Ok(Fetched {
metadata: DownloadFileMetadata { effective_filename },
stored: Some(blob),
validator: None,
request_hash,
url: url.to_string(),
});
}
drop(_download_lock);
let cache = CacheMode {
pin,
enabled: false,
};
let remaining = total_timeout
.checked_sub(started.elapsed())
.filter(|left| !left.is_zero())
.ok_or_else(|| {
eyre!(
"HTTP download timed out after {} for {}",
format_duration(total_timeout),
log_url(&url)
)
})?;
let limits = DownloadLimits {
time: remaining,
..limits
};
return Box::pin(self.download_file_inner(url, &path, headers, cache, pr, limits))
.await;
}
let persist_path = path.clone();
tokio::task::spawn_blocking(move || partial.persist(&persist_path)).await??;
let validator = outcome.validator.lock().unwrap().take();
Ok(Fetched {
metadata,
stored: None,
validator,
request_hash,
url: url.to_string(),
})
}
async fn download_file_attempt(
&self,
url: Url,
headers: &HeaderMap,
partial: &PartialDownload,
pr: Option<&dyn SingleReport>,
progress: &DownloadProgress,
outcome: &AttemptOutcome,
) -> Result<DownloadFileMetadata> {
let max_bytes = outcome.max_bytes;
let too_large = |max: u64| {
eyre!(
"download from {} is larger than {}",
log_url(&url),
bytesize::ByteSize::b(max).display().iec()
)
};
let mut restarted_without_resume = false;
loop {
let resume = if restarted_without_resume {
None
} else {
partial.load()?
};
if let Some((state, partial_size)) = &resume
&& state.total_size == Some(*partial_size)
{
if let Some(pr) = pr {
pr.set_length(*partial_size);
pr.set_position(*partial_size);
}
return Ok(DownloadFileMetadata {
effective_filename: state.effective_filename.clone(),
});
}
let offset = resume.as_ref().map(|(_, size)| *size).unwrap_or(0);
let netrc_state = outcome.netrc.as_ref().expect("download sets netrc state");
let mut request_headers = with_saved_authorization(headers, netrc_state);
request_headers.insert(ACCEPT_ENCODING, HeaderValue::from_static("identity"));
let mut conditional = false;
if resume.is_none()
&& let Some(cond) = &outcome.cond
{
conditional = true;
match cond {
DownloadValidator::Etag(value) => {
request_headers.insert(IF_NONE_MATCH, HeaderValue::from_str(value)?);
}
DownloadValidator::LastModified { value, .. } => {
request_headers.insert(IF_MODIFIED_SINCE, HeaderValue::from_str(value)?);
}
}
}
if let Some((state, _)) = &resume {
request_headers.insert(RANGE, HeaderValue::from_str(&format!("bytes={offset}-"))?);
request_headers.insert(
IF_RANGE,
HeaderValue::from_str(state.validator.as_header_value())?,
);
}
let mut resp = self
.send_once_with_https_fallback_allow_416(
Method::GET,
url.clone(),
&request_headers,
"GET",
netrc_state,
)
.await?;
let response_filename = download_filename_hint(resp.url());
#[cfg(unix)]
let served_by = if github_relay_socket(&url).is_some() {
&url
} else {
resp.url()
};
#[cfg(not(unix))]
let served_by = resp.url();
progress.served_by(served_by);
if conditional && resp.status() == StatusCode::NOT_MODIFIED {
outcome.not_modified.store(true, Ordering::Relaxed);
return Ok(DownloadFileMetadata::default());
}
*outcome.validator.lock().unwrap() = (resp.status() != StatusCode::PARTIAL_CONTENT)
.then(|| response_validator(resp.headers()))
.flatten();
if resp.status() == StatusCode::RANGE_NOT_SATISFIABLE {
if let Some(ParsedContentRange::Unsatisfied { total }) = resp
.headers()
.get(CONTENT_RANGE)
.and_then(|value| value.to_str().ok())
.and_then(parse_content_range)
{
debug!("range request at offset {offset} was unsatisfied for {total} bytes");
}
partial.clear()?;
if offset > 0 && !restarted_without_resume {
restarted_without_resume = true;
continue;
}
resp.error_for_status_ref().map_err(redact_error_url)?;
}
let (write_offset, total_size, validator, resumable, effective_filename) =
if resp.status() == StatusCode::PARTIAL_CONTENT {
let Some((state, _)) = resume else {
partial.clear()?;
if !restarted_without_resume {
restarted_without_resume = true;
continue;
}
bail!("server returned partial content without a resumable request");
};
let content_range = resp
.headers()
.get(CONTENT_RANGE)
.and_then(|value| value.to_str().ok())
.and_then(parse_content_range);
let Some(ParsedContentRange::Bytes { start, end, total }) = content_range
else {
partial.clear()?;
if restarted_without_resume {
bail!("server returned an invalid Content-Range response");
}
restarted_without_resume = true;
continue;
};
let validator = response_validator(resp.headers());
let response_length_matches = resp
.content_length()
.is_none_or(|length| length == end - start + 1);
if start != offset
|| end + 1 != total
|| !response_length_matches
|| state.total_size.is_some_and(|expected| expected != total)
|| validator
.as_ref()
.is_some_and(|value| !value.matches(&state.validator))
{
partial.clear()?;
if restarted_without_resume {
bail!("server returned inconsistent partial content");
}
restarted_without_resume = true;
continue;
}
let effective_filename = state.effective_filename;
let validator = validator.unwrap_or(state.validator);
(
offset,
Some(total),
Some(validator),
true,
effective_filename,
)
} else {
partial.clear()?;
let total_size = resp.content_length();
let validator = response_validator(resp.headers());
let resumable = total_size.is_some() && validator.is_some();
(
0,
total_size,
validator.filter(|_| resumable),
resumable,
response_filename,
)
};
if let Some(max) = max_bytes
&& total_size.is_some_and(|total| total > max)
{
partial.clear()?;
return Err(too_large(max));
}
let state = validator.map(|validator| PartialDownloadState {
version: PARTIAL_DOWNLOAD_STATE_VERSION,
request_hash: partial.request_hash.clone(),
validator,
total_size,
effective_filename: effective_filename.clone(),
});
if let Some(state) = &state {
partial.write_state(state)?;
} else {
partial.remove_state_if_exists()?;
}
if let Some(pr) = pr {
if let Some(total_size) = total_size {
pr.set_length(total_size);
}
pr.set_position(write_offset);
}
let mut file = tokio::fs::OpenOptions::new()
.create(true)
.write(true)
.append(write_offset > 0)
.truncate(write_offset == 0)
.open(&partial.path)
.await?;
let mut over_limit = false;
let transfer = async {
let mut written = write_offset;
while let Some(chunk) = resp.chunk().await.map_err(redact_error_url)? {
if crate::cancel::is_cancelled() {
bail!("download cancelled by user");
}
written += chunk.len() as u64;
if let Some(max) = max_bytes
&& written > max
{
over_limit = true;
return Err(too_large(max));
}
file.write_all(&chunk).await?;
progress
.attempt
.fetch_add(chunk.len() as u64, Ordering::Relaxed);
if let Some(pr) = pr {
pr.inc(chunk.len() as u64);
}
}
Ok::<_, Report>(())
}
.await;
let persisted = async {
file.shutdown().await?;
file.sync_all().await?;
Ok::<_, Report>(())
}
.await;
if transfer.is_err()
&& (!resumable || over_limit)
&& let Err(err) = partial.clear()
{
debug!("failed to remove unvalidated partial download: {err:#}");
}
transfer?;
persisted?;
if let Some(total_size) = total_size {
let actual_size = tokio::fs::metadata(&partial.path).await?.len();
if actual_size != total_size {
return Err(DownloadSizeMismatch {
expected: total_size,
actual: actual_size,
}
.into());
}
}
return Ok(DownloadFileMetadata { effective_filename });
}
}
async fn send_with_https_fallback(
&self,
method: Method,
url: Url,
headers: &HeaderMap,
verb_label: &str,
) -> Result<Response> {
self.send_with_https_fallback_with_retries(
method,
url,
headers,
verb_label,
crate::network::http_retries(&Settings::get()),
true,
)
.await
}
async fn send_with_https_fallback_allow_error_status(
&self,
method: Method,
url: Url,
headers: &HeaderMap,
verb_label: &str,
) -> Result<Response> {
self.send_with_https_fallback_with_retries(
method,
url,
headers,
verb_label,
crate::network::http_retries(&Settings::get()),
false,
)
.await
}
async fn send_with_https_fallback_with_retries(
&self,
method: Method,
url: Url,
headers: &HeaderMap,
verb_label: &str,
retries: i64,
error_for_status: bool,
) -> Result<Response> {
let retry_state = new_retry_state(headers, false);
retry_async_with_retries(verb_label, &url, retries, || async {
let (headers, options) = attempt_options(&retry_state, error_for_status);
self.send_once_with_https_fallback_with_retry_headers(
method.clone(),
url.clone(),
&headers,
verb_label,
options,
)
.await
})
.await
}
async fn send_with_retries<T, F, Fut>(&self, req: RetryableRequest<'_>, read: F) -> Result<T>
where
F: Fn(Response) -> Fut,
Fut: std::future::Future<Output = Result<T>>,
{
self.send_with_retries_body_timeout(
req,
read,
crate::network::http_download_timeout(&Settings::get()),
)
.await
}
async fn send_with_retries_body_timeout<T, F, Fut>(
&self,
req: RetryableRequest<'_>,
read: F,
body_timeout: Duration,
) -> Result<T>
where
F: Fn(Response) -> Fut,
Fut: std::future::Future<Output = Result<T>>,
{
let retry_state = new_retry_state(req.headers, false);
retry_async_with_retries(req.verb_label, &req.url, req.retries, || async {
let (headers, options) = attempt_options(&retry_state, req.error_for_status);
let resp = self
.send_once_with_https_fallback_with_retry_headers(
req.method.clone(),
req.url.clone(),
&headers,
req.verb_label,
options,
)
.await?;
read_body_within(body_timeout, &req.url, read(resp)).await
})
.await
}
async fn send_once_with_https_fallback_allow_416(
&self,
method: Method,
url: Url,
headers: &HeaderMap,
verb_label: &str,
netrc_state: &RetryStateHandle,
) -> Result<Response> {
let use_netrc = netrc_state.lock().unwrap().use_netrc;
self.send_once_with_https_fallback_with_retry_headers(
method,
url,
headers,
verb_label,
SendOnceOptions::new(Some(netrc_state.clone()), use_netrc)
.allow_range_not_satisfiable(),
)
.await
}
async fn send_once_with_https_fallback_with_retry_headers(
&self,
method: Method,
url: Url,
headers: &HeaderMap,
verb_label: &str,
options: SendOnceOptions,
) -> Result<Response> {
match self
.send_once_with_retry_headers(
method.clone(),
url.clone(),
headers,
verb_label,
options.clone(),
)
.await
{
Ok(resp) => Ok(resp),
Err(err) if url.scheme() == "http" && is_unreachable(&err) => {
let mut url = url;
url.set_scheme("https").unwrap();
self.send_once_with_retry_headers(method, url, headers, verb_label, options)
.await
}
Err(err) => Err(err),
}
}
async fn send_once_with_retry_headers(
&self,
method: Method,
url: Url,
headers: &HeaderMap,
verb_label: &str,
options: SendOnceOptions,
) -> Result<Response> {
self.send_once_inner(method, url, headers, verb_label, options)
.await
}
async fn send_once_inner(
&self,
method: Method,
mut url: Url,
headers: &HeaderMap,
verb_label: &str,
options: SendOnceOptions,
) -> Result<Response> {
let original_url = url.clone();
let (headers, forward_rules) = split_forward_rules(headers);
let headers = &headers;
crate::resolve_progress::fetching(&url);
#[cfg(unix)]
if let Some(socket) = github_relay_socket(&url) {
let response = crate::github_relay::unix::request(
std::path::Path::new(&socket),
method,
&url,
headers,
)
.await?;
if options.error_for_status
&& is_github_forbidden(&url, &response)
&& is_github_rate_limited(&response)
{
let status_error = response
.error_for_status_ref()
.expect_err("403 response should be an error");
let status_error = redact_error_url(status_error);
let used_github_token = headers.contains_key(AUTHORIZATION);
let rate_limit = github_rate_limit_summary(&response);
let body = read_bounded_error_body(response, self.timeout).await;
return Err(github_forbidden_report(
status_error,
used_github_token,
rate_limit,
true,
&body,
));
}
return options.check_response(response);
}
apply_url_replacements(&mut url);
crate::resolve_progress::fetching(&url);
let host_key = http_host_key(&url);
if crate::network::prefer_offline(&Settings::get())
&& let Some(host) = &host_key
&& let Some(cause) = UNAVAILABLE_HTTP_HOSTS.lock().unwrap().get(host).cloned()
{
return Err(UnavailableHttpHost {
origin: host.clone(),
cause,
}
.into());
}
debug!("{} {}", verb_label, log_url(&url));
let mut final_headers = headers.clone();
clear_cross_host_credentials(&mut final_headers, &original_url, &mut url);
ensure_secure_replacement_credentials(&original_url, &url, &final_headers)?;
let mut netrc_fallback_used = false;
if options.use_netrc
&& !(options.netrc_replacement_only && url.host() == original_url.host())
{
let before = final_headers.get(AUTHORIZATION).cloned();
final_headers =
apply_netrc_credentials(final_headers, &original_url, &url, netrc_headers(&url));
netrc_fallback_used = url.host() == original_url.host()
&& final_headers.get(AUTHORIZATION) != before.as_ref();
}
let request_timeout = self.request_timeout();
let timeout = matches!(self.kind, ClientKind::Fetch).then_some(request_timeout);
let resp = match self
.send_scoped(&method, &url, &final_headers, &forward_rules, timeout)
.await
{
Ok(resp) => resp,
Err(SendError::Refused(message)) => return Err(eyre!(message)),
Err(SendError::Reqwest(err)) => {
let err = err.without_url();
if crate::network::prefer_offline(&Settings::get())
&& is_hard_connection_failure(&err)
&& let Some(host) = host_key
{
UNAVAILABLE_HTTP_HOSTS
.lock()
.unwrap()
.insert(host, err.to_string());
}
if err.is_timeout() {
let (setting, env_var) = match self.kind {
ClientKind::Http => ("http_timeout", "MISE_HTTP_TIMEOUT"),
ClientKind::Fetch => (
"fetch_remote_versions_timeout",
"MISE_FETCH_REMOTE_VERSIONS_TIMEOUT",
),
};
let hint = format!(
"HTTP timed out after {} for {} (change with `{}` or env `{}`).",
format_duration(request_timeout),
log_url(&url),
setting,
env_var
);
return Err(Report::new(err).wrap_err(hint));
}
return Err(err.into());
}
};
if *env::MISE_LOG_HTTP {
eprintln!("{} {} {}", verb_label, log_url(&url), resp.status());
}
debug!("{} {} {}", verb_label, log_url(&url), resp.status());
display_github_rate_limit(&resp);
if options.retry_github_oauth_401
&& let Some(stale_access_token) =
stale_github_oauth_unauthorized_token(&original_url, &final_headers, &resp)
&& let Some(host) = original_url.host_str()
{
match crate::github::oauth::refresh_cached_token_for_host(host, &stale_access_token)
.await
{
Ok(Some(token)) => {
let mut headers = headers.clone();
if let Ok(value) = HeaderValue::from_str(format!("Bearer {token}").as_str()) {
crate::github::remember_token_source(
host,
&token,
crate::github::TokenSource::GithubOauth,
);
headers.insert(AUTHORIZATION, value);
forward_rules.attach_to(&mut headers);
if let Some(retry_state) = &options.retry_state {
*retry_state.lock().unwrap() = RetryState {
headers: headers.clone(),
use_netrc: false,
netrc_replacement_only: false,
};
}
debug!(
"{} {} retrying with refreshed GitHub OAuth token after 401",
verb_label,
log_url(&url)
);
return Box::pin(self.send_once_inner(
method,
original_url,
&headers,
verb_label,
options.recursive_retry(),
))
.await;
} else {
debug!(
"refreshed GitHub OAuth token contains invalid header bytes; skipping retry"
);
}
}
Ok(None) => {}
Err(err) => {
crate::github::oauth::log_refresh_error(&err);
}
}
}
if netrc_fallback_used
&& options.error_for_status
&& resp.status() == StatusCode::UNAUTHORIZED
&& resp.url().origin() == url.origin()
{
let mut headers = headers.clone();
forward_rules.attach_to(&mut headers);
debug!(
"{} {} retrying without netrc credentials after 401",
verb_label,
log_url(&url)
);
if let Some(retry_state) = &options.retry_state {
*retry_state.lock().unwrap() = RetryState {
headers: headers.clone(),
use_netrc: false,
netrc_replacement_only: false,
};
}
return Box::pin(self.send_once_inner(
method,
original_url,
&headers,
verb_label,
options.recursive_retry(),
))
.await;
}
if let Some(token) = raw_content_token_to_drop(&url, resp.status(), &final_headers) {
let token_source = url
.host_str()
.and_then(|host| crate::github::token_source_for_token(host, token));
let mut headers = final_headers.clone();
headers.remove(AUTHORIZATION);
forward_rules.attach_to(&mut headers);
if let Some(retry_state) = &options.retry_state {
*retry_state.lock().unwrap() = RetryState {
headers: headers.clone(),
use_netrc: false,
netrc_replacement_only: false,
};
}
debug!(
"{} {} retrying without GitHub auth after 404",
verb_label,
log_url(&url)
);
let retried = Box::pin(self.send_once_inner(
method,
original_url,
&headers,
verb_label,
options.recursive_retry(),
))
.await?;
if retried.status().is_success() {
warn_once!("{}", rejected_raw_token_warning(token_source.as_ref()));
}
return Ok(retried);
}
if options.error_for_status && is_github_unauthorized(&url, &resp) {
let status_error = resp
.error_for_status_ref()
.expect_err("401 response should be an error");
let status_error = redact_error_url(status_error);
let used_github_token = final_headers.contains_key(AUTHORIZATION);
let token_source = final_headers
.get(AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "))
.zip(original_url.host_str())
.and_then(|(token, host)| crate::github::token_source_for_token(host, token));
let body = read_bounded_error_body(resp, self.timeout).await;
return Err(github_unauthorized_report(
status_error,
used_github_token,
token_source.as_ref(),
&body,
));
}
if options.error_for_status && is_github_forbidden(&url, &resp) {
let status = resp.status();
let status_error = resp
.error_for_status_ref()
.expect_err("403 response should be an error");
let status_error = redact_error_url(status_error);
let used_github_token = final_headers.contains_key(AUTHORIZATION);
let rate_limit = github_rate_limit_summary(&resp);
let rate_limited = is_github_rate_limited(&resp);
let body = read_bounded_error_body(resp, self.timeout).await;
if used_github_token
&& url.host_str() == Some("api.github.com")
&& body.contains("IP allow list")
{
let mut headers = final_headers;
headers.remove(AUTHORIZATION);
forward_rules.attach_to(&mut headers);
debug!(
"{} {} retrying without GitHub auth after {}",
verb_label,
log_url(&url),
status
);
return Box::pin(self.send_once_inner(
method,
original_url,
&headers,
verb_label,
options.recursive_retry(),
))
.await;
}
return Err(github_forbidden_report(
status_error,
used_github_token,
rate_limit,
rate_limited,
&body,
));
}
options.check_response(resp)
}
}
pub struct TextRequest<'a> {
client: &'a Client,
url: Result<Url, String>,
extra_headers: HeaderMap,
retries: i64,
allow_html: bool,
}
impl TextRequest<'_> {
pub fn headers(mut self, headers: &HeaderMap) -> Self {
self.extra_headers.extend(headers.clone());
self
}
pub fn retries(mut self, retries: i64) -> Self {
self.retries = retries;
self
}
pub fn allow_html(mut self) -> Self {
self.allow_html = true;
self
}
pub async fn send(mut self) -> Result<String> {
ensure!(
!crate::network::offline(&Settings::get()),
"offline mode is enabled"
);
let mut url = self.url.clone().map_err(|e| eyre!(e))?;
let mut headers = host_auth_headers(&url)?;
headers.extend(self.extra_headers.clone());
let text = self
.client
.send_with_retries(
RetryableRequest {
method: Method::GET,
url: url.clone(),
headers: &headers,
verb_label: "GET",
retries: self.retries,
error_for_status: true,
},
|resp| async move {
Ok(buffer_body(resp)
.await?
.text()
.await
.map_err(redact_error_url)?)
},
)
.await?;
if !self.allow_html && text.starts_with("<!DOCTYPE html>") {
if url.scheme() == "http" {
url.set_scheme("https").unwrap();
self.url = Ok(url);
return Box::pin(self.send()).await;
}
bail!("Got HTML instead of text from {}", log_url(&url));
}
Ok(text)
}
}
fn is_github_forbidden(url: &Url, resp: &Response) -> bool {
resp.status() == StatusCode::FORBIDDEN && crate::github::is_github_api_url(url)
}
fn is_github_unauthorized(url: &Url, resp: &Response) -> bool {
resp.status() == StatusCode::UNAUTHORIZED && crate::github::is_github_api_url(url)
}
fn ensure_download_within(path: &Path, url: &Url, max_bytes: u64) -> Result<()> {
if std::fs::metadata(path)?.len() > max_bytes {
let _ = std::fs::remove_file(path);
bail!(
"download from {} is larger than {}",
log_url(url),
bytesize::ByteSize::b(max_bytes).display().iec()
);
}
Ok(())
}
async fn read_body_within<T>(
timeout: Duration,
url: &Url,
read: impl std::future::Future<Output = Result<T>>,
) -> Result<T> {
match tokio::time::timeout(timeout, read).await {
Ok(result) => result,
Err(_) => Err(BodyTimedOut {
timeout,
url: log_url(url).into_owned(),
}
.into()),
}
}
#[derive(Debug, thiserror::Error)]
#[error(
"HTTP response body timed out after {} for {url} (change with `http_download_timeout` or env `MISE_HTTP_DOWNLOAD_TIMEOUT`)",
format_duration(*timeout)
)]
pub struct BodyTimedOut {
timeout: Duration,
url: String,
}
pub const MAX_BODY_BYTES: usize = if cfg!(test) {
1024 * 1024
} else {
128 * 1024 * 1024
};
pub async fn buffer_body(resp: Response) -> Result<Response> {
buffer_body_with_limit(resp, MAX_BODY_BYTES).await
}
pub async fn buffer_body_with_limit(mut resp: Response, limit: usize) -> Result<Response> {
let too_large = |url: &Url| {
eyre!(
"response body from {} is larger than {}",
log_url(url),
bytesize::ByteSize::b(limit as u64).display().iec()
)
};
if resp
.content_length()
.is_some_and(|length| length > limit as u64)
{
return Err(too_large(resp.url()));
}
let url = resp.url().clone();
let read = async {
let mut bytes = Vec::new();
while let Some(chunk) = resp.chunk().await.map_err(redact_error_url)? {
if bytes.len() + chunk.len() > limit {
return Err(too_large(resp.url()));
}
bytes.extend_from_slice(&chunk);
}
Ok(bytes)
};
let bytes = read_body_within(
crate::network::http_download_timeout(&Settings::get()),
&url,
read,
)
.await?;
let mut buffered = ::http::Response::builder()
.status(resp.status())
.version(resp.version())
.url(resp.url().clone())
.body(bytes)?;
*buffered.headers_mut() = std::mem::take(resp.headers_mut());
Ok(buffered.into())
}
const MAX_ERROR_BODY_BYTES: usize = 64 * 1024;
pub async fn read_bounded_error_body(resp: Response, deadline: Duration) -> String {
let read = async move {
let mut resp = resp;
let mut bytes = Vec::new();
while let Ok(Some(chunk)) = resp.chunk().await {
let remaining = MAX_ERROR_BODY_BYTES.saturating_sub(bytes.len());
if remaining == 0 {
break;
}
bytes.extend_from_slice(&chunk[..chunk.len().min(remaining)]);
}
String::from_utf8_lossy(&bytes).to_string()
};
tokio::time::timeout(deadline, read)
.await
.unwrap_or_default()
}
fn raw_content_token_to_drop<'a>(
url: &Url,
status: StatusCode,
headers: &'a HeaderMap,
) -> Option<&'a str> {
if status != StatusCode::NOT_FOUND || url.host_str() != Some("raw.githubusercontent.com") {
return None;
}
headers
.get(AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "))
}
fn rejected_raw_token_warning(token_source: Option<&crate::github::TokenSource>) -> String {
let source = match token_source {
Some(crate::github::TokenSource::EnvVar(var)) => format!("token in `{var}`"),
Some(source) => format!("token from {source}"),
None => "configured GitHub token".to_string(),
};
format!(
"GitHub did not accept the {source}: raw.githubusercontent.com answered 404 until mise \
retried without it. Check that it is valid and not expired with `mise token github` — \
see https://mise.jdx.dev/dev-tools/github-tokens.html"
)
}
fn github_unauthorized_report(
status_error: reqwest::Error,
used_github_token: bool,
token_source: Option<&crate::github::TokenSource>,
body: &str,
) -> Report {
let auth = if !used_github_token {
"no".to_string()
} else {
token_source
.map(|source| format!("yes (token from {source})"))
.unwrap_or_else(|| "yes".to_string())
};
let body = format_response_body(body);
let hint = if used_github_token {
let source = match token_source {
Some(crate::github::TokenSource::EnvVar(var)) => format!("token in `{var}`"),
Some(source) => format!("token from {source}"),
None => "configured GitHub token".to_string(),
};
format!(
"\nhint: the {source} was rejected by GitHub (401 Unauthorized). Verify it is a \
valid, non-expired token for this host with the required scopes — see \
https://mise.jdx.dev/dev-tools/github-tokens.html"
)
} else {
String::new()
};
eyre!("{status_error}\ngithub auth: {auth}\ngithub response: {body}{hint}")
}
fn github_forbidden_report(
status_error: reqwest::Error,
used_github_token: bool,
rate_limit: Option<String>,
rate_limited: bool,
body: &str,
) -> Report {
let token_status = if used_github_token { "yes" } else { "no" };
let rate_limit = rate_limit
.map(|summary| format!("\ngithub rate limit: {summary}"))
.unwrap_or_default();
let body = format_response_body(body);
let message =
format!("{status_error}\ngithub auth: {token_status}{rate_limit}\ngithub response: {body}");
if rate_limited {
return GithubRateLimited(message).into();
}
eyre!("{message}")
}
fn is_github_rate_limited(resp: &Response) -> bool {
let headers = resp.headers();
let exhausted = headers
.get("x-ratelimit-remaining")
.and_then(|h| h.to_str().ok())
.is_some_and(|remaining| remaining == "0");
exhausted || headers.contains_key("retry-after")
}
fn format_response_body(body: &str) -> String {
const MAX_BODY_CHARS: usize = 4096;
if body.trim().is_empty() {
return "<empty>".to_string();
}
let mut chars = body.chars();
let mut formatted: String = chars.by_ref().take(MAX_BODY_CHARS).collect();
if chars.next().is_some() {
formatted.push_str("\n<truncated>");
}
formatted
}
fn github_rate_limit_summary(resp: &Response) -> Option<String> {
let headers = resp.headers();
let limit = headers
.get("x-ratelimit-limit")
.and_then(|h| h.to_str().ok());
let remaining = headers
.get("x-ratelimit-remaining")
.and_then(|h| h.to_str().ok());
let resource = headers
.get("x-ratelimit-resource")
.and_then(|h| h.to_str().ok());
let reset = headers
.get("x-ratelimit-reset")
.and_then(|h| h.to_str().ok());
if limit.is_none() && remaining.is_none() && resource.is_none() && reset.is_none() {
return None;
}
Some(format!(
"{}/{}{}{}",
remaining.unwrap_or("?"),
limit.unwrap_or("?"),
resource
.map(|resource| format!(" ({resource})"))
.unwrap_or_default(),
reset
.map(|reset| format!(", resets at {reset}"))
.unwrap_or_default()
))
}
fn stale_github_oauth_unauthorized_token(
url: &Url,
headers: &HeaderMap,
resp: &Response,
) -> Option<String> {
if resp.status() != StatusCode::UNAUTHORIZED || !crate::github::is_github_api_url(url) {
return None;
}
let host = url.host_str()?;
let token = crate::github::oauth::cached_access_token_for_host(host)?;
let header_token = headers
.get(AUTHORIZATION)
.and_then(|header| header.to_str().ok())
.and_then(|header| header.strip_prefix("Bearer "))?;
if header_token == token {
Some(header_token.to_string())
} else {
None
}
}
pub fn error_code(e: &Report) -> Option<u16> {
if let Some(status) = e
.downcast_ref::<reqwest::Error>()
.and_then(reqwest::Error::status)
{
return Some(status.as_u16());
}
if e.to_string().contains("404") {
return Some(404);
}
None
}
pub fn with_host_auth(url: &Url, headers: &HeaderMap) -> Result<HeaderMap> {
let mut merged = host_auth_headers(url)?;
merged.extend(headers.clone());
Ok(merged)
}
pub fn host_auth_headers(url: &Url) -> Result<HeaderMap> {
if crate::github::is_github_api_url(url) || crate::github::is_github_raw_content_url(url) {
return crate::github::get_headers(url.as_str(), crate::github::API_URL);
}
Ok(HeaderMap::new())
}
fn netrc_should_apply(host_changed: bool, has_existing_auth: bool) -> bool {
host_changed || !has_existing_auth
}
const MAX_MANUAL_REDIRECTS: usize = 10;
enum SendError {
Reqwest(reqwest::Error),
Refused(String),
}
impl From<reqwest::Error> for SendError {
fn from(err: reqwest::Error) -> Self {
Self::Reqwest(err)
}
}
fn has_unscoped_credential(headers: &HeaderMap) -> bool {
headers.iter().any(|(name, value)| {
is_credential_header(name, value)
&& name != AUTHORIZATION
&& name != COOKIE
&& name != PROXY_AUTHORIZATION
})
}
const FORWARD_RULE_PREFIX: &str = "x-mise-forward-";
pub fn is_reserved_header_name(name: &str) -> bool {
name.to_ascii_lowercase().starts_with(FORWARD_RULE_PREFIX)
}
pub fn is_valid_forward_host(pattern: &str) -> bool {
let host = pattern.strip_prefix("*.").unwrap_or(pattern);
!host.is_empty()
&& !host.contains('*')
&& host
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.')
&& !host.starts_with('.')
&& !host.ends_with('.')
}
pub fn forward_rule_header(
name: &HeaderName,
hosts: &[String],
) -> Result<(HeaderName, HeaderValue)> {
for host in hosts {
ensure!(is_valid_forward_host(host), "invalid forward host `{host}`");
}
Ok((
HeaderName::from_bytes(format!("{FORWARD_RULE_PREFIX}{}", name.as_str()).as_bytes())?,
HeaderValue::from_str(&hosts.join(","))?,
))
}
#[derive(Debug, Default)]
struct ForwardRules(HashMap<HeaderName, Vec<String>>);
impl ForwardRules {
fn attach_to(&self, headers: &mut HeaderMap) {
for (name, hosts) in &self.0 {
if let Ok((rule_name, rule_value)) = forward_rule_header(name, hosts) {
headers.insert(rule_name, rule_value);
}
}
}
fn applies_to(&self, headers: &HeaderMap) -> bool {
self.0.keys().any(|name| headers.contains_key(name))
}
fn retain_for(&self, headers: &mut HeaderMap, previous: &Url, next: &Url) {
let host = next.host_str().unwrap_or_default();
let secure = next.scheme() == "https" || previous.scheme() == "http";
let dropped = headers
.iter()
.filter(|(name, value)| is_credential_header(name, value))
.filter(|(name, _)| {
!(secure
&& self
.0
.get(*name)
.is_some_and(|patterns| host_matches_any(patterns, host)))
})
.map(|(name, _)| name.clone())
.collect::<Vec<_>>();
for name in dropped {
headers.remove(name);
}
}
}
fn host_matches_any(patterns: &[String], host: &str) -> bool {
let host = host.to_ascii_lowercase();
patterns.iter().any(|pattern| {
let pattern = pattern.to_ascii_lowercase();
match pattern.strip_prefix("*.") {
Some(suffix) => host
.strip_suffix(suffix)
.is_some_and(|rest| rest.ends_with('.') && rest.len() > 1),
None => pattern == host,
}
})
}
fn split_forward_rules(headers: &HeaderMap) -> (HeaderMap, ForwardRules) {
let mut real = HeaderMap::new();
let mut rules = HashMap::new();
for (name, value) in headers {
if let Some(target) = name.as_str().strip_prefix(FORWARD_RULE_PREFIX) {
if let (Ok(target), Ok(value)) =
(HeaderName::from_bytes(target.as_bytes()), value.to_str())
{
rules.insert(
target,
value.split(',').map(str::to_string).collect::<Vec<_>>(),
);
}
} else {
real.append(name.clone(), value.clone());
}
}
(real, ForwardRules(rules))
}
fn is_credential_header(name: &HeaderName, value: &HeaderValue) -> bool {
if value.is_sensitive()
|| name == AUTHORIZATION
|| name == PROXY_AUTHORIZATION
|| name == COOKIE
{
return true;
}
let name = name.as_str();
name == "api-key"
|| name == "x-api-key"
|| name.ends_with("-api-key")
|| name.contains("token")
|| name.contains("secret")
|| name.contains("credential")
}
pub fn clear_cross_host_credentials(headers: &mut HeaderMap, original_url: &Url, url: &mut Url) {
if url.host() == original_url.host() {
return;
}
let credential_headers = headers
.iter()
.filter(|(name, value)| is_credential_header(name, value))
.map(|(name, _)| name.clone())
.collect::<Vec<_>>();
for name in credential_headers {
headers.remove(name);
}
let inherited_userinfo = (!original_url.username().is_empty()
|| original_url.password().is_some())
&& url.username() == original_url.username()
&& url.password() == original_url.password();
if inherited_userinfo {
url.set_password(None)
.expect("HTTP URLs support clearing passwords");
url.set_username("")
.expect("HTTP URLs support clearing usernames");
}
}
fn apply_netrc_credentials(
mut final_headers: HeaderMap,
original_url: &Url,
url: &Url,
netrc: HeaderMap,
) -> HeaderMap {
let host_changed = url.host() != original_url.host();
let has_auth = final_headers.contains_key(AUTHORIZATION);
if netrc_should_apply(host_changed, has_auth) {
for (name, value) in netrc {
if let Some(name) = name {
final_headers.insert(name, value);
}
}
}
final_headers
}
pub fn ensure_secure_replacement_credentials(
original_url: &Url,
url: &Url,
headers: &HeaderMap,
) -> Result<()> {
let has_credentials = headers
.iter()
.any(|(name, value)| is_credential_header(name, value));
ensure_secure_url_replacement(original_url, url, has_credentials)
}
pub fn ensure_secure_url_replacement(
original_url: &Url,
url: &Url,
has_credentials: bool,
) -> Result<()> {
let downgraded = original_url.scheme() == "https" && url.scheme() == "http";
let has_credentials = has_credentials || !url.username().is_empty() || url.password().is_some();
ensure!(
!downgraded || !has_credentials,
"refusing to send credentials over an HTTPS-to-HTTP URL replacement"
);
Ok(())
}
pub fn netrc_headers(url: &Url) -> HeaderMap {
let mut headers = HeaderMap::new();
if crate::untrusted_hosts::netrc_denied(url) {
return headers;
}
if let Some(host) = url.host_str()
&& let Some((login, password)) = netrc::get_credentials(host)
{
let credentials = BASE64_STANDARD.encode(format!("{login}:{password}"));
if let Ok(value) = HeaderValue::from_str(&format!("Basic {credentials}")) {
headers.insert(reqwest::header::AUTHORIZATION, value);
}
}
headers
}
pub fn resolve_pagination_url(current: &str, next: &str) -> Result<String> {
if next.starts_with("http://") || next.starts_with("https://") {
return Ok(next.to_string());
}
let base = url::Url::parse(current)
.wrap_err_with(|| format!("invalid pagination base URL: {current}"))?;
if next.starts_with('/') {
return Ok(format!("{}{next}", base.origin().ascii_serialization()));
}
base.join(next)
.map(|u| u.to_string())
.wrap_err_with(|| format!("invalid pagination URL: {next}"))
}
#[cfg(unix)]
fn github_relay_socket(url: &Url) -> Option<std::ffi::OsString> {
if matches!(url.host_str(), Some("github.com" | "api.github.com")) {
std::env::var_os("MISE_GITHUB_RELAY_SOCKET")
} else {
None
}
}
pub fn apply_url_replacements(url: &mut Url) {
let settings = Settings::get();
if let Some(replacements) = &settings.url_replacements {
let url_string = url.to_string();
for (pattern, replacement) in replacements {
if let Some(pattern_without_prefix) = pattern.strip_prefix("regex:") {
if let Ok(regex) = Regex::new(pattern_without_prefix) {
let new_url_string = regex.replace(&url_string, replacement.as_str());
if new_url_string != url_string
&& let Ok(new_url) = new_url_string.parse()
{
*url = new_url;
trace!(
"Replaced URL using regex '{}': {} -> {}",
pattern_without_prefix,
redact_url_userinfo(&url_string),
log_url(url)
);
return; }
} else {
warn!(
"Invalid regex pattern in URL replacement: {}",
pattern_without_prefix
);
}
} else {
if url_string.contains(pattern) {
let new_url_string = url_string.replace(pattern, replacement);
if new_url_string != url_string
&& let Ok(new_url) = new_url_string.parse()
{
*url = new_url;
trace!(
"Replaced URL using string replacement '{}': {} -> {}",
pattern,
redact_url_userinfo(&url_string),
log_url(url)
);
return; }
}
}
}
}
}
fn log_url(url: &Url) -> std::borrow::Cow<'_, str> {
match url.query() {
Some(query) if redact_query(query) != query => {
let mut url = url.clone();
url.set_query(Some(&redact_query(query)));
redact_url_userinfo(url.as_str()).into_owned().into()
}
_ => redact_url_userinfo(url.as_str()),
}
}
fn redact_query(query: &str) -> String {
query
.split('&')
.map(|pair| {
let (name, value) = match pair.split_once('=') {
Some((name, value)) => (Some(name), value),
None => (None, pair),
};
let paging = name.is_some_and(|name| matches!(name, "page" | "per_page" | "limit"));
let harmless = value.is_empty()
|| (paging && value.len() <= 6 && value.bytes().all(|b| b.is_ascii_digit()));
match (name, harmless) {
(_, true) => pair.to_string(),
(Some(name), false) => format!("{name}=[redacted]"),
(None, false) => "[redacted]".to_string(),
}
})
.collect::<Vec<_>>()
.join("&")
}
fn redact_error_url(mut err: reqwest::Error) -> reqwest::Error {
if let Some(url) = err.url_mut() {
let _ = url.set_username("");
let _ = url.set_password(None);
if let Some(query) = url.query().map(redact_query) {
url.set_query(Some(&query));
}
}
err
}
fn display_github_rate_limit(resp: &Response) {
let status = resp.status().as_u16();
if status == 403 || status == 429 {
let remaining = resp
.headers()
.get("x-ratelimit-remaining")
.and_then(|r| r.to_str().ok());
if remaining.is_some_and(|r| r == "0") {
if let Some(reset_time) = resp
.headers()
.get("x-ratelimit-reset")
.and_then(|h| h.to_str().ok())
.and_then(|s| s.parse::<i64>().ok())
.and_then(|ts| chrono::DateTime::from_timestamp(ts, 0))
{
warn!(
"GitHub rate limit exceeded. Resets at {}",
reset_time.with_timezone(&chrono::Local)
);
}
return;
}
if let Some(retry_after) = resp
.headers()
.get("retry-after")
.and_then(|h| h.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
{
warn!(
"GitHub rate limit exceeded. Retry after {} seconds",
retry_after
);
}
}
}
pub fn default_backoff_strategy(retries: i64) -> impl Iterator<Item = Duration> {
let schedule = if crate::testing::in_tests() {
[2u64, 10, 40, 150]
} else {
[200u64, 1_000, 4_000, 15_000]
};
schedule
.into_iter()
.chain(std::iter::repeat(15_000))
.map(Duration::from_millis)
.map(equal_jitter)
.take(retries.max(0) as usize)
}
fn equal_jitter(d: Duration) -> Duration {
let factor = 0.5 + rand::random::<f64>() * 0.5;
Duration::from_secs_f64(d.as_secs_f64() * factor)
}
fn is_connection_error(err: &Report) -> bool {
err.chain().any(|e| {
let Some(reqwest_err) = e.downcast_ref::<reqwest::Error>() else {
return false;
};
(reqwest_err.is_connect() || reqwest_err.is_timeout()) && reqwest_err.status().is_none()
})
}
pub fn is_unreachable(err: &Report) -> bool {
is_connection_error(err)
|| is_unavailable_http_host_error(err)
|| err.chain().any(|err| {
err.downcast_ref::<CachedFailure>()
.is_some_and(|failure| failure.unreachable)
})
}
fn http_host_key(url: &Url) -> Option<String> {
let host = url.host_str()?;
let port = url.port_or_known_default()?;
Some(format!("{}://{host}:{port}", url.scheme()))
}
fn is_unavailable_http_host_error(err: &Report) -> bool {
err.chain()
.any(|err| err.downcast_ref::<UnavailableHttpHost>().is_some())
}
fn is_dns_error(err: &(dyn std::error::Error + 'static)) -> bool {
let mut current = Some(err);
while let Some(source) = current {
if source.to_string() == "dns error" {
return true;
}
current = source.source();
}
false
}
fn is_hard_connection_failure(err: &reqwest::Error) -> bool {
is_dns_error(err) || (err.is_connect() && !err.is_timeout())
}
fn is_serde_error(err: &(dyn std::error::Error + 'static)) -> bool {
let mut cur = err.source();
while let Some(e) = cur {
if e.is::<serde_json::Error>() {
return true;
}
cur = e.source();
}
false
}
pub fn is_transient(err: &Report) -> bool {
if is_dns_error(err.as_ref()) {
return false;
}
if err
.downcast_ref::<RetryAfter>()
.is_some_and(|r| r.wait > MAX_RETRY_AFTER)
{
return false;
}
err.chain().any(|e| {
if e.downcast_ref::<DownloadSizeMismatch>().is_some() {
return true;
}
if e.downcast_ref::<std::io::Error>()
.is_some_and(|err| err.kind() == std::io::ErrorKind::TimedOut)
{
return true;
}
if e.downcast_ref::<GithubRateLimited>().is_some() {
return true;
}
let Some(reqwest_err) = e.downcast_ref::<reqwest::Error>() else {
return false;
};
if reqwest_err.is_timeout() || reqwest_err.is_connect() || reqwest_err.is_body() {
return true;
}
if reqwest_err.is_decode() && !is_serde_error(reqwest_err) {
return true;
}
if reqwest_err.is_request() && reqwest_err.status().is_none() {
return true;
}
if let Some(status) = reqwest_err.status() {
let code = status.as_u16();
return code == 408 || code == 429 || (500..600).contains(&code);
}
false
})
}
pub async fn retry_async<F, Fut, T>(verb_label: &str, url: &Url, f: F) -> Result<T>
where
F: FnMut() -> Fut,
Fut: std::future::Future<Output = Result<T>>,
{
retry_async_with_retries(verb_label, url, Settings::get().http_retries, f).await
}
pub async fn retry_async_with_retries<F, Fut, T>(
verb_label: &str,
url: &Url,
retries: i64,
mut f: F,
) -> Result<T>
where
F: FnMut() -> Fut,
Fut: std::future::Future<Output = Result<T>>,
{
let mut backoff = default_backoff_strategy(retries);
let mut attempt: usize = 1;
loop {
let started_at = Instant::now();
match f().await {
Ok(value) => return Ok(value),
Err(err) => {
if !is_transient(&err) {
return Err(err);
}
let Some(delay) = backoff.next() else {
return Err(err);
};
let delay = retry_delay(delay, &err);
warn!(
"HTTP {} {} attempt {} failed after {} (transient): {}; retrying in {:?}",
verb_label,
log_url(url),
attempt,
format_duration(started_at.elapsed()),
err,
delay
);
crate::resolve_progress::retrying(url, attempt + 1, delay);
tokio::time::sleep(delay).await;
attempt += 1;
}
}
}
}
const SLOW_DOWNLOAD_BYTES_PER_SEC: u64 = 16 * 1024;
const SLOW_DOWNLOAD_WINDOW: Duration = Duration::from_secs(60);
const SLOW_DOWNLOAD_SAMPLE_INTERVAL: Duration = Duration::from_secs(5);
#[derive(Default)]
struct DownloadProgress {
attempt: AtomicU64,
earlier_attempts: AtomicU64,
served_by: Mutex<Option<ServedBy>>,
}
#[derive(Clone, Debug, PartialEq)]
struct ServedBy {
host: String,
since: Instant,
total_at_start: u64,
}
impl DownloadProgress {
fn served_by(&self, url: &Url) {
let Some(host) = url.host_str() else {
return;
};
let mut served_by = self.served_by.lock().unwrap();
if served_by.as_ref().is_none_or(|s| s.host != host) {
*served_by = Some(ServedBy {
host: host.to_string(),
since: Instant::now(),
total_at_start: self.total(),
});
}
}
fn start_attempt(&self) {
self.earlier_attempts
.fetch_add(self.attempt.swap(0, Ordering::Relaxed), Ordering::Relaxed);
}
fn total(&self) -> u64 {
self.earlier_attempts.load(Ordering::Relaxed) + self.attempt.load(Ordering::Relaxed)
}
}
struct SlowDownloadDetector {
window_start: Instant,
window_start_total: u64,
}
impl SlowDownloadDetector {
fn new(now: Instant) -> Self {
Self {
window_start: now,
window_start_total: 0,
}
}
fn restart(&mut self, now: Instant, total: u64) {
self.window_start = now;
self.window_start_total = total;
}
fn observe(&mut self, now: Instant, total: u64) -> Option<u64> {
let elapsed = now.duration_since(self.window_start);
if elapsed < SLOW_DOWNLOAD_WINDOW {
return None;
}
let bytes = total.saturating_sub(self.window_start_total);
self.window_start = now;
self.window_start_total = total;
let rate = (bytes as f64 / elapsed.as_secs_f64()) as u64;
(rate < SLOW_DOWNLOAD_BYTES_PER_SEC).then_some(rate)
}
}
struct SlowDownloadWatch {
detector: SlowDownloadDetector,
host: Option<String>,
}
impl SlowDownloadWatch {
fn new(now: Instant) -> Self {
Self {
detector: SlowDownloadDetector::new(now),
host: None,
}
}
fn sample(
&mut self,
now: Instant,
total: u64,
served_by: Option<&ServedBy>,
) -> Option<(Option<String>, u64)> {
if let Some(served) = served_by
&& self.host.as_deref() != Some(served.host.as_str())
{
let previous = self.host.replace(served.host.clone());
let slow = self.detector.observe(served.since, served.total_at_start);
self.detector.restart(served.since, served.total_at_start);
if let Some(rate) = slow {
return Some((previous, rate));
}
}
self.detector
.observe(now, total)
.map(|rate| (self.host.clone(), rate))
}
}
async fn warn_when_download_is_slow(
url: &Url,
progress: &DownloadProgress,
) -> std::convert::Infallible {
let mut watch = SlowDownloadWatch::new(Instant::now());
let mut ticks = tokio::time::interval(SLOW_DOWNLOAD_SAMPLE_INTERVAL);
ticks.tick().await;
let (host, rate) = loop {
ticks.tick().await;
let served_by = progress.served_by.lock().unwrap().clone();
if let Some(sample) = watch.sample(Instant::now(), progress.total(), served_by.as_ref()) {
break sample;
}
};
let host = host
.or_else(|| url.host_str().map(str::to_string))
.unwrap_or_else(|| "the server".to_string());
warn!(
"download from {} is very slow ({}/s over the last minute). \
mise keeps trying until `http_download_timeout` runs out; \
if the host is throttling this connection, switching to a mirror may help",
host,
bytesize::ByteSize::b(rate).display().iec(),
);
std::future::pending().await
}
#[cfg(test)]
mod tests;