Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

diskImage.ts

697 lines25.9 KB

1import type { ArchiveEntry } from "./binaryPreviewProtocol";
2import { isPreviewError, PreviewError } from "./previewFailure";
3​
4/**
5 * Lists an Apple disk image (UDIF .dmg) holding an HFS+ volume by reading only the trailer, the
6 * block map and the volume's catalog. DMGs run to gigabytes, so nothing reads the whole file.
7 */
8​
9export interface ByteSource {
10 readonly size: number;
11 read(offset: number, length: number): Promise<Uint8Array<ArrayBuffer>>;
13​
14const SECTOR = 512;
15/** Compressed bytes one preview may download; a listing needs the catalog, not the payload. */
16const DISK_IMAGE_MAX_FETCH_BYTES = 128 * 1024 * 1024;
17const MAX_CHUNK_BYTES = 64 * 1024 * 1024;
18const MAX_CATALOG_BYTES = 128 * 1024 * 1024;
19const MAX_PLIST_BYTES = 16 * 1024 * 1024;
20const MAX_REQUEST_BYTES = 16 * 1024 * 1024;
21const CACHE_BYTES = 96 * 1024 * 1024;
22const MAX_OVERFLOW_EXTENTS = 100_000;
23const MAX_PATH_LENGTH = 4096;
24const DISK_IMAGE_MAX_ENTRIES = 100_000;
25​
26const damaged = () => new PreviewError({ code: "disk-image-damaged" });
27​
28/** Reads a response body, cancelling it once it passes `limit` bytes. */
29async function readBody(response: Response, limit: number, tooLarge: () => PreviewError) {
30 const reader = response.body?.getReader();
31 if (!reader) throw new PreviewError({ code: "file-unavailable" });
32 const chunks: Uint8Array<ArrayBuffer>[] = [];
33 let size = 0;
34 try {
35 while (true) {
36 const { value, done } = await reader.read();
37 if (done) break;
38 size += value.length;
39 if (size > limit) throw tooLarge();
40 chunks.push(value);
41 }
42 } finally {
43 await reader.cancel().catch(() => undefined);
44 }
45 return new Uint8Array(await new Blob(chunks).arrayBuffer());
47​
48/** Reads ranges over HTTP. A server that ignores Range gets one bounded full download instead. */
49export async function httpByteSource(
50 src: string,
51 fullDownloadLimit: number,
52 signal?: AbortSignal,
53): Promise<ByteSource> {
54 let fetched = 0;
55 const get = async (range: string) => {
56 const response = await fetch(src, {
57 headers: { Range: range },
58 cache: "no-store",
59 signal: signal ?? null,
60 });
61 if (!response.ok) throw new PreviewError({ code: "file-load-failed" });
62 return response;
63 };
64 const probe = await get("bytes=-512");
65 if (probe.status === 206) {
66 const size = Number(probe.headers.get("content-range")?.split("/")[1]);
67 if (!Number.isSafeInteger(size) || size < SECTOR) throw damaged();
68 const tail = await readBody(probe, SECTOR, damaged);
69 return {
70 size,
71 async read(offset, length) {
72 if (offset < 0 || length < 0 || offset + length > size) throw damaged();
73 if (length === 0) return new Uint8Array(0);
74 if (offset === size - tail.length && length <= tail.length) return tail.slice(0, length);
75 fetched += length;
76 if (fetched > DISK_IMAGE_MAX_FETCH_BYTES)
77 throw new PreviewError({ code: "disk-image-too-large" });
78 const response = await get(`bytes=${offset}-${offset + length - 1}`);
79 const failed = () => new PreviewError({ code: "file-load-failed" });
80 if (response.status !== 206) {
81 await response.body?.cancel();
82 throw failed();
83 }
84 const bytes = await readBody(response, length, failed);
85 if (bytes.length !== length) throw failed();
86 return bytes;
87 },
88 };
89 }
90 // Blob URLs and servers without ranges answer 200 with the whole body.
91 if (Number(probe.headers.get("content-length")) > fullDownloadLimit) {
92 await probe.body?.cancel();
93 throw new PreviewError({ code: "file-too-large" });
94 }
95 return bytesSource(
96 await readBody(probe, fullDownloadLimit, () => new PreviewError({ code: "file-too-large" })),
97 );
99​
100export function bytesSource(bytes: Uint8Array<ArrayBuffer>): ByteSource {
101 return {
102 size: bytes.length,
103 read: async (offset, length) => {
104 if (offset < 0 || length < 0 || offset + length > bytes.length) throw damaged();
105 return bytes.slice(offset, offset + length);
106 },
107 };
109​
110const u64 = (view: DataView, at: number) => {
111 const value = view.getBigUint64(at);
112 if (value > BigInt(Number.MAX_SAFE_INTEGER)) throw damaged();
113 return Number(value);
114};
115const viewOf = (bytes: Uint8Array) => new DataView(bytes.buffer, bytes.byteOffset, bytes.length);
116const ascii = (bytes: Uint8Array, at: number, length: number) =>
117 String.fromCharCode(...bytes.subarray(at, at + length));
118​
119// UDIF block chunk types.
120const CHUNK_ZERO = 0x00000000;
121const CHUNK_RAW = 0x00000001;
122const CHUNK_IGNORE = 0x00000002;
123const CHUNK_ADC = 0x80000004;
124const CHUNK_ZLIB = 0x80000005;
125const CHUNK_COMMENT = 0x7ffffffe;
126const CHUNK_END = 0xffffffff;
127​
128interface Chunk {
129 readonly type: number;
130 readonly start: number;
131 readonly length: number;
132 readonly compressedOffset: number;
133 readonly compressedLength: number;
135​
136interface Partition {
137 readonly name: string;
138 readonly chunks: readonly Chunk[];
140​
141/** Apple Data Compression, the LZ77 variant of old UDCO images. */
142function decompressAdc(input: Uint8Array, outputLength: number) {
143 const output = new Uint8Array(outputLength);
144 let read = 0;
145 let written = 0;
146 while (read < input.length && written < outputLength) {
147 const byte = input[read]!;
148 let length: number;
149 let distance: number;
150 if (byte & 0x80) {
151 length = (byte & 0x7f) + 1;
152 if (read + 1 + length > input.length || written + length > outputLength) throw damaged();
153 output.set(input.subarray(read + 1, read + 1 + length), written);
154 read += length + 1;
155 written += length;
156 continue;
157 }
158 if (byte & 0x40) {
159 if (read + 2 >= input.length) throw damaged();
160 length = (byte & 0x3f) + 4;
161 distance = ((input[read + 1]! << 8) | input[read + 2]!) + 1;
162 read += 3;
163 } else {
164 if (read + 1 >= input.length) throw damaged();
165 length = ((byte & 0x3c) >> 2) + 3;
166 distance = (((byte & 0x03) << 8) | input[read + 1]!) + 1;
167 read += 2;
168 }
169 if (distance > written || written + length > outputLength) throw damaged();
170 // Matches may overlap their own output, so copy byte by byte.
171 for (let index = 0; index < length; index++)
172 output[written + index] = output[written - distance + index]!;
173 written += length;
174 }
175 if (written !== outputLength) throw damaged();
176 return output;
178​
179async function inflate(input: Uint8Array<ArrayBuffer>, outputLength: number) {
180 const reader = new ReadableStream<Uint8Array<ArrayBuffer>>({
181 start(controller) {
182 controller.enqueue(input);
183 controller.close();
184 },
185 })
186 .pipeThrough(new DecompressionStream("deflate"))
187 .getReader();
188 const output = new Uint8Array(outputLength);
189 let written = 0;
190 try {
191 while (true) {
192 const { value, done } = await reader.read();
193 if (done) break;
194 if (written + value.length > outputLength) throw damaged();
195 output.set(value, written);
196 written += value.length;
197 }
198 } catch (cause) {
199 throw isPreviewError(cause) ? cause : damaged();
200 } finally {
201 await reader.cancel().catch(() => undefined);
202 }
203 if (written !== outputLength) throw damaged();
204 return output;
206​
207function parseBlockTable(name: string, table: Uint8Array, dataForkOffset: number): Partition {
208 const view = viewOf(table);
209 if (table.length < 204 || ascii(table, 0, 4) !== "mish") throw damaged();
210 const dataOffset = u64(view, 24);
211 const count = view.getUint32(200);
212 if (204 + count * 40 > table.length) throw damaged();
213 const chunks: Chunk[] = [];
214 for (let index = 0; index < count; index++) {
215 const at = 204 + index * 40;
216 const type = view.getUint32(at);
217 if (type === CHUNK_COMMENT) continue;
218 if (type === CHUNK_END) break;
219 const length = u64(view, at + 16) * SECTOR;
220 if (length === 0) continue;
221 // Zero and free runs are never materialized, so only stored chunks need a size bound.
222 if (length > MAX_CHUNK_BYTES && type !== CHUNK_ZERO && type !== CHUNK_IGNORE) throw damaged();
223 chunks.push({
224 type,
225 start: u64(view, at + 8) * SECTOR,
226 length,
227 compressedOffset: dataForkOffset + dataOffset + u64(view, at + 24),
228 compressedLength: u64(view, at + 32),
229 });
230 }
231 chunks.sort((a, b) => a.start - b.start);
232 // Overlapping chunks would let one small read decompress the same range many times over.
233 for (let index = 1; index < chunks.length; index++)
234 if (chunks[index]!.start < chunks[index - 1]!.start + chunks[index - 1]!.length)
235 throw damaged();
236 return { name, chunks };
238​
239const PLIST_ENTITIES: Record<string, string> = {
240 amp: "&",
241 lt: "<",
242 gt: ">",
243 quot: '"',
244 apos: "'",
245};
246const unescapeXml = (text: string) =>
247 text.replace(/&(amp|lt|gt|quot|apos|#\d+|#x[\da-f]+);/gi, (_, entity: string) =>
248 entity[0] === "#"
249 ? String.fromCodePoint(
250 entity[1]?.toLowerCase() === "x"
251 ? Number.parseInt(entity.slice(2), 16)
252 : Number(entity.slice(1)),
253 )
254 : (PLIST_ENTITIES[entity.toLowerCase()] ?? ""),
255 );
256​
257/** Reads the `blkx` partitions from the UDIF property list; workers have no DOMParser. */
258function parsePartitions(plist: string, dataForkOffset: number): Partition[] {
259 const key = plist.indexOf("<key>blkx</key>");
260 if (key < 0) throw damaged();
261 const start = plist.indexOf("<array>", key);
262 const end = plist.indexOf("</array>", start);
263 if (start < 0 || end < 0) throw damaged();
264 const partitions: Partition[] = [];
265 // One forward scan; a regex over unclosed <dict> tags would rescan the rest each time.
266 for (let cursor = plist.indexOf("<dict>", start); cursor >= 0 && cursor < end;) {
267 const close = plist.indexOf("</dict>", cursor);
268 if (close < 0 || close > end) throw damaged();
269 const dict = plist.slice(cursor + 6, close);
270 cursor = plist.indexOf("<dict>", close);
271 const data = /<key>Data<\/key>\s*<data>([^<]*)<\/data>/.exec(dict!)?.[1];
272 if (data === undefined) continue;
273 const name = /<key>(?:CFName|Name)<\/key>\s*<string>([^<]*)<\/string>/.exec(dict!)?.[1] ?? "";
274 let table: Uint8Array;
275 try {
276 table = Uint8Array.from(atob(data.replace(/\s+/g, "")), (char) => char.charCodeAt(0));
277 } catch {
278 throw damaged();
279 }
280 partitions.push(parseBlockTable(unescapeXml(name), table, dataForkOffset));
281 }
282 if (partitions.length === 0) throw damaged();
283 return partitions;
285​
286/** A partition's decompressed bytes, read chunk by chunk with batched range requests. */
287class PartitionReader {
288 private readonly cache = new Map<Chunk, Uint8Array<ArrayBuffer>>();
289 private cached = 0;
290 readonly size: number;
291​
292 constructor(
293 private readonly source: ByteSource,
294 private readonly partition: Partition,
295 ) {
296 const last = partition.chunks.at(-1);
297 this.size = last ? last.start + last.length : 0;
298 }
299​
300 async read(offset: number, length: number): Promise<Uint8Array<ArrayBuffer>> {
301 if (offset < 0 || length < 0 || offset + length > this.size) throw damaged();
302 const output = new Uint8Array(length);
303 const end = offset + length;
304 const chunks = this.partition.chunks.filter(
305 (chunk) => chunk.start < end && chunk.start + chunk.length > offset,
306 );
307 // Hold this read's chunks: loading the rest may evict cached ones before the copy.
308 const held = new Map<Chunk, Uint8Array<ArrayBuffer>>();
309 for (const chunk of chunks) {
310 const bytes = this.cache.get(chunk);
311 if (bytes) held.set(chunk, bytes);
312 }
313 await this.load(
314 chunks.filter((chunk) => !held.has(chunk)),
315 held,
316 );
317 for (const chunk of chunks) {
318 const from = Math.max(offset, chunk.start);
319 const to = Math.min(end, chunk.start + chunk.length);
320 const bytes = held.get(chunk);
321 // Zero and free chunks stay as the zeroed output.
322 if (bytes) output.set(bytes.subarray(from - chunk.start, to - chunk.start), from - offset);
323 }
324 return output;
325 }
326​
327 private async load(chunks: readonly Chunk[], into: Map<Chunk, Uint8Array<ArrayBuffer>>) {
328 const stored = chunks.filter(
329 (chunk) => chunk.type !== CHUNK_ZERO && chunk.type !== CHUNK_IGNORE,
330 );
331 for (const chunk of stored)
332 if (chunk.type !== CHUNK_RAW && chunk.type !== CHUNK_ZLIB && chunk.type !== CHUNK_ADC)
333 throw new PreviewError({ code: "disk-image-compression-unsupported" });
334 // Adjacent compressed chunks share one request.
335 const sorted = stored.toSorted((a, b) => a.compressedOffset - b.compressedOffset);
336 const groups: Chunk[][] = [];
337 for (const chunk of sorted) {
338 const group = groups.at(-1);
339 const last = group?.at(-1);
340 if (
341 group &&
342 last &&
343 last.compressedOffset + last.compressedLength === chunk.compressedOffset &&
344 chunk.compressedOffset + chunk.compressedLength - group[0]!.compressedOffset <=
345 MAX_REQUEST_BYTES
346 )
347 group.push(chunk);
348 else groups.push([chunk]);
349 }
350 for (const group of groups) {
351 const first = group[0]!;
352 const last = group.at(-1)!;
353 const base = first.compressedOffset;
354 const bytes = await this.source.read(
355 base,
356 last.compressedOffset + last.compressedLength - base,
357 );
358 // One chunk at a time, so only one decompressed buffer is allocated at once.
359 for (const chunk of group) {
360 const input = bytes.subarray(
361 chunk.compressedOffset - base,
362 chunk.compressedOffset - base + chunk.compressedLength,
363 );
364 if (chunk.type === CHUNK_RAW && input.length !== chunk.length) throw damaged();
365 const output =
366 chunk.type === CHUNK_RAW
367 ? input.slice()
368 : chunk.type === CHUNK_ADC
369 ? decompressAdc(input, chunk.length)
370 : await inflate(input.slice(), chunk.length);
371 into.set(chunk, output);
372 this.remember(chunk, output);
373 }
374 }
375 }
376​
377 private remember(chunk: Chunk, bytes: Uint8Array<ArrayBuffer>) {
378 this.cache.set(chunk, bytes);
379 this.cached += bytes.length;
380 for (const [key, value] of this.cache) {
381 if (this.cached <= CACHE_BYTES) break;
382 if (key === chunk) continue;
383 this.cache.delete(key);
384 this.cached -= value.length;
385 }
386 }
388​
389interface Extent {
390 readonly start: number;
391 readonly count: number;
393​
394interface Fork {
395 readonly size: number;
396 readonly blocks: number;
397 readonly extents: readonly Extent[];
399​
400function parseFork(view: DataView, at: number): Fork {
401 const extents: Extent[] = [];
402 for (let index = 0; index < 8; index++) {
403 const count = view.getUint32(at + 20 + index * 8);
404 if (count === 0) break;
405 extents.push({ start: view.getUint32(at + 16 + index * 8), count });
406 }
407 return { size: u64(view, at), blocks: view.getUint32(at + 12), extents };
409​
410const HFS_EPOCH_OFFSET = 2_082_844_800;
411const hfsDate = (seconds: number) =>
412 seconds === 0 ? null : new Date((seconds - HFS_EPOCH_OFFSET) * 1000).toISOString();
413​
414const utf16 = (bytes: Uint8Array, at: number, length: number) => {
415 let text = "";
416 const view = viewOf(bytes);
417 for (let index = 0; index < length; index++)
418 text += String.fromCharCode(view.getUint16(at + index * 2));
419 return text;
420};
421​
422const PRIVATE_FILES = "\0\0\0\0HFS+ Private Data";
423const PRIVATE_DIRECTORIES = ".HFS+ Private Directory Data\r";
424const HIDDEN_ROOT_NAMES = new Set([
425 PRIVATE_FILES,
426 PRIVATE_DIRECTORIES,
427 ".journal",
428 ".journal_info_block",
429]);
430const ROOT_FOLDER_ID = 2;
431const UF_COMPRESSED = 0x20;
432​
433interface CatalogFile {
434 readonly parentId: number;
435 readonly name: string;
436 readonly fileId: number;
437 readonly fork: Fork;
438 readonly modified: string | null;
439 readonly type: string;
440 readonly creator: string;
441 readonly linkId: number;
442 readonly compressed: boolean;
444​
445export interface DiskImageListing {
446 readonly volume: string;
447 readonly entries: ArchiveEntry[];
448 /** Reads a listed file's contents. */
449 readonly readFile: (path: string, limit: number) => Promise<Uint8Array<ArrayBuffer>>;
451​
452class HfsVolume {
453 private constructor(
454 private readonly disk: PartitionReader,
455 private readonly blockSize: number,
456 private readonly overflow: Map<string, Extent[]>,
457 ) {}
458​
459 static async open(disk: PartitionReader) {
460 const header = await disk.read(1024, 512);
461 const view = viewOf(header);
462 const signature = ascii(header, 0, 2);
463 if (signature !== "H+" && signature !== "HX") return null;
464 const blockSize = view.getUint32(40);
465 if (blockSize < 512 || blockSize > 1 << 20 || (blockSize & (blockSize - 1)) !== 0)
466 throw damaged();
467 const volume = new HfsVolume(disk, blockSize, new Map());
468 const extentsFork = parseFork(view, 192);
469 let overflowExtents = 0;
470 if (extentsFork.size > 0)
471 await volume.walkLeaves(extentsFork, (node, offset) => {
472 const record = viewOf(node);
473 if (record.getUint16(offset) !== 10) return;
474 const forkType = node[offset + 2]!;
475 const fileId = record.getUint32(offset + 4);
476 const extents = volume.overflow.get(`${fileId}:${forkType}`) ?? [];
477 for (let index = 0; index < 8; index++) {
478 const count = record.getUint32(offset + 12 + index * 8 + 4);
479 if (count === 0) break;
480 if (++overflowExtents > MAX_OVERFLOW_EXTENTS) throw damaged();
481 extents.push({ start: record.getUint32(offset + 12 + index * 8), count });
482 }
483 volume.overflow.set(`${fileId}:${forkType}`, extents);
484 });
485 return { volume, catalog: parseFork(view, 272) };
486 }
487​
488 private extentsOf(fileId: number, fork: Fork) {
489 const extents = [...fork.extents];
490 const listed = extents.reduce((sum, extent) => sum + extent.count, 0);
491 if (listed < fork.blocks) extents.push(...(this.overflow.get(`${fileId}:0`) ?? []));
492 return extents;
493 }
494​
495 async readFork(fileId: number, fork: Fork, length = fork.size) {
496 const output = new Uint8Array(length);
497 let written = 0;
498 for (const extent of this.extentsOf(fileId, fork)) {
499 if (written >= length) break;
500 const take = Math.min(extent.count * this.blockSize, length - written);
501 output.set(await this.disk.read(extent.start * this.blockSize, take), written);
502 written += take;
503 }
504 if (written < length) throw damaged();
505 return output;
506 }
507​
508 /** Visits every record in a B-tree's leaf chain. */
509 async walkLeaves(
510 fork: Fork,
511 visit: (node: Uint8Array<ArrayBuffer>, offset: number) => void,
512 fileId = 3,
513 ) {
514 if (fork.size > MAX_CATALOG_BYTES) throw new PreviewError({ code: "disk-image-too-large" });
515 const tree = await this.readFork(fileId, fork);
516 const view = viewOf(tree);
517 const nodeSize = view.getUint16(32);
518 if (nodeSize < 512 || nodeSize > 32768 || tree.length < nodeSize) throw damaged();
519 const totalNodes = Math.min(view.getUint32(36), Math.floor(tree.length / nodeSize));
520 let next = view.getUint32(24);
521 const visited = new Set<number>();
522 while (next !== 0) {
523 // A leaf chain that loops back would visit its records again.
524 if (visited.has(next) || next >= totalNodes) throw damaged();
525 visited.add(next);
526 const node = tree.subarray(next * nodeSize, (next + 1) * nodeSize);
527 const nodeView = viewOf(node);
528 if (nodeView.getInt8(8) !== -1) throw damaged();
529 const records = nodeView.getUint16(10);
530 for (let index = 0; index < records; index++) {
531 const offset = nodeView.getUint16(nodeSize - 2 * (index + 1));
532 if (offset < 14 || offset >= nodeSize - 2 * records) throw damaged();
533 visit(node, offset);
534 }
535 next = nodeView.getUint32(0);
536 }
537 }
539​
540export async function listDiskImage(source: ByteSource): Promise<DiskImageListing> {
541 const trailer = await source.read(source.size - SECTOR, SECTOR);
542 if (ascii(trailer, 0, 4) !== "koly") {
543 const head = await source.read(0, Math.min(8, source.size));
544 if (["encrcdsa", "cdsaencr"].includes(ascii(head, 0, 8)))
545 throw new PreviewError({ code: "disk-image-encrypted" });
546 throw new PreviewError({ code: "disk-image-unsupported" });
547 }
548 const trailerView = viewOf(trailer);
549 const plistOffset = u64(trailerView, 216);
550 const plistLength = u64(trailerView, 224);
551 if (plistLength === 0) throw new PreviewError({ code: "disk-image-unsupported" });
552 if (plistLength > MAX_PLIST_BYTES) throw new PreviewError({ code: "archive-metadata-too-large" });
553 if (plistOffset + plistLength > source.size) throw damaged();
554 const plist = new TextDecoder().decode(await source.read(plistOffset, plistLength));
555 const partitions = parsePartitions(plist, u64(trailerView, 24));
556 let apfs = false;
557 for (const partition of partitions) {
558 // UDIF names end in "(<type> : <index>)"; inspect the type so volume labels are not skipped.
559 const partitionType = /\(([^():]+):\s*-?\d+\)\s*$/.exec(partition.name)?.[1] ?? partition.name;
560 if (/Apple_APFS/i.test(partitionType)) {
561 apfs = true;
562 continue;
563 }
564 // Partition maps, free space and the GPT copies cannot hold a volume.
565 if (/\b(?:MBR|GPT|DDM)\b|Apple_Free|Apple_partition_map|Driver|Patches/i.test(partitionType))
566 continue;
567 const disk = new PartitionReader(source, partition);
568 if (disk.size < 1536) continue;
569 const opened = await HfsVolume.open(disk);
570 if (!opened) {
571 const superblock = await disk.read(0, 64);
572 if (ascii(superblock, 32, 4) === "NXSB") apfs = true;
573 continue;
574 }
575 return readCatalog(opened.volume, opened.catalog);
576 }
577 throw new PreviewError({ code: apfs ? "disk-image-apfs" : "disk-image-unsupported" });
579​
580async function readCatalog(volume: HfsVolume, catalog: Fork): Promise<DiskImageListing> {
581 const folders = new Map<number, { parentId: number; name: string; modified: string | null }>();
582 const files: CatalogFile[] = [];
583 let volumeName = "";
584 let records = 0;
585 await volume.walkLeaves(
586 catalog,
587 (node, offset) => {
588 if (++records > DISK_IMAGE_MAX_ENTRIES * 2)
589 throw new PreviewError({ code: "disk-image-too-many-entries" });
590 const view = viewOf(node);
591 const keyLength = view.getUint16(offset);
592 const parentId = view.getUint32(offset + 2);
593 const nameLength = view.getUint16(offset + 6);
594 if (keyLength < 6 || 8 + nameLength * 2 > keyLength + 2) throw damaged();
595 const name = utf16(node, offset + 8, nameLength).normalize("NFC");
596 const data = offset + 2 + keyLength;
597 if (data + 2 > node.length) throw damaged();
598 const type = view.getInt16(data);
599 if (type === 1) {
600 if (data + 88 > node.length) throw damaged();
601 const folderId = view.getUint32(data + 8);
602 if (folderId === ROOT_FOLDER_ID) volumeName = name;
603 folders.set(folderId, { parentId, name, modified: hfsDate(view.getUint32(data + 16)) });
604 } else if (type === 2) {
605 if (data + 248 > node.length) throw damaged();
606 files.push({
607 parentId,
608 name,
609 fileId: view.getUint32(data + 8),
610 modified: hfsDate(view.getUint32(data + 16)),
611 compressed: (node[data + 41]! & UF_COMPRESSED) !== 0,
612 linkId: view.getUint32(data + 44),
613 type: ascii(node, data + 48, 4),
614 creator: ascii(node, data + 52, 4),
615 fork: parseFork(view, data + 88),
616 });
617 }
618 },
619 4,
620 );
621​
622 const hiddenFolders = new Set<number>();
623 for (const [id, folder] of folders)
624 if (folder.parentId === ROOT_FOLDER_ID && HIDDEN_ROOT_NAMES.has(folder.name))
625 hiddenFolders.add(id);
626 const paths = new Map<number, string | null>([[ROOT_FOLDER_ID, ""]]);
627 const folderPath = (id: number, depth = 0): string | null => {
628 const known = paths.get(id);
629 if (known !== undefined) return known;
630 const folder = folders.get(id);
631 if (!folder || depth > 512 || hiddenFolders.has(id)) {
632 paths.set(id, null);
633 return null;
634 }
635 const parent = folderPath(folder.parentId, depth + 1);
636 const joined = parent === null ? null : parent ? `${parent}/${folder.name}` : folder.name;
637 // Cached parents restart the depth count, so bound the path itself.
638 const path = joined !== null && joined.length <= MAX_PATH_LENGTH ? joined : null;
639 paths.set(id, path);
640 return path;
641 };
642​
643 // Hard links point at an inode file kept in the hidden private folder.
644 const privateFolder = [...folders].find(
645 ([, folder]) => folder.parentId === ROOT_FOLDER_ID && folder.name === PRIVATE_FILES,
646 )?.[0];
647 const inodes = new Map(
648 files
649 .filter((file) => file.parentId === privateFolder && file.name.startsWith("iNode"))
650 .map((file) => [file.name, file] as const),
651 );
652 const resolve = (file: CatalogFile) =>
653 file.type === "hlnk" && file.creator === "hfs+"
654 ? (inodes.get(`iNode${file.linkId}`) ?? file)
655 : file;
656​
657 const entries: ArchiveEntry[] = [];
658 const contents = new Map<string, CatalogFile>();
659 for (const [id, folder] of folders) {
660 if (id === ROOT_FOLDER_ID) continue;
661 const path = folderPath(id);
662 if (path) entries.push({ path, size: 0, directory: true, modified: folder.modified });
663 }
664 for (const file of files) {
665 const parent = folderPath(file.parentId);
666 if (parent === null) continue;
667 if (file.parentId === ROOT_FOLDER_ID && HIDDEN_ROOT_NAMES.has(file.name)) continue;
668 const path = parent ? `${parent}/${file.name}` : file.name;
669 const target = resolve(file);
670 contents.set(path, target);
671 entries.push({ path, size: target.fork.size, directory: false, modified: file.modified });
672 }
673 if (entries.length > DISK_IMAGE_MAX_ENTRIES)
674 throw new PreviewError({ code: "disk-image-too-many-entries" });
675 if (entries.length === 0) throw new PreviewError({ code: "archive-empty" });
676​
677 // Show where top-level symlinks lead, such as the usual Applications shortcut.
678 for (const entry of entries) {
679 const file = contents.get(entry.path);
680 if (!file || entry.path.includes("/") || file.type !== "slnk" || file.creator !== "rhap")
681 continue;
682 if (file.fork.size === 0 || file.fork.size > 1024) continue;
683 entry.link = new TextDecoder().decode(await volume.readFork(file.fileId, file.fork));
684 }
685​
686 return {
687 volume: volumeName,
688 entries,
689 readFile: async (path, limit) => {
690 const file = contents.get(path);
691 if (!file) throw new PreviewError({ code: "archive-entry-unavailable" });
692 if (file.compressed) throw new PreviewError({ code: "disk-image-entry-compressed" });
693 if (file.fork.size > limit) throw new PreviewError({ code: "archive-entry-too-large" });
694 return volume.readFork(file.fileId, file.fork);
695 },
696 };