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

binaryPreview.worker.ts

382 lines15.9 KB

1import { previewUnlock } from "./previewUnlock";
2import type { Database } from "sql.js";
3​
4import { boundedZip } from "@t3tools/client-runtime/zip/bounded-zip";
5import {
6 ARCHIVE_ENTRY_MAX_BYTES,
7 ARCHIVE_MAX_ENTRIES,
8 ARCHIVE_MAX_RATIO,
9 BINARY_PREVIEW_MAX_BYTES,
10 SQLITE_PAGE_SIZE,
11 type ArchiveEntry,
12 type BinaryWorkerRequest,
13 type BinaryWorkerResult,
14} from "./binaryPreviewProtocol";
15import { isPreviewError, PreviewError } from "./previewFailure";
16import { bytesSource, httpByteSource, listDiskImage, type DiskImageListing } from "./diskImage";
17​
18let database: Database | null = null;
19let tables: string[] = [];
20// Entries over the preview limit keep only their size, so their payload is never copied.
21let files = new Map<string, Uint8Array<ArrayBuffer> | number>();
22let diskImage: DiskImageListing | null = null;
23let diskImageEntries: Promise<unknown> = Promise.resolve();
24const reply = (result: BinaryWorkerResult) => self.postMessage(result, { transfer: [] });
25const quote = (name: string) => `"${name.replaceAll('"', '""')}"`;
26​
27async function gunzipMember(bytes: Uint8Array<ArrayBuffer>, limit: number) {
28 // A stream over the view, not a Blob, so each attempt does not copy the rest of the file.
29 const reader = new ReadableStream<Uint8Array<ArrayBuffer>>({
30 start(controller) {
31 controller.enqueue(bytes);
32 controller.close();
33 },
34 })
35 .pipeThrough(new DecompressionStream("gzip"))
36 .getReader();
37 const chunks: Uint8Array<ArrayBuffer>[] = [];
38 let length = 0;
39 try {
40 while (true) {
41 const { value, done } = await reader.read();
42 if (done) break;
43 length += value.length;
44 if (length > limit) throw new PreviewError({ code: "archive-expanded-too-large" });
45 chunks.push(value);
46 }
47 } finally {
48 await reader.cancel();
49 }
50 return new Uint8Array(await new Blob(chunks).arrayBuffer());
52​
53// DecompressionStream rejects a second member (`cat a.gz b.gz`) as junk, so a rest that does not
54// decode whole is cut at each gzip header. A header-like run in the data fails as truncated and
55// costs a re-decode; a single member (a .tar.gz of .gz files stores many) is tried whole first,
56// and a crafted file gets a few false cuts before it fails.
57const GZIP_MAX_FALSE_CUTS = 16;
58​
59async function gunzip(bytes: ArrayBuffer) {
60 const data = new Uint8Array(bytes);
61 const limit = Math.min(BINARY_PREVIEW_MAX_BYTES, data.length * ARCHIVE_MAX_RATIO);
62 const isHeader = (at: number) => data[at] === 0x1f && data[at + 1] === 0x8b && data[at + 2] === 8;
63 const members: Uint8Array<ArrayBuffer>[] = [];
64 let length = 0;
65 let falseCuts = 0;
66 let start = 0;
67 do {
68 const decode = (end: number) =>
69 gunzipMember(data.subarray(start, end), limit - length).then(
70 (bytes) => ({ bytes, cause: null }),
71 (cause: unknown) => ({ bytes: null, cause }),
72 );
73 const whole = await decode(data.length);
74 let member = whole;
75 let end = data.length;
76 for (let cut = start; member.bytes === null;) {
77 if (isPreviewError(member.cause)) throw member.cause;
78 if (cut > start && ++falseCuts > GZIP_MAX_FALSE_CUTS) throw whole.cause;
79 do cut++;
80 while (cut < data.length && !isHeader(cut));
81 if (cut >= data.length) throw whole.cause;
82 end = cut;
83 member = await decode(end);
84 }
85 members.push(member.bytes);
86 length += member.bytes.length;
87 start = end;
88 } while (start < data.length);
89 return new Uint8Array(await new Blob(members).arrayBuffer());
91​
92// Historic SunOS/BSD tar summed header bytes as signed chars, so accept either sum. A blank
93// field reads as 0, which high-bit bytes can bring the signed sum to, so 0 never matches it.
94function tarChecksumMatches(bytes: Uint8Array<ArrayBuffer>, offset: number, stored: number) {
95 let checksum = 0;
96 let signedChecksum = 0;
97 for (let index = 0; index < 512; index++) {
98 const byte = index >= 148 && index < 156 ? 32 : bytes[offset + index]!;
99 checksum += byte;
100 signedChecksum += byte < 128 ? byte : byte - 256;
101 }
102 return stored === checksum || (stored !== 0 && stored === signedChecksum);
104​
105// A TAR gzipped under a plain .gz name is recognized by a first header whose checksum holds.
106function startsWithTarHeader(bytes: Uint8Array<ArrayBuffer>) {
107 if (bytes.length < 512) return false;
108 const field = new TextDecoder().decode(bytes.subarray(148, 156)).split("\0", 1)[0]!.trim();
109 return /^[0-7]+$/.test(field) && tarChecksumMatches(bytes, 0, Number.parseInt(field, 8));
111​
112function tarEntries(bytes: Uint8Array<ArrayBuffer>) {
113 const entries: ArchiveEntry[] = [];
114 // EF BB BF at the start of a TAR field is part of the name, not a stream BOM.
115 const utf8 = new TextDecoder("utf-8", { ignoreBOM: true });
116 const text = (offset: number, length: number) =>
117 utf8.decode(bytes.subarray(offset, offset + length)).split("\0", 1)[0] ?? "";
118 const number = (offset: number, length: number) => {
119 const value = text(offset, length).trim();
120 if (!/^[0-7]*$/.test(value)) throw new PreviewError({ code: "tar-numeric-format" });
121 return Number.parseInt(value || "0", 8);
122 };
123 const gnuNumber = (offset: number, length: number) => {
124 const first = bytes[offset]!;
125 if ((first & 0x80) === 0) return number(offset, length);
126 let value = BigInt(first & 0x40 ? first - 0x100 : first & 0x7f);
127 for (let index = 1; index < length; index++)
128 value = (value << 8n) | BigInt(bytes[offset + index]!);
129 return Number(value);
130 };
131 let longPath: string | null = null;
132 let longLink: string | null = null;
133 const globalPax: Record<string, string> = {};
134 let localPax: Record<string, string> = {};
135 let offset = 0;
136 while (offset + 512 <= bytes.length) {
137 if (bytes.subarray(offset, offset + 512).every((byte) => byte === 0)) break;
138 if (entries.length >= ARCHIVE_MAX_ENTRIES)
139 throw new PreviewError({ code: "archive-too-many-entries" });
140 if (!tarChecksumMatches(bytes, offset, number(offset + 148, 8)))
141 throw new PreviewError({ code: "tar-header-damaged" });
142 const type = text(offset + 156, 1);
143 const metadata = type === "L" || type === "K" || type === "x" || type === "g";
144 const attributes: Record<string, string> = metadata ? {} : { ...globalPax, ...localPax };
145 const size = attributes.size ? Number(attributes.size) : gnuNumber(offset + 124, 12);
146 if (attributes.size && !/^\d+$/.test(attributes.size))
147 throw new PreviewError({ code: "archive-entry-damaged" });
148 const prefix =
149 text(offset + 257, 6) === "ustar" && text(offset + 263, 2) === "00"
150 ? text(offset + 345, 155)
151 : "";
152 const path =
153 attributes.path || longPath || [prefix, text(offset, 100)].filter(Boolean).join("/");
154 const linkpath = attributes.linkpath ?? longLink ?? text(offset + 157, 100);
155 if (!metadata) {
156 longLink = null;
157 longPath = null;
158 localPax = {};
159 }
160 if (
161 path.length > 1024 ||
162 !Number.isSafeInteger(size) ||
163 size < 0 ||
164 size > BINARY_PREVIEW_MAX_BYTES ||
165 offset + 512 + size > bytes.length
166 )
167 throw new PreviewError({ code: "archive-entry-damaged" });
168 const content = bytes.subarray(offset + 512, offset + 512 + size);
169 if (type === "L") longPath = utf8.decode(content).replace(/\0.*$/s, "");
170 else if (type === "K") longLink = utf8.decode(content).replace(/\0.*$/s, "");
171 else if (type === "x" || type === "g") {
172 if (size > 65536) throw new PreviewError({ code: "archive-metadata-too-large" });
173 for (let cursor = 0; cursor < content.length;) {
174 const separator = content.indexOf(32, cursor);
175 if (separator < cursor || separator - cursor > 10)
176 throw new PreviewError({ code: "tar-metadata-damaged" });
177 const lengthText = new TextDecoder().decode(content.subarray(cursor, separator));
178 const length = Number(lengthText);
179 const end = cursor + length;
180 if (
181 !/^[1-9]\d*$/.test(lengthText) ||
182 !Number.isSafeInteger(length) ||
183 end > content.length ||
184 end <= separator + 1 ||
185 content[end - 1] !== 10
186 )
187 throw new PreviewError({ code: "tar-metadata-damaged" });
188 const record = new TextDecoder().decode(content.subarray(separator + 1, end - 1));
189 const equals = record.indexOf("=");
190 if (equals < 1) throw new PreviewError({ code: "tar-metadata-damaged" });
191 const key = record.slice(0, equals);
192 const value = record.slice(equals + 1);
193 if (["path", "linkpath", "size", "mtime"].includes(key)) {
194 if (type === "x") localPax[key] = value;
195 else if (value || key === "linkpath") globalPax[key] = value;
196 else delete globalPax[key];
197 }
198 cursor = end;
199 }
200 } else if (
201 type === "" ||
202 type === "0" ||
203 // Contiguous files are regular files to every extractor.
204 type === "7" ||
205 type === "5" ||
206 // A hard link shares an earlier member's bytes; one without that member is skipped.
207 (type === "1" && linkpath && files.has(linkpath))
208 ) {
209 if (attributes.mtime && !/^[+-]?\d+(?:\.\d+)?$/.test(attributes.mtime))
210 throw new PreviewError({ code: "tar-metadata-damaged" });
211 const modified =
212 (attributes.mtime ? Number(attributes.mtime) : gnuNumber(offset + 136, 12)) * 1000;
213 const date = new Date(modified);
214 const linked = type === "1" ? files.get(linkpath) : undefined;
215 // Old (v7) archives mark a folder only by a trailing slash on a plain member.
216 const directory = type === "5" || (type !== "1" && path.endsWith("/"));
217 entries.push({
218 path,
219 size: typeof linked === "number" ? linked : (linked?.length ?? size),
220 directory,
221 modified: Number.isNaN(date.getTime()) ? null : date.toISOString(),
222 });
223 if (directory) {
224 files.delete(path);
225 files.delete(path.replace(/\/+$/, ""));
226 } else files.set(path, linked ?? (size > ARCHIVE_ENTRY_MAX_BYTES ? size : content.slice()));
227 } else {
228 files.delete(path);
229 }
230 offset += 512 + Math.ceil(size / 512) * 512;
231 }
232 // Appended members (`tar -r`/`-u`) replace earlier ones with the same path, as extraction does.
233 const last = new Map(entries.map((entry, index) => [entry.path, index] as const));
234 const listed = entries.filter(
235 (entry, index) => last.get(entry.path) === index && (entry.directory || files.has(entry.path)),
236 );
237 if (listed.length === 0) throw new PreviewError({ code: "archive-empty" });
238 return listed;
240​
241async function handle(input: Exclude<BinaryWorkerRequest, { type: "unlock" }>, password?: string) {
242 if (input.type === "entry" && diskImage) {
243 // Reads finish out of order, but the viewer matches replies to requests by arrival order.
244 const image = diskImage;
245 const read = diskImageEntries.then(() => image.readFile(input.path, ARCHIVE_ENTRY_MAX_BYTES));
246 diskImageEntries = read.catch(() => undefined);
247 const bytes = await read;
248 reply({ type: "entry", path: input.path, bytes });
249 return;
250 }
251 if (input.type === "entry") {
252 const bytes = files.get(input.path);
253 if (bytes === undefined) throw new PreviewError({ code: "archive-entry-unavailable" });
254 if (typeof bytes === "number" || bytes.length > ARCHIVE_ENTRY_MAX_BYTES)
255 throw new PreviewError({ code: "archive-entry-too-large" });
256 reply({ type: "entry", path: input.path, bytes });
257 return;
258 }
259 if (input.type === "rows") {
260 if (
261 !database ||
262 !tables.includes(input.table) ||
263 !Number.isSafeInteger(input.page) ||
264 input.page < 0
265 )
266 throw new PreviewError({ code: "table-unavailable" });
267 const columns =
268 database
269 .exec(`PRAGMA table_xinfo(${quote(input.table)})`)[0]
270 ?.values.filter((row) => row[6] !== 1)
271 .map((row) => String(row[1]))
272 .slice(0, 50) ?? [];
273 const fields = columns.map((name) => {
274 const field = quote(name);
275 return `CASE WHEN typeof(${field}) = 'blob' THEN '[blob: ' || length(${field}) || CASE length(${field}) WHEN 1 THEN ' byte]' ELSE ' bytes]' END ELSE substr(CAST(${field} AS TEXT), 1, 1024) END`;
276 });
277 const result = database.exec(
278 `SELECT ${fields.join(",")} FROM ${quote(input.table)} LIMIT ${SQLITE_PAGE_SIZE} OFFSET ${input.page * SQLITE_PAGE_SIZE}`,
279 )[0];
280 reply({
281 type: "rows",
282 table: input.table,
283 page: input.page,
284 columns,
285 rows:
286 result?.values.map((row) => row.map((cell) => (cell === null ? "NULL" : String(cell)))) ??
287 [],
288 });
289 return;
290 }
291 if ("src" in input) {
292 const source = await httpByteSource(input.src, BINARY_PREVIEW_MAX_BYTES);
293 diskImage = await listDiskImage(source);
294 reply({
295 type: "archive",
296 entries: diskImage.entries,
297 volume: diskImage.volume,
298 sizeBytes: source.size,
299 });
300 return;
301 }
302 if (input.bytes.byteLength > BINARY_PREVIEW_MAX_BYTES)
303 throw new PreviewError({ code: "file-too-large" });
304 if (input.kind === "sqlite") {
305 const [{ default: initSqlJs }, { default: wasmUrl }] = await Promise.all([
306 import("sql.js"),
307 import("sql.js/dist/sql-wasm.wasm?url"),
308 ]);
309 const SQL = await initSqlJs({ locateFile: () => wasmUrl });
310 database = new SQL.Database(new Uint8Array(input.bytes));
311 database.run("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF;");
312 tables =
313 database
314 .exec(
315 "SELECT name FROM sqlite_schema WHERE type='table' AND substr(name, 1, 7) != 'sqlite_' AND sql NOT LIKE 'CREATE VIRTUAL TABLE%' ORDER BY name LIMIT 101",
316 )[0]
317 ?.values.map((row) => String(row[0])) ?? [];
318 if (tables.length > 100) throw new PreviewError({ code: "database-too-many-tables" });
319 reply({
320 type: "sqlite",
321 tables: tables.map((name) => ({
322 name,
323 count: Number(
324 database!.exec(`SELECT count(*) FROM ${quote(name)}`)[0]?.values[0]?.[0] ?? 0,
325 ),
326 })),
327 });
328 } else {
329 files = new Map();
330 let entries: ArchiveEntry[];
331 if (
332 /\.(zip|jar)$/i.test(input.name) ||
333 (input.bytes.byteLength >= 4 &&
334 [0x04034b50, 0x06054b50].includes(new DataView(input.bytes).getUint32(0, true)))
335 ) {
336 const archive = await boundedZip(input.bytes, BINARY_PREVIEW_MAX_BYTES, { password });
337 entries = [...archive].map(([path, file]) => {
338 files.set(path, file.bytes);
339 return {
340 path,
341 size: file.bytes.length,
342 directory: file.directory,
343 // ZIP stores wall-clock time without a zone, while JSZip reads those fields as UTC.
344 // Omitting "Z" marks the timestamp as wall-clock so the viewer formats its calendar date.
345 // DOS dates start in 1980; an unset (all zero) field reads as 30 Nov 1979, so it has none.
346 modified:
347 Number.isNaN(file.date.getTime()) || file.date.getUTCFullYear() < 1980
348 ? null
349 : file.date.toISOString().slice(0, -1),
350 };
351 });
352 } else if (
353 /\.(gz|tgz)$/i.test(input.name) ||
354 (input.bytes.byteLength >= 2 && new DataView(input.bytes).getUint16(0) === 0x1f8b)
355 ) {
356 const bytes = await gunzip(input.bytes);
357 if (/\.(tar\.gz|tgz)$/i.test(input.name)) entries = tarEntries(bytes);
358 else {
359 const path = input.name.replace(/\.gz$/i, "") || "contents";
360 if (/\.tar$/i.test(path) || startsWithTarHeader(bytes)) entries = tarEntries(bytes);
361 else {
362 files.set(path, bytes);
363 entries = [{ path, size: bytes.length, directory: false, modified: null }];
364 }
365 }
366 } else if (
367 input.bytes.byteLength >= 512 &&
368 new DataView(input.bytes, input.bytes.byteLength - 512).getUint32(0) === 0x6b6f6c79
369 ) {
370 // A disk image whose name did not say so ends in a UDIF "koly" trailer.
371 diskImage = await listDiskImage(bytesSource(new Uint8Array(input.bytes)));
372 reply({ type: "archive", entries: diskImage.entries, volume: diskImage.volume });
373 return;
374 } else entries = tarEntries(new Uint8Array(input.bytes));
375 reply({ type: "archive", entries });
376 }
378​
379const receive = previewUnlock(handle, reply, "preview-failed");
380self.addEventListener("message", (event: MessageEvent<BinaryWorkerRequest>) => {
381 void receive(event.data);
382});