1use crate::{
3 Error, Result,
4 context::HostContext,
5 error::io_error,
6 local::{LocalConfig, repository_state_path},
7 model::ManagedFile,
8 observation::{self, Entry, Parent},
9 state::PrivateDir,
10};
11use rustix::fs::{self, Mode};
12use serde::{Deserialize, Serialize};
13use sha2::{Digest, Sha256};
14use std::{fs::File, io::Read, path::Path};
15
16pub(crate) const LIMIT: u64 = 16 * 1024 * 1024;
17
18pub(crate) fn digest(bytes: &[u8]) -> String {
19 format!("{:x}", Sha256::digest(bytes))
20}
21
22pub(crate) fn encode<T: Serialize>(value: &T) -> Result<String> {
23 serde_json::to_string(value)
24 .map_err(|_| Error::Invalid("cannot encode transaction metadata".into()))
25}
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(rename_all = "snake_case")]
29pub enum Phase {
30 Preparing,
31 Running,
32 Verifying,
33 Completed,
34 RollingBack,
35 RolledBack,
36}
37
38impl Phase {
39 pub fn terminal(self) -> bool {
40 matches!(self, Self::Completed | Self::RolledBack)
41 }
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(rename_all = "snake_case")]
46pub(crate) enum Role {
47 Directory,
48 Source,
49 Manifest,
50 Destination,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
54#[serde(rename_all = "snake_case")]
55pub(crate) enum Progress {
56 Pending,
57 Intent,
58 Done,
59 UndoIntent,
60 Undone,
61}
62
63#[derive(Clone, Serialize, Deserialize)]
64#[serde(deny_unknown_fields)]
65pub(crate) struct Operation {
66 pub id: usize,
67 pub role: Role,
68 pub before: Entry,
69 pub staged: Entry,
70 pub after: Option<Entry>,
71 pub progress: Progress,
72}
73
74#[derive(Clone, Serialize, Deserialize)]
75#[serde(deny_unknown_fields)]
76pub(crate) struct Header {
77 pub repository_id: String,
78 pub repository: std::path::PathBuf,
79 pub transaction_id: String,
80 pub approved_plan_sha256: String,
81 pub mapping: ManagedFile,
82 pub profiles: Vec<String>,
83 pub manifest: Entry,
84 pub destination: Entry,
85 pub source: Entry,
86 pub local_config: Entry,
87 pub anchors: Vec<Parent>,
88 pub manifest_backup_sha256: String,
89 pub destination_backup_sha256: String,
90}
91
92#[derive(Clone, Serialize, Deserialize)]
93#[serde(deny_unknown_fields)]
94pub(crate) struct Record {
95 pub schema: u32,
96 pub sequence: usize,
97 pub previous_sha256: Option<String>,
98 pub header: Header,
99 pub phase: Phase,
100 pub operations: Vec<Operation>,
101}
102
103#[derive(Serialize, Deserialize)]
104#[serde(deny_unknown_fields)]
105struct Envelope {
106 sha256: String,
107 payload: String,
108}
109
110#[derive(Debug, Serialize)]
112pub struct Diagnosis {
113 pub repository_id: String,
114 pub transaction_id: String,
115 pub phase: Option<Phase>,
116 pub journal_schema: Option<u32>,
118 pub valid_checkpoints: usize,
119 pub problem: Option<String>,
120}
121
122impl Diagnosis {
123 pub fn blocks_writes(&self) -> bool {
124 self.problem.is_some() || self.phase.is_none_or(|p| !p.terminal())
125 }
126}
127
128pub struct WriteBlocker {
130 pub transaction: Diagnosis,
131 pub repository_root: Option<std::path::PathBuf>,
133}
134impl WriteBlocker {
135 pub fn reason(&self) -> &'static str {
136 if self.transaction.problem.is_some() {
137 "Dort can't verify an earlier operation's recovery record."
138 } else {
139 "An earlier operation did not finish."
140 }
141 }
142 pub fn operation(&self) -> &'static str {
143 match self.transaction.journal_schema {
144 Some(1) => "File adoption",
145 Some(2 | 4) => "File changes",
146 Some(3) => "Repository setup",
147 Some(5 | 6) => "Tool declaration change",
148 _ => "Unknown operation",
149 }
150 }
151}
152impl std::fmt::Debug for WriteBlocker {
153 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154 f.debug_struct("WriteBlocker")
155 .field("repository_id", &self.transaction.repository_id)
156 .field("transaction_id", &self.transaction.transaction_id)
157 .field("repository_root", &self.repository_root)
158 .field("operation", &self.operation())
159 .field("reason", &self.reason())
160 .finish()
161 }
162}
163impl std::fmt::Display for WriteBlocker {
164 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165 writeln!(
166 f,
167 "{} New changes are paused to protect your files.",
168 self.reason()
169 )?;
170 writeln!(f, "Operation: {}", self.operation())?;
171 if let Some(root) = &self.repository_root {
172 writeln!(f, "Repository: {root:?}")?;
173 }
174 writeln!(f, "Repository ID: {}", self.transaction.repository_id)?;
175 writeln!(f, "Operation ID: {}", self.transaction.transaction_id)?;
176 write!(
177 f,
178 "Open Recovery, or run `dort recovery list`, to inspect it."
179 )
180 }
181}
182
183pub(crate) struct Journal {
184 pub directory: PrivateDir,
185 pub record: Record,
186 last_sha256: Option<String>,
187 next: usize,
188}
189
190pub(crate) fn valid_id(id: &str) -> bool {
191 id.len() == 64
192 && id
193 .bytes()
194 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
195}
196
197pub(crate) fn transactions(host: &HostContext, repository_id: &str) -> Result<std::path::PathBuf> {
198 Ok(repository_state_path(host, repository_id)?.join("transactions"))
199}
200
201pub(crate) fn read_bytes(directory: &PrivateDir, name: &str) -> Result<Vec<u8>> {
202 let mut file = File::from(
203 fs::openat(
204 &directory.file,
205 name,
206 fs::OFlags::RDONLY | fs::OFlags::NOFOLLOW | fs::OFlags::NONBLOCK | fs::OFlags::CLOEXEC,
207 Mode::empty(),
208 )
209 .map_err(|e| io_error("open transaction artifact", directory.path.join(name), e))?,
210 );
211 directory.check_file(&file, name)?;
212 let before = observation::Fingerprint::from_stat(
213 &fs::fstat(&file)
214 .map_err(|e| io_error("inspect transaction artifact", &directory.path, e))?,
215 );
216 if before.size < 0 || before.size as u64 > LIMIT {
217 return Err(Error::Invalid(
218 "transaction artifact exceeds size limit".into(),
219 ));
220 }
221 let mut bytes = vec![];
222 (&mut file)
223 .take(LIMIT + 1)
224 .read_to_end(&mut bytes)
225 .map_err(|e| io_error("read transaction artifact", &directory.path, e))?;
226 let after = observation::Fingerprint::from_stat(
227 &fs::fstat(&file)
228 .map_err(|e| io_error("recheck transaction artifact", &directory.path, e))?,
229 );
230 let named = observation::Fingerprint::from_stat(
231 &fs::statat(&directory.file, name, fs::AtFlags::SYMLINK_NOFOLLOW)
232 .map_err(|e| io_error("recheck named transaction artifact", &directory.path, e))?,
233 );
234 if before != after || after != named || bytes.len() as u64 > LIMIT {
235 return Err(Error::Invalid(
236 "transaction artifact changed during read".into(),
237 ));
238 }
239 Ok(bytes)
240}
241
242impl Journal {
243 pub(crate) fn begin(host: &HostContext, header: Header) -> Result<Self> {
244 let root = transactions(host, &header.repository_id)?;
245 let parent = PrivateDir::open(&root, true)?.expect("created transactions directory");
246 fs::mkdirat(
247 &parent.file,
248 header.transaction_id.as_str(),
249 Mode::RUSR | Mode::WUSR | Mode::XUSR,
250 )
251 .map_err(|e| io_error("allocate unique transaction", &root, e))?;
252 parent.sync()?;
253 let directory =
254 PrivateDir::open(&root.join(&header.transaction_id), false)?.expect("new transaction");
255 let record = Record {
256 schema: 1,
257 sequence: 0,
258 previous_sha256: None,
259 header,
260 phase: Phase::Preparing,
261 operations: vec![],
262 };
263 let mut journal = Self {
264 directory,
265 record,
266 last_sha256: None,
267 next: 0,
268 };
269 journal.save()?;
270 Ok(journal)
271 }
272
273 pub(crate) fn save(&mut self) -> Result<()> {
275 self.record.sequence = self.next;
276 self.record.previous_sha256 = self.last_sha256.clone();
277 let payload = encode(&self.record)?;
278 let checksum = digest(payload.as_bytes());
279 let envelope = encode(&Envelope {
280 sha256: checksum.clone(),
281 payload,
282 })?;
283 if envelope.len() as u64 > LIMIT {
284 return Err(Error::Invalid("checkpoint exceeds size limit".into()));
285 }
286 self.directory
287 .create(&format!("{:06}.json", self.next), envelope.as_bytes())?;
288 self.last_sha256 = Some(checksum);
289 self.next += 1;
290 Ok(())
291 }
292
293 pub(crate) fn open(
294 host: &HostContext,
295 repository_id: &str,
296 transaction_id: &str,
297 ) -> Result<Self> {
298 if !valid_id(transaction_id) {
299 return Err(Error::Invalid("invalid transaction ID".into()));
300 }
301 let path = transactions(host, repository_id)?.join(transaction_id);
302 let directory = PrivateDir::open(&path, false)?
303 .ok_or_else(|| Error::Invalid("unknown transaction".into()))?;
304 let (diagnosis, latest, hash) = scan(&directory, repository_id, transaction_id);
305 if diagnosis.problem.is_some() || latest.is_none() {
306 return Err(Error::Invalid(
307 "malformed transaction; read-only diagnosis/manual repair required".into(),
308 ));
309 }
310 Ok(Self {
311 directory,
312 record: latest.unwrap(),
313 last_sha256: hash,
314 next: diagnosis.valid_checkpoints,
315 })
316 }
317
318 pub(crate) fn verify_backups(&self) -> Result<()> {
319 for (name, expected) in [
320 (
321 "manifest.backup",
322 &self.record.header.manifest_backup_sha256,
323 ),
324 (
325 "destination.backup",
326 &self.record.header.destination_backup_sha256,
327 ),
328 ] {
329 if digest(&read_bytes(&self.directory, name)?) != *expected {
330 return Err(Error::Invalid(
331 "backup integrity mismatch; recovery refused".into(),
332 ));
333 }
334 }
335 Ok(())
336 }
337}
338
339fn transition(previous: &Record, next: &Record) -> Result<()> {
340 if encode(&previous.header)? != encode(&next.header)? || previous.phase.terminal() {
341 if !(previous.phase == Phase::Completed
343 && next.phase == Phase::RollingBack
344 && encode(&previous.header)? == encode(&next.header)?)
345 {
346 return Err(Error::Invalid(
347 "invalid journal header/terminal transition".into(),
348 ));
349 }
350 }
351 let allowed = match previous.phase {
352 Phase::Preparing => matches!(next.phase, Phase::Running | Phase::RolledBack),
353 Phase::Running => matches!(
354 next.phase,
355 Phase::Running | Phase::Verifying | Phase::RollingBack
356 ),
357 Phase::Verifying => matches!(next.phase, Phase::Completed | Phase::RollingBack),
358 Phase::Completed => next.phase == Phase::RollingBack,
359 Phase::RollingBack => matches!(next.phase, Phase::RollingBack | Phase::RolledBack),
360 Phase::RolledBack => false,
361 };
362 if !allowed {
363 return Err(Error::Invalid("invalid journal phase transition".into()));
364 }
365 if previous.phase != Phase::Preparing {
366 if previous.operations.len() != next.operations.len() {
367 return Err(Error::Invalid("journal operation set changed".into()));
368 }
369 for (a, b) in previous.operations.iter().zip(&next.operations) {
370 if a.id != b.id
371 || a.role != b.role
372 || a.before != b.before
373 || a.staged != b.staged
374 || (a.after.is_some() && a.after != b.after)
375 {
376 return Err(Error::Invalid("journal operation identity changed".into()));
377 }
378 let ok = a.progress == b.progress
379 || matches!(
380 (a.progress, b.progress),
381 (Progress::Pending, Progress::Intent)
382 | (Progress::Intent, Progress::Done)
383 | (
384 Progress::Pending | Progress::Intent | Progress::Done,
385 Progress::UndoIntent
386 )
387 | (Progress::UndoIntent, Progress::Undone)
388 );
389 if !ok {
390 return Err(Error::Invalid("invalid operation transition".into()));
391 }
392 }
393 }
394 Ok(())
395}
396
397fn validate_structure(record: &Record, directory: &Path) -> Result<()> {
398 let h = &record.header;
399 if !valid_id(&h.approved_plan_sha256)
400 || !valid_id(&h.manifest_backup_sha256)
401 || !valid_id(&h.destination_backup_sha256)
402 {
403 return Err(Error::Invalid("invalid transaction digest binding".into()));
404 }
405 if record.phase == Phase::Preparing && !record.operations.is_empty() {
406 return Err(Error::Invalid(
407 "preparing checkpoint cannot contain live operations".into(),
408 ));
409 }
410 if record.operations.is_empty() {
411 if !matches!(record.phase, Phase::Preparing | Phase::RolledBack) {
412 return Err(Error::Invalid("missing adoption operation set".into()));
413 }
414 return Ok(());
415 }
416 let n = record.operations.len();
417 if n < 3 {
418 return Err(Error::Invalid("incomplete adoption operation set".into()));
419 }
420 if h.source.kind != observation::Kind::Missing
421 || h.manifest.kind != observation::Kind::Regular
422 || h.destination.kind != observation::Kind::Regular
423 || h.manifest.sha256.as_ref() != Some(&h.manifest_backup_sha256)
424 || h.destination.sha256.as_ref() != Some(&h.destination_backup_sha256)
425 {
426 return Err(Error::Invalid(
427 "invalid adoption input/backup binding".into(),
428 ));
429 }
430 let mut forward_boundary = false;
431 let mut undone_suffix = false;
432 let mut inverse_intents = 0;
433 for (id, op) in record.operations.iter().enumerate() {
434 let expected = if id == n - 3 {
435 (Role::Source, &h.source)
436 } else if id == n - 2 {
437 (Role::Manifest, &h.manifest)
438 } else if id == n - 1 {
439 (Role::Destination, &h.destination)
440 } else {
441 (Role::Directory, &op.before)
442 };
443 if op.id != id
444 || op.role != expected.0
445 || &op.before != expected.1
446 || op.staged.path != directory.join(format!("op-{id:04}"))
447 || op
448 .after
449 .as_ref()
450 .is_some_and(|after| after.path != op.before.path)
451 || (op.progress == Progress::Done && op.after.is_none())
452 || (matches!(op.progress, Progress::Pending | Progress::Intent) && op.after.is_some())
453 {
454 return Err(Error::Invalid(
455 "invalid operation ID, binding or postcondition".into(),
456 ));
457 }
458 let staged_kind = match op.role {
459 Role::Directory => observation::Kind::Directory,
460 Role::Source | Role::Manifest => observation::Kind::Regular,
461 Role::Destination => observation::Kind::Symlink,
462 };
463 if op.staged.kind != staged_kind
464 || (op.role == Role::Directory && op.before.kind != observation::Kind::Missing)
465 || (op.role == Role::Source && op.staged.sha256 != h.destination.sha256)
466 || (op.role == Role::Destination
467 && op.staged.link_target.as_ref() != Some(&h.source.path))
468 {
469 return Err(Error::Invalid(
470 "invalid prepared operation postcondition".into(),
471 ));
472 }
473 match record.phase {
474 Phase::Running => match op.progress {
475 Progress::Done if !forward_boundary => {}
476 Progress::Intent if !forward_boundary => forward_boundary = true,
477 Progress::Pending => forward_boundary = true,
478 _ => return Err(Error::Invalid("invalid forward operation ordering".into())),
479 },
480 Phase::Verifying | Phase::Completed if op.progress != Progress::Done => {
481 return Err(Error::Invalid(
482 "completion without verified operations".into(),
483 ));
484 }
485 Phase::RollingBack => {
486 if op.progress == Progress::UndoIntent {
487 inverse_intents += 1;
488 }
489 if inverse_intents > 1 {
490 return Err(Error::Invalid("multiple inverse intents".into()));
491 }
492 if matches!(op.progress, Progress::UndoIntent | Progress::Undone) {
493 undone_suffix = true;
494 } else if undone_suffix {
495 return Err(Error::Invalid("invalid inverse operation ordering".into()));
496 }
497 }
498 Phase::RolledBack if op.progress != Progress::Undone => {
499 return Err(Error::Invalid(
500 "rollback completion without inverse operations".into(),
501 ));
502 }
503 _ => {}
504 }
505 }
506 Ok(())
507}
508
509fn scan(
510 directory: &PrivateDir,
511 repository_id: &str,
512 transaction_id: &str,
513) -> (Diagnosis, Option<Record>, Option<String>) {
514 let mut diagnosis = Diagnosis {
515 repository_id: repository_id.into(),
516 transaction_id: transaction_id.into(),
517 journal_schema: None,
518 phase: None,
519 valid_checkpoints: 0,
520 problem: None,
521 };
522 let mut latest: Option<Record> = None;
523 let mut hash = None;
524 let result: Result<()> = (|| {
525 let names = observation::names(&directory.path, 4096)?;
526 for name in &names {
527 let name = name
528 .to_str()
529 .ok_or_else(|| Error::Invalid("unrepresentable transaction artifact".into()))?;
530 let stage = name
531 .strip_prefix("op-")
532 .is_some_and(|id| id.len() == 4 && id.bytes().all(|b| b.is_ascii_digit()));
533 if !name.ends_with(".json")
534 && !stage
535 && !matches!(name, "manifest.backup" | "destination.backup")
536 {
537 return Err(Error::Invalid("unknown transaction artifact".into()));
538 }
539 }
540 let checkpoints: Vec<_> = names
541 .iter()
542 .filter_map(|n| n.to_str())
543 .filter(|n| n.ends_with(".json"))
544 .collect();
545 if checkpoints.is_empty() {
546 return Err(Error::Invalid("transaction has no durable intent".into()));
547 }
548 for (i, name) in checkpoints.into_iter().enumerate() {
549 if name != format!("{i:06}.json") {
550 return Err(Error::Invalid(
551 "checkpoint sequence gap or unknown record".into(),
552 ));
553 }
554 let bytes = read_bytes(directory, name)?;
555 let envelope: Envelope = serde_json::from_slice(&bytes)
556 .map_err(|_| Error::Invalid("truncated or malformed checkpoint".into()))?;
557 if digest(envelope.payload.as_bytes()) != envelope.sha256 {
558 return Err(Error::Invalid("checkpoint checksum mismatch".into()));
559 }
560 let record: Record = serde_json::from_str(&envelope.payload)
561 .map_err(|_| Error::Invalid("unsupported or malformed checkpoint".into()))?;
562 if record.schema != 1
563 || record.sequence != i
564 || record.previous_sha256 != hash
565 || record.header.repository_id != repository_id
566 || record.header.transaction_id != transaction_id
567 {
568 return Err(Error::Invalid(
569 "unsupported schema or invalid checkpoint binding".into(),
570 ));
571 }
572 validate_structure(&record, &directory.path)?;
573 if let Some(previous) = &latest {
574 transition(previous, &record)?;
575 } else if record.phase != Phase::Preparing || !record.operations.is_empty() {
576 return Err(Error::Invalid("first checkpoint must be preparing".into()));
577 }
578 diagnosis.valid_checkpoints += 1;
579 diagnosis.phase = Some(record.phase);
580 diagnosis.journal_schema = Some(record.schema);
581 hash = Some(envelope.sha256);
582 latest = Some(record);
583 }
584 if let Some(record) = &latest
585 && !record.operations.is_empty()
586 {
587 for (name, expected) in [
588 ("manifest.backup", &record.header.manifest_backup_sha256),
589 (
590 "destination.backup",
591 &record.header.destination_backup_sha256,
592 ),
593 ] {
594 if digest(&read_bytes(directory, name)?) != *expected {
595 return Err(Error::Invalid("backup integrity mismatch".into()));
596 }
597 }
598 }
599 Ok(())
600 })();
601 if let Err(error) = result {
602 diagnosis.problem = Some(error.to_string());
603 }
604 (diagnosis, latest, hash)
605}
606
607pub fn diagnose(host: &HostContext) -> Result<Vec<Diagnosis>> {
609 let root = host.state_dir.join("repositories");
610 if PrivateDir::open(&host.state_dir, false)?.is_none() {
611 return Ok(vec![]);
612 }
613 if observation::inspect(&root, false)?.kind == observation::Kind::Missing {
614 return Ok(vec![]);
615 }
616 let mut reports = vec![];
617 for repository in observation::names(&root, 4096)? {
618 let id = repository
619 .to_str()
620 .filter(|id| valid_id(id))
621 .ok_or_else(|| Error::Invalid("invalid repository state directory".into()))?;
622 let path = transactions(host, id)?;
623 if observation::inspect(&path, false)?.kind == observation::Kind::Missing {
624 continue;
625 }
626 PrivateDir::open(&path, false)?
627 .ok_or_else(|| Error::Invalid("missing transactions directory".into()))?;
628 for name in observation::names(&path, 4096)? {
629 let Some(txid) = name.to_str().filter(|id| valid_id(id)) else {
630 reports.push(Diagnosis {
631 repository_id: id.into(),
632 transaction_id: "<invalid name>".into(),
633 journal_schema: None,
634 phase: None,
635 valid_checkpoints: 0,
636 problem: Some("unknown transaction entry".into()),
637 });
638 continue;
639 };
640 match PrivateDir::open(&path.join(txid), false) {
641 Ok(Some(directory)) => reports.push(if crate::bootstrap::is_schema3(&directory) {
642 crate::bootstrap::scan(&directory, id, txid).0
643 } else if crate::tool_journal::is_declaration(&directory) {
644 crate::tool_journal::scan(&directory, id, txid).0
645 } else if crate::batch_journal::is_schema4(&directory) {
646 crate::batch_journal::scan(&directory, id, txid).0
647 } else if crate::lifecycle_journal::is_schema2(&directory) {
648 crate::lifecycle_journal::scan(&directory, id, txid).0
649 } else {
650 scan(&directory, id, txid).0
651 }),
652 _ => reports.push(Diagnosis {
653 repository_id: id.into(),
654 transaction_id: txid.into(),
655 journal_schema: None,
656 phase: None,
657 valid_checkpoints: 0,
658 problem: Some("unsafe transaction directory".into()),
659 }),
660 }
661 }
662 }
663 Ok(reports)
664}
665
666pub(crate) fn ensure_writable(host: &HostContext) -> Result<()> {
668 if let Some(transaction) = diagnose(host)?.into_iter().find(Diagnosis::blocks_writes) {
669 let repository_root = crate::local::LocalConfig::load(host)
670 .ok()
671 .and_then(|config| {
672 config
673 .repositories
674 .get(&transaction.repository_id)
675 .map(|r| r.root.clone())
676 });
677 return Err(Error::RecoveryRequired(Box::new(WriteBlocker {
678 transaction,
679 repository_root,
680 })));
681 }
682 Ok(())
683}
684
685pub(crate) fn registered_root(host: &HostContext, id: &str, root: &Path) -> Result<()> {
686 let local = LocalConfig::load(host)?;
687 if local.repositories.get(id).is_none_or(|r| r.root != root) {
688 return Err(Error::Invalid(
689 "transaction repository is not registered at this root".into(),
690 ));
691 }
692 Ok(())
693}