use std::io::Read;
use std::path::Path;
use flate2::read::GzDecoder;
use tar::EntryType;
use super::{Error, File};
pub(super) fn ensure_archive(path: &Path, bytes: &[u8]) -> Result<(), Error> {
if bytes.starts_with(&[0x1f, 0x8b, 0x08]) {
return Ok(());
}
let name = path.display();
let ext = path.extension().and_then(|e| e.to_str());
if matches!(ext, Some("yml" | "yaml")) {
return Err(Error::NotAnArchive(format!(
"file '{name}' seems to be a YAML file, but expected a gzipped archive"
)));
}
let head = &bytes[..bytes.len().min(512)];
let text = head
.iter()
.all(|b| matches!(b, b'\t' | b'\n' | b'\r' | 0x0c | 0x20..=0x7e | 0x80..=0xff));
let kind = if text {
"text/plain; charset=utf-8"
} else {
"application/octet-stream"
};
Err(Error::NotAnArchive(format!(
"file '{name}' does not appear to be a gzipped archive; got '{kind}'"
)))
}
pub(super) fn trim_bom(mut data: Vec<u8>) -> Vec<u8> {
if data.starts_with(&[0xef, 0xbb, 0xbf]) {
data.drain(..3);
}
data
}
fn clean_path(path: &str) -> String {
let rooted = path.starts_with('/');
let mut parts: Vec<&str> = Vec::new();
for part in path.split('/') {
match part {
"" | "." => {}
".." => {
if parts.last().is_some_and(|p| *p != "..") {
parts.pop();
} else if !rooted {
parts.push("..");
}
}
other => parts.push(other),
}
}
let joined = parts.join("/");
match (rooted, joined.is_empty()) {
(true, _) => format!("/{joined}"),
(false, true) => ".".into(),
(false, false) => joined,
}
}
pub(super) fn read_archive(bytes: &[u8], budget: i64) -> Result<Vec<File>, Error> {
let corrupt = |e: std::io::Error| Error::Archive(format!("unable to load chart archive: {e}"));
if !bytes.starts_with(&[0x1f, 0x8b]) {
return Err(Error::NotAnArchive(
"stream does not appear to be a valid chart file (details: gzip: invalid header)"
.into(),
));
}
let mut archive = tar::Archive::new(GzDecoder::new(bytes));
let mut remaining = budget;
let mut files = Vec::new();
for entry in archive.entries().map_err(corrupt)? {
let mut entry = entry.map_err(corrupt)?;
let kind = entry.header().entry_type();
let raw_name = String::from_utf8_lossy(&entry.path_bytes()).into_owned();
if kind.is_dir()
|| (kind == EntryType::Regular && raw_name.ends_with('/'))
|| matches!(kind, EntryType::XGlobalHeader | EntryType::XHeader)
{
continue;
}
let delimiter = if raw_name.contains('\\') { '\\' } else { '/' };
let parts: Vec<&str> = raw_name.split(delimiter).collect();
let joined = parts[1..].join(&delimiter.to_string());
let unslashed = joined.replace(delimiter, "/");
if unslashed.starts_with('/') {
return Err(Error::Archive(
"chart illegally contains absolute paths".into(),
));
}
let name = clean_path(&unslashed);
if name == "." {
return Err(Error::Archive(format!(
"chart illegally contains content outside the base directory: {raw_name:?}"
)));
}
if name.starts_with("..") {
return Err(Error::Archive(
"chart illegally references parent directory".into(),
));
}
if is_drive_path(&name) {
return Err(Error::Archive(
"chart contains illegally named files".into(),
));
}
if parts[0] == "Chart.yaml" {
return Err(Error::Archive("chart yaml not in base directory".into()));
}
let size = i64::try_from(entry.size()).unwrap_or(i64::MAX);
if size > remaining {
return Err(Error::TooLarge { limit: budget });
}
let mut data = Vec::new();
let written = entry
.by_ref()
.take(u64::try_from(remaining).unwrap_or(0))
.read_to_end(&mut data)
.map_err(corrupt)?;
let written = i64::try_from(written).unwrap_or(i64::MAX);
remaining -= written;
if written < size || remaining <= 0 {
return Err(Error::TooLarge { limit: budget });
}
files.push(File {
name,
data: trim_bom(data),
mod_time: None,
});
}
if files.is_empty() {
return Err(Error::EmptyArchive);
}
Ok(files)
}
fn is_drive_path(name: &str) -> bool {
let bytes = name.as_bytes();
bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && bytes[2] == b'/'
}