~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/vuln-notif

0
0
main
842 lines · 27.8 KB Raw History
//! SourceForge release source: project RSS feed plus files listing.
//!
//! `pkg:sourceforge/{project}` has no registry API. Versions come from the
//! project's RSS feed (`/projects/{project}/rss?path=/`) and its files listing
//! (`/projects/{project}/files/`); release folders and file names are
//! normalized into versions. Artifacts use the direct download host
//! (`downloads.sourceforge.net/project/{project}/{path}`) and take their size
//! from the listing row when present; the digest falls back to the artifact
//! downloader. SourceForge exposes no typed status signal, so
//! [`SourceforgeSource::statuses`] is always
//! [`UnsupportedReason::NoStatuses`].
//!
//! Missing projects and HTML error pages (SourceForge answers both with a 404
//! page) are typed [`UnsupportedReason::Unavailable`] failures and are never
//! parsed as records.

use std::collections::BTreeMap;
use std::fmt;
use std::sync::{Arc, OnceLock};

use anyhow::Result;
use async_trait::async_trait;
use regex::Regex;
use roxmltree::{Document, Node};
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_SOURCEFORGE_SITE_URL: &str = "https://sourceforge.net";
pub const DEFAULT_SOURCEFORGE_DOWNLOADS_URL: &str = "https://downloads.sourceforge.net";

const FILE_SUFFIXES: &[&str] = &[
    ".tar.gz",
    ".tar.bz2",
    ".tar.xz",
    ".tar.zst",
    ".tar.z",
    ".tgz",
    ".tbz2",
    ".txz",
    ".zip",
    ".7z",
    ".rar",
    ".gz",
    ".bz2",
    ".xz",
    ".zst",
    ".jar",
    ".whl",
    ".exe",
    ".msi",
    ".dmg",
    ".pkg",
    ".deb",
    ".rpm",
    ".apk",
    ".iso",
    ".img",
    ".pdf",
    ".txt",
    ".run",
    ".appimage",
];

/// Typed unsupported failure carried through [`anyhow::Error`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SourceforgeUnsupported {
    pub reason: UnsupportedReason,
}

impl fmt::Display for SourceforgeUnsupported {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "unsupported SourceForge source request: {:?}",
            self.reason
        )
    }
}

impl std::error::Error for SourceforgeUnsupported {}

fn unsupported(reason: UnsupportedReason) -> anyhow::Error {
    anyhow::Error::new(SourceforgeUnsupported { reason })
}

/// Recover the typed reason from an error returned by this source.
pub fn unsupported_reason(error: &anyhow::Error) -> Option<UnsupportedReason> {
    error
        .downcast_ref::<SourceforgeUnsupported>()
        .map(|error| error.reason.clone())
}

pub struct SourceforgeSource {
    http: Arc<dyn RegistryHttp>,
    site_base: String,
    downloads_base: String,
}

impl SourceforgeSource {
    pub fn new(http: Arc<dyn RegistryHttp>) -> Self {
        Self::with_bases(
            http,
            DEFAULT_SOURCEFORGE_SITE_URL,
            DEFAULT_SOURCEFORGE_DOWNLOADS_URL,
        )
    }

    pub fn with_bases(
        http: Arc<dyn RegistryHttp>,
        site_base: impl Into<String>,
        downloads_base: impl Into<String>,
    ) -> Self {
        Self {
            http,
            site_base: site_base.into().trim_end_matches('/').to_owned(),
            downloads_base: downloads_base.into().trim_end_matches('/').to_owned(),
        }
    }

    fn rss_url(&self, project: &str) -> String {
        format!("{}/projects/{project}/rss?path=/", self.site_base)
    }

    fn files_url(&self, project: &str) -> String {
        format!("{}/projects/{project}/files/", self.site_base)
    }

    fn absolute_url(&self, base: &str, href: &str) -> String {
        if href.starts_with("http://") || href.starts_with("https://") {
            href.to_owned()
        } else if href.starts_with('/') {
            format!("{}{href}", self.site_base)
        } else {
            format!(
                "{}/{}",
                base.trim_end_matches('/'),
                href.trim_start_matches('/')
            )
        }
    }

    async fn fetch_text(&self, url: &str) -> Result<String> {
        match self.http.get_text(url).await {
            Ok(text) if is_error_page(&text) => Err(unsupported(UnsupportedReason::Unavailable(
                "SourceForge returned an HTML error page",
            ))),
            Ok(text) => Ok(text),
            Err(error) if transport_unavailable(&error) => Err(unsupported(
                UnsupportedReason::Unavailable("SourceForge project is unavailable"),
            )),
            Err(error) => Err(error),
        }
    }
}

