Skip to main content

gix_pack/data/file/decode/
header.rs

1use gix_error::{Result, corruption};
2use gix_error::{ResultExt, bail};
3
4use crate::{
5    data,
6    data::{File, delta, file::decode::DeltaBaseUnresolved},
7};
8
9/// A return value of a resolve function, which given an [`ObjectId`][gix_hash::ObjectId] determines where an object can be found.
10#[derive(Debug, PartialEq, Eq, Hash, Ord, PartialOrd, Clone)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12pub enum ResolvedBase {
13    /// Indicate an object is within this pack, at the given entry, and thus can be looked up locally.
14    InPack(data::Entry),
15    /// Indicates the object of `kind` was found outside of the pack.
16    OutOfPack {
17        /// The kind of object we found when reading the header of the out-of-pack base.
18        kind: gix_object::Kind,
19        /// The amount of deltas encountered if the object was packed as well.
20        num_deltas: Option<u32>,
21    },
22}
23
24/// Additional information and statistics about a successfully decoded object produced by [`File::decode_header()`].
25///
26/// Useful to understand the effectiveness of the pack compression or the cost of decompression.
27#[derive(Debug, PartialEq, Eq, Hash, Ord, PartialOrd, Clone, Copy)]
28#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
29pub struct Outcome {
30    /// The kind of resolved object.
31    pub kind: gix_object::Kind,
32    /// The decompressed size of the object.
33    pub object_size: u64,
34    /// The amount of deltas in the chain of objects that had to be resolved beforehand.
35    pub num_deltas: u32,
36}
37
38/// Obtain object information quickly.
39impl<T> File<T>
40where
41    T: crate::FileData,
42{
43    /// Resolve the object header information starting at `entry`, following the chain of entries as needed.
44    ///
45    /// The `entry` determines which object to decode, and is commonly obtained with the help of a pack index file or through pack iteration.
46    /// `inflate` will be used for (partially) decompressing entries, and will be reset before first use, but not after the last use.
47    ///
48    /// `resolve` is a function to lookup objects with the given [`ObjectId`][gix_hash::ObjectId], in case the full object id
49    /// is used to refer to a base object, instead of an in-pack offset. Return `Ok(None)` if the base could not be found;
50    /// lookup errors are propagated unchanged instead of being treated as missing bases.
51    ///
52    /// For delta entries, this only probes the initial delta header bytes to determine the result
53    /// object size. It can reject streams that end or overflow within that probe, but it does not
54    /// fully validate that the compressed stream produces exactly the decompressed size declared in
55    /// the pack entry header. Use [`File::decode_entry()`][crate::data::File::decode_entry()] when
56    /// callers need that full validation.
57    pub fn decode_header(
58        &self,
59        mut entry: data::Entry,
60        inflate: &mut gix_zlib::Inflate,
61        resolve: &dyn Fn(&gix_hash::oid) -> Result<Option<ResolvedBase>>,
62    ) -> Result<Outcome> {
63        use crate::data::entry::Header::*;
64        let mut num_deltas = 0;
65        let mut first_delta_decompressed_size = None::<u64>;
66        let mut cycle = super::DeltaCycle::new(entry.data_offset);
67        loop {
68            match entry.header {
69                Tree | Blob | Commit | Tag => {
70                    return Ok(Outcome {
71                        kind: entry.header.as_kind().expect("always valid for non-refs"),
72                        object_size: first_delta_decompressed_size.unwrap_or(entry.decompressed_size),
73                        num_deltas,
74                    });
75                }
76                OfsDelta { base_distance } => {
77                    num_deltas += 1;
78                    if first_delta_decompressed_size.is_none() {
79                        first_delta_decompressed_size = Some(self.decode_delta_object_size(inflate, &entry)?);
80                    }
81                    let offset = entry
82                        .checked_base_pack_offset(base_distance)
83                        .ok_or_else(|| {
84                            corruption("Pack entry is truncated: an ofs-delta base distance pointing before pack start")
85                        })
86                        .or_error()?;
87                    entry = self.entry(offset)?;
88                }
89                RefDelta { base_id } => {
90                    num_deltas += 1;
91                    if first_delta_decompressed_size.is_none() {
92                        first_delta_decompressed_size = Some(self.decode_delta_object_size(inflate, &entry)?);
93                    }
94                    match resolve(base_id.as_ref())? {
95                        Some(ResolvedBase::InPack(base_entry)) => entry = base_entry,
96                        Some(ResolvedBase::OutOfPack {
97                            kind,
98                            num_deltas: origin_num_deltas,
99                        }) => {
100                            return Ok(Outcome {
101                                kind,
102                                object_size: first_delta_decompressed_size.unwrap_or(entry.decompressed_size),
103                                num_deltas: origin_num_deltas.unwrap_or_default() + num_deltas,
104                            });
105                        }
106                        None => bail!(DeltaBaseUnresolved(base_id)),
107                    }
108                }
109            }
110            cycle.check(entry.data_offset)?;
111        }
112    }
113
114    /// Decode the result object size from the initial delta header bytes in `inflate`, using `entry`
115    /// for offsets.
116    ///
117    /// This intentionally mirrors Git's cheap header probe: only the first 20 decompressed bytes
118    /// are inspected, which is enough for the two `u64` varints that make up a valid delta header.
119    /// If the zlib stream ends within that probe, we can reject declared-size mismatches here.
120    /// Otherwise this result only proves that the delta header prefix is parseable; full
121    /// decompression through `decode_entry()` must still validate that the stream length matches
122    /// the pack entry header.
123    #[inline]
124    fn decode_delta_object_size(&self, inflate: &mut gix_zlib::Inflate, entry: &data::Entry) -> Result<u64> {
125        let mut buf = [0_u8; 20];
126        let max_size = entry.decompressed_size.min(buf.len() as u64) as usize;
127        let (status, _consumed_in, consumed_out) =
128            self.decompress_entry_from_data_offset_unchecked(entry.data_offset, inflate, &mut buf[..max_size])?;
129        if status == gix_zlib::Status::StreamEnd {
130            if consumed_out as u64 != entry.decompressed_size {
131                bail!(corruption(
132                    "Pack entry is truncated: pack entry decompressed to fewer bytes than declared in the entry header"
133                ));
134            }
135        } else if entry.decompressed_size == max_size as u64 {
136            bail!(corruption(
137                "Pack entry is truncated: pack entry decompressed to more bytes than declared in the entry header",
138            ));
139        }
140        let buf = &buf[..consumed_out];
141        let (_base_size, offset) = delta::decode_header_size(buf)?;
142        let (result_size, _offset) = delta::decode_header_size(&buf[offset..])?;
143        Ok(result_size)
144    }
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150
151    #[test]
152    fn size_of_decode_entry_outcome() {
153        assert_eq!(
154            std::mem::size_of::<Outcome>(),
155            16,
156            "this shouldn't change without use noticing as it's returned a lot"
157        );
158    }
159}