1#[allow(
36 unused_imports,
37 clippy::wildcard_imports,
38 reason = "Standard workspace crate prelude"
39)]
40pub(crate) use ctb_utilities::*;
41
42use anyhow::anyhow;
43
44pub mod bookmark;
45mod shared;
46
47use std::collections::BTreeMap;
48use std::path::{Path, PathBuf};
49
50use shared::{
51 build_posix_path_from_components, carbon_path_to_pathbuf,
52 normalize_path_string, read_fixed_bytes, read_i32_le, read_u32_le,
53 resolve_posix_target,
54};
55
56#[cfg(test)]
57pub(crate) fn get_alias_data(key: &str) -> Option<Vec<u8>> {
58 ctb_utilities::load_manifest_fixture(env!("CARGO_MANIFEST_DIR"), key)
59}
60
61const ALIAS_FILE_MAGIC: &[u8; 16] = b"book\0\0\0\0mark\0\0\0\0";
62const ALIAS_FILE_HEADER_SIZE: usize = 56;
63const ALIAS_TOC_CHUNK_TYPE: i32 = -2;
64
65const ALIAS_ITEM_TARGET_PATH_COMPONENTS: u32 = 0x1004;
66const ALIAS_ITEM_TARGET_URL: u32 = 0x1003;
67const ALIAS_ITEM_TARGET_FILENAME: u32 = 0x1020;
68const ALIAS_ITEM_DISPLAY_NAME: u32 = 0xf017;
69const ALIAS_ITEM_ALIAS_DATA: u32 = 0xfe00;
70
71const ALIAS_DATA_TYPE_STRING: i32 = 0x0101;
72const ALIAS_DATA_TYPE_DATA: i32 = 0x0201;
73const ALIAS_DATA_TYPE_ARRAY: i32 = 0x0601;
74const ALIAS_DATA_TYPE_URL: i32 = 0x0901;
75
76const ALIAS_VERSION_2: u16 = 2;
77const ALIAS_VERSION_3: u16 = 3;
78
79const ALIAS_KIND_FILE: u16 = 0;
80const ALIAS_KIND_FOLDER: u16 = 1;
81
82const ALIAS_FIXED_DISK: u16 = 0;
83
84const ALIAS_TAG_END: i16 = -1;
85const ALIAS_TAG_CARBON_FOLDER_NAME: i16 = 0;
86const ALIAS_TAG_CNID_PATH: i16 = 1;
87const ALIAS_TAG_CARBON_PATH: i16 = 2;
88const ALIAS_TAG_APPLESHARE_ZONE: i16 = 3;
89const ALIAS_TAG_APPLESHARE_SERVER: i16 = 4;
90const ALIAS_TAG_APPLESHARE_USERNAME: i16 = 5;
91const ALIAS_TAG_DRIVER_NAME: i16 = 6;
92const ALIAS_TAG_NETWORK_MOUNT_INFO: i16 = 9;
93const ALIAS_TAG_DIALUP_INFO: i16 = 10;
94const ALIAS_TAG_UNICODE_FILENAME: i16 = 14;
95const ALIAS_TAG_UNICODE_VOLUME_NAME: i16 = 15;
96const ALIAS_TAG_HIGH_RES_VOLUME_DATE: i16 = 16;
97const ALIAS_TAG_HIGH_RES_CREATION_DATE: i16 = 17;
98const ALIAS_TAG_POSIX_PATH: i16 = 18;
99const ALIAS_TAG_POSIX_PATH_TO_MOUNTPOINT: i16 = 19;
100const ALIAS_TAG_RECURSIVE_ALIAS_DISK_IMAGE: i16 = 20;
101const ALIAS_TAG_USER_HOME_PREFIX_LEN: i16 = 21;
102
103pub fn create_simple_alias<P: AsRef<Path>>(
105 target_path: P,
106 name: Option<&str>,
107) -> Result<Vec<u8>> {
108 let target_path = target_path.as_ref();
109 let path_string = normalize_path_string(target_path)?;
110 let display_name = name
112 .map(ToString::to_string)
113 .or_else(|| {
114 target_path
115 .file_name()
116 .map(|value| value.to_string_lossy().to_string())
117 })
118 .unwrap_or_else(|| path_string.clone());
119
120 let alias_record = AliasRecord::new_simple(&path_string, name)?;
121 let alias_record_bytes = alias_record.to_bytes()?;
122 build_alias_file(&path_string, &display_name, &alias_record_bytes)
123}
124
125pub fn read_path_from_alias<P: AsRef<Path>>(alias_path: P) -> Result<PathBuf> {
127 let bytes = std::fs::read(alias_path.as_ref()).with_context(|| {
128 format!(
129 "Failed to read alias file {}",
130 alias_path.as_ref().display()
131 )
132 })?;
133 read_path_from_alias_bytes(&bytes)
134}
135
136pub fn read_path_from_alias_bytes(bytes: &[u8]) -> Result<PathBuf> {
137 if is_alias_file(bytes) {
138 return read_path_from_alias_file(bytes);
139 }
140
141 let record = AliasRecord::from_bytes(bytes)
142 .context("Alias data did not parse as an alias record")?;
143 read_path_from_alias_record(&record)
144}
145
146fn read_path_from_alias_record(record: &AliasRecord) -> Result<PathBuf> {
147 record
148 .target
149 .posix_path
150 .as_ref()
151 .map(|value| {
152 resolve_posix_target(value, record.volume.posix_path.as_deref())
153 })
154 .or_else(|| {
155 record
156 .target
157 .carbon_path
158 .as_ref()
159 .map(|value| carbon_path_to_pathbuf(value.as_slice()))
160 })
161 .or_else(|| {
162 record.target.filename.as_ref().map(|name| {
163 resolve_posix_target(name, record.volume.posix_path.as_deref())
164 })
165 })
166 .context("Alias record did not include a path")
167}
168
169fn is_alias_file(bytes: &[u8]) -> bool {
170 bytes.len() >= ALIAS_FILE_HEADER_SIZE && bytes.starts_with(ALIAS_FILE_MAGIC)
171}
172
173#[derive(Debug, Clone)]
174struct AliasFileHeader {
175 data_start: usize,
176 data_length: usize,
177}
178
179fn parse_alias_file_header(bytes: &[u8]) -> Result<AliasFileHeader> {
180 if !is_alias_file(bytes) {
181 bail!("Not an alias file");
182 }
183
184 let data_start = read_u32_le(bytes, 16)?;
185 let data_start_usize =
186 usize::try_from(data_start).context("Alias data start overflow")?;
187 if data_start_usize < ALIAS_FILE_HEADER_SIZE {
188 bail!("Alias data start offset too small");
189 }
190
191 let data_length = read_u32_le(bytes, 24)?;
192 let data_length_usize =
193 usize::try_from(data_length).context("Alias data length overflow")?;
194 let data_end = data_start_usize
195 .checked_add(data_length_usize)
196 .context("Alias data end overflow")?;
197 if data_end > bytes.len() {
198 bail!("Alias data section truncated");
199 }
200
201 Ok(AliasFileHeader {
202 data_start: data_start_usize,
203 data_length: data_length_usize,
204 })
205}
206
207fn read_path_from_alias_file(bytes: &[u8]) -> Result<PathBuf> {
208 let header = parse_alias_file_header(bytes)?;
209 let toc_entries = parse_alias_toc_entries(bytes, &header)?;
210
211 if let Some(offset) = toc_entries.get(&ALIAS_ITEM_TARGET_PATH_COMPONENTS) {
212 let components = read_alias_path_components(bytes, &header, *offset)?;
213 return Ok(build_posix_path_from_components(&components));
214 }
215
216 if let Some(offset) = toc_entries.get(&ALIAS_ITEM_TARGET_URL) {
217 if let Some(path) = read_alias_url_path(bytes, &header, *offset)? {
218 return Ok(path);
219 }
220 }
221
222 if let Some(offset) = toc_entries.get(&ALIAS_ITEM_ALIAS_DATA) {
223 let record_chunk = read_alias_chunk(bytes, &header, *offset)?;
224 if record_chunk.chunk_type == ALIAS_DATA_TYPE_DATA {
225 let record = AliasRecord::from_bytes(&record_chunk.data)
226 .context("Alias data chunk did not parse as an alias record")?;
227 return read_path_from_alias_record(&record);
228 }
229 }
230
231 bail!("Alias file did not contain a target path")
232}
233
234fn parse_alias_toc_entries(
235 bytes: &[u8],
236 header: &AliasFileHeader,
237) -> Result<BTreeMap<u32, u32>> {
238 let mut entries = BTreeMap::new();
239 let mut next_offset = read_u32_le(bytes, header.data_start)?;
240
241 while next_offset != 0 {
242 let toc_chunk = read_alias_chunk(bytes, header, next_offset)?;
243 if toc_chunk.chunk_type != ALIAS_TOC_CHUNK_TYPE {
244 bail!("Alias TOC chunk had invalid type");
245 }
246 if toc_chunk.data.len() < 12 {
247 bail!("Alias TOC chunk too short");
248 }
249
250 let next = read_u32_le(&toc_chunk.data, 4)?;
251 let count = read_u32_le(&toc_chunk.data, 8)?;
252 let count_usize =
253 usize::try_from(count).context("Alias TOC count overflow")?;
254 let items_size = count_usize
255 .checked_mul(12)
256 .context("Alias TOC size overflow")?;
257 let items_end = 12usize
258 .checked_add(items_size)
259 .context("Alias TOC size overflow")?;
260 if items_end > toc_chunk.data.len() {
261 bail!("Alias TOC data truncated");
262 }
263
264 let mut entry_offset = 12usize;
265 for _ in 0..count_usize {
266 let item_type = read_u32_le(&toc_chunk.data, entry_offset)?;
267 let item_offset =
268 read_u32_le(&toc_chunk.data, entry_offset.saturating_add(4))?;
269 entries.insert(item_type, item_offset);
270 entry_offset = entry_offset
271 .checked_add(12)
272 .context("Alias TOC entry overflow")?;
273 }
274
275 next_offset = next;
276 }
277
278 Ok(entries)
279}
280
281#[derive(Debug)]
282struct AliasChunk {
283 chunk_type: i32,
284 data: Vec<u8>,
285}
286
287fn read_alias_chunk(
288 bytes: &[u8],
289 header: &AliasFileHeader,
290 offset: u32,
291) -> Result<AliasChunk> {
292 let offset_usize =
293 usize::try_from(offset).context("Alias chunk offset overflow")?;
294 let chunk_start = header
295 .data_start
296 .checked_add(offset_usize)
297 .context("Alias chunk offset overflow")?;
298 let data_section_end = header
299 .data_start
300 .checked_add(header.data_length)
301 .context("Alias data section overflow")?;
302 if chunk_start.saturating_add(8) > data_section_end {
303 bail!("Alias chunk header out of bounds");
304 }
305
306 let length = read_u32_le(bytes, chunk_start)?;
307 let chunk_type = read_i32_le(bytes, chunk_start.saturating_add(4))?;
308 let length_usize =
309 usize::try_from(length).context("Alias chunk size overflow")?;
310 let data_start = chunk_start
311 .checked_add(8)
312 .context("Alias chunk data overflow")?;
313 let data_end = data_start
314 .checked_add(length_usize)
315 .context("Alias chunk data overflow")?;
316 if data_end > data_section_end {
317 bail!("Alias chunk data out of bounds");
318 }
319 let data = bytes
320 .get(data_start..data_end)
321 .context("Alias chunk data out of bounds")?
322 .to_vec();
323
324 Ok(AliasChunk { chunk_type, data })
325}
326
327fn read_alias_path_components(
328 bytes: &[u8],
329 header: &AliasFileHeader,
330 offset: u32,
331) -> Result<Vec<String>> {
332 let chunk = read_alias_chunk(bytes, header, offset)?;
333 if chunk.chunk_type != ALIAS_DATA_TYPE_ARRAY {
334 bail!("Alias path components were not stored as an array");
335 }
336
337 if chunk.data.len() % 4 != 0 {
338 bail!("Alias path component array had invalid length");
339 }
340
341 let mut components = Vec::new();
342 let mut offset_index = 0usize;
343 while offset_index < chunk.data.len() {
344 let end = offset_index
345 .checked_add(4)
346 .context("Alias path component offset overflow")?;
347 let slice = chunk
348 .data
349 .get(offset_index..end)
350 .context("Alias path component offset out of range")?;
351 let arr: [u8; 4] =
352 slice.try_into().context("invalid offset slice size")?;
353 let offset_value = u32::from_le_bytes(arr);
354 let component_chunk = read_alias_chunk(bytes, header, offset_value)?;
355 if component_chunk.chunk_type != ALIAS_DATA_TYPE_STRING {
356 bail!("Alias path component was not a string");
357 }
358 let component = String::from_utf8(component_chunk.data)
359 .context("Alias path component was not UTF-8")?;
360 components.push(component);
361 offset_index = end;
362 }
363
364 Ok(components)
365}
366
367fn read_alias_url_path(
368 bytes: &[u8],
369 header: &AliasFileHeader,
370 offset: u32,
371) -> Result<Option<PathBuf>> {
372 let chunk = read_alias_chunk(bytes, header, offset)?;
373 if chunk.chunk_type != ALIAS_DATA_TYPE_URL
374 && chunk.chunk_type != ALIAS_DATA_TYPE_STRING
375 {
376 return Ok(None);
377 }
378
379 let url =
380 String::from_utf8(chunk.data).context("Alias URL was not UTF-8")?;
381 if let Some(path) = url.strip_prefix("file://") {
382 let path = path.trim_start_matches('/');
383 return Ok(Some(PathBuf::from("/").join(path)));
384 }
385
386 Ok(None)
387}
388
389fn build_alias_file(
390 target_path: &str,
391 display_name: &str,
392 alias_record: &[u8],
393) -> Result<Vec<u8>> {
394 let components = target_path
395 .trim_start_matches('/')
396 .split('/')
397 .filter(|component| !component.is_empty())
398 .map(ToString::to_string)
399 .collect::<Vec<_>>();
400
401 let file_name = components
403 .last()
404 .cloned()
405 .unwrap_or_else(|| display_name.to_string());
406 let url = build_file_url(target_path);
407
408 let mut data_section = Vec::new();
409 data_section.extend_from_slice(&0u32.to_le_bytes());
410
411 let mut component_offsets = Vec::new();
412 for component in &components {
413 let offset = append_alias_chunk(
414 &mut data_section,
415 ALIAS_DATA_TYPE_STRING,
416 component.as_bytes(),
417 )?;
418 component_offsets.push(offset);
419 }
420
421 let file_name_offset = if file_name.is_empty() {
422 None
423 } else {
424 Some(append_alias_chunk(
425 &mut data_section,
426 ALIAS_DATA_TYPE_STRING,
427 file_name.as_bytes(),
428 )?)
429 };
430
431 let display_name_offset = if display_name.is_empty() {
432 None
433 } else {
434 Some(append_alias_chunk(
435 &mut data_section,
436 ALIAS_DATA_TYPE_STRING,
437 display_name.as_bytes(),
438 )?)
439 };
440
441 let url_offset = if url.is_empty() {
442 None
443 } else {
444 Some(append_alias_chunk(
445 &mut data_section,
446 ALIAS_DATA_TYPE_URL,
447 url.as_bytes(),
448 )?)
449 };
450
451 let alias_data_offset = append_alias_chunk(
452 &mut data_section,
453 ALIAS_DATA_TYPE_DATA,
454 alias_record,
455 )?;
456
457 let mut path_array_data = Vec::new();
458 for offset in &component_offsets {
459 path_array_data.extend_from_slice(&offset.to_le_bytes());
460 }
461 let path_array_offset = append_alias_chunk(
462 &mut data_section,
463 ALIAS_DATA_TYPE_ARRAY,
464 &path_array_data,
465 )?;
466
467 let mut toc_entries = Vec::new();
468 toc_entries.push((ALIAS_ITEM_TARGET_PATH_COMPONENTS, path_array_offset));
469 if let Some(offset) = url_offset {
470 toc_entries.push((ALIAS_ITEM_TARGET_URL, offset));
471 }
472 if let Some(offset) = file_name_offset {
473 toc_entries.push((ALIAS_ITEM_TARGET_FILENAME, offset));
474 }
475 if let Some(offset) = display_name_offset {
476 toc_entries.push((ALIAS_ITEM_DISPLAY_NAME, offset));
477 }
478 toc_entries.push((ALIAS_ITEM_ALIAS_DATA, alias_data_offset));
479
480 let toc_data = build_alias_toc_data(&toc_entries)?;
481 let toc_offset =
482 append_alias_chunk(&mut data_section, ALIAS_TOC_CHUNK_TYPE, &toc_data)?;
483 data_section
484 .get_mut(0..4)
485 .context("invalid alias data section size")?
486 .copy_from_slice(&toc_offset.to_le_bytes());
487
488 let data_length = u32::try_from(data_section.len())
489 .context("Alias data section too large")?;
490 let data_offset = u32::try_from(ALIAS_FILE_HEADER_SIZE)
491 .context("Alias header size overflow")?;
492
493 let mut bytes = Vec::new();
494 bytes.extend_from_slice(ALIAS_FILE_MAGIC);
495 bytes.extend_from_slice(&data_offset.to_le_bytes());
496 bytes.extend_from_slice(&data_offset.to_le_bytes());
497 bytes.extend_from_slice(&data_length.to_le_bytes());
498 bytes.extend_from_slice(&0u32.to_le_bytes());
499 bytes.extend_from_slice(&0u32.to_le_bytes());
500 bytes.extend_from_slice(&0u32.to_le_bytes());
501 bytes.extend_from_slice(&0u64.to_le_bytes());
502 bytes.extend_from_slice(&0u64.to_le_bytes());
503 bytes.extend_from_slice(&data_section);
504
505 Ok(bytes)
506}
507
508fn append_alias_chunk(
509 data_section: &mut Vec<u8>,
510 chunk_type: i32,
511 data: &[u8],
512) -> Result<u32> {
513 let offset = u32::try_from(data_section.len())
514 .context("Alias chunk offset overflow")?;
515 let size =
516 u32::try_from(data.len()).context("Alias chunk size overflow")?;
517 data_section.extend_from_slice(&size.to_le_bytes());
518 data_section.extend_from_slice(&chunk_type.to_le_bytes());
519 data_section.extend_from_slice(data);
520 let padding = (4usize.saturating_sub(data.len() % 4)) % 4;
521 let new_len = data_section
522 .len()
523 .checked_add(padding)
524 .context("Alias chunk padding overflow")?;
525 data_section.resize(new_len, 0);
526 Ok(offset)
527}
528
529fn build_alias_toc_data(entries: &[(u32, u32)]) -> Result<Vec<u8>> {
530 let count =
531 u32::try_from(entries.len()).context("Alias TOC count overflow")?;
532 let mut data = Vec::new();
533 data.extend_from_slice(&1u32.to_le_bytes());
534 data.extend_from_slice(&0u32.to_le_bytes());
535 data.extend_from_slice(&count.to_le_bytes());
536 for (item_type, offset) in entries {
537 data.extend_from_slice(&item_type.to_le_bytes());
538 data.extend_from_slice(&offset.to_le_bytes());
539 data.extend_from_slice(&0u32.to_le_bytes());
540 }
541 Ok(data)
542}
543
544fn build_file_url(target_path: &str) -> String {
545 let trimmed = target_path.trim_start_matches('/');
546 if trimmed.is_empty() {
547 String::from("file:///")
548 } else {
549 format!("file:///{trimmed}")
550 }
551}
552
553#[derive(Debug, Clone, PartialEq, Eq)]
554pub struct AliasRecord {
555 pub app_info: [u8; 4],
556 pub version: u16,
557 pub volume: VolumeInfo,
558 pub target: TargetInfo,
559 pub extra: Vec<AliasExtra>,
560}
561
562#[derive(Debug, Clone, PartialEq, Eq)]
563pub struct VolumeInfo {
564 pub name: String,
565 pub creation_date: MacTimestamp,
566 pub fs_type: [u8; 4],
567 pub disk_type: u16,
568 pub attribute_flags: u32,
569 pub fs_id: [u8; 2],
570 pub appleshare_info: Option<AppleShareInfo>,
571 pub driver_name: Option<Vec<u8>>,
572 pub posix_path: Option<String>,
573 pub disk_image_alias: Option<Box<AliasRecord>>,
574 pub dialup_info: Option<Vec<u8>>,
575 pub network_mount_info: Option<Vec<u8>>,
576}
577
578#[derive(Debug, Clone, PartialEq, Eq)]
579pub struct AppleShareInfo {
580 pub zone: Option<Vec<u8>>,
581 pub server: Option<Vec<u8>>,
582 pub user: Option<Vec<u8>>,
583}
584
585#[derive(Debug, Clone, PartialEq, Eq)]
586pub struct TargetInfo {
587 pub kind: u16,
588 pub filename: Option<String>,
589 pub folder_cnid: u32,
590 pub cnid: u32,
591 pub creation_date: MacTimestamp,
592 pub creator_code: [u8; 4],
593 pub type_code: [u8; 4],
594 pub levels_from: i16,
595 pub levels_to: i16,
596 pub folder_name: Option<String>,
597 pub cnid_path: Option<Vec<u32>>,
598 pub carbon_path: Option<Vec<u8>>,
599 pub posix_path: Option<String>,
600 pub user_home_prefix_len: Option<i16>,
601}
602
603#[derive(Debug, Clone, PartialEq, Eq)]
604pub struct AliasExtra {
605 pub tag: i16,
606 pub value: Vec<u8>,
607}
608
609#[derive(Debug, Clone, Copy, PartialEq, Eq)]
610pub struct MacTimestamp {
611 pub seconds: u64,
612 pub fraction: u16,
613}
614
615impl MacTimestamp {
616 fn from_seconds(seconds: u64) -> Self {
617 Self {
618 seconds,
619 fraction: 0,
620 }
621 }
622
623 fn from_fixed_point(value: u64) -> Result<Self> {
624 let seconds = value / 65536;
625 let fraction = u16::try_from(value % 65536)
626 .context("Fixed-point timestamp overflow")?;
627 Ok(Self { seconds, fraction })
628 }
629
630 fn to_fixed_point(self) -> u64 {
631 (self.seconds.saturating_mul(65536))
632 .saturating_add(u64::from(self.fraction))
633 }
634}
635
636impl AliasRecord {
637 pub fn new_simple(target_path: &str, name: Option<&str>) -> Result<Self> {
638 let filename = name.map(ToString::to_string).or_else(|| {
639 Path::new(target_path)
640 .file_name()
641 .map(|value| value.to_string_lossy().to_string())
642 });
643 let folder_name = Path::new(target_path)
644 .parent()
645 .and_then(|parent| parent.file_name())
646 .map(|value| value.to_string_lossy().to_string());
647 let kind = if Path::new(target_path).extension().is_none() {
648 ALIAS_KIND_FOLDER
649 } else {
650 ALIAS_KIND_FILE
651 };
652
653 Ok(Self {
654 app_info: [0, 0, 0, 0],
655 version: ALIAS_VERSION_2,
656 volume: VolumeInfo {
657 name: String::from("/"),
658 creation_date: MacTimestamp::from_seconds(0),
659 fs_type: [b'H', b'+', 0, 0],
660 disk_type: ALIAS_FIXED_DISK,
661 attribute_flags: 0,
662 fs_id: [0, 0],
663 appleshare_info: None,
664 driver_name: None,
665 posix_path: Some(String::from("/")),
666 disk_image_alias: None,
667 dialup_info: None,
668 network_mount_info: None,
669 },
670 target: TargetInfo {
671 kind,
672 filename,
673 folder_cnid: 0,
674 cnid: 0,
675 creation_date: MacTimestamp::from_seconds(0),
676 creator_code: [0, 0, 0, 0],
677 type_code: [0, 0, 0, 0],
678 levels_from: -1,
679 levels_to: -1,
680 folder_name,
681 cnid_path: None,
682 carbon_path: None,
683 posix_path: Some(target_path.to_string()),
684 user_home_prefix_len: None,
685 },
686 extra: Vec::new(),
687 })
688 }
689
690 #[allow(
691 clippy::too_many_lines,
692 reason = "from_bytes is a complex parsing routine for Mac OS alias records"
693 )]
694 pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
695 if bytes.len() < 8 {
696 bail!("Alias record too short");
697 }
698
699 let app_info: [u8; 4] = bytes
700 .get(0..4)
701 .context("Alias record too short for app info")?
702 .try_into()
703 .context("Invalid app info size")?;
704 let record_size = read_u16_be(bytes, 4)?;
705 let version = read_u16_be(bytes, 6)?;
706 if record_size < 150 {
707 bail!("Alias record size too small");
708 }
709 let record_size_usize = usize::from(record_size);
710 if bytes.len() < record_size_usize {
711 bail!("Alias record truncated");
712 }
713 if version != ALIAS_VERSION_2 && version != ALIAS_VERSION_3 {
714 bail!("Unsupported alias record version");
715 }
716
717 let mut offset = 8usize;
718 let (volume, target) = if version == ALIAS_VERSION_2 {
719 let kind = read_u16_be(bytes, offset)?;
720 offset = offset.checked_add(2).context("Alias header overflow")?;
721 let volname = read_pascal_string(bytes, offset, 28)?;
722 offset = offset.checked_add(28).context("Alias header overflow")?;
723 let volume_date = read_u32_be(bytes, offset)?;
724 offset = offset.checked_add(4).context("Alias header overflow")?;
725 let fs_type = read_fixed_bytes(bytes, offset, 2)?;
726 offset = offset.checked_add(2).context("Alias header overflow")?;
727 let disk_type = read_u16_be(bytes, offset)?;
728 offset = offset.checked_add(2).context("Alias header overflow")?;
729 let folder_cnid = read_u32_be(bytes, offset)?;
730 offset = offset.checked_add(4).context("Alias header overflow")?;
731 let filename = read_pascal_string(bytes, offset, 64)?;
732 offset = offset.checked_add(64).context("Alias header overflow")?;
733 let cnid = read_u32_be(bytes, offset)?;
734 offset = offset.checked_add(4).context("Alias header overflow")?;
735 let creation_date = read_u32_be(bytes, offset)?;
736 offset = offset.checked_add(4).context("Alias header overflow")?;
737 let creator_code = read_fixed_bytes(bytes, offset, 4)?;
738 offset = offset.checked_add(4).context("Alias header overflow")?;
739 let type_code = read_fixed_bytes(bytes, offset, 4)?;
740 offset = offset.checked_add(4).context("Alias header overflow")?;
741 let levels_from = read_i16_be(bytes, offset)?;
742 offset = offset.checked_add(2).context("Alias header overflow")?;
743 let levels_to = read_i16_be(bytes, offset)?;
744 offset = offset.checked_add(2).context("Alias header overflow")?;
745 let attribute_flags = read_u32_be(bytes, offset)?;
746 offset = offset.checked_add(4).context("Alias header overflow")?;
747 let fs_id = read_fixed_bytes(bytes, offset, 2)?;
748 offset = offset.checked_add(2).context("Alias header overflow")?;
749 offset = offset.checked_add(10).context("Alias header overflow")?;
750
751 let &[fst0, fst1] = fs_type.as_slice() else {
752 bail!("invalid fs_type size");
753 };
754 let &[fid0, fid1] = fs_id.as_slice() else {
755 bail!("invalid fs_id size");
756 };
757 let &[cc0, cc1, cc2, cc3] = creator_code.as_slice() else {
758 bail!("invalid creator_code size");
759 };
760 let &[tc0, tc1, tc2, tc3] = type_code.as_slice() else {
761 bail!("invalid type_code size");
762 };
763
764 (
765 VolumeInfo {
766 name: volname,
767 creation_date: MacTimestamp::from_seconds(u64::from(
768 volume_date,
769 )),
770 fs_type: [fst0, fst1, 0, 0],
771 disk_type,
772 attribute_flags,
773 fs_id: [fid0, fid1],
774 appleshare_info: None,
775 driver_name: None,
776 posix_path: None,
777 disk_image_alias: None,
778 dialup_info: None,
779 network_mount_info: None,
780 },
781 TargetInfo {
782 kind,
783 filename: Some(filename),
784 folder_cnid,
785 cnid,
786 creation_date: MacTimestamp::from_seconds(u64::from(
787 creation_date,
788 )),
789 creator_code: [cc0, cc1, cc2, cc3],
790 type_code: [tc0, tc1, tc2, tc3],
791 levels_from,
792 levels_to,
793 folder_name: None,
794 cnid_path: None,
795 carbon_path: None,
796 posix_path: None,
797 user_home_prefix_len: None,
798 },
799 )
800 } else {
801 let kind = read_u16_be(bytes, offset)?;
802 offset = offset.checked_add(2).context("Alias header overflow")?;
803 let volume_date = read_u64_be(bytes, offset)?;
804 offset = offset.checked_add(8).context("Alias header overflow")?;
805 let fs_type = read_fixed_bytes(bytes, offset, 4)?;
806 offset = offset.checked_add(4).context("Alias header overflow")?;
807 let disk_type = read_u16_be(bytes, offset)?;
808 offset = offset.checked_add(2).context("Alias header overflow")?;
809 let folder_cnid = read_u32_be(bytes, offset)?;
810 offset = offset.checked_add(4).context("Alias header overflow")?;
811 let cnid = read_u32_be(bytes, offset)?;
812 offset = offset.checked_add(4).context("Alias header overflow")?;
813 let creation_date = read_u64_be(bytes, offset)?;
814 offset = offset.checked_add(8).context("Alias header overflow")?;
815 let attribute_flags = read_u32_be(bytes, offset)?;
816 offset = offset.checked_add(4).context("Alias header overflow")?;
817 offset = offset.checked_add(14).context("Alias header overflow")?;
818
819 let &[fst0, fst1, fst2, fst3] = fs_type.as_slice() else {
820 bail!("invalid fs_type size");
821 };
822
823 (
824 VolumeInfo {
825 name: String::new(),
826 creation_date: MacTimestamp::from_fixed_point(volume_date)?,
827 fs_type: [fst0, fst1, fst2, fst3],
828 disk_type,
829 attribute_flags,
830 fs_id: [0, 0],
831 appleshare_info: None,
832 driver_name: None,
833 posix_path: None,
834 disk_image_alias: None,
835 dialup_info: None,
836 network_mount_info: None,
837 },
838 TargetInfo {
839 kind,
840 filename: None,
841 folder_cnid,
842 cnid,
843 creation_date: MacTimestamp::from_fixed_point(
844 creation_date,
845 )?,
846 creator_code: [0, 0, 0, 0],
847 type_code: [0, 0, 0, 0],
848 levels_from: -1,
849 levels_to: -1,
850 folder_name: None,
851 cnid_path: None,
852 carbon_path: None,
853 posix_path: None,
854 user_home_prefix_len: None,
855 },
856 )
857 };
858
859 let mut record = Self {
860 app_info,
861 version,
862 volume,
863 target,
864 extra: Vec::new(),
865 };
866
867 while offset.saturating_add(4) <= record_size_usize {
868 let tag = read_i16_be(bytes, offset)?;
869 offset = offset.checked_add(2).context("Alias tag overflow")?;
870 if tag == ALIAS_TAG_END {
871 break;
872 }
873 let length = read_u16_be(bytes, offset)?;
874 offset = offset.checked_add(2).context("Alias tag overflow")?;
875 let length_usize = usize::from(length);
876 let data_end = offset
877 .checked_add(length_usize)
878 .context("Alias tag overflow")?;
879 if data_end > record_size_usize {
880 bail!("Alias tag exceeded record size");
881 }
882 let value = bytes
883 .get(offset..data_end)
884 .context("Alias tag out of bounds")?
885 .to_vec();
886 offset = data_end;
887 if length % 2 != 0 {
888 offset = offset
889 .checked_add(1)
890 .context("Alias tag padding overflow")?;
891 }
892
893 match tag {
894 ALIAS_TAG_CARBON_FOLDER_NAME => {
895 record.target.folder_name =
896 Some(String::from_utf8_lossy(&value).to_string());
897 }
898 ALIAS_TAG_CNID_PATH => {
899 let mut cnids = Vec::new();
900 let mut value_offset = 0usize;
901 while value_offset < value.len() {
902 let end = value_offset
903 .checked_add(4)
904 .context("Alias CNID path overflow")?;
905 let slice = value
906 .get(value_offset..end)
907 .context("Alias CNID path out of bounds")?;
908 let arr: [u8; 4] = slice
909 .try_into()
910 .context("Alias CNID path chunk invalid size")?;
911 let cnid = u32::from_be_bytes(arr);
912 cnids.push(cnid);
913 value_offset = end;
914 }
915 record.target.cnid_path = Some(cnids);
916 }
917 ALIAS_TAG_CARBON_PATH => {
918 record.target.carbon_path = Some(value);
919 }
920 ALIAS_TAG_APPLESHARE_ZONE => {
921 let appleshare = record
922 .volume
923 .appleshare_info
924 .get_or_insert(AppleShareInfo {
925 zone: None,
926 server: None,
927 user: None,
928 });
929 appleshare.zone = Some(value);
930 }
931 ALIAS_TAG_APPLESHARE_SERVER => {
932 let appleshare = record
933 .volume
934 .appleshare_info
935 .get_or_insert(AppleShareInfo {
936 zone: None,
937 server: None,
938 user: None,
939 });
940 appleshare.server = Some(value);
941 }
942 ALIAS_TAG_APPLESHARE_USERNAME => {
943 let appleshare = record
944 .volume
945 .appleshare_info
946 .get_or_insert(AppleShareInfo {
947 zone: None,
948 server: None,
949 user: None,
950 });
951 appleshare.user = Some(value);
952 }
953 ALIAS_TAG_DRIVER_NAME => {
954 record.volume.driver_name = Some(value);
955 }
956 ALIAS_TAG_NETWORK_MOUNT_INFO => {
957 record.volume.network_mount_info = Some(value);
958 }
959 ALIAS_TAG_DIALUP_INFO => {
960 record.volume.dialup_info = Some(value);
961 }
962 ALIAS_TAG_UNICODE_FILENAME => {
963 record.target.filename = Some(decode_utf16_be(&value)?);
964 }
965 ALIAS_TAG_UNICODE_VOLUME_NAME => {
966 record.volume.name = decode_utf16_be(&value)?;
967 }
968 ALIAS_TAG_HIGH_RES_VOLUME_DATE => {
969 if let Ok(arr) = value.as_slice().try_into() {
970 let value = u64::from_be_bytes(arr);
971 record.volume.creation_date =
972 MacTimestamp::from_fixed_point(value)?;
973 }
974 }
975 ALIAS_TAG_HIGH_RES_CREATION_DATE => {
976 if let Ok(arr) = value.as_slice().try_into() {
977 let value = u64::from_be_bytes(arr);
978 record.target.creation_date =
979 MacTimestamp::from_fixed_point(value)?;
980 }
981 }
982 ALIAS_TAG_POSIX_PATH => {
983 record.target.posix_path =
984 Some(String::from_utf8_lossy(&value).to_string());
985 }
986 ALIAS_TAG_POSIX_PATH_TO_MOUNTPOINT => {
987 record.volume.posix_path =
988 Some(String::from_utf8_lossy(&value).to_string());
989 }
990 ALIAS_TAG_RECURSIVE_ALIAS_DISK_IMAGE => {
991 record.volume.disk_image_alias =
992 Some(Box::new(AliasRecord::from_bytes(&value)?));
993 }
994 ALIAS_TAG_USER_HOME_PREFIX_LEN => {
995 if let Some(slice_prefix) = value.get(0..2) {
996 if let Ok(arr) = slice_prefix.try_into() {
997 let length = i16::from_be_bytes(arr);
998 record.target.user_home_prefix_len = Some(length);
999 }
1000 }
1001 }
1002 _ => record.extra.push(AliasExtra { tag, value }),
1003 }
1004 }
1005
1006 Ok(record)
1007 }
1008
1009 #[allow(
1010 clippy::too_many_lines,
1011 reason = "to_bytes is a complex serialization routine for Mac OS alias records"
1012 )]
1013 pub fn to_bytes(&self) -> Result<Vec<u8>> {
1014 let mut bytes = Vec::new();
1015 bytes.extend_from_slice(&self.app_info);
1016 bytes.extend_from_slice(&0u16.to_be_bytes());
1017 bytes.extend_from_slice(&self.version.to_be_bytes());
1018
1019 if self.version == ALIAS_VERSION_2 {
1020 let volume_name = self.volume.name.replace(':', "/");
1021 let filename = self
1023 .target
1024 .filename
1025 .clone()
1026 .unwrap_or_default()
1027 .replace(':', "/");
1028 bytes.extend_from_slice(&self.target.kind.to_be_bytes());
1029 write_pascal_string(&mut bytes, &volume_name, 28)?;
1030 bytes.extend_from_slice(
1031 &u32::try_from(self.volume.creation_date.seconds)?
1032 .to_be_bytes(),
1033 );
1034 bytes.extend_from_slice(&self.volume.fs_type[0..2]);
1035 bytes.extend_from_slice(&self.volume.disk_type.to_be_bytes());
1036 bytes.extend_from_slice(&self.target.folder_cnid.to_be_bytes());
1037 write_pascal_string(&mut bytes, &filename, 64)?;
1038 bytes.extend_from_slice(&self.target.cnid.to_be_bytes());
1039 bytes.extend_from_slice(
1040 &u32::try_from(self.target.creation_date.seconds)?
1041 .to_be_bytes(),
1042 );
1043 bytes.extend_from_slice(&self.target.creator_code);
1044 bytes.extend_from_slice(&self.target.type_code);
1045 bytes.extend_from_slice(&self.target.levels_from.to_be_bytes());
1046 bytes.extend_from_slice(&self.target.levels_to.to_be_bytes());
1047 bytes.extend_from_slice(&self.volume.attribute_flags.to_be_bytes());
1048 bytes.extend_from_slice(&self.volume.fs_id);
1049 bytes.extend_from_slice(&[0u8; 10]);
1050 } else {
1051 bytes.extend_from_slice(&self.target.kind.to_be_bytes());
1052 bytes.extend_from_slice(
1053 &self.volume.creation_date.to_fixed_point().to_be_bytes(),
1054 );
1055 bytes.extend_from_slice(&self.volume.fs_type);
1056 bytes.extend_from_slice(&self.volume.disk_type.to_be_bytes());
1057 bytes.extend_from_slice(&self.target.folder_cnid.to_be_bytes());
1058 bytes.extend_from_slice(&self.target.cnid.to_be_bytes());
1059 bytes.extend_from_slice(
1060 &self.target.creation_date.to_fixed_point().to_be_bytes(),
1061 );
1062 bytes.extend_from_slice(&self.volume.attribute_flags.to_be_bytes());
1063 bytes.extend_from_slice(&[0u8; 14]);
1064 }
1065
1066 if let Some(folder_name) = &self.target.folder_name {
1067 let name = folder_name.replace(':', "/");
1068 write_tag_bytes(
1069 &mut bytes,
1070 ALIAS_TAG_CARBON_FOLDER_NAME,
1071 name.as_bytes(),
1072 )?;
1073 }
1074
1075 write_tag_u64(
1076 &mut bytes,
1077 ALIAS_TAG_HIGH_RES_VOLUME_DATE,
1078 self.volume.creation_date.to_fixed_point(),
1079 )?;
1080 write_tag_u64(
1081 &mut bytes,
1082 ALIAS_TAG_HIGH_RES_CREATION_DATE,
1083 self.target.creation_date.to_fixed_point(),
1084 )?;
1085
1086 if let Some(cnid_path) = &self.target.cnid_path {
1087 let mut data = Vec::new();
1088 for cnid in cnid_path {
1089 data.extend_from_slice(&cnid.to_be_bytes());
1090 }
1091 write_tag_bytes(&mut bytes, ALIAS_TAG_CNID_PATH, &data)?;
1092 }
1093
1094 if let Some(carbon_path) = &self.target.carbon_path {
1095 write_tag_bytes(&mut bytes, ALIAS_TAG_CARBON_PATH, carbon_path)?;
1096 }
1097
1098 if let Some(appleshare) = &self.volume.appleshare_info {
1099 if let Some(zone) = appleshare.zone.as_ref() {
1100 write_tag_bytes(&mut bytes, ALIAS_TAG_APPLESHARE_ZONE, zone)?;
1101 }
1102 if let Some(server) = appleshare.server.as_ref() {
1103 write_tag_bytes(
1104 &mut bytes,
1105 ALIAS_TAG_APPLESHARE_SERVER,
1106 server,
1107 )?;
1108 }
1109 if let Some(user) = appleshare.user.as_ref() {
1110 write_tag_bytes(
1111 &mut bytes,
1112 ALIAS_TAG_APPLESHARE_USERNAME,
1113 user,
1114 )?;
1115 }
1116 }
1117
1118 if let Some(driver_name) = &self.volume.driver_name {
1119 write_tag_bytes(&mut bytes, ALIAS_TAG_DRIVER_NAME, driver_name)?;
1120 }
1121
1122 if let Some(network_mount) = &self.volume.network_mount_info {
1123 write_tag_bytes(
1124 &mut bytes,
1125 ALIAS_TAG_NETWORK_MOUNT_INFO,
1126 network_mount,
1127 )?;
1128 }
1129
1130 if let Some(dialup_info) = &self.volume.dialup_info {
1131 write_tag_bytes(&mut bytes, ALIAS_TAG_DIALUP_INFO, dialup_info)?;
1132 }
1133
1134 if let Some(filename) = &self.target.filename {
1135 write_tag_utf16(&mut bytes, ALIAS_TAG_UNICODE_FILENAME, filename)?;
1136 }
1137
1138 write_tag_utf16(
1139 &mut bytes,
1140 ALIAS_TAG_UNICODE_VOLUME_NAME,
1141 &self.volume.name,
1142 )?;
1143
1144 if let Some(posix_path) = &self.target.posix_path {
1145 write_tag_bytes(
1146 &mut bytes,
1147 ALIAS_TAG_POSIX_PATH,
1148 posix_path.as_bytes(),
1149 )?;
1150 }
1151
1152 if let Some(posix_path) = &self.volume.posix_path {
1153 write_tag_bytes(
1154 &mut bytes,
1155 ALIAS_TAG_POSIX_PATH_TO_MOUNTPOINT,
1156 posix_path.as_bytes(),
1157 )?;
1158 }
1159
1160 if let Some(disk_alias) = &self.volume.disk_image_alias {
1161 let alias_bytes = disk_alias.to_bytes()?;
1162 write_tag_bytes(
1163 &mut bytes,
1164 ALIAS_TAG_RECURSIVE_ALIAS_DISK_IMAGE,
1165 &alias_bytes,
1166 )?;
1167 }
1168
1169 if let Some(prefix_len) = self.target.user_home_prefix_len {
1170 let mut data = Vec::new();
1171 data.extend_from_slice(&prefix_len.to_be_bytes());
1172 write_tag_bytes(&mut bytes, ALIAS_TAG_USER_HOME_PREFIX_LEN, &data)?;
1173 }
1174
1175 for extra in &self.extra {
1176 write_tag_bytes(&mut bytes, extra.tag, &extra.value)?;
1177 }
1178
1179 bytes.extend_from_slice(&ALIAS_TAG_END.to_be_bytes());
1180 bytes.extend_from_slice(&0u16.to_be_bytes());
1181
1182 let record_size =
1183 u16::try_from(bytes.len()).context("Alias record too large")?;
1184 bytes
1185 .get_mut(4..6)
1186 .context("invalid alias header size")?
1187 .copy_from_slice(&record_size.to_be_bytes());
1188 Ok(bytes)
1189 }
1190}
1191
1192fn decode_utf16_be(bytes: &[u8]) -> Result<String> {
1193 if bytes.len() < 2 {
1194 return Ok(String::new());
1195 }
1196 let mut data = Vec::new();
1197 let mut offset = 2usize;
1198 while offset.saturating_add(1) < bytes.len() {
1199 let end = offset.checked_add(2).context("UTF-16 data overflow")?;
1200 let slice = bytes.get(offset..end).context("UTF-16 out of bounds")?;
1201 let arr: [u8; 2] =
1202 slice.try_into().context("UTF-16 invalid chunk size")?;
1203 let value = u16::from_be_bytes(arr);
1204 data.push(value);
1205 offset = end;
1206 }
1207 String::from_utf16(&data).context("UTF-16 string decode failed")
1208}
1209
1210fn write_tag_bytes(buffer: &mut Vec<u8>, tag: i16, value: &[u8]) -> Result<()> {
1211 buffer.extend_from_slice(&tag.to_be_bytes());
1212 let length = u16::try_from(value.len()).context("Alias tag too large")?;
1213 buffer.extend_from_slice(&length.to_be_bytes());
1214 buffer.extend_from_slice(value);
1215 if length % 2 != 0 {
1216 buffer.push(0);
1217 }
1218 Ok(())
1219}
1220
1221fn write_tag_u64(buffer: &mut Vec<u8>, tag: i16, value: u64) -> Result<()> {
1222 write_tag_bytes(buffer, tag, &value.to_be_bytes())
1223}
1224
1225fn write_tag_utf16(buffer: &mut Vec<u8>, tag: i16, value: &str) -> Result<()> {
1226 let mut data = Vec::new();
1227 let utf16 = value.encode_utf16().collect::<Vec<_>>();
1228 let len = u16::try_from(utf16.len()).context("UTF-16 string too large")?;
1229 data.extend_from_slice(&len.to_be_bytes());
1230 for value in utf16 {
1231 data.extend_from_slice(&value.to_be_bytes());
1232 }
1233 write_tag_bytes(buffer, tag, &data)
1234}
1235
1236fn write_pascal_string(
1237 buffer: &mut Vec<u8>,
1238 value: &str,
1239 size: usize,
1240) -> Result<()> {
1241 let bytes = value.as_bytes();
1242 let max_len = size
1243 .checked_sub(1)
1244 .context("Pascal string size too small")?;
1245 if bytes.len() > max_len {
1246 bail!("Pascal string too long");
1247 }
1248 let length = u8::try_from(bytes.len()).context("Pascal string too long")?;
1249 buffer.push(length);
1250 buffer.extend_from_slice(bytes);
1251 let pad_len = max_len
1252 .checked_sub(bytes.len())
1253 .context("Pascal string padding overflow")?;
1254 let new_len = buffer
1255 .len()
1256 .checked_add(pad_len)
1257 .context("Pascal string padding overflow")?;
1258 buffer.resize(new_len, 0);
1259 Ok(())
1260}
1261
1262#[allow(
1263 clippy::range_plus_one,
1264 reason = "Pascal string length calculations naturally fit range_plus_one"
1265)]
1266fn read_pascal_string(
1267 bytes: &[u8],
1268 offset: usize,
1269 size: usize,
1270) -> Result<String> {
1271 let slice = read_fixed_bytes(bytes, offset, size)?;
1272 if slice.is_empty() {
1273 return Ok(String::new());
1274 }
1275 let len = usize::from(*slice.get(0).context("Pascal string empty")?);
1276 if len > slice.len().saturating_sub(1) {
1277 bail!("Pascal string length invalid");
1278 }
1279 let value = slice
1280 .get(1..1_usize.saturating_add(len))
1281 .context("Pascal string out of bounds")?;
1282 Ok(String::from_utf8_lossy(value).to_string())
1283}
1284
1285fn read_u16_be(bytes: &[u8], offset: usize) -> Result<u16> {
1286 let slice = read_fixed_bytes(bytes, offset, 2)?;
1287 let arr: [u8; 2] = slice
1288 .try_into()
1289 .map_err(|_| anyhow!("invalid u16 slice size"))?;
1290 Ok(u16::from_be_bytes(arr))
1291}
1292
1293fn read_i16_be(bytes: &[u8], offset: usize) -> Result<i16> {
1294 let slice = read_fixed_bytes(bytes, offset, 2)?;
1295 let arr: [u8; 2] = slice
1296 .try_into()
1297 .map_err(|_| anyhow!("invalid i16 slice size"))?;
1298 Ok(i16::from_be_bytes(arr))
1299}
1300
1301fn read_u32_be(bytes: &[u8], offset: usize) -> Result<u32> {
1302 let slice = read_fixed_bytes(bytes, offset, 4)?;
1303 let arr: [u8; 4] = slice
1304 .try_into()
1305 .map_err(|_| anyhow!("invalid u32 slice size"))?;
1306 Ok(u32::from_be_bytes(arr))
1307}
1308
1309fn read_u64_be(bytes: &[u8], offset: usize) -> Result<u64> {
1310 let slice = read_fixed_bytes(bytes, offset, 8)?;
1311 let arr: [u8; 8] = slice
1312 .try_into()
1313 .map_err(|_| anyhow!("invalid u64 slice size"))?;
1314 Ok(u64::from_be_bytes(arr))
1315}
1316
1317#[cfg(test)]
1318#[allow(
1319 clippy::panic,
1320 clippy::expect_used,
1321 clippy::unwrap_used,
1322 clippy::unwrap_in_result,
1323 clippy::panic_in_result_fn,
1324 clippy::indexing_slicing,
1325 clippy::arithmetic_side_effects,
1326 reason = "Standard repository test boilerplate"
1327)]
1328mod tests {
1329 use std::fs;
1330 use std::path::PathBuf;
1331
1332 use tempfile::TempDir;
1333
1334 use super::*;
1335
1336 #[crate::ctb_test]
1337 fn test_create_alias_round_trip() {
1338 let dir = TempDir::new().unwrap();
1339 let alias_bytes = create_simple_alias(
1340 "/tmp/ctb/alias-target.txt",
1341 Some("alias-target"),
1342 )
1343 .unwrap();
1344 let path = dir.path().join("alias");
1345 fs::write(&path, alias_bytes).unwrap();
1346 let target = read_path_from_alias(&path).unwrap();
1347 assert_eq!(target, PathBuf::from("/tmp/ctb/alias-target.txt"));
1348 }
1349
1350 #[crate::ctb_test]
1351 fn test_read_reference_alias_files() {
1352 let dir = TempDir::new().unwrap();
1353 let fixtures = [
1354 (
1355 get_alias_data("fixtures/folder.alias")
1356 .expect("Missing folder.alias fixture"),
1357 PathBuf::from("/System/Library/Perl"),
1358 ),
1359 (
1360 get_alias_data("fixtures/removable.alias")
1361 .expect("Missing removable.alias fixture"),
1362 PathBuf::from("/Volumes/SANDISK/untitled"),
1363 ),
1364 (
1365 get_alias_data("fixtures/root.alias")
1366 .expect("Missing root.alias fixture"),
1367 PathBuf::from("/"),
1368 ),
1369 ];
1370
1371 for (index, (bytes, expected)) in fixtures.iter().enumerate() {
1372 let path = dir.path().join(format!("fixture-{index}.alias"));
1373 fs::write(&path, bytes).unwrap();
1374 let target = read_path_from_alias(&path).unwrap();
1375 assert_eq!(target, *expected);
1376 }
1377 }
1378
1379 #[crate::ctb_test]
1380 fn test_alias_record_round_trip() {
1381 let record =
1382 AliasRecord::new_simple("/tmp/alias-record.txt", Some("alias.txt"))
1383 .unwrap();
1384 let bytes = record.to_bytes().unwrap();
1385 let parsed = AliasRecord::from_bytes(&bytes).unwrap();
1386 assert_eq!(
1387 parsed.target.posix_path,
1388 Some("/tmp/alias-record.txt".to_string())
1389 );
1390 assert_eq!(parsed.target.filename, Some("alias.txt".to_string()));
1391 }
1392}
1393
1394