#[async_trait]
impl ReleaseSource for SourceforgeSource {
    fn name(&self) -> &'static str {
        "sourceforge"
    }

    fn capabilities(&self) -> SourceCapabilities {
        SourceCapabilities {
            versions: true,
            artifacts: true,
            statuses: false,
            project_meta: true,
        }
    }

    async fn versions(&self, project: &ProjectRef) -> Result<Vec<VersionInfo>> {
        let project = project_name(project)?;
        let mut by_version: BTreeMap<String, VersionInfo> = BTreeMap::new();
        let mut unavailable: Option<UnsupportedReason> = None;
        let mut errors: Vec<anyhow::Error> = Vec::new();
        let mut answered = false;

        match self.fetch_text(&self.rss_url(project)).await {
            Ok(text) => match parse_rss(&text) {
                Ok(feed) => {
                    answered = true;
                    for version in feed_versions(&feed, project) {
                        by_version.entry(version.version.clone()).or_insert(version);
                    }
                }
                Err(reason) => unavailable = Some(reason),
            },
            Err(error) => match unsupported_reason(&error) {
                Some(reason) => unavailable = Some(reason),
                None => errors.push(error),
            },
        }
        match self.fetch_text(&self.files_url(project)).await {
            Ok(text) => match parse_listing(&text) {
                Ok(entries) => {
                    answered = true;
                    for version in listing_versions(&entries, project) {
                        by_version.entry(version.version.clone()).or_insert(version);
                    }
                }
                Err(reason) => unavailable = Some(reason),
            },
            Err(error) => match unsupported_reason(&error) {
                Some(reason) => unavailable = Some(reason),
                None => errors.push(error),
            },
        }

        let mut versions: Vec<VersionInfo> = by_version.into_values().collect();
        if !versions.is_empty() {
            sort_newest_first(&mut versions);
            return Ok(versions);
        }
        if answered {
            return Err(unsupported(UnsupportedReason::NoVersions));
        }
        if let Some(reason) = unavailable {
            return Err(unsupported(reason));
        }
        Err(errors
            .into_iter()
            .next()
            .unwrap_or_else(|| unsupported(UnsupportedReason::NoVersions)))
    }

    async fn artifacts(
        &self,
        project: &ProjectRef,
        version: &VersionInfo,
    ) -> Result<Vec<ArtifactInfo>> {
        let project = project_name(project)?;
        let target = target_version(version);
        let root_url = self.files_url(project);
        let root_text = self.fetch_text(&root_url).await?;
        let root = parse_listing(&root_text).map_err(unsupported)?;

        let folder = root.iter().find(|entry| {
            entry.is_dir && version_label(&entry.name).is_some_and(|(_, found)| found == target)
        });
        let in_version_folder = folder.is_some();
        let entries = match folder {
            Some(folder) => {
                let folder_url = self.absolute_url(&root_url, &folder.href);
                let text = self.fetch_text(&folder_url).await?;
                parse_listing(&text).map_err(unsupported)?
            }
            None => root,
        };

        let mut artifacts: BTreeMap<String, ArtifactInfo> = BTreeMap::new();
        for entry in entries {
            if entry.is_dir {
                continue;
            }
            if !in_version_folder
                && entry_version(&entry, project).is_none_or(|(_, found)| found != target)
            {
                continue;
            }
            let relative =
                files_relative(&entry.href, project).unwrap_or_else(|| entry.name.clone());
            let url = format!(
                "{}/project/{}/{}",
                self.downloads_base,
                project,
                relative.trim_start_matches('/')
            );
            artifacts
                .entry(url.clone())
                .or_insert_with(|| ArtifactInfo {
                    file_name: entry.name.clone(),
                    url,
                    sha256: None,
                    size: entry.size,
                    mime_type: mime_type(&entry.name),
                });
        }

        let mut artifacts: Vec<ArtifactInfo> = artifacts.into_values().collect();
        if artifacts.is_empty() {
            return Err(unsupported(UnsupportedReason::NoArtifacts));
        }
        artifacts.sort_by(|left, right| {
            left.file_name
                .cmp(&right.file_name)
                .then_with(|| left.url.cmp(&right.url))
        });
        Ok(artifacts)
    }

    async fn statuses(
        &self,
        _project: &ProjectRef,
        _version: &VersionInfo,
    ) -> Result<Vec<StatusInfo>> {
        Err(unsupported(UnsupportedReason::NoStatuses))
    }

    async fn project_meta(&self, project: &ProjectRef) -> Result<Value> {
        let project = project_name(project)?;
        let mut feed: Option<RssFeed> = None;
        let mut listing_categories: Vec<String> = Vec::new();
        let mut unavailable: Option<UnsupportedReason> = None;
        let mut errors: Vec<anyhow::Error> = Vec::new();
        let mut answered = false;

        match self.fetch_text(&self.rss_url(project)).await {
            Ok(text) => match parse_rss(&text) {
                Ok(parsed) => {
                    answered = true;
                    feed = Some(parsed);
                }
                Err(reason) => unavailable = Some(reason),
            },
            Err(error) => match unsupported_reason(&error) {
                Some(reason) => unavailable = Some(reason),
                None => errors.push(error),
            },
        }
        match self.fetch_text(&self.files_url(project)).await {
            Ok(text) => {
                answered = true;
                listing_categories = parse_categories(&text);
            }
            Err(error) => match unsupported_reason(&error) {
                Some(reason) => unavailable = Some(reason),
                None => errors.push(error),
            },
        }

        if !answered {
            if let Some(reason) = unavailable {
                return Err(unsupported(reason));
            }
            if let Some(error) = errors.into_iter().next() {
                return Err(error);
            }
            return Err(unsupported(UnsupportedReason::Unavailable(
                "SourceForge project is unavailable",
            )));
        }

        let mut categories = Vec::new();
        if let Some(feed) = &feed {
            for category in &feed.categories {
                push_unique(&mut categories, category);
            }
        }
        for category in listing_categories {
            push_unique(&mut categories, &category);
        }

        let mut meta = Map::new();
        meta.insert("source".to_owned(), Value::String("sourceforge".to_owned()));
        meta.insert("project".to_owned(), Value::String(project.to_owned()));
        meta.insert(
            "homepage".to_owned(),
            Value::String(format!("{}/projects/{project}/", self.site_base)),
        );
        if let Some(feed) = &feed {
            if let Some(title) = &feed.title {
                meta.insert("title".to_owned(), Value::String(title.clone()));
            }
            if let Some(description) = &feed.description {
                meta.insert("description".to_owned(), Value::String(description.clone()));
            }
            if let Some(date) = feed.items.iter().find_map(|item| item.pub_date.clone()) {
                meta.insert("latest_release".to_owned(), Value::String(date));
            }
        }
        if !categories.is_empty() {
            meta.insert(
                "categories".to_owned(),
                Value::Array(categories.into_iter().map(Value::String).collect()),
            );
        }
        Ok(Value::Object(meta))
    }
}

