//! GNU FTP source adapter. //! //! `pkg:gnu/{project}` reads the `https://ftp.gnu.org/gnu/{project}/` //! autoindex. Version numbers come from archive file names; `.sig` files are //! ignored, sizes come from the listing row, and no digest is reported because //! GNU publishes signatures, not SHA-256 sidecars. use std::collections::BTreeMap; use std::sync::{Arc, OnceLock}; use anyhow::Result; use async_trait::async_trait; use regex::Regex; use serde_json::{Map, Value}; use crate::release::http::RegistryHttp; use crate::release::source::{ ArtifactInfo, ProjectRef, ReleaseSource, SourceCapabilities, StatusInfo, UnsupportedReason, VersionInfo, }; use crate::release::versioning::{VersionScheme, compare, normalize_version}; pub const DEFAULT_GNU_BASE_URL: &str = "https://ftp.gnu.org/gnu"; const ARCHIVE_SUFFIXES: &[&str] = &[ ".tar.gz", ".tar.bz2", ".tar.xz", ".tar.lz", ".tar.zst", ".tar.Z", ".tgz", ".tbz2", ".txz", ".zip", ".tar", ]; pub struct GnuSource { http: Arc, base_url: String, } impl GnuSource { pub fn new(http: Arc) -> Self { Self::with_base_url(http, DEFAULT_GNU_BASE_URL) } pub fn with_base_url(http: Arc, base_url: impl Into) -> Self { Self { http, base_url: base_url.into().trim_end_matches('/').to_owned(), } } fn index_url(&self, project: &str) -> String { format!("{}/{project}/", self.base_url) } } #[async_trait] impl ReleaseSource for GnuSource { fn name(&self) -> &'static str { "gnu" } fn capabilities(&self) -> SourceCapabilities { SourceCapabilities { versions: true, artifacts: true, statuses: false, project_meta: true, } } async fn versions(&self, project: &ProjectRef) -> Result> { let project = project_name(project)?; let html = self.http.get_text(&self.index_url(project)).await?; let mut by_version = BTreeMap::new(); for entry in parse_index(&html) { if entry.is_dir || !is_archive(&entry.name) { continue; } if let Some((raw, version)) = file_version(&entry.name, project) { by_version .entry(version.clone()) .or_insert_with(|| VersionInfo { raw, version, deprecated: false, reason: String::new(), }); } } let mut versions: Vec = by_version.into_values().collect(); sort_versions(&mut versions); if versions.is_empty() { return Err(unsupported(UnsupportedReason::NoVersions)); } Ok(versions) } async fn artifacts( &self, project: &ProjectRef, version: &VersionInfo, ) -> Result> { let project = project_name(project)?; let index_url = self.index_url(project); let html = self.http.get_text(&index_url).await?; let mut artifacts = Vec::new(); for entry in parse_index(&html) { if entry.is_dir || !is_archive(&entry.name) { continue; } if file_version(&entry.name, project).is_none_or(|(_, found)| found != version.version) { continue; } artifacts.push(ArtifactInfo { file_name: entry.name.clone(), url: join_url(&index_url, &entry.href), sha256: None, size: entry.size, mime_type: archive_mime(&entry.name), }); } artifacts.sort_by(|left, right| left.file_name.cmp(&right.file_name)); if artifacts.is_empty() { return Err(unsupported(UnsupportedReason::NoArtifacts)); } Ok(artifacts) } async fn statuses( &self, _project: &ProjectRef, _version: &VersionInfo, ) -> Result> { Err(unsupported(UnsupportedReason::NoStatuses)) } async fn project_meta(&self, project: &ProjectRef) -> Result { let project = project_name(project)?; let mut meta = Map::new(); meta.insert("source".to_owned(), Value::String("gnu".to_owned())); meta.insert("project".to_owned(), Value::String(project.to_owned())); meta.insert("index".to_owned(), Value::String(self.index_url(project))); Ok(Value::Object(meta)) } } fn project_name(project: &ProjectRef) -> Result<&str> { if project.purl_type != "gnu" { return Err(unsupported(UnsupportedReason::UnknownPurlType( project.purl_type.clone(), ))); } let name = project.name.trim().trim_matches('/'); if name.is_empty() || name.contains('/') || !name.chars().all(|character| { character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.') }) { return Err(unsupported(UnsupportedReason::Unavailable( "invalid GNU project name", ))); } Ok(name) } #[derive(Debug, Clone)] struct IndexEntry { href: String, name: String, is_dir: bool, size: Option, } fn parse_index(html: &str) -> Vec { static ANCHOR: OnceLock = OnceLock::new(); let anchor = ANCHOR.get_or_init(|| { Regex::new(r#"]*>([^<]*)([^<\n]*)"#) .expect("static GNU index regex") }); let mut entries = Vec::new(); for capture in anchor.captures_iter(html) { let href = capture[1].trim().to_owned(); if href.is_empty() || href.starts_with(['?', '#']) || href == "../" || href == "/" { continue; } let display = capture[2].trim(); let name = if display.is_empty() { href.trim_end_matches('/').to_owned() } else { display.to_owned() }; let is_dir = href.ends_with('/'); let size = if is_dir { None } else { parse_row_size(&capture[3]) }; entries.push(IndexEntry { href, name, is_dir, size, }); } entries } fn parse_row_size(rest: &str) -> Option { let tokens: Vec<&str> = rest.split_whitespace().collect(); let candidate = if tokens.len() >= 3 && is_date(tokens[0]) { tokens[2] } else { *tokens.last()? }; parse_size(candidate) } fn is_date(token: &str) -> bool { let bytes = token.as_bytes(); bytes.len() == 10 && bytes.get(4) == Some(&b'-') && bytes.get(7) == Some(&b'-') && bytes .iter() .enumerate() .all(|(index, byte)| matches!(index, 4 | 7) || byte.is_ascii_digit()) } fn parse_size(token: &str) -> Option { let token = token.trim(); if token.is_empty() || token == "-" { return None; } let (number, multiplier) = match token.chars().last()? { 'K' | 'k' => (&token[..token.len() - 1], 1024_u64), 'M' | 'm' => (&token[..token.len() - 1], 1024_u64 * 1024), 'G' | 'g' => (&token[..token.len() - 1], 1024_u64 * 1024 * 1024), _ => (token, 1), }; number .parse::() .ok() .map(|value| (value * multiplier as f64) as u64) } fn file_version(name: &str, project: &str) -> Option<(String, String)> { let stem = strip_archive(name)?; let rest = match stem.split_once(project) { Some((_, rest)) => rest, None => stem, }; let rest = rest.trim_start_matches(['-', '_', '.']); let candidate = rest.split(['-', '_']).next()?; if candidate.is_empty() || !candidate.starts_with(|character: char| character.is_ascii_digit()) || !candidate.chars().all(|character| { character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_' | '+') }) { return None; } let version = normalize_version(candidate)?; Some((candidate.to_owned(), version)) } fn strip_archive(name: &str) -> Option<&str> { ARCHIVE_SUFFIXES .iter() .find_map(|suffix| name.strip_suffix(suffix)) } fn is_archive(name: &str) -> bool { strip_archive(name).is_some() } fn archive_mime(name: &str) -> Option { if name.ends_with(".tar.gz") || name.ends_with(".tgz") { Some("application/gzip".to_owned()) } else if name.ends_with(".tar.bz2") || name.ends_with(".tbz2") { Some("application/x-bzip2".to_owned()) } else if name.ends_with(".tar.xz") || name.ends_with(".txz") { Some("application/x-xz".to_owned()) } else if name.ends_with(".zip") { Some("application/zip".to_owned()) } else { None } } fn join_url(base: &str, href: &str) -> String { if href.starts_with("http://") || href.starts_with("https://") { href.to_owned() } else { format!( "{}/{}", base.trim_end_matches('/'), href.trim_start_matches('/') ) } } fn sort_versions(versions: &mut [VersionInfo]) { versions.sort_by(|left, right| { compare(VersionScheme::Lexical, &left.version, &right.version) .then_with(|| left.raw.cmp(&right.raw)) }); } fn unsupported(reason: UnsupportedReason) -> anyhow::Error { anyhow::anyhow!("unsupported source input: {reason:?}") }