//! purl2cpe database download and read-only load. //! //! The upstream SQLite file is ~542 MB; it is never loaded whole. [`load_purl_map`] //! streams `SELECT purl, cpe` on a blocking thread and keeps only wanted CPE //! product keys, with versionless purls. use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; use std::sync::LazyLock; use std::time::Duration; use anyhow::{Context, Result, anyhow}; use regex::Regex; use rusqlite::{Connection, OpenFlags}; use crate::constants::PURL2CPE_URL; pub use crate::identity::observe::{Cpe as CpeComponents, parse_cpe}; /// Parse a CPE 2.3/2.2 string into every bound component (version, update, /// edition, language, target software/hardware, and so on). /// /// This is the full-component view used by canonical identity; the compact /// [`cpe_product_key`] helper below keeps its historical behavior for the /// software graph. pub fn cpe_components(cpe: &str) -> Option { parse_cpe(cpe) } static CPE23_PRODUCT_RE: LazyLock = LazyLock::new(|| { Regex::new(r"^cpe:2\.3:([aho]):([^:]+):([^:]+):").expect("cpe 2.3 product regex") }); static CPE22_PRODUCT_RE: LazyLock = LazyLock::new(|| Regex::new(r"^cpe:/([aho]):([^:]+):([^:]+)").expect("cpe 2.2 product regex")); /// `part:vendor:product` from a CPE 2.3 or 2.2 string. pub fn cpe_product_key(cpe: &str) -> Option { let captures = CPE23_PRODUCT_RE .captures(cpe) .or_else(|| CPE22_PRODUCT_RE.captures(cpe))?; Some(format!( "{}:{}:{}", captures.get(1)?.as_str(), captures.get(2)?.as_str(), captures.get(3)?.as_str() )) } /// Strip qualifier/subpath and version from a purl. pub fn versionless_purl(purl: &str) -> String { let base = purl.split('#').next().unwrap_or(purl); let base = base.split('?').next().unwrap_or(base); match base.rsplit_once('@') { Some((prefix, _version)) => prefix.to_owned(), None => base.to_owned(), } } fn temp_path(path: &Path, tag: &str) -> PathBuf { let name = path .file_name() .map(|name| name.to_string_lossy().into_owned()) .unwrap_or_else(|| "purl2cpe.db".to_owned()); path.with_file_name(format!(".{name}.{}.{tag}.tmp", std::process::id())) } /// Download the purl2cpe zip and extract its first `.db` member when absent. pub async fn ensure_purl_db(path: &Path, client: &reqwest::Client) -> Result<()> { if path.exists() { return Ok(()); } if let Some(parent) = path.parent() && !parent.as_os_str().is_empty() { tokio::fs::create_dir_all(parent) .await .with_context(|| format!("create purl2cpe directory {}", parent.display()))?; } let zip_path = temp_path(path, "zip"); let download = async { use tokio::io::AsyncWriteExt; let mut response = client .get(PURL2CPE_URL) .timeout(Duration::from_secs(300)) .send() .await .context("download purl2cpe")? .error_for_status() .context("download purl2cpe")?; let mut file = tokio::fs::File::create(&zip_path) .await .with_context(|| format!("create {}", zip_path.display()))?; while let Some(chunk) = response.chunk().await.context("download purl2cpe")? { file.write_all(&chunk).await.context("write purl2cpe zip")?; } file.flush().await.context("flush purl2cpe zip")?; Ok::<(), anyhow::Error>(()) } .await; if let Err(error) = download { let _ = tokio::fs::remove_file(&zip_path).await; return Err(error); } let output = path.to_path_buf(); let extract_zip = zip_path.clone(); let extracted = tokio::task::spawn_blocking(move || extract_first_db(&extract_zip, &output)) .await .context("join purl2cpe extraction")?; let _ = tokio::fs::remove_file(&zip_path).await; extracted } fn extract_first_db(zip_path: &Path, output: &Path) -> Result<()> { let file = std::fs::File::open(zip_path).with_context(|| format!("open {}", zip_path.display()))?; let mut archive = zip::ZipArchive::new(file).context("read purl2cpe zip")?; let mut member_index = None; for index in 0..archive.len() { let member = archive.by_index(index)?; if member.name()?.ends_with(".db") { member_index = Some(index); break; } } let index = member_index.ok_or_else(|| anyhow!("purl2cpe zip has no .db member"))?; let mut member = archive.by_index(index)?; let extract_path = temp_path(output, "extract"); { let mut file = std::fs::File::create(&extract_path) .with_context(|| format!("create {}", extract_path.display()))?; std::io::copy(&mut member, &mut file).context("extract purl2cpe db")?; file.sync_all().context("sync purl2cpe db")?; } std::fs::rename(&extract_path, output) .with_context(|| format!("rename {} -> {}", extract_path.display(), output.display()))?; Ok(()) } /// Stream `purl2cpe(purl, cpe)` and keep wanted product keys only. pub async fn load_purl_map( path: &Path, wanted: &BTreeSet, ) -> Result>> { let path = path.to_path_buf(); let wanted = wanted.clone(); tokio::task::spawn_blocking(move || load_purl_map_blocking(&path, &wanted)) .await .context("join purl2cpe load")? } fn load_purl_map_blocking( path: &Path, wanted: &BTreeSet, ) -> Result>> { let connection = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY) .with_context(|| format!("open purl2cpe {}", path.display()))?; connection .execute_batch("PRAGMA query_only=ON;") .context("configure purl2cpe connection")?; let mut statement = connection .prepare("SELECT purl, cpe FROM purl2cpe") .context("prepare purl2cpe query")?; let mut rows = statement.query([]).context("query purl2cpe")?; let mut result: BTreeMap> = BTreeMap::new(); while let Some(row) = rows.next().context("read purl2cpe row")? { let cpe: Option = row.get(1)?; let Some(cpe) = cpe else { continue }; let Some(key) = cpe_product_key(&cpe) else { continue; }; if !wanted.contains(&key) { continue; } let purl: Option = row.get(0)?; if let Some(purl) = purl { result .entry(key) .or_default() .insert(versionless_purl(&purl)); } } Ok(result) }