fn project_name(project: &ProjectRef) -> Result<&str> {
    if project.purl_type != "sourceforge" {
        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 SourceForge project name",
        )));
    }
    Ok(name)
}

// ---------------------------------------------------------------------------
// RSS feed
// ---------------------------------------------------------------------------

#[derive(Debug, Default)]
struct RssFeed {
    title: Option<String>,
    description: Option<String>,
    categories: Vec<String>,
    items: Vec<RssItem>,
}

#[derive(Debug)]
struct RssItem {
    link: Option<String>,
    guid: Option<String>,
    pub_date: Option<String>,
}

fn parse_rss(text: &str) -> std::result::Result<RssFeed, UnsupportedReason> {
    let document = Document::parse(text)
        .map_err(|_| UnsupportedReason::Unavailable("SourceForge RSS is not XML"))?;
    let root = document.root_element();
    if root.tag_name().name() != "rss" {
        return Err(UnsupportedReason::Unavailable(
            "SourceForge response is not an RSS feed",
        ));
    }
    let channel = root
        .children()
        .find(|node| node.is_element() && node.tag_name().name() == "channel")
        .ok_or(UnsupportedReason::Unavailable(
            "SourceForge RSS has no channel",
        ))?;

    let mut feed = RssFeed {
        title: child_text(channel, "title"),
        description: child_text(channel, "description"),
        ..RssFeed::default()
    };
    for child in channel.children().filter(Node::is_element) {
        match child.tag_name().name() {
            "category" => {
                if let Some(category) = child.text().map(str::trim).filter(|text| !text.is_empty())
                {
                    feed.categories.push(category.to_owned());
                }
            }
            "item" => feed.items.push(RssItem {
                link: child_text(child, "link"),
                guid: child_text(child, "guid"),
                pub_date: child_text(child, "pubDate"),
            }),
            _ => {}
        }
    }
    Ok(feed)
}

