Skip to main content

znippy_common/plugins/native/
deb_native.rs

1//! Native Debian plugin.
2//!
3//! A `.deb` is a Unix **ar** archive whose members are `debian-binary`,
4//! `control.tar[.gz|.xz|.zst|.bz2]`, and `data.tar.*`. The authoritative
5//! Package/Version/Architecture (plus Depends, Maintainer, Description, …) live in
6//! the `control` file inside the **control tarball** — NOT the filename. Parsing it
7//! (under the `host-decompressors` feature: `tar` for the inner tar, plus
8//! `lgz`/`lbzip2`/`lzma-rs`/`ruzstd` for the gz/bz2/xz/zst codecs) is what lets the
9//! read-side [`DebView`](crate::views::DebView) surface real control metadata.
10//!
11//! On any failure (off-feature, unknown codec, malformed) the plugin falls back to
12//! the `{name}_{version}_{arch}.deb` filename — never panics, always returns a row,
13//! exactly like the `gem`/`conda` native plugins.
14
15use crate::plugin::{file_name, ArchiveTypePlugin, Col, ExtensionRow, ExtensionValue, HandlerSpec};
16use std::collections::HashMap;
17
18/// Native deb plugin. `name`/`version`/`arch` + the raw `control` stanza come from
19/// the control tarball when the `.deb` is parseable, else `(name, version, arch)`
20/// from the filename (no control stanza).
21pub struct DebPlugin;
22
23impl DebPlugin {
24    /// `{name}_{version}_{arch}.deb` filename fallback. Neither the package name
25    /// nor the version contains `_` in a valid pool filename, so a 3-way split is
26    /// exact.
27    fn parse_filename(path: &str) -> (String, Option<String>, Option<String>) {
28        let fname = file_name(path);
29        let stem = fname
30            .strip_suffix(".deb")
31            .or_else(|| fname.strip_suffix(".udeb"))
32            .unwrap_or(fname);
33        let mut it = stem.splitn(3, '_');
34        let name = it.next().unwrap_or(stem).to_string();
35        let version = it.next().filter(|s| !s.is_empty()).map(str::to_string);
36        let arch = it.next().filter(|s| !s.is_empty()).map(str::to_string);
37        (name, version, arch)
38    }
39
40    /// Parse the authoritative `control` stanza out of a `.deb` (ar → control
41    /// tarball → `control`). Returns the raw stanza text. `None` on any failure.
42    #[cfg(feature = "host-decompressors")]
43    fn parse_control(data: &[u8]) -> Option<String> {
44        let member = ar_find_member(data, "control.tar")?;
45        let tar_bytes = decompress_control(member.name, member.data)?;
46        let control = tar_find_file(&tar_bytes, "control")?;
47        let text = String::from_utf8_lossy(&control).into_owned();
48        text.lines().any(|l| l.starts_with("Package:")).then_some(text)
49    }
50
51    // Called only from `resolve` and from the control-stanza test, both of
52    // which already carry `#[cfg(feature = "host-decompressors")]`. Same gate,
53    // same reason as `CondaIndex` in `conda_native.rs`: without it the default
54    // build warned ``associated function `control_coords` is never used``,
55    // which was true of that build. A gate, not an `allow` — the function is
56    // genuinely absent without the decompressors, and an `allow` would have
57    // hidden a real disuse later.
58    #[cfg(feature = "host-decompressors")]
59    /// `(name, version, arch)` from a control stanza's single-line Package /
60    /// Version / Architecture fields.
61    fn control_coords(control: &str) -> (Option<String>, Option<String>, Option<String>) {
62        let field = |key: &str| -> Option<String> {
63            control
64                .lines()
65                .find_map(|l| l.strip_prefix(key))
66                .map(|v| v.trim().to_string())
67                .filter(|s| !s.is_empty())
68        };
69        (field("Package:"), field("Version:"), field("Architecture:"))
70    }
71
72    /// Resolve coords + the raw control stanza: authoritative control first,
73    /// filename fallback (no control) otherwise.
74    fn resolve(
75        path: &str,
76        data: &[u8],
77    ) -> (String, Option<String>, Option<String>, Option<String>) {
78        #[cfg(feature = "host-decompressors")]
79        if let Some(control) = Self::parse_control(data) {
80            let (n, v, a) = Self::control_coords(&control);
81            if let Some(name) = n {
82                return (name, v, a, Some(control));
83            }
84        }
85        let _ = data;
86        let (name, version, arch) = Self::parse_filename(path);
87        (name, version, arch, None)
88    }
89}
90
91// ── ar + control-tarball helpers (host-decompressors only) ──────────────────
92
93#[cfg(feature = "host-decompressors")]
94struct ArMember<'a> {
95    name: &'a str,
96    data: &'a [u8],
97}
98
99/// Find the first ar member whose (trimmed) name starts with `name_prefix`. The
100/// `.deb` ar uses short, space-padded names (`control.tar.xz`, `debian-binary`).
101/// Fully bounds-checked; `None` on any malformation.
102#[cfg(feature = "host-decompressors")]
103fn ar_find_member<'a>(data: &'a [u8], name_prefix: &str) -> Option<ArMember<'a>> {
104    if data.get(0..8)? != b"!<arch>\n" {
105        return None;
106    }
107    let mut pos = 8usize;
108    while pos.checked_add(60)? <= data.len() {
109        let hdr = &data[pos..pos + 60];
110        let name = std::str::from_utf8(&hdr[0..16]).ok()?.trim_end().trim_end_matches('/');
111        let size: usize = std::str::from_utf8(&hdr[48..58]).ok()?.trim().parse().ok()?;
112        let dstart = pos.checked_add(60)?;
113        let dend = dstart.checked_add(size)?;
114        if dend > data.len() {
115            return None;
116        }
117        if name.starts_with(name_prefix) {
118            return Some(ArMember { name, data: &data[dstart..dend] });
119        }
120        pos = dend.checked_add(size & 1)?; // members are padded to an even boundary
121    }
122    None
123}
124
125/// Decompress a control tarball member by its codec extension: uncompressed, gz
126/// (lgz), bz2 (lbzip2), xz (lzma-rs), zst (ruzstd). Any unknown codec returns
127/// `None` (the caller falls back to the filename).
128#[cfg(feature = "host-decompressors")]
129fn decompress_control(name: &str, data: &[u8]) -> Option<Vec<u8>> {
130    use crate::plugins::npm_native::MAX_INGEST_DECOMPRESS;
131    use std::io::Read;
132    if name == "control.tar" {
133        Some(data.to_vec())
134    } else if name.ends_with(".gz") {
135        lgz::decompress_gz_capped(data, MAX_INGEST_DECOMPRESS).ok()
136    } else if name.ends_with(".xz") {
137        let mut out = Vec::new();
138        let mut w = CappedWriter { out: &mut out, cap: MAX_INGEST_DECOMPRESS };
139        lzma_rs::xz_decompress(&mut std::io::Cursor::new(data), &mut w).ok()?;
140        Some(out)
141    } else if name.ends_with(".bz2") {
142        lbzip2::stream::decompress_capped(data, MAX_INGEST_DECOMPRESS).ok()
143    } else if name.ends_with(".zst") {
144        // Pure-Rust zstd (ruzstd), capped so a bomb can't OOM at ingest.
145        let dec = ruzstd::decoding::StreamingDecoder::new(std::io::Cursor::new(data)).ok()?;
146        let mut out = Vec::new();
147        dec.take(MAX_INGEST_DECOMPRESS as u64).read_to_end(&mut out).ok()?;
148        (out.len() < MAX_INGEST_DECOMPRESS).then_some(out)
149    } else {
150        None
151    }
152}
153
154/// Extract the `control` member (`control` or `./control`) from an uncompressed
155/// control tarball, capped so a tar bomb can't OOM at ingest.
156#[cfg(feature = "host-decompressors")]
157fn tar_find_file(tar_bytes: &[u8], want: &str) -> Option<Vec<u8>> {
158    use crate::plugins::npm_native::MAX_INGEST_DECOMPRESS;
159    use std::io::Read;
160    let mut archive = tar::Archive::new(tar_bytes);
161    for entry in archive.entries().ok()? {
162        let mut entry = entry.ok()?;
163        let path = entry.path().ok()?.to_string_lossy().to_string();
164        if path.trim_start_matches("./") == want {
165            let mut buf = Vec::new();
166            let read =
167                entry.by_ref().take(MAX_INGEST_DECOMPRESS as u64).read_to_end(&mut buf).ok()?;
168            if read >= MAX_INGEST_DECOMPRESS {
169                return None;
170            }
171            return Some(buf);
172        }
173    }
174    None
175}
176
177/// An `io::Write` that errors once `cap` bytes have been written — bounds a
178/// decompression bomb at ingest (the streaming codecs write into this).
179#[cfg(feature = "host-decompressors")]
180struct CappedWriter<'a> {
181    out: &'a mut Vec<u8>,
182    cap: usize,
183}
184
185#[cfg(feature = "host-decompressors")]
186impl std::io::Write for CappedWriter<'_> {
187    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
188        if self.out.len().saturating_add(buf.len()) > self.cap {
189            return Err(std::io::Error::other("control tarball decompress cap exceeded"));
190        }
191        self.out.extend_from_slice(buf);
192        Ok(buf.len())
193    }
194    fn flush(&mut self) -> std::io::Result<()> {
195        Ok(())
196    }
197}
198
199/// The deb handler, stated once: the coords the read-side
200/// [`DebView`](crate::views::DebView) resolves on plus the raw `control` stanza.
201pub static DEB_SPEC: HandlerSpec = HandlerSpec {
202    name: "deb",
203    aliases: &["debian", "ubuntu", "apt", "dpkg"],
204    type_id: 9,
205    ecosystem: "Debian packages (Debian / Ubuntu)",
206    extensions: &[".deb", ".udeb"],
207    description: "Debian packages — authoritative control fields from the control tarball",
208    fields: &[("name", Col::Utf8), ("version", Col::Utf8), ("arch", Col::Utf8), ("control", Col::Utf8)],
209    commands: &[],
210};
211
212impl ArchiveTypePlugin for DebPlugin {
213    fn spec(&self) -> &HandlerSpec {
214        &DEB_SPEC
215    }
216
217    fn extract_metadata(&self, path: &str, data: &[u8]) -> Option<ExtensionRow> {
218        let (name, version, arch, control) = Self::resolve(path, data);
219        let mut fields = HashMap::new();
220        fields.insert("name".into(), ExtensionValue::Str(name));
221        fields.insert("version".into(), ExtensionValue::OptStr(version));
222        fields.insert("arch".into(), ExtensionValue::OptStr(arch));
223        fields.insert("control".into(), ExtensionValue::OptStr(control));
224        Some(ExtensionRow { fields })
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    #[test]
233    fn filename_fallback_splits_name_version_arch() {
234        let (n, v, a) = DebPlugin::parse_filename("pool/main/h/hello/hello_2.10-3_amd64.deb");
235        assert_eq!(n, "hello");
236        assert_eq!(v.as_deref(), Some("2.10-3"));
237        assert_eq!(a.as_deref(), Some("amd64"));
238    }
239
240    #[test]
241    fn matches_deb_and_udeb_only() {
242        assert!(DebPlugin.matches_path("pool/main/x_1_amd64.deb"));
243        assert!(DebPlugin.matches_path("pool/main/x_1_amd64.udeb"));
244        assert!(!DebPlugin.matches_path("foo.rpm"));
245    }
246
247    #[test]
248    fn schema_has_name_version_arch_control() {
249        let f = DebPlugin.schema_fields();
250        let names: Vec<&str> = f.iter().map(|x| x.name().as_str()).collect();
251        assert_eq!(names, vec!["name", "version", "arch", "control"]);
252    }
253
254    #[test]
255    fn extract_falls_back_to_filename_for_garbage() {
256        let row = DebPlugin
257            .extract_metadata("pool/main/zlib_1.2.11_amd64.deb", b"not a deb")
258            .expect("row");
259        assert_eq!(row.fields.get("name"), Some(&ExtensionValue::Str("zlib".into())));
260        assert_eq!(
261            row.fields.get("version"),
262            Some(&ExtensionValue::OptStr(Some("1.2.11".into())))
263        );
264        assert_eq!(row.fields.get("control"), Some(&ExtensionValue::OptStr(None)));
265    }
266
267    // ── host-decompressors: real control-tarball parsing ────────────────────
268
269    /// Build a one-file `control` tar (uncompressed `ustar`).
270    #[cfg(feature = "host-decompressors")]
271    fn control_tar(control: &str) -> Vec<u8> {
272        let mut b = tar::Builder::new(Vec::new());
273        let mut header = tar::Header::new_ustar();
274        header.set_path("./control").unwrap();
275        header.set_size(control.len() as u64);
276        header.set_mode(0o644);
277        header.set_cksum();
278        b.append(&header, control.as_bytes()).unwrap();
279        b.into_inner().unwrap()
280    }
281
282    /// Wrap members into a `.deb` ar archive (`!<arch>\n` + 60-byte headers).
283    #[cfg(feature = "host-decompressors")]
284    fn ar_build(members: &[(&str, &[u8])]) -> Vec<u8> {
285        let mut out = b"!<arch>\n".to_vec();
286        for (name, data) in members {
287            let mut hdr = [b' '; 60];
288            let nb = name.as_bytes();
289            hdr[0..nb.len()].copy_from_slice(nb);
290            let size = format!("{}", data.len());
291            hdr[48..48 + size.len()].copy_from_slice(size.as_bytes());
292            hdr[58] = b'`';
293            hdr[59] = b'\n';
294            out.extend_from_slice(&hdr);
295            out.extend_from_slice(data);
296            if data.len() % 2 == 1 {
297                out.push(b'\n');
298            }
299        }
300        out
301    }
302
303    const SAMPLE_CONTROL: &str = "Package: hello\n\
304        Version: 2.10-3\n\
305        Architecture: amd64\n\
306        Maintainer: Someone <a@b.c>\n\
307        Depends: libc6 (>= 2.2.5)\n\
308        Description: example\n\
309        \x20more description\n";
310
311    #[cfg(feature = "host-decompressors")]
312    #[test]
313    fn parses_control_from_uncompressed_control_tar() {
314        let tar = control_tar(SAMPLE_CONTROL);
315        let deb = ar_build(&[("debian-binary", b"2.0\n"), ("control.tar", &tar)]);
316        let control = DebPlugin::parse_control(&deb).expect("parses");
317        let (n, v, a) = DebPlugin::control_coords(&control);
318        assert_eq!(n.as_deref(), Some("hello"));
319        assert_eq!(v.as_deref(), Some("2.10-3"));
320        assert_eq!(a.as_deref(), Some("amd64"));
321        assert!(control.contains("Depends: libc6 (>= 2.2.5)"), "real Depends flows through");
322    }
323
324    #[cfg(feature = "host-decompressors")]
325    #[test]
326    fn parses_control_from_xz_control_tar() {
327        // dpkg's modern default control compression.
328        let tar = control_tar(SAMPLE_CONTROL);
329        let mut xz = Vec::new();
330        lzma_rs::xz_compress(&mut std::io::Cursor::new(&tar), &mut xz).unwrap();
331        let deb = ar_build(&[("debian-binary", b"2.0\n"), ("control.tar.xz", &xz)]);
332        let row = DebPlugin.extract_metadata("pool/main/wrong_0_all.deb", &deb).expect("row");
333        // Header is authoritative over the (deliberately wrong) filename.
334        assert_eq!(row.fields.get("name"), Some(&ExtensionValue::Str("hello".into())));
335        assert_eq!(
336            row.fields.get("version"),
337            Some(&ExtensionValue::OptStr(Some("2.10-3".into())))
338        );
339        match row.fields.get("control") {
340            Some(ExtensionValue::OptStr(Some(c))) => assert!(c.contains("Maintainer:")),
341            other => panic!("expected control stanza, got {other:?}"),
342        }
343    }
344
345    #[cfg(feature = "host-decompressors")]
346    #[test]
347    fn parses_control_from_zst_control_tar() {
348        // Newer Ubuntu / dpkg zstd control compression, decoded via ruzstd. The
349        // committed fixture is `zstd(tar(control))` for a `Package: hello` control.
350        let zst = include_bytes!("testdata/control.tar.zst");
351        let deb = ar_build(&[("debian-binary", b"2.0\n"), ("control.tar.zst", zst)]);
352        let row = DebPlugin.extract_metadata("pool/main/wrong_0_all.deb", &deb).expect("row");
353        assert_eq!(row.fields.get("name"), Some(&ExtensionValue::Str("hello".into())));
354        assert_eq!(
355            row.fields.get("version"),
356            Some(&ExtensionValue::OptStr(Some("2.10-3".into())))
357        );
358        match row.fields.get("control") {
359            Some(ExtensionValue::OptStr(Some(c))) => {
360                assert!(c.contains("Depends: libc6 (>= 2.2.5)"), "real control from the .zst");
361            }
362            other => panic!("expected control stanza, got {other:?}"),
363        }
364    }
365
366    #[cfg(feature = "host-decompressors")]
367    #[test]
368    fn unknown_codec_falls_back_to_filename() {
369        // A codec we don't support (e.g. lzip) must degrade to the filename, not error.
370        let deb = ar_build(&[("debian-binary", b"2.0\n"), ("control.tar.lz", b"\x00\x01\x02")]);
371        let (n, v, a, control) = DebPlugin::resolve("pool/main/curl_8.5.0_arm64.deb", &deb);
372        assert_eq!(n, "curl");
373        assert_eq!(v.as_deref(), Some("8.5.0"));
374        assert_eq!(a.as_deref(), Some("arm64"));
375        assert!(control.is_none(), "no control stanza for an unsupported codec");
376    }
377
378    #[cfg(feature = "host-decompressors")]
379    #[test]
380    fn malformed_ar_never_panics() {
381        for bad in [&b"!<arch>\n"[..], b"not ar at all", b"!<arch>\nshort"] {
382            assert!(DebPlugin::parse_control(bad).is_none());
383        }
384    }
385}