Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/synapse/blob/main/crates/synapse-git/src/pack.rs # synapse A component of the AienOS ecosystem. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `synapse / crates / synapse-git / src / pack.rs` 958 lines ยท 37164 bytes Raw Blame History 1 //! Native Git packfile (version 2) and pack index (version 2) codec for the bridge (ADR 0003 2 //! step H1, section 5.10: "Export ... written as packfiles, not loose objects"). Formats follow 3 //! `gitformat-pack` (Git 2.43 manual on this host): `PACK`, version, object count, entries of 4 //! "n-byte type and length (3-bit type, (n-1)*7+4-bit length)" then zlib data, deltified 5 //! entries (`OBJ_OFS_DELTA` 6 with the "offset encoding", `OBJ_REF_DELTA` 7 with the base 6 //! object name), and a trailing SHA-1 of everything before it. The index is `\377tOc`, 7 //! version 2, a 256-entry fan-out, sorted object names, CRC-32 of each packed entry, 31-bit 8 //! offsets with an 8-byte table for offsets of 2 GiB and more, the pack checksum, and its own 9 //! SHA-1. 10 //! 11 //! The writer emits whole (undeltified) objects in object ID order, so the same object set 12 //! always gives the same pack and index bytes. Deltas are read, never written: ADR 0003 keeps 13 //! deltas "only on the bridge wire" (thin packs, step H2). The reader resolves both delta 14 //! kinds and checks every size, offset and checksum before it trusts them; malformed input is 15 //! refused with `RefusalCode::GitObjectCorrupt`. 16 17 use crate::inflate::{zlib_decompress, zlib_inflate_prefix}; 18 use crate::object::{GitObject, ObjectKind}; 19 use crate::zlib_compress_store; 20 use sha1::{Digest, Sha1}; 21 use std::collections::{BTreeMap, HashMap}; 22 use synapse_core::{GitOid, RefusalCode, SynapseError, SynapseResult}; 23 24 fn corrupt(msg: impl Into) -> SynapseError { 25 SynapseError::new(RefusalCode::GitObjectCorrupt, msg) 26 } 27 28 fn over_cap(what: &str, size: u64, cap: u64) -> SynapseError { 29 SynapseError::new( 30 RefusalCode::QuotaPayloadTooLarge, 31 format!("{what} declares {size} bytes, over the {cap} byte cap"), 32 ) 33 } 34 35 const PACK_SIGNATURE: &[u8; 4] = b"PACK"; 36 const PACK_VERSION: u32 = 2; 37 const IDX_MAGIC: [u8; 4] = [0xff, b't', b'O', b'c']; 38 const IDX_VERSION: u32 = 2; 39 const OBJ_OFS_DELTA: u8 = 6; 40 const OBJ_REF_DELTA: u8 = 7; 41 /// Default for the most bytes one resolved object may hold while reading a pack (a declared size 42 /// above the cap is refused with `QuotaPayloadTooLarge` before anything is allocated). 43 pub const MAX_PACK_OBJECT_BYTES: u64 = 1 << 30; 44 /// Longest delta chain the reader follows (Git's own `pack.depth` maximum is 4095). 45 pub const MAX_DELTA_CHAIN: usize = 4096; 46 47 /// CRC-32 (IEEE 802.3, reflected polynomial 0xEDB88320), the checksum `gitformat-pack` puts in 48 /// the version 2 index for each packed entry (the same CRC zlib's `crc32` computes). 49 pub fn crc32(data: &[u8]) -> u32 { 50 static TABLE: std::sync::OnceLock<[u32; 256]> = std::sync::OnceLock::new(); 51 let table = TABLE.get_or_init(|| { 52 let mut t = [0u32; 256]; 53 for (i, slot) in t.iter_mut().enumerate() { 54 let mut c = i as u32; 55 for _ in 0..8 { 56 c = if c & 1 != 0 { 57 0xedb8_8320 ^ (c >> 1) 58 } else { 59 c >> 1 60 }; 61 } 62 *slot = c; 63 } 64 t 65 }); 66 let mut crc = !0u32; 67 for &b in data { 68 crc = table[((crc ^ u32::from(b)) & 0xff) as usize] ^ (crc >> 8); 69 } 70 !crc 71 } 72 73 /// One object's place in a pack: its ID, the offset of its entry header, and the CRC-32 of the 74 /// whole packed entry (header, delta base reference, and compressed data). 75 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 76 pub struct PackIndexEntry { 77 pub oid: GitOid, 78 pub offset: u64, 79 pub crc32: u32, 80 } 81 82 /// A written pack and its index. 83 #[derive(Debug, Clone, PartialEq, Eq)] 84 pub struct WrittenPack { 85 pub pack: Vec, 86 pub idx: Vec, 87 /// The pack's trailing SHA-1, which also names the files (`pack-.pack`). 88 pub checksum: GitOid, 89 pub entries: Vec, 90 } 91 92 fn encode_entry_header(pack_type: u8, size: u64, out: &mut Vec) { 93 let mut byte = (pack_type << 4) | (size & 0x0f) as u8; 94 let mut rest = size >> 4; 95 while rest != 0 { 96 out.push(byte | 0x80); 97 byte = (rest & 0x7f) as u8; 98 rest >>= 7; 99 } 100 out.push(byte); 101 } 102 103 /// Write `objects` (duplicates collapse) as one version 2 pack of whole objects in object ID 104 /// order, and its version 2 index. The output is a function of the object set alone. 105 pub fn write_pack(objects: &[GitObject]) -> WrittenPack { 106 let mut by_oid: BTreeMap = BTreeMap::new(); 107 for object in objects { 108 by_oid.entry(object.oid()).or_insert(object); 109 } 110 let mut pack = Vec::new(); 111 pack.extend_from_slice(PACK_SIGNATURE); 112 pack.extend_from_slice(&PACK_VERSION.to_be_bytes()); 113 pack.extend_from_slice(&(by_oid.len() as u32).to_be_bytes()); 114 let mut entries = Vec::with_capacity(by_oid.len()); 115 for (oid, object) in &by_oid { 116 let offset = pack.len(); 117 encode_entry_header( 118 object.kind.pack_type(), 119 object.payload.len() as u64, 120 &mut pack, 121 ); 122 pack.extend_from_slice(&zlib_compress_store(&object.payload)); 123 entries.push(PackIndexEntry { 124 oid: *oid, 125 offset: offset as u64, 126 crc32: crc32(&pack[offset..]), 127 }); 128 } 129 let checksum: [u8; 20] = Sha1::digest(&pack).into(); 130 pack.extend_from_slice(&checksum); 131 let checksum = GitOid(checksum); 132 let idx = write_idx(&entries, checksum); 133 WrittenPack { 134 pack, 135 idx, 136 checksum, 137 entries, 138 } 139 } 140 141 /// Encode a version 2 pack index for `entries` (sorted by object ID here) of the pack whose 142 /// trailing checksum is `pack_checksum`. 143 pub fn write_idx(entries: &[PackIndexEntry], pack_checksum: GitOid) -> Vec { 144 let mut sorted = entries.to_vec(); 145 sorted.sort_by_key(|e| e.oid); 146 let mut idx = Vec::with_capacity(8 + 1024 + sorted.len() * 28 + 40); 147 idx.extend_from_slice(&IDX_MAGIC); 148 idx.extend_from_slice(&IDX_VERSION.to_be_bytes()); 149 let mut fanout = [0u32; 256]; 150 for e in &sorted { 151 fanout[usize::from(e.oid.0[0])] += 1; 152 } 153 let mut running = 0u32; 154 for count in fanout { 155 running += count; 156 idx.extend_from_slice(&running.to_be_bytes()); 157 } 158 for e in &sorted { 159 idx.extend_from_slice(&e.oid.0); 160 } 161 for e in &sorted { 162 idx.extend_from_slice(&e.crc32.to_be_bytes()); 163 } 164 let mut large = Vec::new(); 165 for e in &sorted { 166 if e.offset < 0x8000_0000 { 167 idx.extend_from_slice(&(e.offset as u32).to_be_bytes()); 168 } else { 169 idx.extend_from_slice(&(0x8000_0000u32 | large.len() as u32).to_be_bytes()); 170 large.push(e.offset); 171 } 172 } 173 for offset in large { 174 idx.extend_from_slice(&offset.to_be_bytes()); 175 } 176 idx.extend_from_slice(&pack_checksum.0); 177 let own: [u8; 20] = Sha1::digest(&idx).into(); 178 idx.extend_from_slice(&own); 179 idx 180 } 181 182 /// Decode and check a version 2 pack index: magic, version, monotone fan-out that matches the 183 /// names, strictly ascending names, offsets (large ones through the 8-byte table), and the 184 /// index's own SHA-1. Returns the entries in name order and the pack checksum it records. 185 pub fn decode_idx(idx: &[u8]) -> SynapseResult<(Vec, GitOid)> { 186 if idx.len() < 8 + 1024 + 40 || idx[..4] != IDX_MAGIC { 187 return Err(corrupt( 188 "pack index is not version 2 (bad magic or too short)", 189 )); 190 } 191 if u32::from_be_bytes([idx[4], idx[5], idx[6], idx[7]]) != IDX_VERSION { 192 return Err(corrupt("pack index version is not 2")); 193 } 194 let body = &idx[..idx.len() - 20]; 195 let own: [u8; 20] = Sha1::digest(body).into(); 196 if own[..] != idx[idx.len() - 20..] { 197 return Err(corrupt("pack index checksum mismatch")); 198 } 199 let be32 = |at: usize| u32::from_be_bytes([idx[at], idx[at + 1], idx[at + 2], idx[at + 3]]); 200 let mut prev = 0u32; 201 for i in 0..256 { 202 let v = be32(8 + i * 4); 203 if v < prev { 204 return Err(corrupt("pack index fan-out is not monotone")); 205 } 206 prev = v; 207 } 208 let n = prev as usize; 209 let names_at = 8 + 1024; 210 let crcs_at = names_at + n * 20; 211 let offs_at = crcs_at + n * 4; 212 let large_at = offs_at + n * 4; 213 if large_at + 40 > idx.len() { 214 return Err(corrupt("pack index is shorter than its object count")); 215 } 216 let large_len = idx.len() - 40 - large_at; 217 if !large_len.is_multiple_of(8) { 218 return Err(corrupt( 219 "pack index large offset table is not whole entries", 220 )); 221 } 222 let mut entries = Vec::with_capacity(n); 223 let mut large_used = 0usize; 224 for i in 0..n { 225 let mut oid = [0u8; 20]; 226 oid.copy_from_slice(&idx[names_at + i * 20..names_at + i * 20 + 20]); 227 let oid = GitOid(oid); 228 if let Some(last) = entries.last().map(|e: &PackIndexEntry| e.oid) { 229 if oid <= last { 230 return Err(corrupt("pack index names are not strictly ascending")); 231 } 232 } 233 let first = usize::from(oid.0[0]); 234 let below = if first == 0 { 235 0 236 } else { 237 be32(8 + (first - 1) * 4) 238 }; 239 if (i as u32) < below || (i as u32) >= be32(8 + first * 4) { 240 return Err(corrupt("pack index fan-out does not match its names")); 241 } 242 let raw = be32(offs_at + i * 4); 243 let offset = if raw & 0x8000_0000 == 0 { 244 u64::from(raw) 245 } else { 246 let slot = (raw & 0x7fff_ffff) as usize; 247 if slot * 8 + 8 > large_len { 248 return Err(corrupt("pack index large offset slot out of range")); 249 } 250 large_used = large_used.max(slot + 1); 251 let at = large_at + slot * 8; 252 let mut b = [0u8; 8]; 253 b.copy_from_slice(&idx[at..at + 8]); 254 u64::from_be_bytes(b) 255 }; 256 entries.push(PackIndexEntry { 257 oid, 258 offset, 259 crc32: be32(crcs_at + i * 4), 260 }); 261 } 262 if large_used * 8 != large_len { 263 return Err(corrupt("pack index large offset table has unused entries")); 264 } 265 let mut checksum = [0u8; 20]; 266 checksum.copy_from_slice(&idx[idx.len() - 40..idx.len() - 20]); 267 Ok((entries, GitOid(checksum))) 268 } 269 270 /// One raw pack entry before delta resolution. 271 enum RawEntry { 272 Whole(ObjectKind, Vec), 273 OfsDelta(u64, Vec), 274 RefDelta(GitOid, Vec), 275 } 276 277 /// A version 2 (or 3) pack held in memory with its object ID to offset map. Objects are 278 /// resolved on demand (delta chains followed iteratively) and checked against the requested 279 /// object ID. 280 pub struct PackReader { 281 data: Vec, 282 by_oid: HashMap, 283 entries: Vec, 284 cache: HashMap>)>, 285 cache_bytes: usize, 286 max_object_bytes: u64, 287 } 288 289 const CACHE_BOUND_BYTES: usize = 256 << 20; 290 291 fn check_pack_framing(data: &[u8]) -> SynapseResult { 292 if data.len() < 12 + 20 || &data[..4] != PACK_SIGNATURE { 293 return Err(corrupt("not a Git pack (bad signature or too short)")); 294 } 295 let version = u32::from_be_bytes([data[4], data[5], data[6], data[7]]); 296 if version != 2 && version != 3 { 297 return Err(corrupt(format!("pack version {version} is not 2 or 3"))); 298 } 299 let body = &data[..data.len() - 20]; 300 let sum: [u8; 20] = Sha1::digest(body).into(); 301 if sum[..] != data[data.len() - 20..] { 302 return Err(corrupt("pack checksum mismatch")); 303 } 304 Ok(u32::from_be_bytes([data[8], data[9], data[10], data[11]])) 305 } 306 307 impl PackReader { 308 /// Open a pack with its version 2 index (as Git writes them side by side). The index must 309 /// record this pack's checksum and name exactly the pack's object count; every offset must 310 /// fall inside the pack body. 311 pub fn with_index(data: Vec, idx: &[u8]) -> SynapseResult { 312 Self::with_index_limited(data, idx, MAX_PACK_OBJECT_BYTES) 313 } 314 315 /// [`Self::with_index`] with a per-object cap: no entry, delta stream or delta result may 316 /// declare more than `max_object_bytes`. 317 pub fn with_index_limited( 318 data: Vec, 319 idx: &[u8], 320 max_object_bytes: u64, 321 ) -> SynapseResult { 322 let count = check_pack_framing(&data)?; 323 let (entries, pack_sum) = decode_idx(idx)?; 324 if pack_sum.0[..] != data[data.len() - 20..] { 325 return Err(corrupt("pack index names a different pack checksum")); 326 } 327 if entries.len() != count as usize { 328 return Err(corrupt( 329 "pack index object count differs from the pack header", 330 )); 331 } 332 let body_end = (data.len() - 20) as u64; 333 let mut by_oid = HashMap::with_capacity(entries.len()); 334 for e in &entries { 335 if e.offset < 12 || e.offset >= body_end { 336 return Err(corrupt("pack index offset outside the pack body")); 337 } 338 by_oid.insert(e.oid, e.offset); 339 } 340 Ok(Self { 341 data, 342 by_oid, 343 entries, 344 cache: HashMap::new(), 345 cache_bytes: 0, 346 max_object_bytes, 347 }) 348 } 349 350 /// Index a pack with no index file (`git index-pack` done natively): walk every entry in 351 /// order, resolve it, and compute its object ID and CRC-32. The entries must end exactly at 352 /// the trailing checksum. Every `OBJ_REF_DELTA` base must be in the pack (a self-contained 353 /// pack, as `gitformat-pack` requires on disk). 354 pub fn index(data: Vec) -> SynapseResult { 355 Self::index_with_limits(data, &crate::repo::ReadLimits::default()) 356 } 357 358 /// [`Self::index`] under `limits`: no entry may declare more than `max_object_bytes`, and 359 /// the sizes every entry declares it resolves to (whole sizes, and delta result sizes read 360 /// from the first bytes of each delta stream) must fit `max_total_object_bytes` before any 361 /// entry is resolved, as when a repository is opened. Each entry is resolved once, plus 362 /// once more for each reference delta base it waits on (no repeated rounds over the pack). 363 pub fn index_with_limits( 364 data: Vec, 365 limits: &crate::repo::ReadLimits, 366 ) -> SynapseResult { 367 let max = limits.max_object_bytes; 368 let count = check_pack_framing(&data)?; 369 let body_end = data.len() - 20; 370 let mut offsets = Vec::with_capacity((count as usize).min(body_end / 2)); 371 let mut pos = 12usize; 372 let mut declared = 0u64; 373 for _ in 0..count { 374 if pos >= body_end { 375 return Err(corrupt("pack holds fewer entries than its header declares")); 376 } 377 let size = declared_object_size(&data[..body_end], pos as u64, max)?; 378 declared = declared.saturating_add(size); 379 if declared > limits.max_total_object_bytes { 380 return Err(SynapseError::new( 381 RefusalCode::QuotaPayloadTooLarge, 382 format!( 383 "pack entries declare over the {} byte budget", 384 limits.max_total_object_bytes 385 ), 386 )); 387 } 388 let (_, next) = read_raw_entry(&data[..body_end], pos as u64, max)?; 389 offsets.push((pos as u64, crc32(&data[pos..next]))); 390 pos = next; 391 } 392 if pos != body_end { 393 return Err(corrupt( 394 "pack has bytes between its last entry and its checksum", 395 )); 396 } 397 let mut reader = Self { 398 data, 399 by_oid: HashMap::with_capacity(offsets.len()), 400 entries: Vec::with_capacity(offsets.len()), 401 cache: HashMap::new(), 402 cache_bytes: 0, 403 max_object_bytes: max, 404 }; 405 // Whole objects and offset deltas resolve by position alone; an entry whose chain 406 // reaches a reference delta with an unresolved base waits on that base's ID and is 407 // retried once that ID resolves. 408 let mut waiting: HashMap> = HashMap::new(); 409 let mut ready: Vec<(u64, u32)> = offsets.into_iter().rev().collect(); 410 while let Some((offset, crc)) = ready.pop() { 411 match reader.try_resolve_at(offset)? { 412 Ok((kind, payload)) => { 413 let oid = GitOid::compute_git_object(kind.name(), &payload); 414 if reader.by_oid.insert(oid, offset).is_some() { 415 return Err(corrupt(format!("pack holds object {oid} twice"))); 416 } 417 reader.entries.push(PackIndexEntry { 418 oid, 419 offset, 420 crc32: crc, 421 }); 422 if let Some(w) = waiting.remove(&oid) { 423 ready.extend(w); 424 } 425 } 426 Err(base) => waiting.entry(base).or_default().push((offset, crc)), 427 } 428 } 429 if !waiting.is_empty() { 430 return Err(corrupt( 431 "pack has reference deltas whose base is not in the pack (thin pack)", 432 )); 433 } 434 reader.entries.sort_by_key(|e| e.oid); 435 Ok(reader) 436 } 437 438 /// Entries in object ID order. 439 pub fn entries(&self) -> &[PackIndexEntry] { 440 &self.entries 441 } 442 443 pub fn contains(&self, oid: GitOid) -> bool { 444 self.by_oid.contains_key(&oid) 445 } 446 447 /// Sum of the sizes every entry declares it resolves to, read from entry headers and the 448 /// first bytes of each delta stream without resolving anything. Resolving an entry 449 /// produces exactly its declared size (checked on every read), so this bounds what reading 450 /// the whole pack can hold. An entry over the per-object cap is refused. 451 pub fn declared_bytes(&self) -> SynapseResult { 452 let body = &self.data[..self.data.len() - 20]; 453 let mut total = 0u64; 454 for e in &self.entries { 455 let size = declared_object_size(body, e.offset, self.max_object_bytes)?; 456 total = total 457 .checked_add(size) 458 .ok_or_else(|| corrupt("pack declared sizes overflow u64"))?; 459 } 460 Ok(total) 461 } 462 463 /// Read and resolve object `oid`, checking that its content hashes to `oid`. 464 pub fn read(&mut self, oid: GitOid) -> SynapseResult> { 465 let Some(&offset) = self.by_oid.get(&oid) else { 466 return Ok(None); 467 }; 468 let (kind, payload) = self.resolve_at(offset)?; 469 let object = GitObject::new(kind, payload.as_ref().clone()); 470 if object.oid() != oid { 471 return Err(corrupt(format!( 472 "pack object at offset {offset} hashes to {} not {oid}", 473 object.oid() 474 ))); 475 } 476 Ok(Some(object)) 477 } 478 479 fn remember(&mut self, offset: u64, kind: ObjectKind, payload: std::sync::Arc>) { 480 if self.cache_bytes + payload.len() > CACHE_BOUND_BYTES { 481 self.cache.clear(); 482 self.cache_bytes = 0; 483 } 484 self.cache_bytes += payload.len(); 485 self.cache.insert(offset, (kind, payload)); 486 } 487 488 fn resolve_at(&mut self, offset: u64) -> SynapseResult<(ObjectKind, std::sync::Arc>)> { 489 self.try_resolve_at(offset)? 490 .map_err(|base| corrupt(format!("pack reference delta base not found: {base}"))) 491 } 492 493 /// Resolve the entry at `offset`, or name the reference delta base its chain reaches that 494 /// is not (yet) indexed. 495 #[allow(clippy::type_complexity)] 496 fn try_resolve_at( 497 &mut self, 498 offset: u64, 499 ) -> SynapseResult>), GitOid>> { 500 let body_end = self.data.len() - 20; 501 let mut chain: Vec<(u64, Vec)> = Vec::new(); 502 let mut at = offset; 503 let (kind, mut payload) = loop { 504 if let Some((kind, payload)) = self.cache.get(&at) { 505 break (*kind, payload.clone()); 506 } 507 if chain.len() > MAX_DELTA_CHAIN { 508 return Err(corrupt( 509 "pack delta chain is longer than the reader follows", 510 )); 511 } 512 let (raw, _) = read_raw_entry(&self.data[..body_end], at, self.max_object_bytes)?; 513 match raw { 514 RawEntry::Whole(kind, payload) => break (kind, std::sync::Arc::new(payload)), 515 RawEntry::OfsDelta(base, delta) => { 516 chain.push((at, delta)); 517 at = base; 518 } 519 RawEntry::RefDelta(base_oid, delta) => { 520 let Some(&base) = self.by_oid.get(&base_oid) else { 521 return Ok(Err(base_oid)); 522 }; 523 chain.push((at, delta)); 524 at = base; 525 } 526 } 527 if chain.iter().any(|(o, _)| *o == at) { 528 return Err(corrupt("pack delta chain loops")); 529 } 530 }; 531 while let Some((at, delta)) = chain.pop() { 532 payload = std::sync::Arc::new(apply_delta_limited( 533 &payload, 534 &delta, 535 self.max_object_bytes, 536 )?); 537 self.remember(at, kind, payload.clone()); 538 } 539 Ok(Ok((kind, payload))) 540 } 541 } 542 543 fn read_size_encoding(data: &[u8], pos: &mut usize) -> SynapseResult { 544 let mut value = 0u64; 545 let mut shift = 0u32; 546 loop { 547 let byte = *data 548 .get(*pos) 549 .ok_or_else(|| corrupt("size encoding truncated"))?; 550 *pos += 1; 551 if shift > 63 || (shift == 63 && byte & 0x7e != 0) { 552 return Err(corrupt("size encoding overflows u64")); 553 } 554 value |= u64::from(byte & 0x7f) << shift; 555 if byte & 0x80 == 0 { 556 return Ok(value); 557 } 558 shift += 7; 559 } 560 } 561 562 /// A pack entry's header: its pack type, declared size (the object's size for whole entries, 563 /// the delta stream's size for deltas), delta base (offset, or object ID for a reference 564 /// delta), and where its zlib data starts. 565 struct EntryHeader { 566 pack_type: u8, 567 size: u64, 568 base: Option>, 569 data_pos: usize, 570 } 571 572 /// Parse the header of the entry at `offset`. A declared size over `max_object_bytes` is 573 /// refused (`QuotaPayloadTooLarge`) before anything is allocated. 574 fn read_entry_header( 575 body: &[u8], 576 offset: u64, 577 max_object_bytes: u64, 578 ) -> SynapseResult { 579 let mut pos = usize::try_from(offset).map_err(|_| corrupt("pack offset overflows"))?; 580 let first = *body 581 .get(pos) 582 .ok_or_else(|| corrupt("pack entry offset past the pack body"))?; 583 pos += 1; 584 let pack_type = (first >> 4) & 0x07; 585 let mut size = u64::from(first & 0x0f); 586 if first & 0x80 != 0 { 587 let rest = read_size_encoding(body, &mut pos)?; 588 if rest > (u64::MAX >> 4) { 589 return Err(corrupt("pack entry size overflows u64")); 590 } 591 size |= rest << 4; 592 } 593 if size > max_object_bytes { 594 return Err(over_cap("pack entry", size, max_object_bytes)); 595 } 596 let entry_start = offset; 597 let base = match pack_type { 598 1..=4 => None, 599 OBJ_OFS_DELTA => { 600 let mut byte = *body 601 .get(pos) 602 .ok_or_else(|| corrupt("offset delta truncated"))?; 603 pos += 1; 604 let mut back = u64::from(byte & 0x7f); 605 while byte & 0x80 != 0 { 606 byte = *body 607 .get(pos) 608 .ok_or_else(|| corrupt("offset delta truncated"))?; 609 pos += 1; 610 back = back 611 .checked_add(1) 612 .and_then(|b| b.checked_mul(128)) 613 .map(|b| b | u64::from(byte & 0x7f)) 614 .ok_or_else(|| corrupt("offset delta overflows"))?; 615 } 616 if back == 0 || back > entry_start { 617 return Err(corrupt("offset delta base is not before the entry")); 618 } 619 Some(Ok(entry_start - back)) 620 } 621 OBJ_REF_DELTA => { 622 let raw = body 623 .get(pos..pos + 20) 624 .ok_or_else(|| corrupt("reference delta truncated"))?; 625 pos += 20; 626 let mut oid = [0u8; 20]; 627 oid.copy_from_slice(raw); 628 Some(Err(GitOid(oid))) 629 } 630 other => return Err(corrupt(format!("pack entry type {other} is invalid"))), 631 }; 632 if pos > body.len() { 633 return Err(corrupt("pack entry truncated")); 634 } 635 Ok(EntryHeader { 636 pack_type, 637 size, 638 base, 639 data_pos: pos, 640 }) 641 } 642 643 /// The size of the object the entry at `offset` resolves to, read without resolving it: the 644 /// header's size for a whole entry, the result size at the start of the delta stream for a 645 /// delta (only its first bytes are inflated). Over `max_object_bytes` is refused. 646 fn declared_object_size(body: &[u8], offset: u64, max_object_bytes: u64) -> SynapseResult { 647 let h = read_entry_header(body, offset, max_object_bytes)?; 648 if h.base.is_none() { 649 return Ok(h.size); 650 } 651 // Two size encodings of at most 10 bytes each start every delta stream. 652 let head = zlib_inflate_prefix(&body[h.data_pos..], 20)?; 653 let mut pos = 0usize; 654 read_size_encoding(&head, &mut pos)?; 655 let result_size = read_size_encoding(&head, &mut pos)?; 656 if result_size > max_object_bytes { 657 return Err(over_cap("delta result", result_size, max_object_bytes)); 658 } 659 Ok(result_size) 660 } 661 662 /// Read the entry at `offset`: header, delta base, and decompressed data. Returns the entry 663 /// and the offset just past it. 664 fn read_raw_entry( 665 body: &[u8], 666 offset: u64, 667 max_object_bytes: u64, 668 ) -> SynapseResult<(RawEntry, usize)> { 669 let EntryHeader { 670 pack_type, 671 size, 672 base, 673 data_pos: pos, 674 } = read_entry_header(body, offset, max_object_bytes)?; 675 let (data, used) = zlib_decompress(&body[pos..], size as usize)?; 676 if data.len() as u64 != size { 677 return Err(corrupt(format!( 678 "pack entry declares {size} bytes but inflates to {}", 679 data.len() 680 ))); 681 } 682 let entry = match base { 683 None => RawEntry::Whole(ObjectKind::from_pack_type(pack_type)?, data), 684 Some(Ok(base)) => RawEntry::OfsDelta(base, data), 685 Some(Err(oid)) => RawEntry::RefDelta(oid, data), 686 }; 687 Ok((entry, pos + used)) 688 } 689 690 /// Apply a Git delta (`gitformat-pack`, "Deltified representation") to `base`, with the 691 /// default per-object cap. 692 pub fn apply_delta(base: &[u8], delta: &[u8]) -> SynapseResult> { 693 apply_delta_limited(base, delta, MAX_PACK_OBJECT_BYTES) 694 } 695 696 /// [`apply_delta`] refusing a declared result over `max_object_bytes` before any allocation. 697 /// The output grows as instructions produce bytes (never reserved up front past what the 698 /// base and delta could give in one pass) and may never pass the declared result size. 699 pub fn apply_delta_limited( 700 base: &[u8], 701 delta: &[u8], 702 max_object_bytes: u64, 703 ) -> SynapseResult> { 704 let mut pos = 0usize; 705 let base_size = read_size_encoding(delta, &mut pos)?; 706 if base_size != base.len() as u64 { 707 return Err(corrupt(format!( 708 "delta expects a {base_size} byte base, base has {}", 709 base.len() 710 ))); 711 } 712 let result_size = read_size_encoding(delta, &mut pos)?; 713 if result_size > max_object_bytes { 714 return Err(over_cap("delta result", result_size, max_object_bytes)); 715 } 716 let mut out = Vec::with_capacity(result_size.min((base.len() + delta.len()) as u64) as usize); 717 while pos < delta.len() { 718 let op = delta[pos]; 719 pos += 1; 720 if op & 0x80 != 0 { 721 let mut fields = [0u64; 7]; 722 for (bit, field) in fields.iter_mut().enumerate() { 723 if op & (1 << bit) != 0 { 724 *field = u64::from( 725 *delta 726 .get(pos) 727 .ok_or_else(|| corrupt("delta copy instruction truncated"))?, 728 ); 729 pos += 1; 730 } 731 } 732 let offset = fields[0] | fields[1] << 8 | fields[2] << 16 | fields[3] << 24; 733 let mut size = fields[4] | fields[5] << 8 | fields[6] << 16; 734 if size == 0 { 735 size = 0x10000; 736 } 737 let end = offset 738 .checked_add(size) 739 .filter(|&e| e <= base.len() as u64) 740 .ok_or_else(|| corrupt("delta copy reaches past the base"))?; 741 out.extend_from_slice(&base[offset as usize..end as usize]); 742 } else if op != 0 { 743 let n = usize::from(op); 744 let data = delta 745 .get(pos..pos + n) 746 .ok_or_else(|| corrupt("delta insert instruction truncated"))?; 747 out.extend_from_slice(data); 748 pos += n; 749 } else { 750 return Err(corrupt("delta instruction 0 is reserved")); 751 } 752 if out.len() as u64 > result_size { 753 return Err(corrupt("delta output exceeds its declared size")); 754 } 755 } 756 if out.len() as u64 != result_size { 757 return Err(corrupt(format!( 758 "delta declares {result_size} bytes, produced {}", 759 out.len() 760 ))); 761 } 762 Ok(out) 763 } 764 765 #[cfg(test)] 766 mod tests { 767 use super::*; 768 769 fn refusal(r: SynapseResult, case: &str) -> SynapseError { 770 match r { 771 Ok(p) => panic!( 772 "{case}: indexed {} entries instead of refusing", 773 p.entries().len() 774 ), 775 Err(e) => e, 776 } 777 } 778 779 /// A pack whose first entry is a reference delta on the blob stored after it (legal on 780 /// disk: the base is in the pack), or with the base left out (a thin pack). 781 fn ref_delta_before_base_pack(with_base: bool) -> (Vec, GitObject, GitObject) { 782 let base = GitObject::new(ObjectKind::Blob, b"hello base object\n".repeat(4)); 783 let mut result = base.payload.clone(); 784 result.push(b'!'); 785 let target = GitObject::new(ObjectKind::Blob, result.clone()); 786 // Sizes (one byte each, both under 128), copy the whole base, insert one byte. 787 let delta = vec![ 788 base.payload.len() as u8, 789 result.len() as u8, 790 0x90, 791 base.payload.len() as u8, 792 0x01, 793 b'!', 794 ]; 795 let mut pack = Vec::new(); 796 pack.extend_from_slice(PACK_SIGNATURE); 797 pack.extend_from_slice(&PACK_VERSION.to_be_bytes()); 798 pack.extend_from_slice(&(1 + u32::from(with_base)).to_be_bytes()); 799 encode_entry_header(OBJ_REF_DELTA, delta.len() as u64, &mut pack); 800 pack.extend_from_slice(&base.oid().0); 801 pack.extend_from_slice(&zlib_compress_store(&delta)); 802 if with_base { 803 encode_entry_header(base.kind.pack_type(), base.payload.len() as u64, &mut pack); 804 pack.extend_from_slice(&zlib_compress_store(&base.payload)); 805 } 806 let sum: [u8; 20] = Sha1::digest(&pack).into(); 807 pack.extend_from_slice(&sum); 808 (pack, base, target) 809 } 810 811 #[test] 812 fn indexer_resolves_a_reference_delta_stored_before_its_base_within_the_budget() { 813 let (pack, base, target) = ref_delta_before_base_pack(true); 814 let declared = (base.payload.len() + target.payload.len()) as u64; 815 let fits = crate::repo::ReadLimits { 816 max_total_object_bytes: declared, 817 ..Default::default() 818 }; 819 let mut reader = PackReader::index_with_limits(pack.clone(), &fits).unwrap(); 820 assert_eq!(reader.entries().len(), 2); 821 assert_eq!(reader.read(base.oid()).unwrap().unwrap(), base); 822 assert_eq!(reader.read(target.oid()).unwrap().unwrap(), target); 823 // One byte short of what the entries declare: refused before anything is resolved. 824 let short = crate::repo::ReadLimits { 825 max_total_object_bytes: declared - 1, 826 ..Default::default() 827 }; 828 let err = refusal( 829 PackReader::index_with_limits(pack, &short), 830 "one byte short", 831 ); 832 assert_eq!(err.code, RefusalCode::QuotaPayloadTooLarge); 833 // The per-object cap applies to the delta result as well. 834 let (pack, _, _) = ref_delta_before_base_pack(true); 835 let capped = crate::repo::ReadLimits { 836 max_object_bytes: base.payload.len() as u64, 837 ..Default::default() 838 }; 839 let err = refusal( 840 PackReader::index_with_limits(pack, &capped), 841 "delta result over the cap", 842 ); 843 assert_eq!(err.code, RefusalCode::QuotaPayloadTooLarge); 844 let (thin, _, _) = ref_delta_before_base_pack(false); 845 let err = refusal(PackReader::index(thin), "thin pack"); 846 assert_eq!(err.code, RefusalCode::GitObjectCorrupt); 847 assert!(err.message.contains("thin pack"), "{}", err.message); 848 } 849 850 #[test] 851 fn crc32_matches_the_ieee_check_value() { 852 assert_eq!(crc32(b"`123456789`"), 0xcbf4_3926); 853 assert_eq!(crc32(b""), 0); 854 } 855 856 #[test] 857 fn written_pack_indexes_back_to_the_same_entries_and_objects() { 858 let objects = vec![ 859 GitObject::new(ObjectKind::Blob, b"hello\n".to_vec()), 860 GitObject::new(ObjectKind::Blob, vec![7u8; 70_000]), 861 GitObject::new(ObjectKind::Tree, Vec::new()), 862 GitObject::new(ObjectKind::Blob, b"hello\n".to_vec()), 863 ]; 864 let written = write_pack(&objects); 865 assert_eq!(written.entries.len(), 3); 866 assert_eq!(write_pack(&objects), written, "deterministic"); 867 let mut reader = PackReader::index(written.pack.clone()).unwrap(); 868 assert_eq!(reader.entries(), &written.entries[..]); 869 let (decoded, sum) = decode_idx(&written.idx).unwrap(); 870 assert_eq!(decoded, written.entries); 871 assert_eq!(sum, written.checksum); 872 for o in &objects { 873 assert_eq!(reader.read(o.oid()).unwrap().as_ref(), Some(o)); 874 } 875 let mut with_idx = PackReader::with_index(written.pack.clone(), &written.idx).unwrap(); 876 assert_eq!( 877 with_idx.read(objects[1].oid()).unwrap().as_ref(), 878 Some(&objects[1]) 879 ); 880 } 881 882 #[test] 883 fn large_offsets_use_the_eight_byte_table() { 884 let entries = vec![ 885 PackIndexEntry { 886 oid: GitOid([1; 20]), 887 offset: 12, 888 crc32: 5, 889 }, 890 PackIndexEntry { 891 oid: GitOid([2; 20]), 892 offset: 0x1_0000_0000, 893 crc32: 6, 894 }, 895 ]; 896 let idx = write_idx(&entries, GitOid([9; 20])); 897 assert_eq!(decode_idx(&idx).unwrap(), (entries, GitOid([9; 20]))); 898 } 899 900 #[test] 901 fn delta_copy_and_insert_apply_and_bad_deltas_are_refused() { 902 let base = b"`0123456789abcdef`"; 903 // base 16, result 7: copy offset 10 size 3 ("abc"), insert "XYZ!"? (4 bytes). 904 let delta = [16u8, 7, 0x91, 10, 3, 4, b'X', b'Y', b'Z', b'!']; 905 assert_eq!(apply_delta(base, &delta).unwrap(), b"abcXYZ!"); 906 assert!( 907 apply_delta(base, &[15, 7, 0x91, 10, 3]).is_err(), 908 "base size" 909 ); 910 assert!( 911 apply_delta(base, &[16, 3, 0x91, 15, 3]).is_err(), 912 "copy past base" 913 ); 914 assert!(apply_delta(base, &[16, 3, 0x00]).is_err(), "reserved op"); 915 assert!( 916 apply_delta(base, &[16, 4, 0x91, 10, 3]).is_err(), 917 "short result" 918 ); 919 // A declared result over the cap is refused before any output is produced. 920 let e = apply_delta_limited(base, &[16, 7, 0x91, 10, 3, 4, b'X', b'Y', b'Z', b'!'], 6) 921 .unwrap_err(); 922 assert_eq!(e.code, RefusalCode::QuotaPayloadTooLarge); 923 assert_eq!( 924 apply_delta_limited(base, &delta, 7).unwrap(), 925 b"abcXYZ!", 926 "exactly at the cap" 927 ); 928 } 929 930 #[test] 931 fn every_truncation_and_bit_flip_of_a_pack_is_refused_without_panic() { 932 let written = write_pack(&[ 933 GitObject::new(ObjectKind::Blob, b"a".to_vec()), 934 GitObject::new(ObjectKind::Tree, Vec::new()), 935 ]); 936 let p = &written.pack; 937 for cut in 0..p.len() { 938 assert!(PackReader::index(p[..cut].to_vec()).is_err()); 939 } 940 for bit in 0..p.len() * 8 { 941 let mut d = p.clone(); 942 d[bit / 8] ^= 1 << (bit % 8); 943 assert!(PackReader::index(d.clone()).is_err(), "flip {bit}"); 944 assert!( 945 PackReader::with_index(d, &written.idx).is_err(), 946 "flip {bit}" 947 ); 948 } 949 for bit in 0..written.idx.len() * 8 { 950 let mut d = written.idx.clone(); 951 d[bit / 8] ^= 1 << (bit % 8); 952 assert!( 953 PackReader::with_index(p.clone(), &d).is_err(), 954 "idx flip {bit}" 955 ); 956 } 957 } 958 }