fn child_text(node: Node<'_, '_>, name: &str) -> Option<String> {
    node.children()
        .find(|child| child.is_element() && child.tag_name().name() == name)
        .and_then(|child| child.text())
        .map(str::trim)
        .filter(|text| !text.is_empty())
        .map(str::to_owned)
}

fn feed_versions(feed: &RssFeed, project: &str) -> Vec<VersionInfo> {
    let mut by_version: BTreeMap<String, VersionInfo> = BTreeMap::new();
    for item in &feed.items {
        let Some(href) = item.link.as_deref().or(item.guid.as_deref()) else {
            continue;
        };
        let Some(relative) = files_relative(href, project) else {
            continue;
        };
        let Some((raw, version)) = version_from_relative_path(&relative, project) else {
            continue;
        };
        by_version.entry(version.clone()).or_insert(VersionInfo {
            raw,
            version,
            deprecated: false,
            reason: String::new(),
        });
    }
    by_version.into_values().collect()
}

// ---------------------------------------------------------------------------
// Files listing
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
struct ListingEntry {
    href: String,
    name: String,
    is_dir: bool,
    size: Option<u64>,
}

fn parse_listing(html: &str) -> std::result::Result<Vec<ListingEntry>, UnsupportedReason> {
    if is_error_page(html) {
        return Err(UnsupportedReason::Unavailable(
            "SourceForge returned an HTML error page",
        ));
    }
    let mut entries = Vec::new();
    for capture in regex(&ROW, ROW_PATTERN).captures_iter(html) {
        let attributes = &capture[1];
        let body = &capture[2];
        let class = regex(&CLASS, CLASS_PATTERN)
            .captures(attributes)
            .map(|capture| capture[1].to_ascii_lowercase())
            .unwrap_or_default();
        let is_dir = class.split_whitespace().any(|token| token == "folder");
        let is_file = class.split_whitespace().any(|token| token == "file");
        if !is_dir && !is_file {
            continue;
        }
        let Some(anchor) = regex(&ANCHOR, ANCHOR_PATTERN).captures(body) else {
            continue;
        };
        let href = anchor[1].trim().to_owned();
        if href.is_empty() || href.starts_with(['?', '#']) || href == "../" || href == "/" {
            continue;
        }
        let anchor_text = html_unescape(strip_tags(&anchor[2]).trim());
        let title = regex(&TITLE, TITLE_PATTERN)
            .captures(attributes)
            .map(|capture| html_unescape(capture[1].trim()))
            .filter(|title| !title.is_empty());
        let name = title
            .or_else(|| (!anchor_text.is_empty()).then_some(anchor_text))
            .unwrap_or_else(|| {
                href.trim_end_matches('/')
                    .rsplit('/')
                    .next()
                    .unwrap_or_default()
                    .to_owned()
            });
        if name.is_empty() {
            continue;
        }
        let size = if is_dir {
            None
        } else {
            regex(&SIZE_CELL, SIZE_PATTERN)
                .captures(body)
                .and_then(|capture| parse_size(&capture[1]))
        };
        entries.push(ListingEntry {
            href,
            name,
            is_dir,
            size,
        });
    }
    Ok(entries)
}

fn listing_versions(entries: &[ListingEntry], project: &str) -> Vec<VersionInfo> {
    let mut by_version: BTreeMap<String, VersionInfo> = BTreeMap::new();
    for entry in entries {
        let Some((raw, version)) = entry_version(entry, project) else {
            continue;
        };
        by_version.entry(version.clone()).or_insert(VersionInfo {
            raw,
            version,
            deprecated: false,
            reason: String::new(),
        });
    }
    by_version.into_values().collect()
}

fn entry_version(entry: &ListingEntry, project: &str) -> Option<(String, String)> {
    if entry.is_dir {
        return version_label(&entry.name);
    }
    let relative = files_relative(&entry.href, project).unwrap_or_else(|| entry.name.clone());
    version_from_relative_path(&relative, project)
}

