1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
//! 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<CpeComponents> {
parse_cpe(cpe)
}
static CPE23_PRODUCT_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"^cpe:2\.3:([aho]):([^:]+):([^:]+):").expect("cpe 2.3 product regex")
});
static CPE22_PRODUCT_RE: LazyLock<Regex> =
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<String> {
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<String>,
) -> Result<BTreeMap<String, BTreeSet<String>>> {
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<String>,
) -> Result<BTreeMap<String, BTreeSet<String>>> {
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<String, BTreeSet<String>> = BTreeMap::new();
while let Some(row) = rows.next().context("read purl2cpe row")? {
let cpe: Option<String> = 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<String> = row.get(0)?;
if let Some(purl) = purl {
result
.entry(key)
.or_default()
.insert(versionless_purl(&purl));
}
}
Ok(result)
}