1#[allow(
25 unused_imports,
26 clippy::wildcard_imports,
27 reason = "Standard workspace module prelude"
28)]
29use crate::utilities::*;
30
31use ctb_formats_checksum::{Sha256Stream, xxhash};
32use ctb_formats_dcstring::{
33 DcMixedEncode, DcMstring, DcProjectionPolicy, SharedJson,
34 SharedValueContext,
35};
36use ctb_io::file::Natural;
37use ctb_io::file::entity::{FileEntity, FileEntityKind, FileEntityWithPayload};
38use ctb_io::file::identity::{
39 FileIdentity, FileOrigin, InodeKey, resolve_relative_path_for_os,
40};
41use ctb_io::file::link_path::LinkPath;
42use ctb_io::file::metadata::{FileFlag, FileMetadata, FileTimestamps};
43use ctb_io::file::streams::{AttachedStream, StreamKind, StreamName};
44use ctb_io_environment::EnvDescription;
45use std::collections::HashMap;
46use std::fs::File;
47use std::io::{BufRead, BufReader, Cursor, Read, Seek, SeekFrom, Write};
48use std::path::{Path, PathBuf};
49use std::sync::Arc;
50use std::time::UNIX_EPOCH;
51
52use super::{
53 JOURNAL_MAGIC, JournalErrorRecord, JournalErrorRecordPayload,
54 JournalReader, JournalSessionRecord, JournalSnapshot, JournalWarningRecord,
55 JournalWarningRecordPayload, PLATFORM_WINDOWS, ReadMode,
56 SESSION_ENVIRONMENT_BINDING,
57};
58
59pub const JOURNAL_MAGIC_V1: &[u8; 8] = b"CTBCSCJ\x01";
60
61pub const TAG_SESSION_HEADER: u8 = 1;
62pub const TAG_ENTITY: u8 = 2;
63pub const TAG_BATCH_COMMIT: u8 = 3;
64pub const TAG_JOB_COMPLETED: u8 = 4;
65pub const TAG_SESSION_ENV: u8 = 5;
66pub const TAG_ERROR_RECORD: u8 = 6;
67pub const TAG_WARNING_RECORD: u8 = 7;
68
69pub fn read_legacy_journal_snapshot<R: Read + Seek>(
71 reader: &mut BufReader<R>,
72 journal_path: &Path,
73 policy: &DcProjectionPolicy,
74) -> Result<JournalSnapshot> {
75 if reader.stream_position()? == 0 {
76 let mut magic = [0_u8; 8];
77 reader
78 .read_exact(&mut magic)
79 .context("Incomplete journal magic")?;
80 anyhow::ensure!(
81 &magic == JOURNAL_MAGIC_V1,
82 "Expected legacy journal magic CTBCSCJ\\x01"
83 );
84 }
85
86 let mut sources = Vec::new();
87 let mut destination = PathBuf::new();
88 let mut origin_platform = 0_u8;
89
90 let mut committed_entities = HashMap::new();
91 let mut pending_entities = HashMap::new();
92 let mut batch_hasher = Sha256Stream::new();
93
94 let mut last_batch_id = 0_u64;
95 let mut is_completed = false;
96 let mut valid_length = 0_u64;
97 let mut environment: Option<Arc<EnvDescription>> = None;
98 let mut shared_context = SharedValueContext::default();
99 let mut errors = Vec::new();
100 let mut warnings = Vec::new();
101
102 let mut tag_buf = [0_u8; 1];
103 while reader.read_exact(&mut tag_buf).is_ok() {
104 match tag_buf[0] {
105 TAG_SESSION_HEADER => {
106 let Ok(plat) = read_u8(reader) else {
107 break;
108 };
109 origin_platform = plat;
110
111 let Ok(src_count) = read_u32(reader) else {
112 break;
113 };
114 let mut valid_sources = true;
115 for _ in 0..src_count {
116 if let Ok(bytes) = read_bytes(reader) {
117 let is_windows = origin_platform == PLATFORM_WINDOWS;
118 let src_path =
119 resolve_relative_path_for_os(&bytes, is_windows)?;
120 sources.push(src_path);
121 } else {
122 valid_sources = false;
123 break;
124 }
125 }
126 if !valid_sources {
127 break;
128 }
129 let Ok(dest_bytes) = read_bytes(reader) else {
130 break;
131 };
132 let is_windows = origin_platform == PLATFORM_WINDOWS;
133 destination =
134 resolve_relative_path_for_os(&dest_bytes, is_windows)?;
135 valid_length = reader.stream_position()?;
136 }
137 TAG_SESSION_ENV => {
138 let Ok(env_bytes) = read_bytes(reader) else {
139 break;
140 };
141 let json_str = std::str::from_utf8(&env_bytes)
142 .context("Invalid journal environment UTF-8")?;
143 let env_desc = EnvDescription::from_json(json_str)
144 .context("Invalid journal environment JSON")?;
145 let definition = Arc::new(env_desc);
146 shared_context.insert(
147 SESSION_ENVIRONMENT_BINDING,
148 Arc::clone(&definition),
149 )?;
150 environment = Some(definition);
151 valid_length = reader.stream_position()?;
152 }
153 TAG_ENTITY => {
154 is_completed = false;
155 let Ok(payload_len) = read_u32(reader) else {
156 break;
157 };
158 let mut expected_checksum = [0_u8; 8];
159 if reader.read_exact(&mut expected_checksum).is_err() {
160 break;
161 }
162 let Ok(payload_len_usize) = usize::try_from(payload_len) else {
163 break;
164 };
165 let mut payload = vec![0_u8; payload_len_usize];
166 if reader.read_exact(&mut payload).is_err() {
167 break;
168 }
169 let actual_checksum = xxhash::xxhash3_64(&payload);
170 if actual_checksum != expected_checksum {
171 break;
172 }
173
174 batch_hasher.update(&payload);
175
176 match read_entity_payload(
177 &payload[..],
178 origin_platform,
179 &shared_context,
180 policy,
181 ) {
182 Ok(entity) => {
183 let path_key = entity
185 .identity
186 .path_bytes()
187 .map_or_else(Vec::new, <[u8]>::to_vec);
188 pending_entities.insert(path_key, entity);
189 }
190 Err(error) => {
191 return Err(error).context(
192 "Checksummed journal entity cannot be decoded without losing metadata",
193 );
194 }
195 }
196 }
197 TAG_BATCH_COMMIT => {
198 let Ok(batch_id) = read_u64(reader) else {
199 break;
200 };
201 let mut expected_batch_hash = [0_u8; 32];
202 if reader.read_exact(&mut expected_batch_hash).is_err() {
203 break;
204 }
205 let actual_batch_hash = batch_hasher.finalize();
206 if actual_batch_hash != expected_batch_hash {
207 break;
208 }
209
210 last_batch_id = batch_id;
211 committed_entities.extend(pending_entities.drain());
212 batch_hasher = Sha256Stream::new();
213 valid_length = reader.stream_position()?;
214 }
215 TAG_JOB_COMPLETED => {
216 anyhow::ensure!(
217 pending_entities.is_empty(),
218 "Completion marker precedes batch commit"
219 );
220 is_completed = true;
221 valid_length = reader.stream_position()?;
222 }
223 TAG_ERROR_RECORD => {
224 let Ok(err_bytes) = read_bytes(reader) else {
225 break;
226 };
227 let Ok(json_str) = std::str::from_utf8(&err_bytes) else {
228 break;
229 };
230 let Ok(record) =
231 serde_json::from_str::<JournalErrorRecord>(json_str)
232 else {
233 break;
234 };
235 errors.push(record);
236 if pending_entities.is_empty() {
237 valid_length = reader.stream_position()?;
238 }
239 }
240 TAG_WARNING_RECORD => {
241 let Ok(warn_bytes) = read_bytes(reader) else {
242 break;
243 };
244 let Ok(json_str) = std::str::from_utf8(&warn_bytes) else {
245 break;
246 };
247 let Ok(record) =
248 serde_json::from_str::<JournalWarningRecord>(json_str)
249 else {
250 break;
251 };
252 warnings.push(record);
253 if pending_entities.is_empty() {
254 valid_length = reader.stream_position()?;
255 }
256 }
257 _ => {
258 break;
259 }
260 }
261 }
262
263 anyhow::ensure!(valid_length > 0, "Journal session header is incomplete");
264 let desc_path = journal_path.with_extension("cscdesc");
265 let noatime_used = if desc_path.exists() {
266 if let Ok(desc_content) = std::fs::read_to_string(&desc_path) {
267 desc_content
268 .lines()
269 .any(|l| l.trim() == "NoatimeUsed: true")
270 } else {
271 false
272 }
273 } else {
274 false
275 };
276
277 Ok(JournalSnapshot {
278 sources,
279 destination,
280 origin_platform,
281 committed_entities,
282 is_completed,
283 last_batch_id,
284 valid_length,
285 noatime_used,
286 environment,
287 errors,
288 warnings,
289 applied_directories: HashMap::new(),
290 move_sources: HashMap::new(),
291 })
292}
293
294pub(crate) fn read_legacy_journal_reader(
296 mut file: File,
297 mode: ReadMode,
298 policy: &DcProjectionPolicy,
299) -> Result<JournalReader> {
300 file.seek(SeekFrom::Start(0))?;
301 let file_len = file.metadata()?.len();
302 let mut reader = BufReader::new(file.try_clone()?);
303 let snapshot =
304 read_legacy_journal_snapshot(&mut reader, Path::new(""), policy)?;
305 if mode == ReadMode::Complete {
306 ensure!(
307 snapshot.is_completed && snapshot.valid_length == file_len,
308 "Legacy CSC journal is incomplete or truncated"
309 );
310 }
311 let mut members: Vec<FileEntityWithPayload> = snapshot
312 .committed_entities
313 .into_values()
314 .map(|entity| FileEntityWithPayload {
315 entity,
316 payload: None,
317 })
318 .collect();
319 members.sort_by(|a, b| {
320 a.entity
321 .identity
322 .path_bytes()
323 .cmp(&b.entity.identity.path_bytes())
324 });
325 Ok(JournalReader {
326 file,
327 session: JournalSessionRecord {
328 sources: snapshot.sources,
329 destination: snapshot.destination,
330 origin_platform: u32::from(snapshot.origin_platform),
331 environment: snapshot.environment,
332 },
333 members,
334 errors: snapshot.errors,
335 warnings: snapshot.warnings,
336 completed: snapshot.is_completed,
337 sequence: snapshot.last_batch_id,
338 valid_length: snapshot.valid_length,
339 is_legacy: true,
340 })
341}
342
343pub fn convert_legacy_journal<R: Read + Seek, W: Write>(
346 reader: &mut BufReader<R>,
347 writer: &mut W,
348) -> Result<()> {
349 convert_legacy_journal_with_policy(
350 reader,
351 writer,
352 &DcProjectionPolicy::strict(),
353 )
354}
355
356pub fn convert_legacy_journal_with_policy<R: Read + Seek, W: Write>(
358 reader: &mut BufReader<R>,
359 writer: &mut W,
360 policy: &DcProjectionPolicy,
361) -> Result<()> {
362 if reader.stream_position()? == 0 {
364 let mut magic = [0_u8; 8];
365 reader
366 .read_exact(&mut magic)
367 .context("Incomplete journal magic")?;
368 anyhow::ensure!(
369 &magic == JOURNAL_MAGIC_V1,
370 "Expected legacy journal magic CTBCSCJ\\x01"
371 );
372 }
373
374 writer.write_all(JOURNAL_MAGIC)?;
375 let mut header = DcMstring::new();
376 header.push_system_graph_most_recent()?;
377 writer.write_all(header.as_bytes())?;
378
379 let mut origin_platform = 0_u8;
380 let mut sources = Vec::new();
381 let mut destination = PathBuf::new();
382 let mut environment: Option<Arc<EnvDescription>> = None;
383 let mut shared_context = SharedValueContext::default();
384
385 let mut pending_entities = Vec::new();
386 let mut batch_hasher = Sha256Stream::new();
387 let mut header_written = false;
388
389 let mut tag_buf = [0_u8; 1];
390 while reader.read_exact(&mut tag_buf).is_ok() {
391 match tag_buf[0] {
392 TAG_SESSION_HEADER => {
393 let Ok(plat) = read_u8(reader) else {
394 break;
395 };
396 origin_platform = plat;
397
398 let Ok(src_count) = read_u32(reader) else {
399 break;
400 };
401 let mut valid_sources = true;
402 for _ in 0..src_count {
403 if let Ok(bytes) = read_bytes(reader) {
404 let is_windows = origin_platform == PLATFORM_WINDOWS;
405 let src_path =
406 resolve_relative_path_for_os(&bytes, is_windows)?;
407 sources.push(src_path);
408 } else {
409 valid_sources = false;
410 break;
411 }
412 }
413 if !valid_sources {
414 break;
415 }
416 let Ok(dest_bytes) = read_bytes(reader) else {
417 break;
418 };
419 let is_windows = origin_platform == PLATFORM_WINDOWS;
420 destination =
421 resolve_relative_path_for_os(&dest_bytes, is_windows)?;
422
423 let has_env = if let Ok(buf) = reader.fill_buf() {
425 buf.first().copied() == Some(TAG_SESSION_ENV)
426 } else {
427 false
428 };
429 if has_env {
430 let mut env_tag = [0_u8; 1];
431 let _ = reader.read_exact(&mut env_tag);
432 if let Ok(env_bytes) = read_bytes(reader) {
433 if let Ok(json_str) = std::str::from_utf8(&env_bytes) {
434 if let Ok(env_desc) =
435 EnvDescription::from_json(json_str)
436 {
437 let definition = Arc::new(env_desc);
438 let _ = shared_context.insert(
439 SESSION_ENVIRONMENT_BINDING,
440 Arc::clone(&definition),
441 );
442 let _ = shared_context.insert(
443 "environment",
444 Arc::clone(&definition),
445 );
446 environment = Some(definition);
447 }
448 }
449 }
450 }
451
452 let record = JournalSessionRecord {
453 sources: sources.clone(),
454 destination: destination.clone(),
455 origin_platform: u32::from(origin_platform),
456 environment: environment.clone(),
457 };
458 let mut mst = DcMstring::new();
459 record.encode_dc_mixed(&mut mst)?;
460 writer.write_all(mst.payload_bytes())?;
461 header_written = true;
462 }
463 TAG_SESSION_ENV => {
464 let Ok(env_bytes) = read_bytes(reader) else {
465 break;
466 };
467 if let Ok(json_str) = std::str::from_utf8(&env_bytes) {
468 if let Ok(env_desc) = EnvDescription::from_json(json_str) {
469 let definition = Arc::new(env_desc);
470 let _ = shared_context.insert(
471 SESSION_ENVIRONMENT_BINDING,
472 Arc::clone(&definition),
473 );
474 let _ = shared_context
475 .insert("environment", Arc::clone(&definition));
476 environment = Some(definition);
477 }
478 }
479 }
480 TAG_ENTITY => {
481 let Ok(payload_len) = read_u32(reader) else {
482 break;
483 };
484 let mut expected_checksum = [0_u8; 8];
485 if reader.read_exact(&mut expected_checksum).is_err() {
486 break;
487 }
488 let Ok(payload_len_usize) = usize::try_from(payload_len) else {
489 break;
490 };
491 let mut payload = vec![0_u8; payload_len_usize];
492 if reader.read_exact(&mut payload).is_err() {
493 break;
494 }
495 let actual_checksum = xxhash::xxhash3_64(&payload);
496 if actual_checksum != expected_checksum {
497 break;
498 }
499
500 batch_hasher.update(&payload);
501
502 match read_entity_payload(
503 &payload[..],
504 origin_platform,
505 &shared_context,
506 policy,
507 ) {
508 Ok(entity) => {
509 pending_entities.push(entity);
510 }
511 Err(error) => {
512 return Err(error).context(
513 "Checksummed journal entity cannot be decoded without losing metadata",
514 );
515 }
516 }
517 }
518 TAG_BATCH_COMMIT => {
519 let Ok(batch_id) = read_u64(reader) else {
520 break;
521 };
522 let mut expected_batch_hash = [0_u8; 32];
523 if reader.read_exact(&mut expected_batch_hash).is_err() {
524 break;
525 }
526 let actual_batch_hash = batch_hasher.finalize();
527 if actual_batch_hash != expected_batch_hash {
528 break;
529 }
530 batch_hasher = Sha256Stream::new();
531
532 let mut mst = DcMstring::new();
533 for entity in &pending_entities {
534 if let Some(read_time) = entity.metadata.read_time {
535 read_time.duration_since(UNIX_EPOCH).context(
536 "Read time timestamp is before Unix epoch",
537 )?;
538 }
539 entity.encode_dc_mixed_with_context(
540 &mut mst,
541 &shared_context,
542 )?;
543 }
544
545 crate::section::write_section(writer, batch_id, |output| {
546 output.write_all(mst.payload_bytes())?;
547 Ok(())
548 })?;
549 pending_entities.clear();
550 }
551 TAG_JOB_COMPLETED => {
552 anyhow::ensure!(
553 pending_entities.is_empty(),
554 "Completion marker precedes batch commit"
555 );
556 let mut mst = DcMstring::new();
557 mst.push_char(ctb_formats_dcdata::dc::DC_OPERATION_COMPLETED);
558 writer.write_all(mst.payload_bytes())?;
559 }
560 TAG_ERROR_RECORD => {
561 let Ok(err_bytes) = read_bytes(reader) else {
562 break;
563 };
564 if let Ok(json_str) = std::str::from_utf8(&err_bytes) {
565 if let Ok(error) =
566 serde_json::from_str::<JournalErrorRecord>(json_str)
567 {
568 let stage_code = u64::from(error.stage.to_code());
569 let os_code = match error.os_error {
570 Some(error_code) => {
571 anyhow::ensure!(
572 error_code != 0,
573 "Zero OS error code cannot be distinguished from an absent error in this journal format"
574 );
575 u64::from(u32::from_le_bytes(
576 error_code.to_le_bytes(),
577 ))
578 }
579 None => 0_u64,
580 };
581 let packed = (stage_code << 32) | os_code;
582 let payload = JournalErrorRecordPayload::new(
583 error.path,
584 packed,
585 error.error_message,
586 error.timestamp_sec,
587 );
588 let mut mst = DcMstring::new();
589 payload.encode_dc_mixed(&mut mst)?;
590 writer.write_all(mst.payload_bytes())?;
591 }
592 }
593 }
594 TAG_WARNING_RECORD => {
595 let Ok(warn_bytes) = read_bytes(reader) else {
596 break;
597 };
598 if let Ok(json_str) = std::str::from_utf8(&warn_bytes) {
599 if let Ok(record) =
600 serde_json::from_str::<JournalWarningRecord>(json_str)
601 {
602 let payload = JournalWarningRecordPayload::new(
603 &record.code,
604 &record.message,
605 record.timestamp_sec,
606 );
607 let mut mst = DcMstring::new();
608 payload.encode_dc_mixed(&mut mst)?;
609 writer.write_all(mst.payload_bytes())?;
610 }
611 }
612 }
613 _ => {
614 break;
615 }
616 }
617 }
618
619 anyhow::ensure!(header_written, "Journal session header is incomplete");
620 writer.flush()?;
621 Ok(())
622}
623
624pub fn convert_legacy_journal_bytes(bytes: &[u8]) -> Result<Vec<u8>> {
626 convert_legacy_journal_bytes_with_policy(
627 bytes,
628 &DcProjectionPolicy::strict(),
629 )
630}
631
632pub fn convert_legacy_journal_bytes_with_policy(
634 bytes: &[u8],
635 policy: &DcProjectionPolicy,
636) -> Result<Vec<u8>> {
637 let mut cursor = Cursor::new(bytes);
638 let mut reader = BufReader::new(&mut cursor);
639 let mut out = Vec::new();
640 convert_legacy_journal_with_policy(&mut reader, &mut out, policy)?;
641 Ok(out)
642}
643
644fn attach_legacy_session_environment(
645 entity: &mut FileEntity,
646 env: &Arc<EnvDescription>,
647) {
648 if entity.metadata.environment.is_none()
649 || entity
650 .metadata
651 .environment
652 .as_ref()
653 .is_some_and(|existing| existing == env)
654 {
655 entity.metadata.environment = Some(Arc::clone(env));
656 }
657 for stream in &mut entity.streams {
658 attach_legacy_session_environment(&mut stream.entity, env);
659 }
660}
661
662#[derive(serde::Serialize, serde::Deserialize)]
663pub(crate) struct PreservationRecord {
664 #[serde(default)]
665 pub(crate) identity_dc: Option<Vec<u8>>,
666 pub(crate) metadata: serde_json::Value,
667 pub(crate) extents: Vec<ctb_io::file::Extent>,
668 pub(crate) streams: Vec<PreservedStream>,
669}
670
671#[derive(serde::Serialize, serde::Deserialize)]
672pub(crate) struct PreservedStream {
673 #[serde(default)]
674 pub(crate) name: Option<StreamName>,
675 pub(crate) kind: StreamKind,
676 pub(crate) descriptor: Vec<u8>,
677 pub(crate) data: Option<Vec<u8>>,
678}
679
680pub(crate) fn write_entity_payload(
683 w: &mut impl Write,
684 entity: &FileEntity,
685 context: &SharedValueContext,
686) -> Result<()> {
687 write_bytes(w, entity.identity.path_bytes().unwrap_or(&[]))?;
689 write_bytes(w, entity.identity.filename_bytes().unwrap_or(&[]))?;
691 match &entity.identity.enclosing_path {
692 Some(p) => {
693 w.write_all(&[1])?;
694 write_bytes(w, p.as_os_str().as_encoded_bytes())?;
695 }
696 None => {
697 w.write_all(&[0])?;
698 }
699 }
700 write_u64(w, entity.identity.nlink)?;
701 let device_id = match &entity.identity.origin {
702 FileOrigin::Filesystem { key, .. } => key.device_id,
703 _ => 0,
704 };
705 match &entity.identity.hardlink_group {
706 Some(grp) => {
707 w.write_all(&[1])?;
708 write_natural(w, grp)?;
709 write_u64(w, device_id)?;
710 }
711 None => {
712 w.write_all(&[0])?;
713 }
714 }
715 write_u32(w, entity.metadata.mode.unwrap_or(0o644))?;
717 write_u32(w, entity.metadata.uid.unwrap_or(0))?;
719 write_u32(w, entity.metadata.gid.unwrap_or(0))?;
721 let (
722 mtime_sec,
723 mtime_nsec,
724 atime_sec,
725 atime_nsec,
726 ctime_sec,
727 ctime_nsec,
728 birthtime_sec,
729 birthtime_nsec,
730 ) = match &entity.metadata.timestamps {
731 Some(ts) => (
732 ts.mtime_sec,
733 ts.mtime_nsec,
734 ts.atime_sec,
735 ts.atime_nsec,
736 ts.ctime_sec,
737 ts.ctime_nsec,
738 ts.birthtime_sec,
739 ts.birthtime_nsec,
740 ),
741 None => (0, 0, 0, 0, 0, 0, None, None),
742 };
743 write_i64(w, mtime_sec)?;
744 write_u32(w, mtime_nsec)?;
745 write_i64(w, atime_sec)?;
746 write_u32(w, atime_nsec)?;
747 write_i64(w, ctime_sec)?;
748 write_u32(w, ctime_nsec)?;
749 write_opt_timestamp(w, birthtime_sec, birthtime_nsec)?;
750 let (read_sec, read_nsec) = match entity.metadata.read_time {
751 Some(t) => {
752 let d = t
753 .duration_since(UNIX_EPOCH)
754 .context("Read time timestamp is before Unix epoch")?;
755 let s = i64::try_from(d.as_secs())
756 .context("Read time seconds exceed i64::MAX")?;
757 (Some(s), Some(d.subsec_nanos()))
758 }
759 None => (None, None),
760 };
761 write_opt_timestamp(w, read_sec, read_nsec)?;
762 let flags_slice = entity.metadata.flags.as_deref().unwrap_or(&[]);
764 write_u32(w, u32::try_from(flags_slice.len())?)?;
765 for flag in flags_slice {
766 write_flag(w, *flag)?;
767 }
768
769 match &entity.kind {
770 FileEntityKind::Regular {
771 size,
772 sha256,
773 is_sparse,
774 ..
775 } => {
776 w.write_all(&[0])?;
777 write_u64(w, *size)?;
778 w.write_all(sha256)?;
779 w.write_all(&[u8::from(*is_sparse)])?;
780 }
781 FileEntityKind::Directory => {
782 w.write_all(&[1])?;
783 }
784 FileEntityKind::Symlink { target } => {
785 w.write_all(&[2])?;
786 write_bytes(w, &target.to_bytes())?;
787 }
788 FileEntityKind::Hardlink {
789 target_relative_path,
790 } => {
791 w.write_all(&[3])?;
792 write_bytes(w, &target_relative_path.to_bytes())?;
793 }
794 FileEntityKind::Fifo => {
795 w.write_all(&[4])?;
796 }
797 FileEntityKind::CharDevice { rdev } => {
798 w.write_all(&[5])?;
799 write_u64(w, *rdev)?;
800 }
801 FileEntityKind::BlockDevice { rdev } => {
802 w.write_all(&[6])?;
803 write_u64(w, *rdev)?;
804 }
805 FileEntityKind::Socket => {
806 w.write_all(&[7])?;
807 }
808 FileEntityKind::Door => {
809 w.write_all(&[8])?;
810 }
811 FileEntityKind::Bundle { bundle_type } => {
812 w.write_all(&[9])?;
813 write_bytes(w, bundle_type.as_bytes())?;
814 }
815 FileEntityKind::Inaccessible => {
816 w.write_all(&[10])?;
817 }
818 }
819
820 write_u32(w, u32::try_from(entity.streams.len())?)?;
821 for s in &entity.streams {
822 let name_bytes = s
824 .name
825 .as_ref()
826 .map(|n| n.as_bytes().into_owned())
827 .unwrap_or_default();
828 write_bytes(w, &name_bytes)?;
829 let hash = match &s.entity.kind {
830 FileEntityKind::Regular { sha256, .. } => *sha256,
831 _ => [0_u8; 32],
832 };
833 w.write_all(&hash)?;
834 }
835 match &entity.identity.origin {
836 FileOrigin::Filesystem {
837 key,
838 canonical_path,
839 } => {
840 w.write_all(&[1])?;
841 write_u64(w, key.device_id)?;
842 write_natural(w, &key.inode)?;
843 write_bytes(w, canonical_path.as_os_str().as_encoded_bytes())?;
844 }
845 _ => w.write_all(&[0])?,
846 }
847 let mut streams = Vec::with_capacity(entity.streams.len());
848 for stream in &entity.streams {
849 let mut descriptor = Vec::new();
850 write_entity_payload(&mut descriptor, &stream.entity, context)?;
851 streams.push(PreservedStream {
852 name: stream.name.clone(),
853 kind: stream.kind,
854 descriptor,
855 data: stream.data.clone(),
856 });
857 }
858 let record = PreservationRecord {
859 identity_dc: Some(entity.identity.to_dc_mixed()?.as_bytes().to_vec()),
860 metadata: entity.metadata.encode_json_with_context(context)?,
861 extents: match &entity.kind {
862 FileEntityKind::Regular { extents, .. } => extents.clone(),
863 _ => Vec::new(),
864 },
865 streams,
866 };
867 w.write_all(b"CTBMETA3")?;
868 write_bytes(w, &serde_json::to_vec(&record)?)?;
869 Ok(())
870}
871
872pub fn read_entity_payload(
873 mut r: &[u8],
874 origin_platform: u8,
875 context: &SharedValueContext,
876 policy: &DcProjectionPolicy,
877) -> Result<FileEntity> {
878 let raw_rel_path = read_bytes(&mut r)?;
879 let raw_filename = read_bytes(&mut r)?;
880 let has_enc = read_u8(&mut r)?;
881 let is_windows = origin_platform == PLATFORM_WINDOWS;
882 let enclosing_path = if has_enc == 1 {
883 let enc_bytes = read_bytes(&mut r)?;
884 Some(resolve_relative_path_for_os(&enc_bytes, is_windows)?)
885 } else {
886 None
887 };
888 let nlink = read_u64(&mut r)?;
889 let has_grp = read_u8(&mut r)?;
890 let (hardlink_group, origin_device_id) = if has_grp == 1 {
891 let grp = read_natural(&mut r)?;
892 let dev = read_u64(&mut r)?;
893 (Some(grp), dev)
894 } else {
895 (None, 0)
896 };
897
898 let mode = read_u32(&mut r)?;
899 let uid = read_u32(&mut r)?;
900 let gid = read_u32(&mut r)?;
901 let mtime_sec = read_i64(&mut r)?;
902 let mtime_nsec = read_u32(&mut r)?;
903 let atime_sec = read_i64(&mut r)?;
904 let atime_nsec = read_u32(&mut r)?;
905 let ctime_sec = read_i64(&mut r)?;
906 let ctime_nsec = read_u32(&mut r)?;
907 let (birthtime_sec, birthtime_nsec) = read_opt_timestamp(&mut r)?;
908 let (read_sec, read_nsec) = read_opt_timestamp(&mut r)?;
909 let read_time = match (read_sec, read_nsec) {
910 (Some(sec), Some(nsec)) => {
911 let u_sec = u64::try_from(sec)
912 .context("Journal read_time seconds is negative")?;
913 anyhow::ensure!(
914 nsec < 1_000_000_000,
915 "Journal read_time nanoseconds out of range: {nsec}"
916 );
917 let duration = std::time::Duration::new(u_sec, nsec);
918 let time = UNIX_EPOCH
919 .checked_add(duration)
920 .context("Journal read_time overflow")?;
921 Some(time)
922 }
923 _ => None,
924 };
925 let flag_count = read_u32(&mut r)?;
926 let mut flags = Vec::with_capacity(usize::try_from(flag_count)?);
927 for _ in 0..flag_count {
928 if let Some(flag) = read_flag(&mut r)? {
929 flags.push(flag);
930 }
931 }
932
933 let kind_tag = read_u8(&mut r)?;
934 let kind = match kind_tag {
935 0 => {
936 let size = read_u64(&mut r)?;
937 let mut sha256 = [0_u8; 32];
938 r.read_exact(&mut sha256)?;
939 let is_sparse = read_u8(&mut r)? != 0;
940 FileEntityKind::Regular {
941 size,
942 sha256,
943 is_sparse,
944 extents: Vec::new(),
945 }
946 }
947 1 => FileEntityKind::Directory,
948 2 => {
949 let target = read_bytes(&mut r)?;
950 FileEntityKind::Symlink {
951 target: LinkPath::from_bytes(&target, is_windows),
952 }
953 }
954 3 => {
955 let target_relative_path = read_bytes(&mut r)?;
956 FileEntityKind::Hardlink {
957 target_relative_path: LinkPath::from_bytes(
958 &target_relative_path,
959 is_windows,
960 ),
961 }
962 }
963 4 => FileEntityKind::Fifo,
964 5 => {
965 let rdev = read_u64(&mut r)?;
966 FileEntityKind::CharDevice { rdev }
967 }
968 6 => {
969 let rdev = read_u64(&mut r)?;
970 FileEntityKind::BlockDevice { rdev }
971 }
972 7 => FileEntityKind::Socket,
973 8 => FileEntityKind::Door,
974 9 => {
975 let bundle_bytes = read_bytes(&mut r)?;
976 let bundle_type = String::from_utf8(bundle_bytes)?;
977 FileEntityKind::Bundle { bundle_type }
978 }
979 10 => FileEntityKind::Inaccessible,
980 other => anyhow::bail!("Unknown entity kind in journal: {other}"),
981 };
982
983 let stream_count = read_u32(&mut r)?;
984 let mut streams = Vec::with_capacity(usize::try_from(stream_count)?);
985 for _ in 0..stream_count {
986 let name_bytes = read_bytes(&mut r)?;
987 let name = if name_bytes.is_empty() {
988 None
989 } else {
990 Some(StreamName::from_bytes(&name_bytes))
991 };
992 let mut sha256 = [0_u8; 32];
993 r.read_exact(&mut sha256)?;
994 streams.push(AttachedStream {
995 name,
996 kind: StreamKind::ExtendedAttribute,
997 entity: Box::new(FileEntity {
998 identity: FileIdentity {
999 origin: FileOrigin::Synthetic,
1000 relative_path: None,
1001 enclosing_path: None,
1002 nlink: 1,
1003 hardlink_group: None,
1004 },
1005 metadata: FileMetadata::empty(),
1006 kind: FileEntityKind::Regular {
1007 size: 0,
1008 sha256,
1009 is_sparse: false,
1010 extents: Vec::new(),
1011 },
1012 streams: Vec::new(),
1013 }),
1014 data: None,
1015 payload: None,
1016 });
1017 }
1018
1019 let origin = if read_u8(&mut r)? == 1 {
1020 let dev = read_u64(&mut r)?;
1021 let ino = read_natural(&mut r)?;
1022 let canon = read_bytes(&mut r)?;
1023 let is_windows = origin_platform == PLATFORM_WINDOWS;
1024 FileOrigin::Filesystem {
1025 key: InodeKey {
1026 device_id: dev,
1027 inode: ino,
1028 },
1029 canonical_path: resolve_relative_path_for_os(&canon, is_windows)?,
1030 }
1031 } else {
1032 FileOrigin::Synthetic
1033 };
1034
1035 let is_windows = origin_platform == PLATFORM_WINDOWS;
1036 let relative_path = if raw_rel_path.is_empty() {
1037 None
1038 } else {
1039 Some(resolve_relative_path_for_os(&raw_rel_path, is_windows)?)
1040 };
1041
1042 if !raw_filename.is_empty() {
1043 let legacy_filename =
1044 resolve_relative_path_for_os(&raw_filename, is_windows)?;
1045 let derived_filename = relative_path
1046 .as_deref()
1047 .and_then(Path::file_name)
1048 .map(PathBuf::from);
1049 if let Some(derived) = derived_filename {
1050 anyhow::ensure!(
1051 derived == legacy_filename,
1052 "Journal entity filename disagrees with relative path: {legacy_filename:?} vs {derived:?}"
1053 );
1054 }
1055 }
1056
1057 let hardlink_group = if hardlink_group.is_some() {
1058 hardlink_group
1059 } else if nlink > 1 {
1060 match &origin {
1061 FileOrigin::Filesystem { key, .. } => {
1062 let dev = if origin_device_id != 0 {
1063 origin_device_id
1064 } else {
1065 key.device_id
1066 };
1067 if dev != 0 {
1068 Some(key.inode.clone())
1069 } else {
1070 None
1071 }
1072 }
1073 _ => None,
1074 }
1075 } else {
1076 None
1077 };
1078
1079 let mut entity = FileEntity {
1080 identity: FileIdentity {
1081 origin,
1082 relative_path,
1083 enclosing_path,
1084 nlink,
1085 hardlink_group,
1086 },
1087 metadata: FileMetadata {
1088 native: None,
1089 mode: Some(mode),
1090 uid: Some(uid),
1091 gid: Some(gid),
1092 timestamps: Some(FileTimestamps {
1093 atime_sec,
1094 atime_nsec,
1095 mtime_sec,
1096 mtime_nsec,
1097 ctime_sec,
1098 ctime_nsec,
1099 birthtime_sec,
1100 birthtime_nsec,
1101 resolution_nsec: None,
1102 }),
1103 flags: Some(flags),
1104 platform_raw_flags: None,
1105 read_time,
1106 filesystem_type: None,
1107 environment: None,
1108 apple: None,
1109 warnings: Vec::new(),
1110 errors: Vec::new(),
1111 },
1112 kind,
1113 streams,
1114 };
1115 let mut legacy = true;
1116 let mut has_semantic_identity = false;
1117 if !r.is_empty() {
1118 let mut magic = [0_u8; 8];
1119 r.read_exact(&mut magic)?;
1120 anyhow::ensure!(
1121 &magic == b"CTBMETA1"
1122 || &magic == b"CTBMETA2"
1123 || &magic == b"CTBMETA3",
1124 "Unknown preservation record version"
1125 );
1126 legacy = &magic == b"CTBMETA1";
1127 let mut record: PreservationRecord =
1128 serde_json::from_slice(&read_bytes(&mut r)?)?;
1129 anyhow::ensure!(
1130 record.streams.len() == entity.streams.len(),
1131 "Stream descriptor count mismatch"
1132 );
1133 has_semantic_identity = record.identity_dc.is_some();
1134 anyhow::ensure!(
1135 &magic != b"CTBMETA3" || has_semantic_identity,
1136 "Semantic identity is missing from CTBMETA3 preservation record"
1137 );
1138 if let Some(identity_dc) = record.identity_dc {
1139 let (identity_doc, identity_log) =
1140 ctb_formats_dcstring::dcmm_to_dcmstring(&identity_dc)?;
1141 identity_log.auto_log();
1142 let identity = identity_doc.decode::<FileIdentity>(policy)?;
1143 let semantic_path = identity
1144 .relative_path
1145 .as_deref()
1146 .filter(|value| !value.as_os_str().is_empty());
1147 let legacy_path = entity
1148 .identity
1149 .relative_path
1150 .as_deref()
1151 .filter(|value| !value.as_os_str().is_empty());
1152 anyhow::ensure!(
1153 semantic_path == legacy_path,
1154 "Semantic journal identity disagrees with its primary path"
1155 );
1156 entity.identity = identity;
1157 }
1158 if let Some(flags) = record.metadata.get_mut("platform_raw_flags") {
1159 if flags.is_object() {
1160 let raw = flags.get("raw_value").and_then(serde_json::Value::as_u64)
1161 .context("Legacy platform_raw_flags must contain an unsigned raw_value")?;
1162 *flags = serde_json::Value::from(raw);
1163 }
1164 }
1165 entity.metadata = if legacy {
1166 serde_json::from_value(record.metadata)?
1167 } else {
1168 FileMetadata::decode_json_with_context(record.metadata, context)?
1169 };
1170 if let FileEntityKind::Regular { extents, .. } = &mut entity.kind {
1171 *extents = record.extents;
1172 }
1173 for (stream, preserved) in entity.streams.iter_mut().zip(record.streams)
1174 {
1175 stream.name = preserved.name;
1176 stream.kind = preserved.kind;
1177 *stream.entity = read_entity_payload(
1178 &preserved.descriptor,
1179 origin_platform,
1180 context,
1181 policy,
1182 )?;
1183 stream.data = preserved.data;
1184 }
1185 anyhow::ensure!(r.is_empty(), "Unexpected preservation record data");
1186 }
1187 if legacy && context.contains(SESSION_ENVIRONMENT_BINDING) {
1188 let environment =
1189 context.resolve::<EnvDescription>(SESSION_ENVIRONMENT_BINDING)?;
1190 attach_legacy_session_environment(&mut entity, &environment);
1191 }
1192 if !has_semantic_identity {
1193 let warning = "Legacy journal lacks semantic identity; absent versus empty paths and non-filesystem origin provenance may not be recoverable";
1194 entity.metadata.push_warning(warning);
1195 warn_fmt!("{}: {warning}", entity.identity.display_path());
1196 }
1197 Ok(entity)
1198}
1199
1200pub(crate) fn write_bytes(w: &mut impl Write, bytes: &[u8]) -> Result<()> {
1203 write_u32(w, u32::try_from(bytes.len())?)?;
1204 w.write_all(bytes)?;
1205 Ok(())
1206}
1207
1208pub(crate) fn read_bytes(r: &mut impl Read) -> Result<Vec<u8>> {
1209 let len = usize::try_from(read_u32(r)?)?;
1210 let mut buf = vec![0_u8; len];
1211 r.read_exact(&mut buf)?;
1212 Ok(buf)
1213}
1214
1215pub(crate) fn write_u32(w: &mut impl Write, v: u32) -> Result<()> {
1216 w.write_all(&v.to_le_bytes())?;
1217 Ok(())
1218}
1219
1220pub(crate) fn read_u32(r: &mut impl Read) -> Result<u32> {
1221 let mut buf = [0_u8; 4];
1222 r.read_exact(&mut buf)?;
1223 Ok(u32::from_le_bytes(buf))
1224}
1225
1226pub(crate) fn write_u64(w: &mut impl Write, v: u64) -> Result<()> {
1227 w.write_all(&v.to_le_bytes())?;
1228 Ok(())
1229}
1230
1231pub(crate) fn read_u64(r: &mut impl Read) -> Result<u64> {
1232 let mut buf = [0_u8; 8];
1233 r.read_exact(&mut buf)?;
1234 Ok(u64::from_le_bytes(buf))
1235}
1236
1237pub(crate) fn write_natural(w: &mut impl Write, val: &Natural) -> Result<()> {
1238 write_bytes(w, val.to_string().as_bytes())
1239}
1240
1241pub(crate) fn read_natural(r: &mut impl Read) -> Result<Natural> {
1242 let bytes = read_bytes(r)?;
1243 let s = std::str::from_utf8(&bytes)?;
1244 use std::str::FromStr;
1245 Natural::from_str(s)
1246 .map_err(|()| anyhow::anyhow!("Invalid natural in journal: {s}"))
1247}
1248
1249pub(crate) fn write_i64(w: &mut impl Write, v: i64) -> Result<()> {
1250 w.write_all(&v.to_le_bytes())?;
1251 Ok(())
1252}
1253
1254pub(crate) fn read_i64(r: &mut impl Read) -> Result<i64> {
1255 let mut buf = [0_u8; 8];
1256 r.read_exact(&mut buf)?;
1257 Ok(i64::from_le_bytes(buf))
1258}
1259
1260pub(crate) fn read_u8(r: &mut impl Read) -> Result<u8> {
1261 let mut buf = [0_u8; 1];
1262 r.read_exact(&mut buf)?;
1263 Ok(buf[0])
1264}
1265
1266pub(crate) fn write_flag(w: &mut impl Write, flag: FileFlag) -> Result<()> {
1267 write_bytes(w, flag.name().as_bytes())
1268}
1269
1270pub(crate) fn read_flag(r: &mut impl Read) -> Result<Option<FileFlag>> {
1271 let bytes = read_bytes(r)?;
1272 let s = std::str::from_utf8(&bytes)?;
1273 Ok(FileFlag::from_name(s))
1274}
1275
1276pub(crate) fn write_opt_timestamp(
1277 w: &mut impl Write,
1278 sec: Option<i64>,
1279 nsec: Option<u32>,
1280) -> Result<()> {
1281 match (sec, nsec) {
1282 (Some(s), Some(ns)) => {
1283 w.write_all(&[1])?;
1284 write_i64(w, s)?;
1285 write_u32(w, ns)?;
1286 }
1287 _ => {
1288 w.write_all(&[0])?;
1289 }
1290 }
1291 Ok(())
1292}
1293
1294pub(crate) fn read_opt_timestamp(
1295 r: &mut impl Read,
1296) -> Result<(Option<i64>, Option<u32>)> {
1297 let mut tag = [0_u8; 1];
1298 r.read_exact(&mut tag)?;
1299 if tag[0] == 1 {
1300 let sec = read_i64(r)?;
1301 let nsec = read_u32(r)?;
1302 Ok((Some(sec), Some(nsec)))
1303 } else {
1304 Ok((None, None))
1305 }
1306}