fn parse_categories(html: &str) -> Vec<String> {
    let mut categories = Vec::new();
    for capture in regex(&CATEGORY, CATEGORY_PATTERN).captures_iter(html) {
        let text = html_unescape(strip_tags(&capture[2]).trim());
        let category = if text.is_empty() {
            capture[1].to_owned()
        } else {
            text
        };
        push_unique(&mut categories, &category);
    }
    categories
}

fn push_unique(categories: &mut Vec<String>, category: &str) {
    if !categories
        .iter()
        .any(|existing| existing.eq_ignore_ascii_case(category))
    {
        categories.push(category.to_owned());
    }
}

// ---------------------------------------------------------------------------
// Version extraction
// ---------------------------------------------------------------------------

fn version_from_relative_path(relative: &str, project: &str) -> Option<(String, String)> {
    let is_folder = relative.ends_with('/');
    let cleaned = relative.trim_matches('/');
    let segments: Vec<&str> = cleaned
        .split('/')
        .filter(|segment| !segment.is_empty())
        .collect();
    let (last, ancestors) = segments.split_last()?;
    for ancestor in ancestors.iter().rev() {
        if let Some(version) = version_label(ancestor) {
            return Some(version);
        }
    }
    if is_folder {
        return version_label(last);
    }
    version_from_file_name(last, project)
}

fn version_from_file_name(name: &str, project: &str) -> Option<(String, String)> {
    let stem = file_stem(name);
    let rest = strip_project_prefix(stem, project).unwrap_or(stem);
    rest.split(['-', '_']).find_map(version_label)
}

fn version_label(raw: &str) -> Option<(String, String)> {
    let raw = raw.trim().trim_end_matches('/');
    let candidate = match raw.strip_prefix(['v', 'V']) {
        Some(rest) if rest.starts_with(|character: char| character.is_ascii_digit()) => rest,
        _ => raw,
    };
    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((raw.to_owned(), version))
}

fn file_stem(name: &str) -> &str {
    let lower = name.to_ascii_lowercase();
    FILE_SUFFIXES
        .iter()
        .find_map(|suffix| {
            lower
                .ends_with(suffix)
                .then(|| &name[..name.len() - suffix.len()])
        })
        .unwrap_or(name)
}

fn strip_project_prefix<'a>(stem: &'a str, project: &str) -> Option<&'a str> {
    let prefix = stem.get(..project.len())?;
    if !prefix.eq_ignore_ascii_case(project) {
        return None;
    }
    let rest = stem[project.len()..].trim_start_matches(['-', '_', '.']);
    (!rest.is_empty()).then_some(rest)
}

fn target_version(version: &VersionInfo) -> String {
    normalize_version(&version.version)
        .unwrap_or_else(|| version.version.trim().to_ascii_lowercase())
}

fn sort_newest_first(versions: &mut [VersionInfo]) {
    versions.sort_by(|left, right| {
        compare(VersionScheme::Lexical, &right.version, &left.version)
            .then_with(|| left.raw.cmp(&right.raw))
    });
}

// ---------------------------------------------------------------------------
// URLs, MIME, and listing helpers
// ---------------------------------------------------------------------------

/// Path inside the project's files tree, including the `/download` suffix
/// removal. A trailing slash marks a folder entry.
fn files_relative(href: &str, project: &str) -> Option<String> {
    let href = href.split(['?', '#']).next()?;
    let marker = format!("/projects/{project}/files/");
    let path = href
        .find(&marker)
        .map(|index| &href[index + marker.len()..])
        .or_else(|| {
            href.find("/files/")
                .map(|index| &href[index + "/files/".len()..])
        })?;
    let path = path.strip_suffix("/download").unwrap_or(path);
    (!path.is_empty()).then(|| path.to_owned())
}

