use libloading::Library;
use std::path::Path;
use tokio::fs;
use super::types::ValidationResult;
use super::PackageValidator;
impl PackageValidator {
pub(super) async fn validate_file_format(
&self,
package_path: &Path,
result: &mut ValidationResult,
) {
match fs::read(package_path).await {
Ok(data) if data.len() >= 4 => {
let is_valid_format = if &data[0..4] == b"\x7fELF" {
if data.len() >= 5 {
match data[4] {
1 => result.compatibility.architecture = "32-bit".to_string(),
2 => result.compatibility.architecture = "64-bit".to_string(),
_ => result.warnings.push("Unknown ELF class".to_string()),
}
}
true
} else if data.len() >= 4 && &data[0..4] == b"\xcf\xfa\xed\xfe" {
result.compatibility.architecture = "64-bit".to_string();
true
} else if data.len() >= 4 && &data[0..4] == b"\xce\xfa\xed\xfe" {
result.compatibility.architecture = "32-bit".to_string();
true
} else if data.len() >= 2 && &data[0..2] == b"MZ" {
result.compatibility.architecture = "Windows".to_string();
true
} else {
false
};
if !is_valid_format {
result.errors.push(
"Package is not a valid dynamic library (not ELF, Mach-O, or PE format)"
.to_string(),
);
}
}
Ok(_) => result
.errors
.push("Package file is too small to be a valid dynamic library".to_string()),
Err(e) => result
.errors
.push(format!("Failed to read package file: {}", e)),
}
match unsafe { Library::new(package_path) } {
Ok(_) => {
}
Err(e) => {
result.errors.push(format!(
"Package cannot be loaded as dynamic library: {}",
e
));
}
}
}
}