gix_pack/index/verify.rs
1use gix_error::{Result, corruption, message};
2use std::sync::atomic::AtomicBool;
3
4use gix_error::{ResultExt, bail};
5use gix_object::WriteTo;
6use gix_object::bstr::ByteSlice;
7use gix_utils::progress::{DynNestedProgress, Progress};
8
9use crate::index;
10
11///
12pub mod integrity {
13 use std::marker::PhantomData;
14
15 /// Returned by [`index::File::verify_integrity()`][crate::index::File::verify_integrity()].
16 pub struct Outcome {
17 /// The computed checksum of the index which matched the stored one.
18 pub actual_index_checksum: gix_hash::ObjectId,
19 /// The packs traversal outcome, if one was provided
20 pub pack_traverse_statistics: Option<crate::index::traverse::Statistics>,
21 }
22
23 /// Additional options to define how the integrity should be verified.
24 #[derive(Clone)]
25 pub struct Options<F> {
26 /// The thoroughness of the verification
27 pub verify_mode: crate::index::verify::Mode,
28 /// The way to traverse packs
29 pub traversal: crate::index::traverse::Algorithm,
30 /// The amount of threads to use of `Some(N)`, with `None|Some(0)` using all available cores are used.
31 pub thread_limit: Option<usize>,
32 /// A function to create a pack cache
33 pub make_pack_lookup_cache: F,
34 }
35
36 impl Default for Options<fn() -> crate::cache::Never> {
37 fn default() -> Self {
38 Options {
39 verify_mode: Default::default(),
40 traversal: Default::default(),
41 thread_limit: None,
42 make_pack_lookup_cache: || crate::cache::Never,
43 }
44 }
45 }
46
47 /// The progress ids used in [`index::File::verify_integrity()`][crate::index::File::verify_integrity()].
48 ///
49 /// Use this information to selectively extract the progress of interest in case the parent application has custom visualization.
50 #[derive(Debug, Copy, Clone)]
51 pub enum ProgressId {
52 /// The amount of bytes read to verify the index checksum.
53 ChecksumBytes,
54 /// A root progress for traversal which isn't actually used directly, but here to link to the respective `ProgressId` types.
55 Traverse(PhantomData<crate::index::verify::index::traverse::ProgressId>),
56 }
57
58 impl From<ProgressId> for gix_utils::progress::Id {
59 fn from(v: ProgressId) -> Self {
60 match v {
61 ProgressId::ChecksumBytes => *b"PTHI",
62 ProgressId::Traverse(_) => gix_utils::progress::UNKNOWN,
63 }
64 }
65 }
66}
67
68/// Various ways in which a pack and index can be verified
69#[derive(Default, Debug, Eq, PartialEq, Hash, Clone, Copy)]
70pub enum Mode {
71 /// Validate the object hash and CRC32
72 HashCrc32,
73 /// Validate hash and CRC32, and decode each non-Blob object.
74 /// Each object should be valid, i.e. be decodable.
75 HashCrc32Decode,
76 /// Validate hash and CRC32, and decode and encode each non-Blob object.
77 /// Each object should yield exactly the same hash when re-encoded.
78 #[default]
79 HashCrc32DecodeEncode,
80}
81
82/// Information to allow verifying the integrity of an index with the help of its corresponding pack.
83pub struct PackContext<'a, F, D = crate::MMap> {
84 /// The pack data file itself.
85 pub data: &'a crate::data::File<D>,
86 /// The options further configuring the pack traversal and verification
87 pub options: integrity::Options<F>,
88}
89
90/// Verify and validate the content of the index file
91impl<T> index::File<T>
92where
93 T: crate::FileData + Sync,
94{
95 /// Returns the trailing hash stored at the end of this index file.
96 ///
97 /// It's a hash over all bytes of the index.
98 pub fn index_checksum(&self) -> gix_hash::ObjectId {
99 gix_hash::ObjectId::from_bytes_or_panic(&self.data[self.data.len() - self.hash_len..])
100 }
101
102 /// Returns the hash of the pack data file that this index file corresponds to.
103 ///
104 /// It should [`crate::data::File::checksum()`] of the corresponding pack data file.
105 pub fn pack_checksum(&self) -> gix_hash::ObjectId {
106 let from = self.data.len() - self.hash_len * 2;
107 gix_hash::ObjectId::from_bytes_or_panic(&self.data[from..][..self.hash_len])
108 }
109
110 /// Validate that our [`index_checksum()`][index::File::index_checksum()] matches the actual contents
111 /// of this index file, and return it if it does.
112 pub fn verify_checksum(
113 &self,
114 progress: &mut dyn Progress,
115 should_interrupt: &AtomicBool,
116 ) -> Result<gix_hash::ObjectId> {
117 crate::verify::checksum_on_disk_or_mmap(
118 self.path(),
119 &self.data,
120 self.index_checksum(),
121 self.object_hash,
122 progress,
123 should_interrupt,
124 )
125 }
126
127 /// The most thorough validation of integrity of both index file and the corresponding pack data file, if provided.
128 /// Returns the checksum of the index file, the traversal outcome and the given progress if the integrity check is successful.
129 ///
130 /// If `pack` is provided, it is expected (and validated to be) the pack belonging to this index.
131 /// It will be used to validate internal integrity of the pack before checking each objects integrity
132 /// is indeed as advertised via its SHA1 as stored in this index, as well as the CRC32 hash.
133 /// The last member of the Option is a function returning an implementation of [`crate::cache::DecodeEntry`] to be used if
134 /// the [`index::traverse::Algorithm`] is `Lookup`.
135 /// To set this to `None`, use `None::<(_, _, _, fn() -> crate::cache::Never)>`.
136 ///
137 /// The `thread_limit` optionally specifies the amount of threads to be used for the [pack traversal][index::File::traverse()].
138 /// `make_cache` is only used in case a `pack` is specified, use existing implementations in the [`crate::cache`] module.
139 ///
140 /// # Tradeoffs
141 ///
142 /// The given `progress` is inevitably consumed if there is an error, which is a tradeoff chosen to easily allow using `?` in the
143 /// error case.
144 pub fn verify_integrity<C, F, D>(
145 &self,
146 pack: Option<PackContext<'_, F, D>>,
147 progress: &mut dyn DynNestedProgress,
148 should_interrupt: &AtomicBool,
149 ) -> Result<integrity::Outcome>
150 where
151 C: crate::cache::DecodeEntry,
152 F: Fn() -> C + Send + Clone,
153 D: crate::FileData + Send + Sync,
154 {
155 if let Some(first_invalid) = crate::verify::fan(&self.fan) {
156 bail!(corruption(format!(
157 "The fan at index {first_invalid} is out of order as it's larger then the following value."
158 )));
159 }
160
161 match pack {
162 Some(PackContext {
163 data: pack,
164 options:
165 integrity::Options {
166 verify_mode,
167 traversal,
168 thread_limit,
169 make_pack_lookup_cache,
170 },
171 }) => self
172 .traverse(
173 pack,
174 progress,
175 should_interrupt,
176 {
177 let mut encode_buf = Vec::with_capacity(2048);
178 move |kind, data, index_entry, progress| {
179 Self::verify_entry(verify_mode, &mut encode_buf, kind, data, index_entry, progress)
180 }
181 },
182 index::traverse::Options {
183 traversal,
184 thread_limit,
185 check: index::traverse::SafetyCheck::All,
186 alloc_limit_bytes: pack.alloc_limit_bytes,
187 make_pack_lookup_cache,
188 },
189 )
190 .map(|o| integrity::Outcome {
191 actual_index_checksum: o.actual_index_checksum,
192 pack_traverse_statistics: Some(o.statistics),
193 }),
194 None => self
195 .verify_checksum(
196 &mut progress
197 .add_child_with_id("checksum of index".into(), integrity::ProgressId::ChecksumBytes.into()),
198 should_interrupt,
199 )
200 .map(|id| integrity::Outcome {
201 actual_index_checksum: id,
202 pack_traverse_statistics: None,
203 }),
204 }
205 }
206
207 #[allow(clippy::too_many_arguments)]
208 fn verify_entry(
209 verify_mode: Mode,
210 encode_buf: &mut Vec<u8>,
211 object_kind: gix_object::Kind,
212 buf: &[u8],
213 index_entry: &index::Entry,
214 _progress: &dyn gix_utils::progress::Progress,
215 ) -> Result {
216 if let Mode::HashCrc32Decode | Mode::HashCrc32DecodeEncode = verify_mode {
217 use gix_object::Kind::*;
218 match object_kind {
219 Tree | Commit | Tag => {
220 let object =
221 gix_object::ObjectRef::from_bytes(buf, object_kind, index_entry.oid.kind()).or_raise(|| {
222 message!("{object_kind} object {} could not be decoded", index_entry.oid).corrupted()
223 })?;
224 if let Mode::HashCrc32DecodeEncode = verify_mode {
225 encode_buf.clear();
226 object
227 .write_to(&mut *encode_buf)
228 .or_raise(|| corruption("Reserialization of an object failed"))?;
229 if encode_buf.as_slice() != buf {
230 bail!(corruption(format!(
231 "{object_kind} object {} wasn't re-encoded without change, wanted\n{}\n\nGOT\n\n{}",
232 index_entry.oid,
233 buf.as_bstr(),
234 encode_buf.as_bstr()
235 )));
236 }
237 }
238 }
239 Blob => {}
240 }
241 }
242 Ok(())
243 }
244}