fn mime_type(name: &str) -> Option<String> {
    let lower = name.to_ascii_lowercase();
    let mime = if lower.ends_with(".tar.gz") || lower.ends_with(".tgz") {
        "application/gzip"
    } else if lower.ends_with(".tar.bz2") || lower.ends_with(".tbz2") {
        "application/x-bzip2"
    } else if lower.ends_with(".tar.xz") || lower.ends_with(".txz") {
        "application/x-xz"
    } else if lower.ends_with(".tar.zst") {
        "application/zstd"
    } else if lower.ends_with(".zip") || lower.ends_with(".whl") {
        "application/zip"
    } else if lower.ends_with(".7z") {
        "application/x-7z-compressed"
    } else if lower.ends_with(".rar") {
        "application/vnd.rar"
    } else if lower.ends_with(".jar") {
        "application/java-archive"
    } else if lower.ends_with(".exe") {
        "application/vnd.microsoft.portable-executable"
    } else if lower.ends_with(".msi") {
        "application/x-msi"
    } else if lower.ends_with(".dmg") {
        "application/x-apple-diskimage"
    } else if lower.ends_with(".deb") {
        "application/vnd.debian.binary-package"
    } else if lower.ends_with(".rpm") {
        "application/x-rpm"
    } else if lower.ends_with(".iso") {
        "application/x-iso9660-image"
    } else if lower.ends_with(".pdf") {
        "application/pdf"
    } else if lower.ends_with(".gz") {
        "application/gzip"
    } else if lower.ends_with(".xz") {
        "application/x-xz"
    } else if lower.ends_with(".bz2") {
        "application/x-bzip2"
    } else {
        return None;
    };
    Some(mime.to_owned())
}

fn parse_size(cell: &str) -> Option<u64> {
    let text = html_unescape(&strip_tags(cell)).replace(',', " ");
    let text = text.trim();
    let start = text.find(|character: char| character.is_ascii_digit())?;
    let text = &text[start..];
    let end = text
        .find(|character: char| !(character.is_ascii_digit() || character == '.'))
        .unwrap_or(text.len());
    let number: f64 = text[..end].parse().ok()?;
    let unit = text[end..].trim().to_ascii_lowercase();
    let multiplier = if unit.is_empty() || unit.starts_with('b') {
        1.0
    } else if unit.starts_with('k') {
        1024.0
    } else if unit.starts_with('m') {
        1024.0 * 1024.0
    } else if unit.starts_with('g') {
        1024.0 * 1024.0 * 1024.0
    } else if unit.starts_with('t') {
        1024.0 * 1024.0 * 1024.0 * 1024.0
    } else {
        return None;
    };
    Some((number * multiplier) as u64)
}

fn strip_tags(text: &str) -> String {
    let mut result = String::with_capacity(text.len());
    let mut in_tag = false;
    for character in text.chars() {
        match character {
            '<' => in_tag = true,
            '>' => in_tag = false,
            _ if !in_tag => result.push(character),
            _ => {}
        }
    }
    result
}

fn html_unescape(text: &str) -> String {
    text.replace("&nbsp;", " ")
        .replace("&amp;", "&")
        .replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", "\"")
        .replace("&#39;", "'")
}

fn is_error_page(html: &str) -> bool {
    let lower = html.to_ascii_lowercase();
    lower.contains("<html")
        && (lower.contains("page not found")
            || lower.contains("project not found")
            || lower.contains("the page you requested")
            || lower.contains("<title>error"))
}

fn transport_unavailable(error: &anyhow::Error) -> bool {
    let message = format!("{error:#}").to_ascii_lowercase();
    ["404", "403", "410", "not found", "forbidden"]
        .iter()
        .any(|needle| message.contains(needle))
}

fn regex(cell: &'static OnceLock<Regex>, pattern: &'static str) -> &'static Regex {
    cell.get_or_init(|| Regex::new(pattern).expect("static SourceForge regex"))
}

static ROW: OnceLock<Regex> = OnceLock::new();
static ANCHOR: OnceLock<Regex> = OnceLock::new();
static CLASS: OnceLock<Regex> = OnceLock::new();
static TITLE: OnceLock<Regex> = OnceLock::new();
static SIZE_CELL: OnceLock<Regex> = OnceLock::new();
static CATEGORY: OnceLock<Regex> = OnceLock::new();

const ROW_PATTERN: &str = r#"(?is)<tr\b([^>]*)>(.*?)</tr>"#;
const ANCHOR_PATTERN: &str = r#"(?is)<a\b[^>]*\bhref\s*=\s*"([^"]+)"[^>]*>(.*?)</a>"#;
const CLASS_PATTERN: &str = r#"(?i)\bclass\s*=\s*"([^"]*)""#;
const TITLE_PATTERN: &str = r#"(?i)\btitle\s*=\s*"([^"]*)""#;
const SIZE_PATTERN: &str = r#"(?is)<td\b[^>]*\bclass\s*=\s*"[^"]*\bsize\b[^"]*"[^>]*>(.*?)</td>"#;
const CATEGORY_PATTERN: &str =
    r#"(?is)<a\b[^>]*\bhref\s*=\s*"[^"]*/directory/([a-z0-9_-]+)/?"[^>]*>(.*?)</a>"#;