Skip to main content

gix_pack/index/
init.rs

1use gix_error::Result;
2use std::{
3    borrow::Cow,
4    mem::size_of,
5    path::{Path, PathBuf},
6};
7
8use gix_error::{ResultExt, bail, message};
9
10use crate::index::{self, FAN_LEN, V2_SIGNATURE, Version};
11
12fn corrupt(message: impl Into<Cow<'static, str>>) -> gix_error::Error {
13    gix_error::corruption(message).into()
14}
15
16const N32_SIZE: usize = size_of::<u32>();
17
18/// Instantiation
19impl index::File<crate::MMap> {
20    /// Open the pack index file at the given `path`.
21    ///
22    /// The `object_hash` is a way to read (and write) the same file format with different hashes, as the hash kind
23    /// isn't stored within the file format itself.
24    pub fn at(path: impl AsRef<Path>, object_hash: gix_hash::Kind) -> Result<Self> {
25        Self::at_inner(path.as_ref(), object_hash)
26    }
27
28    fn at_inner(path: &Path, object_hash: gix_hash::Kind) -> Result<Self> {
29        let data = crate::mmap::read_only(path)
30            .or_raise(|| message!("Could not open pack index file at \"{}\"", path.display()))?;
31        Self::from_data(data, path.to_owned(), object_hash)
32    }
33}
34
35impl<T> index::File<T>
36where
37    T: crate::FileData,
38{
39    /// Instantiate an index file from `data` as assumed to be read or memory-mapped from `path`.
40    pub fn from_data(data: T, path: PathBuf, object_hash: gix_hash::Kind) -> Result<Self> {
41        let idx_len = data.len();
42        let hash_len = object_hash.len_in_bytes();
43
44        let footer_size = hash_len * 2;
45        if idx_len < FAN_LEN * N32_SIZE + footer_size {
46            return Err(corrupt(format!(
47                "Pack index of size {idx_len} is too small for even an empty index"
48            )));
49        }
50        let (kind, fan, num_objects) = {
51            let (kind, d) = {
52                let (sig, d) = data.split_at(V2_SIGNATURE.len());
53                if sig == V2_SIGNATURE {
54                    (Version::V2, d)
55                } else {
56                    (Version::V1, &data[..])
57                }
58            };
59            let d = {
60                if let Version::V2 = kind {
61                    let (vd, dr) = d.split_at(N32_SIZE);
62                    let version = crate::read_u32(vd);
63                    if version != Version::V2 as u32 {
64                        bail!("Unsupported index version: {version})".unsupported());
65                    }
66                    dr
67                } else {
68                    d
69                }
70            };
71            let (fan, bytes_read) = read_fan(d);
72            let (_, _d) = d.split_at(bytes_read);
73            let num_objects = fan[FAN_LEN - 1];
74
75            (kind, fan, num_objects)
76        };
77        validate_fan(&fan)?;
78        validate_size(&data, kind, num_objects, hash_len)?;
79        Ok(Self {
80            data,
81            path,
82            version: kind,
83            num_objects,
84            fan,
85            hash_len,
86            object_hash,
87        })
88    }
89}
90
91fn read_fan(d: &[u8]) -> ([u32; FAN_LEN], usize) {
92    assert!(d.len() >= FAN_LEN * N32_SIZE);
93
94    let mut fan = [0; FAN_LEN];
95    for (c, f) in d.as_chunks::<N32_SIZE>().0.iter().zip(fan.iter_mut()) {
96        *f = crate::read_u32(c);
97    }
98    (fan, FAN_LEN * N32_SIZE)
99}
100
101fn validate_fan(fan: &[u32; FAN_LEN]) -> Result {
102    if !crate::fan_is_monotonically_increasing(fan) {
103        return Err(corrupt("Pack index fan-out table must be monotonically increasing"));
104    }
105    Ok(())
106}
107
108fn validate_size(data: &[u8], kind: Version, num_objects: u32, hash_len: usize) -> Result {
109    let num_objects = num_objects as usize;
110    let footer_size = hash_len * 2;
111    let expected_size = match kind {
112        Version::V1 => FAN_LEN
113            .checked_mul(N32_SIZE)
114            .and_then(|size| size.checked_add(num_objects.checked_mul(N32_SIZE + hash_len)?))
115            .and_then(|size| size.checked_add(footer_size))
116            .ok_or_else(|| corrupt("Pack index size overflowed while validating version 1 layout"))?,
117        Version::V2 => {
118            let v2_header_size = V2_SIGNATURE.len() + N32_SIZE + FAN_LEN * N32_SIZE;
119            let oid_bytes = num_objects
120                .checked_mul(hash_len)
121                .ok_or_else(|| corrupt("Pack index size overflowed while validating object ids"))?;
122            let table_bytes = num_objects
123                .checked_mul(N32_SIZE)
124                .ok_or_else(|| corrupt("Pack index size overflowed while validating 32-bit tables"))?;
125            let offset32_start = v2_header_size
126                .checked_add(oid_bytes)
127                .and_then(|size| size.checked_add(table_bytes))
128                .ok_or_else(|| corrupt("Pack index size overflowed while locating 32-bit offsets"))?;
129            let offset32_end = offset32_start
130                .checked_add(table_bytes)
131                .ok_or_else(|| corrupt("Pack index size overflowed while locating 32-bit offsets"))?;
132            if offset32_end > data.len() {
133                return Err(corrupt(format!(
134                    "Pack index of size {} is too small for {} objects in version 2",
135                    data.len(),
136                    num_objects
137                )));
138            }
139            let (large_offsets, max_large_offset_index) = data[offset32_start..offset32_end]
140                .as_chunks::<N32_SIZE>()
141                .0
142                .iter()
143                .filter_map(|offset| {
144                    let offset = crate::read_u32(offset);
145                    (offset & (1 << 31) != 0).then_some((offset ^ (1 << 31)) as usize)
146                })
147                .fold((0usize, 0usize), |(count, max_index), index| {
148                    (count + 1, max_index.max(index))
149                });
150            v2_header_size
151                .checked_add(oid_bytes)
152                .and_then(|size| size.checked_add(table_bytes))
153                .and_then(|size| size.checked_add(table_bytes))
154                .and_then(|size| size.checked_add(large_offsets.checked_mul(size_of::<u64>())?))
155                .and_then(|size| size.checked_add(footer_size))
156                .ok_or_else(|| corrupt("Pack index size overflowed while validating version 2 layout"))
157                .and_then(|expected_size| {
158                    if large_offsets > 0 && max_large_offset_index >= large_offsets {
159                        return Err(corrupt(format!(
160                            "Pack index references large offset {max_large_offset_index}, but only {large_offsets} large offsets are present"
161                        )));
162                    }
163                    Ok(expected_size)
164                })?
165        }
166    };
167    if data.len() != expected_size {
168        // Aborting here is needed for protection against malformed inputs, or the offset access done later can panic
169        // as it's done without explicit error handling.
170        return Err(corrupt(format!(
171            "Pack index size is incorrect, expected {expected_size} bytes for {num_objects} objects in version {kind:?}, but got {} bytes",
172            data.len()
173        )));
174    }
175    Ok(())
176}