synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-git / src / repo.rs
| 1 | //! Native Git repository reader and pack exporter for the bridge (ADR 0003 step H1). |
| 2 | //! |
| 3 | //! [`GitRepository`] reads a repository's object database directly: loose objects |
| 4 | //! (`objects/xx/<38 hex>`, zlib) and every `objects/pack/pack-*.pack` with its version 2 |
| 5 | //! `.idx`, resolving deltas natively; and its references (loose refs, `packed-refs`, `HEAD`). |
| 6 | //! [`GitRepository::full_history`] collects every object reachable from every reference, so an |
| 7 | //! import sees the whole history: merge parents, annotated tags (including tags of tags), |
| 8 | //! file modes, and signatures inside commit and tag headers. |
| 9 | //! |
| 10 | //! [`export_repository`] writes an object set into a new bare repository as one pack and its |
| 11 | //! index plus the references, never as loose objects. It refuses an existing destination, so it |
| 12 | //! can never move a human branch of a repository that already exists. |
| 13 | //! |
| 14 | //! No Git process is started here; the system `git` is used only by the tests, as an |
| 15 | //! independent oracle. |
| 16 | |
| 17 | use crate::inflate::{zlib_decompress, zlib_inflate_prefix}; |
| 18 | use crate::object::{object_links, GitObject, ObjectKind}; |
| 19 | use crate::pack::{write_pack, PackReader, WrittenPack}; |
| 20 | use std::collections::{BTreeMap, BTreeSet, VecDeque}; |
| 21 | use std::fs::{self, File}; |
| 22 | use std::io::{Read, Write}; |
| 23 | use std::path::{Path, PathBuf}; |
| 24 | use synapse_core::{GitOid, RefusalCode, SynapseError, SynapseResult}; |
| 25 | |
| 26 | fn corrupt(msg: impl Into<String>) -> SynapseError { |
| 27 | SynapseError::new(RefusalCode::GitObjectCorrupt, msg) |
| 28 | } |
| 29 | |
| 30 | fn io(e: std::io::Error, what: &Path) -> SynapseError { |
| 31 | SynapseError::new(RefusalCode::IoFailure, format!("{}: {e}", what.display())) |
| 32 | } |
| 33 | |
| 34 | fn over_cap(what: &Path, size: u64, cap: u64) -> SynapseError { |
| 35 | SynapseError::new( |
| 36 | RefusalCode::QuotaPayloadTooLarge, |
| 37 | format!( |
| 38 | "{} holds {size} bytes, over the {cap} byte cap", |
| 39 | what.display() |
| 40 | ), |
| 41 | ) |
| 42 | } |
| 43 | |
| 44 | fn not_regular(what: &Path, detail: &str) -> SynapseError { |
| 45 | SynapseError::new( |
| 46 | RefusalCode::PathInvalid, |
| 47 | format!( |
| 48 | "{} is {detail}; the bridge reads only regular files and directories inside the repository", |
| 49 | what.display() |
| 50 | ), |
| 51 | ) |
| 52 | } |
| 53 | |
| 54 | fn describe(t: fs::FileType) -> &'static str { |
| 55 | if t.is_symlink() { |
| 56 | "a symbolic link" |
| 57 | } else if t.is_dir() { |
| 58 | "a directory" |
| 59 | } else { |
| 60 | "not a regular file (a pipe, socket or device)" |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | /// Most bytes a loose object may inflate to by default. |
| 65 | pub const MAX_LOOSE_OBJECT_BYTES: usize = 1 << 30; |
| 66 | |
| 67 | /// Default cap on a loose reference file and on `HEAD` (a 40-hex ID or `ref: <name>`). |
| 68 | pub const DEFAULT_MAX_REF_FILE_BYTES: u64 = 4096; |
| 69 | /// Default cap on `packed-refs`. |
| 70 | pub const DEFAULT_MAX_PACKED_REFS_BYTES: u64 = 64 << 20; |
| 71 | /// Default cap on all `.pack` and `.idx` files together (they are held in memory). |
| 72 | pub const DEFAULT_MAX_PACK_FILES_BYTES: u64 = 2 << 30; |
| 73 | /// Default budget for the inflated bytes of every object a read may hold. |
| 74 | pub const DEFAULT_MAX_TOTAL_OBJECT_BYTES: u64 = 1 << 30; |
| 75 | |
| 76 | /// What reading a repository may cost. Every limit is checked before the bytes it bounds are |
| 77 | /// allocated, and an excess is refused with `QuotaPayloadTooLarge`. |
| 78 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 79 | pub struct ReadLimits { |
| 80 | /// A loose reference file or `HEAD`. |
| 81 | pub max_ref_file_bytes: u64, |
| 82 | /// `packed-refs`. |
| 83 | pub max_packed_refs_bytes: u64, |
| 84 | /// Every `.pack` and `.idx` file together. |
| 85 | pub max_pack_files_bytes: u64, |
| 86 | /// One object (whole, delta stream, or delta result), packed or loose. |
| 87 | pub max_object_bytes: u64, |
| 88 | /// The objects of the whole read: the sizes every pack entry declares (counted at |
| 89 | /// [`GitRepository::open_with_limits`]) plus every loose object read. |
| 90 | pub max_total_object_bytes: u64, |
| 91 | } |
| 92 | |
| 93 | impl Default for ReadLimits { |
| 94 | fn default() -> Self { |
| 95 | Self { |
| 96 | max_ref_file_bytes: DEFAULT_MAX_REF_FILE_BYTES, |
| 97 | max_packed_refs_bytes: DEFAULT_MAX_PACKED_REFS_BYTES, |
| 98 | max_pack_files_bytes: DEFAULT_MAX_PACK_FILES_BYTES, |
| 99 | max_object_bytes: MAX_LOOSE_OBJECT_BYTES as u64, |
| 100 | max_total_object_bytes: DEFAULT_MAX_TOTAL_OBJECT_BYTES, |
| 101 | } |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | /// Read `path` if it is a regular file of at most `max` bytes. `Ok(None)` when it does not |
| 106 | /// exist. A symbolic link, directory, pipe, socket or device is refused (`PathInvalid`) |
| 107 | /// without being opened, so a pipe cannot block the reader and a link cannot lead outside the |
| 108 | /// repository. The open itself uses `O_NOFOLLOW | O_NONBLOCK` and the opened file must be the |
| 109 | /// regular file inspected (same device and inode), so a file swapped between the check and the |
| 110 | /// open is refused too; at most `max + 1` bytes are read even if it grows. |
| 111 | pub(crate) fn read_regular(path: &Path, max: u64) -> SynapseResult<Option<Vec<u8>>> { |
| 112 | let meta = match fs::symlink_metadata(path) { |
| 113 | Ok(m) => m, |
| 114 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), |
| 115 | Err(e) => return Err(io(e, path)), |
| 116 | }; |
| 117 | if !meta.file_type().is_file() { |
| 118 | return Err(not_regular(path, describe(meta.file_type()))); |
| 119 | } |
| 120 | if meta.len() > max { |
| 121 | return Err(over_cap(path, meta.len(), max)); |
| 122 | } |
| 123 | let (file, opened) = open_inspected(path, &meta)?; |
| 124 | let mut bytes = Vec::with_capacity(opened.len().min(max) as usize); |
| 125 | file.take(max.saturating_add(1)) |
| 126 | .read_to_end(&mut bytes) |
| 127 | .map_err(|e| io(e, path))?; |
| 128 | if bytes.len() as u64 > max { |
| 129 | return Err(over_cap(path, bytes.len() as u64, max)); |
| 130 | } |
| 131 | Ok(Some(bytes)) |
| 132 | } |
| 133 | |
| 134 | /// Open `path`, which `symlink_metadata` reported as `meta` (a regular file), and require the |
| 135 | /// opened file to be that same regular file. `O_NOFOLLOW`: a link swapped in after the check |
| 136 | /// fails to open (`ELOOP`). `O_NONBLOCK`: a pipe swapped in opens at once instead of waiting for |
| 137 | /// a writer, and the device and inode check refuses it. |
| 138 | fn open_inspected(path: &Path, meta: &fs::Metadata) -> SynapseResult<(File, fs::Metadata)> { |
| 139 | use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; |
| 140 | let file = fs::OpenOptions::new() |
| 141 | .read(true) |
| 142 | .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) |
| 143 | .open(path) |
| 144 | .map_err(|e| match e.raw_os_error() { |
| 145 | Some(libc::ELOOP) => not_regular(path, "a symbolic link"), |
| 146 | _ => io(e, path), |
| 147 | })?; |
| 148 | let opened = file.metadata().map_err(|e| io(e, path))?; |
| 149 | if !opened.file_type().is_file() || opened.ino() != meta.ino() || opened.dev() != meta.dev() { |
| 150 | return Err(not_regular(path, "a file that changed while being opened")); |
| 151 | } |
| 152 | Ok((file, opened)) |
| 153 | } |
| 154 | |
| 155 | /// `Ok(true)` if `path` is a real directory, `Ok(false)` if it does not exist; a symbolic link |
| 156 | /// or any other file type is refused. |
| 157 | fn real_dir(path: &Path) -> SynapseResult<bool> { |
| 158 | match fs::symlink_metadata(path) { |
| 159 | Ok(m) if m.file_type().is_dir() => Ok(true), |
| 160 | Ok(m) => Err(not_regular(path, describe(m.file_type()))), |
| 161 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false), |
| 162 | Err(e) => Err(io(e, path)), |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | /// A Git repository opened for reading (its `.git` directory or a bare repository). |
| 167 | pub struct GitRepository { |
| 168 | git_dir: PathBuf, |
| 169 | packs: Vec<PackReader>, |
| 170 | limits: ReadLimits, |
| 171 | /// Object bytes counted against `limits.max_total_object_bytes` so far. |
| 172 | object_bytes: u64, |
| 173 | } |
| 174 | |
| 175 | /// Every object reachable from a repository's references, with the references themselves. |
| 176 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 177 | pub struct GitHistory { |
| 178 | /// Reference name to object ID (`refs/...`), sorted by name. |
| 179 | pub refs: BTreeMap<String, GitOid>, |
| 180 | /// The branch `HEAD` names (`refs/heads/...`), or `None` for a detached or missing `HEAD`. |
| 181 | pub head: Option<String>, |
| 182 | /// The commit a detached `HEAD` names (its history is collected too). |
| 183 | pub detached_head: Option<GitOid>, |
| 184 | /// Every reachable object, keyed by ID. |
| 185 | pub objects: BTreeMap<GitOid, GitObject>, |
| 186 | } |
| 187 | |
| 188 | /// What `HEAD` holds. |
| 189 | enum HeadState { |
| 190 | Missing, |
| 191 | Symbolic(String), |
| 192 | Detached(GitOid), |
| 193 | } |
| 194 | |
| 195 | enum RefValue { |
| 196 | Direct(GitOid), |
| 197 | Symbolic(String), |
| 198 | } |
| 199 | |
| 200 | fn resolve_ref( |
| 201 | name: &str, |
| 202 | refs: &BTreeMap<String, RefValue>, |
| 203 | resolved: &mut BTreeMap<String, GitOid>, |
| 204 | ) -> SynapseResult<GitOid> { |
| 205 | let mut cursor = name.to_string(); |
| 206 | let mut path = Vec::new(); |
| 207 | let mut visiting = BTreeSet::new(); |
| 208 | let oid = loop { |
| 209 | if let Some(oid) = resolved.get(&cursor) { |
| 210 | break *oid; |
| 211 | } |
| 212 | if !visiting.insert(cursor.clone()) { |
| 213 | return Err(corrupt(format!("symbolic reference cycle at {cursor}"))); |
| 214 | } |
| 215 | match refs.get(&cursor) { |
| 216 | Some(RefValue::Direct(oid)) => break *oid, |
| 217 | Some(RefValue::Symbolic(target)) => { |
| 218 | if !valid_ref_name(target) { |
| 219 | return Err(corrupt(format!( |
| 220 | "invalid symbolic reference target {target:?}" |
| 221 | ))); |
| 222 | } |
| 223 | path.push(cursor); |
| 224 | cursor = target.clone(); |
| 225 | } |
| 226 | None => { |
| 227 | return Err(corrupt(format!( |
| 228 | "symbolic reference {cursor} has no target" |
| 229 | ))) |
| 230 | } |
| 231 | } |
| 232 | }; |
| 233 | resolved.insert(cursor, oid); |
| 234 | for alias in path { |
| 235 | resolved.insert(alias, oid); |
| 236 | } |
| 237 | Ok(oid) |
| 238 | } |
| 239 | |
| 240 | impl GitRepository { |
| 241 | /// Open `git_dir` with the default [`ReadLimits`]. |
| 242 | pub fn open(git_dir: &Path) -> SynapseResult<Self> { |
| 243 | Self::open_with_limits(git_dir, ReadLimits::default()) |
| 244 | } |
| 245 | |
| 246 | /// Open `git_dir` and load the index of every pack in `objects/pack` (a pack without its |
| 247 | /// `.idx` is ignored, as Git ignores it). The pack and index files must be regular files |
| 248 | /// within `limits.max_pack_files_bytes` together, and the sizes their entries declare must |
| 249 | /// fit `limits.max_total_object_bytes`; both are checked before any object is resolved. |
| 250 | pub fn open_with_limits(git_dir: &Path, limits: ReadLimits) -> SynapseResult<Self> { |
| 251 | let objects = git_dir.join("objects"); |
| 252 | if !real_dir(&objects)? { |
| 253 | return Err(SynapseError::new( |
| 254 | RefusalCode::PathInvalid, |
| 255 | format!("{} has no objects directory", git_dir.display()), |
| 256 | )); |
| 257 | } |
| 258 | if fs::symlink_metadata(git_dir.join("objects/info/alternates")).is_ok() { |
| 259 | return Err(corrupt( |
| 260 | "repositories with alternate object stores are not read by the bridge", |
| 261 | )); |
| 262 | } |
| 263 | let mut packs = Vec::new(); |
| 264 | let mut file_bytes = 0u64; |
| 265 | let mut object_bytes = 0u64; |
| 266 | let pack_dir = objects.join("pack"); |
| 267 | if real_dir(&pack_dir)? { |
| 268 | let mut names: Vec<PathBuf> = fs::read_dir(&pack_dir) |
| 269 | .map_err(|e| io(e, &pack_dir))? |
| 270 | .filter_map(|e| e.ok().map(|e| e.path())) |
| 271 | .filter(|p| p.extension().is_some_and(|x| x == "idx")) |
| 272 | .collect(); |
| 273 | names.sort(); |
| 274 | for idx_path in names { |
| 275 | let pack_path = idx_path.with_extension("pack"); |
| 276 | if fs::symlink_metadata(&pack_path).is_err() { |
| 277 | continue; |
| 278 | } |
| 279 | let room = limits.max_pack_files_bytes - file_bytes; |
| 280 | let idx = read_regular(&idx_path, room)? |
| 281 | .ok_or_else(|| corrupt(format!("{} vanished", idx_path.display())))?; |
| 282 | file_bytes += idx.len() as u64; |
| 283 | let room = limits.max_pack_files_bytes - file_bytes; |
| 284 | let data = read_regular(&pack_path, room)? |
| 285 | .ok_or_else(|| corrupt(format!("{} vanished", pack_path.display())))?; |
| 286 | file_bytes += data.len() as u64; |
| 287 | let pack = PackReader::with_index_limited(data, &idx, limits.max_object_bytes)?; |
| 288 | object_bytes = object_bytes.saturating_add(pack.declared_bytes()?); |
| 289 | if object_bytes > limits.max_total_object_bytes { |
| 290 | return Err(SynapseError::new( |
| 291 | RefusalCode::QuotaPayloadTooLarge, |
| 292 | format!( |
| 293 | "pack objects declare {object_bytes} bytes, over the {} byte budget", |
| 294 | limits.max_total_object_bytes |
| 295 | ), |
| 296 | )); |
| 297 | } |
| 298 | packs.push(pack); |
| 299 | } |
| 300 | } |
| 301 | Ok(Self { |
| 302 | git_dir: git_dir.to_path_buf(), |
| 303 | packs, |
| 304 | limits, |
| 305 | object_bytes, |
| 306 | }) |
| 307 | } |
| 308 | |
| 309 | /// Read object `oid` from the packs or the loose store, checking that it hashes to `oid`. |
| 310 | /// A loose object's declared size is read from the first bytes of its stream and checked |
| 311 | /// against the per-object cap and the remaining budget before it is inflated. |
| 312 | pub fn read_object(&mut self, oid: GitOid) -> SynapseResult<Option<GitObject>> { |
| 313 | for pack in &mut self.packs { |
| 314 | if let Some(object) = pack.read(oid)? { |
| 315 | return Ok(Some(object)); |
| 316 | } |
| 317 | } |
| 318 | let hex = oid.to_hex(); |
| 319 | // The fan-out directory must be a real directory too: `O_NOFOLLOW` covers only the |
| 320 | // last path component, so a linked `objects/ab` could lead the read outside. |
| 321 | let fanout = self.git_dir.join("objects").join(&hex[..2]); |
| 322 | if !real_dir(&fanout)? { |
| 323 | return Ok(None); |
| 324 | } |
| 325 | let path = fanout.join(&hex[2..]); |
| 326 | // An incompressible object stored as zlib grows by 5 bytes per 65,535-byte block plus |
| 327 | // 6; allow the object cap plus 1/64 and 1 KiB for that and the object header. |
| 328 | let max_file = self.limits.max_object_bytes / 64 * 65 + 1024; |
| 329 | let Some(compressed) = read_regular(&path, max_file)? else { |
| 330 | return Ok(None); |
| 331 | }; |
| 332 | let head = zlib_inflate_prefix(&compressed, 64)?; |
| 333 | let nul = head |
| 334 | .iter() |
| 335 | .position(|&b| b == 0) |
| 336 | .ok_or_else(|| corrupt(format!("loose object {hex} has no header")))?; |
| 337 | let size: u64 = std::str::from_utf8(&head[..nul]) |
| 338 | .ok() |
| 339 | .and_then(|h| h.split_once(' ')) |
| 340 | .and_then(|(_, n)| n.parse().ok()) |
| 341 | .ok_or_else(|| corrupt(format!("loose object {hex} has a malformed header")))?; |
| 342 | if size > self.limits.max_object_bytes { |
| 343 | return Err(over_cap(&path, size, self.limits.max_object_bytes)); |
| 344 | } |
| 345 | let total = self.object_bytes.saturating_add(size); |
| 346 | if total > self.limits.max_total_object_bytes { |
| 347 | return Err(SynapseError::new( |
| 348 | RefusalCode::QuotaPayloadTooLarge, |
| 349 | format!( |
| 350 | "loose object {hex} brings the read to {total} bytes, over the {} byte budget", |
| 351 | self.limits.max_total_object_bytes |
| 352 | ), |
| 353 | )); |
| 354 | } |
| 355 | self.object_bytes = total; |
| 356 | let (raw, used) = zlib_decompress(&compressed, nul + 1 + size as usize)?; |
| 357 | if used != compressed.len() { |
| 358 | return Err(corrupt(format!("loose object {hex} has trailing bytes"))); |
| 359 | } |
| 360 | let object = GitObject::decode_loose(&raw)?; |
| 361 | if object.oid() != oid { |
| 362 | return Err(corrupt(format!( |
| 363 | "loose object {hex} hashes to {}", |
| 364 | object.oid() |
| 365 | ))); |
| 366 | } |
| 367 | Ok(Some(object)) |
| 368 | } |
| 369 | |
| 370 | fn head_state(&self) -> SynapseResult<HeadState> { |
| 371 | let path = self.git_dir.join("HEAD"); |
| 372 | let Some(bytes) = read_regular(&path, self.limits.max_ref_file_bytes)? else { |
| 373 | return Ok(HeadState::Missing); |
| 374 | }; |
| 375 | let text = std::str::from_utf8(&bytes).map_err(|_| corrupt("HEAD is not UTF-8"))?; |
| 376 | let value = text.trim_end(); |
| 377 | if let Some(name) = value.strip_prefix("ref: ") { |
| 378 | return Ok(HeadState::Symbolic(name.to_string())); |
| 379 | } |
| 380 | Ok(HeadState::Detached(GitOid::from_hex(value).map_err( |
| 381 | |_| corrupt("HEAD is neither a symbolic reference nor an object ID"), |
| 382 | )?)) |
| 383 | } |
| 384 | |
| 385 | /// Every reference: loose refs under `refs/` override `packed-refs`; peeled lines (`^`) |
| 386 | /// and comments are skipped, as are `*.lock` files (Git's in-progress updates). Also |
| 387 | /// returns the branch `HEAD` points to, if symbolic. Every file read must be a regular file |
| 388 | /// within its cap; a symbolic link, pipe or device anywhere under `refs/` is refused. |
| 389 | pub fn refs(&self) -> SynapseResult<(BTreeMap<String, GitOid>, Option<String>)> { |
| 390 | let mut ref_values = BTreeMap::new(); |
| 391 | let packed = self.git_dir.join("packed-refs"); |
| 392 | if let Some(bytes) = read_regular(&packed, self.limits.max_packed_refs_bytes)? { |
| 393 | let text = |
| 394 | std::str::from_utf8(&bytes).map_err(|_| corrupt("packed-refs is not UTF-8"))?; |
| 395 | for line in text.lines() { |
| 396 | if line.is_empty() || line.starts_with('#') || line.starts_with('^') { |
| 397 | continue; |
| 398 | } |
| 399 | let (hex, name) = line |
| 400 | .split_once(' ') |
| 401 | .ok_or_else(|| corrupt("malformed packed-refs line"))?; |
| 402 | if !valid_ref_name(name) { |
| 403 | return Err(corrupt(format!("invalid packed reference name {name:?}"))); |
| 404 | } |
| 405 | ref_values.insert(name.to_string(), RefValue::Direct(GitOid::from_hex(hex)?)); |
| 406 | } |
| 407 | } |
| 408 | let root = self.git_dir.join("refs"); |
| 409 | let mut stack = if real_dir(&root)? { |
| 410 | vec![root] |
| 411 | } else { |
| 412 | Vec::new() |
| 413 | }; |
| 414 | while let Some(dir) = stack.pop() { |
| 415 | for entry in fs::read_dir(&dir).map_err(|e| io(e, &dir))? { |
| 416 | let entry = entry.map_err(|e| io(e, &dir))?; |
| 417 | let path = entry.path(); |
| 418 | // `DirEntry::file_type` does not follow symbolic links. |
| 419 | let file_type = entry.file_type().map_err(|e| io(e, &path))?; |
| 420 | if file_type.is_dir() { |
| 421 | stack.push(path); |
| 422 | continue; |
| 423 | } |
| 424 | if !file_type.is_file() { |
| 425 | return Err(not_regular(&path, describe(file_type))); |
| 426 | } |
| 427 | if path.extension().is_some_and(|x| x == "lock") { |
| 428 | continue; |
| 429 | } |
| 430 | let rel = path |
| 431 | .strip_prefix(&self.git_dir) |
| 432 | .ok() |
| 433 | .and_then(|p| p.to_str()) |
| 434 | .ok_or_else(|| corrupt("reference name is not UTF-8"))? |
| 435 | .replace(std::path::MAIN_SEPARATOR, "/"); |
| 436 | let bytes = read_regular(&path, self.limits.max_ref_file_bytes)? |
| 437 | .ok_or_else(|| corrupt(format!("reference {rel} vanished")))?; |
| 438 | let text = std::str::from_utf8(&bytes) |
| 439 | .map_err(|_| corrupt(format!("reference {rel} is not UTF-8")))?; |
| 440 | let value = text.trim_end(); |
| 441 | if !valid_ref_name(&rel) { |
| 442 | return Err(corrupt(format!("invalid reference name {rel:?}"))); |
| 443 | } |
| 444 | if let Some(target) = value.strip_prefix("ref: ") { |
| 445 | if !valid_ref_name(target) { |
| 446 | return Err(corrupt(format!( |
| 447 | "symbolic reference {rel} has invalid target {target:?}" |
| 448 | ))); |
| 449 | } |
| 450 | ref_values.insert(rel, RefValue::Symbolic(target.to_string())); |
| 451 | } else { |
| 452 | ref_values.insert(rel, RefValue::Direct(GitOid::from_hex(value)?)); |
| 453 | } |
| 454 | } |
| 455 | } |
| 456 | let mut resolved_refs = BTreeMap::new(); |
| 457 | for name in ref_values.keys() { |
| 458 | resolve_ref(name, &ref_values, &mut resolved_refs)?; |
| 459 | } |
| 460 | let refs = ref_values |
| 461 | .keys() |
| 462 | .map(|name| (name.clone(), resolved_refs[name])) |
| 463 | .collect(); |
| 464 | let head = match self.head_state()? { |
| 465 | HeadState::Symbolic(name) => Some(name), |
| 466 | HeadState::Missing | HeadState::Detached(_) => None, |
| 467 | }; |
| 468 | Ok((refs, head)) |
| 469 | } |
| 470 | |
| 471 | /// Collect every object reachable from every reference and from a detached `HEAD` |
| 472 | /// (breadth first). A missing object or an object of the wrong kind for its link is |
| 473 | /// refused (`GitObjectCorrupt`): a partial or shallow repository cannot be imported as |
| 474 | /// full history. |
| 475 | pub fn full_history(&mut self) -> SynapseResult<GitHistory> { |
| 476 | if fs::symlink_metadata(self.git_dir.join("shallow")).is_ok() { |
| 477 | return Err(corrupt("shallow repositories do not hold full history")); |
| 478 | } |
| 479 | let (refs, head) = self.refs()?; |
| 480 | let detached_head = match self.head_state()? { |
| 481 | HeadState::Detached(oid) => Some(oid), |
| 482 | _ => None, |
| 483 | }; |
| 484 | let mut objects = BTreeMap::new(); |
| 485 | let mut queued: BTreeSet<GitOid> = BTreeSet::new(); |
| 486 | let mut queue: VecDeque<(GitOid, Option<ObjectKind>)> = VecDeque::new(); |
| 487 | for oid in refs.values() { |
| 488 | if queued.insert(*oid) { |
| 489 | queue.push_back((*oid, None)); |
| 490 | } |
| 491 | } |
| 492 | if let Some(oid) = detached_head { |
| 493 | if queued.insert(oid) { |
| 494 | queue.push_back((oid, Some(ObjectKind::Commit))); |
| 495 | } |
| 496 | } |
| 497 | while let Some((oid, expected)) = queue.pop_front() { |
| 498 | let object = self |
| 499 | .read_object(oid)? |
| 500 | .ok_or_else(|| corrupt(format!("object {oid} is missing")))?; |
| 501 | if let Some(kind) = expected { |
| 502 | if object.kind != kind { |
| 503 | return Err(corrupt(format!( |
| 504 | "object {oid} is a {} where a {} is linked", |
| 505 | object.kind.name(), |
| 506 | kind.name() |
| 507 | ))); |
| 508 | } |
| 509 | } |
| 510 | for (link, kind) in object_links(&object)? { |
| 511 | if queued.insert(link) { |
| 512 | queue.push_back((link, Some(kind))); |
| 513 | } |
| 514 | } |
| 515 | objects.insert(oid, object); |
| 516 | } |
| 517 | Ok(GitHistory { |
| 518 | refs, |
| 519 | head, |
| 520 | detached_head, |
| 521 | objects, |
| 522 | }) |
| 523 | } |
| 524 | } |
| 525 | |
| 526 | /// What [`export_repository`] wrote. |
| 527 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 528 | pub struct ExportReceipt { |
| 529 | pub pack_path: PathBuf, |
| 530 | pub idx_path: PathBuf, |
| 531 | pub pack_checksum: GitOid, |
| 532 | pub object_count: usize, |
| 533 | pub pack_bytes: u64, |
| 534 | } |
| 535 | |
| 536 | fn write_file_synced(path: &Path, bytes: &[u8]) -> SynapseResult<()> { |
| 537 | let tmp = path.with_extension(format!("tmp.{}", std::process::id())); |
| 538 | { |
| 539 | let mut f = File::create(&tmp).map_err(|e| io(e, &tmp))?; |
| 540 | f.write_all(bytes).map_err(|e| io(e, &tmp))?; |
| 541 | f.sync_all().map_err(|e| io(e, &tmp))?; |
| 542 | } |
| 543 | fs::rename(&tmp, path).map_err(|e| io(e, path)) |
| 544 | } |
| 545 | |
| 546 | fn valid_ref_name(name: &str) -> bool { |
| 547 | name.starts_with("refs/") |
| 548 | && !name.ends_with('/') |
| 549 | && !name.ends_with(".lock") |
| 550 | && name |
| 551 | .split('/') |
| 552 | .all(|c| !c.is_empty() && !c.starts_with('.') && c != ".." && !c.contains("..")) |
| 553 | && !name |
| 554 | .bytes() |
| 555 | .any(|b| b < 0x20 || b == 0x7f || b" ~^:?*[\\".contains(&b)) |
| 556 | } |
| 557 | |
| 558 | /// Create the bare repository `dest` (which must not exist) holding `objects` as one version 2 |
| 559 | /// pack with its index, the references `refs`, and `HEAD` naming `head` (default |
| 560 | /// `refs/heads/main`). Every reference must name an object in the set. Returns where the pack |
| 561 | /// went; the same inputs always give the same pack bytes. |
| 562 | pub fn export_repository( |
| 563 | dest: &Path, |
| 564 | objects: &[GitObject], |
| 565 | refs: &BTreeMap<String, GitOid>, |
| 566 | head: Option<&str>, |
| 567 | ) -> SynapseResult<ExportReceipt> { |
| 568 | if dest.exists() { |
| 569 | return Err(SynapseError::new( |
| 570 | RefusalCode::PathInvalid, |
| 571 | format!( |
| 572 | "{} already exists; export writes only a new repository", |
| 573 | dest.display() |
| 574 | ), |
| 575 | )); |
| 576 | } |
| 577 | let present: BTreeSet<GitOid> = objects.iter().map(GitObject::oid).collect(); |
| 578 | for (name, oid) in refs { |
| 579 | if !valid_ref_name(name) { |
| 580 | return Err(SynapseError::new( |
| 581 | RefusalCode::PathInvalid, |
| 582 | format!("invalid reference name {name:?}"), |
| 583 | )); |
| 584 | } |
| 585 | if !present.contains(oid) { |
| 586 | return Err(corrupt(format!( |
| 587 | "reference {name} names {oid}, not exported" |
| 588 | ))); |
| 589 | } |
| 590 | } |
| 591 | let head = head.unwrap_or("refs/heads/main"); |
| 592 | if !valid_ref_name(head) { |
| 593 | return Err(SynapseError::new( |
| 594 | RefusalCode::PathInvalid, |
| 595 | format!("invalid HEAD target {head:?}"), |
| 596 | )); |
| 597 | } |
| 598 | let pack_dir = dest.join("objects/pack"); |
| 599 | for dir in [ |
| 600 | pack_dir.clone(), |
| 601 | dest.join("objects/info"), |
| 602 | dest.join("refs/heads"), |
| 603 | dest.join("refs/tags"), |
| 604 | ] { |
| 605 | fs::create_dir_all(&dir).map_err(|e| io(e, &dir))?; |
| 606 | } |
| 607 | write_file_synced( |
| 608 | &dest.join("config"), |
| 609 | b"[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = true\n", |
| 610 | )?; |
| 611 | let WrittenPack { |
| 612 | pack, |
| 613 | idx, |
| 614 | checksum, |
| 615 | entries, |
| 616 | } = write_pack(objects); |
| 617 | let base = pack_dir.join(format!("pack-{}", checksum.to_hex())); |
| 618 | let pack_path = base.with_extension("pack"); |
| 619 | let idx_path = base.with_extension("idx"); |
| 620 | // The pack first, then its index: Git ignores a pack until its index exists. |
| 621 | write_file_synced(&pack_path, &pack)?; |
| 622 | write_file_synced(&idx_path, &idx)?; |
| 623 | for (name, oid) in refs { |
| 624 | let path = dest.join(name); |
| 625 | if let Some(parent) = path.parent() { |
| 626 | fs::create_dir_all(parent).map_err(|e| io(e, parent))?; |
| 627 | } |
| 628 | write_file_synced(&path, format!("{}\n", oid.to_hex()).as_bytes())?; |
| 629 | } |
| 630 | write_file_synced(&dest.join("HEAD"), format!("ref: {head}\n").as_bytes())?; |
| 631 | Ok(ExportReceipt { |
| 632 | pack_path, |
| 633 | idx_path, |
| 634 | pack_checksum: checksum, |
| 635 | object_count: entries.len(), |
| 636 | pack_bytes: pack.len() as u64, |
| 637 | }) |
| 638 | } |
| 639 | |
| 640 | #[cfg(test)] |
| 641 | mod tests { |
| 642 | use super::*; |
| 643 | use std::sync::mpsc; |
| 644 | use std::time::Duration; |
| 645 | |
| 646 | fn scratch(label: &str) -> PathBuf { |
| 647 | let dir = std::env::temp_dir().join(format!( |
| 648 | "synapse-h1-open-{label}-{}-{}", |
| 649 | std::process::id(), |
| 650 | std::time::SystemTime::now() |
| 651 | .duration_since(std::time::UNIX_EPOCH) |
| 652 | .unwrap() |
| 653 | .as_nanos() |
| 654 | )); |
| 655 | fs::create_dir_all(&dir).unwrap(); |
| 656 | dir |
| 657 | } |
| 658 | |
| 659 | /// The file is inspected as a regular file, then swapped before the open (the race the |
| 660 | /// `symlink_metadata` check alone cannot close). The open must refuse it at once. |
| 661 | #[test] |
| 662 | fn a_file_swapped_for_a_pipe_or_link_after_the_check_is_refused_without_blocking() { |
| 663 | for swap in ["pipe", "link"] { |
| 664 | let dir = scratch(swap); |
| 665 | let path = dir.join("ref"); |
| 666 | fs::write(&path, b"0000000000000000000000000000000000000000\n").unwrap(); |
| 667 | let meta = fs::symlink_metadata(&path).unwrap(); |
| 668 | fs::remove_file(&path).unwrap(); |
| 669 | if swap == "pipe" { |
| 670 | let ok = std::process::Command::new("mkfifo") |
| 671 | .arg(&path) |
| 672 | .status() |
| 673 | .unwrap() |
| 674 | .success(); |
| 675 | assert!(ok); |
| 676 | } else { |
| 677 | fs::write(dir.join("elsewhere"), b"x").unwrap(); |
| 678 | std::os::unix::fs::symlink(dir.join("elsewhere"), &path).unwrap(); |
| 679 | } |
| 680 | let (tx, rx) = mpsc::channel(); |
| 681 | let p = path.clone(); |
| 682 | std::thread::spawn(move || { |
| 683 | let _ = tx.send(open_inspected(&p, &meta).map(|_| ())); |
| 684 | }); |
| 685 | let result = match rx.recv_timeout(Duration::from_secs(10)) { |
| 686 | Ok(r) => r, |
| 687 | Err(_) => { |
| 688 | drop(fs::OpenOptions::new().write(true).open(&path)); |
| 689 | panic!("{swap}: open blocked for more than 10 s"); |
| 690 | } |
| 691 | }; |
| 692 | assert_eq!(result.unwrap_err().code, RefusalCode::PathInvalid, "{swap}"); |
| 693 | } |
| 694 | } |
| 695 | } |