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

chromiumLocalStorage.ts

446 lines15.0 KB

1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Path from "effect/Path";
4import * as PlatformError from "effect/PlatformError";
5import * as Schema from "effect/Schema";
6​
7/**
8 * It reads the database files directly and never takes LevelDB's lock, so it
9 * works while another app version has the profile open. Live files come from
10 * the MANIFEST that CURRENT names, and the newest sequence number wins, which
11 * is how LevelDB itself resolves overwrites and deletions.
12 */
13​
14const LOG_BLOCK_SIZE = 32 * 1024;
15const LOG_HEADER_SIZE = 7;
16const TABLE_FOOTER_SIZE = 48;
17const BLOCK_TRAILER_SIZE = 5;
18​
19class LevelDbFormatError extends Schema.TaggedError<LevelDbFormatError>()("LevelDbFormatError", {
20 detail: Schema.String,
21}) {}
22​
23const isLevelDbFormatError = Schema.is(LevelDbFormatError);
24​
25const fail = (detail: string): never => {
26 throw new LevelDbFormatError({ detail });
27};
28​
29// ignoreBOM keeps a leading U+FEFF that is part of the stored string.
30const textDecoderUtf16 = new TextDecoder("utf-16le", { ignoreBOM: true });
31const textDecoderUtf8 = new TextDecoder();
32​
33/** True ISO-8859-1. WHATWG's "latin1" label is windows-1252, which remaps 0x80-0x9F. */
34function decodeLatin1(bytes: Uint8Array): string {
35 let result = "";
36 for (let offset = 0; offset < bytes.length; offset += 0x8000) {
37 result += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
38 }
39 return result;
41​
42class Reader {
43 readonly bytes: Uint8Array;
44 offset: number;
45 constructor(bytes: Uint8Array, offset = 0) {
46 this.bytes = bytes;
47 this.offset = offset;
48 }
49 get done() {
50 return this.offset >= this.bytes.length;
51 }
52 byte(): number {
53 if (this.offset >= this.bytes.length) fail("unexpected end of data");
54 return this.bytes[this.offset++]!;
55 }
56 varint(): number {
57 let result = 0;
58 let multiplier = 1;
59 for (let shift = 0; shift < 64; shift += 7) {
60 const byte = this.byte();
61 result += (byte & 0x7f) * multiplier;
62 if ((byte & 0x80) === 0) return result;
63 multiplier *= 128;
64 }
65 return fail("varint too long");
66 }
67 take(length: number): Uint8Array {
68 if (length < 0 || this.offset + length > this.bytes.length) fail("length out of range");
69 const slice = this.bytes.subarray(this.offset, this.offset + length);
70 this.offset += length;
71 return slice;
72 }
73 lengthPrefixed(): Uint8Array {
74 return this.take(this.varint());
75 }
77​
78const readUint32 = (bytes: Uint8Array, offset: number) =>
79 (bytes[offset]! | (bytes[offset + 1]! << 8) | (bytes[offset + 2]! << 16)) +
80 bytes[offset + 3]! * 0x1000000;
81​
82const CRC32C_TABLE = (() => {
83 const table = new Uint32Array(256);
84 for (let index = 0; index < 256; index++) {
85 let crc = index;
86 for (let bit = 0; bit < 8; bit++) crc = crc & 1 ? (crc >>> 1) ^ 0x82f63b78 : crc >>> 1;
87 table[index] = crc >>> 0;
88 }
89 return table;
90})();
91​
92function crc32c(bytes: Uint8Array): number {
93 let crc = 0xffffffff;
94 for (const byte of bytes) crc = CRC32C_TABLE[(crc ^ byte) & 0xff]! ^ (crc >>> 8);
95 return (crc ^ 0xffffffff) >>> 0;
97​
98const unmaskCrc = (masked: number) => {
99 const rotated = (masked - 0xa282ead8) >>> 0;
100 return ((rotated >>> 17) | (rotated << 15)) >>> 0;
101};
102​
103function decompressSnappy(input: Uint8Array): Uint8Array {
104 const reader = new Reader(input);
105 const output = new Uint8Array(reader.varint());
106 let written = 0;
107 while (!reader.done) {
108 const tag = reader.byte();
109 const kind = tag & 3;
110 if (kind === 0) {
111 let length = tag >>> 2;
112 if (length >= 60) {
113 const extraBytes = length - 59;
114 length = 0;
115 for (let index = 0; index < extraBytes; index++) length += reader.byte() * 256 ** index;
116 }
117 length += 1;
118 if (written + length > output.length) fail("snappy literal overflows output");
119 output.set(reader.take(length), written);
120 written += length;
121 continue;
122 }
123 let length: number;
124 let offset: number;
125 if (kind === 1) {
126 length = 4 + ((tag >>> 2) & 7);
127 offset = ((tag >>> 5) << 8) | reader.byte();
128 } else if (kind === 2) {
129 length = (tag >>> 2) + 1;
130 offset = reader.byte() | (reader.byte() << 8);
131 } else {
132 length = (tag >>> 2) + 1;
133 offset = readUint32(reader.take(4), 0);
134 }
135 if (offset === 0 || offset > written || written + length > output.length) {
136 fail("snappy copy out of range");
137 }
138 // Copies may overlap their own output, so they go byte by byte.
139 for (let index = 0; index < length; index++) {
140 output[written] = output[written - offset]!;
141 written++;
142 }
143 }
144 if (written !== output.length) fail("snappy output length mismatch");
145 return output;
147​
148/**
149 * Like LevelDB's own reader, a corrupt record or zero padding skips the rest of
150 * its block, since a reused log keeps appending after a torn write, and a
151 * record cut off by the end of the file ends the log.
152 */
153function readLogRecords(bytes: Uint8Array): Uint8Array[] {
154 const records: Uint8Array[] = [];
155 let pending: Uint8Array[] | null = null;
156 let offset = 0;
157 while (offset + LOG_HEADER_SIZE <= bytes.length) {
158 const blockRemaining = LOG_BLOCK_SIZE - (offset % LOG_BLOCK_SIZE);
159 if (blockRemaining < LOG_HEADER_SIZE) {
160 offset += blockRemaining;
161 continue;
162 }
163 const length = bytes[offset + 4]! | (bytes[offset + 5]! << 8);
164 const type = bytes[offset + 6]!;
165 const end = offset + LOG_HEADER_SIZE + length;
166 const fitsBlock = LOG_HEADER_SIZE + length <= blockRemaining;
167 if (fitsBlock && end > bytes.length) break;
168 const typeAndPayload = bytes.subarray(offset + 6, end);
169 if (
170 type === 0 ||
171 !fitsBlock ||
172 crc32c(typeAndPayload) !== unmaskCrc(readUint32(bytes, offset))
173 ) {
174 offset += blockRemaining;
175 pending = null;
176 continue;
177 }
178 const payload = typeAndPayload.subarray(1);
179 offset = end;
180 if (type === 1) {
181 records.push(payload);
182 pending = null;
183 } else if (type === 2) {
184 pending = [payload];
185 } else if (type === 3 && pending) {
186 pending.push(payload);
187 } else if (type === 4 && pending) {
188 pending.push(payload);
189 const total = pending.reduce((sum, part) => sum + part.length, 0);
190 const record = new Uint8Array(total);
191 let position = 0;
192 for (const part of pending) {
193 record.set(part, position);
194 position += part.length;
195 }
196 records.push(record);
197 pending = null;
198 } else {
199 pending = null;
200 }
201 }
202 return records;
204​
205interface LiveFiles {
206 readonly tables: ReadonlyArray<number>;
207 readonly logNumber: number;
208 readonly previousLogNumber: number;
210​
211function readManifest(bytes: Uint8Array): LiveFiles {
212 const tables = new Set<number>();
213 let logNumber = 0;
214 let previousLogNumber = 0;
215 // LevelDB refuses to open a MANIFEST missing any of these, and so do we.
216 const required = new Set([2, 3, 4]);
217 for (const record of readLogRecords(bytes)) {
218 const reader = new Reader(record);
219 while (!reader.done) {
220 const tag = reader.varint();
221 required.delete(tag);
222 switch (tag) {
223 case 1:
224 reader.lengthPrefixed();
225 break;
226 case 2:
227 logNumber = reader.varint();
228 break;
229 case 3:
230 case 4:
231 reader.varint();
232 break;
233 case 5:
234 reader.varint();
235 reader.lengthPrefixed();
236 break;
237 case 6:
238 reader.varint();
239 tables.delete(reader.varint());
240 break;
241 case 7: {
242 reader.varint();
243 tables.add(reader.varint());
244 reader.varint();
245 reader.lengthPrefixed();
246 reader.lengthPrefixed();
247 break;
248 }
249 case 9:
250 previousLogNumber = reader.varint();
251 break;
252 default:
253 fail(`unknown manifest tag ${tag}`);
254 }
255 }
256 }
257 if (required.size > 0) fail("incomplete manifest");
258 return { tables: [...tables], logNumber, previousLogNumber };
260​
261interface VersionedEntry {
262 readonly sequence: number;
263 readonly value: Uint8Array | null;
265​
266type EntryMap = Map<string, { readonly key: Uint8Array; readonly entry: VersionedEntry }>;
267​
268const keyId = decodeLatin1;
269​
270function record(entries: EntryMap, key: Uint8Array, entry: VersionedEntry) {
271 const id = keyId(key);
272 const existing = entries.get(id);
273 if (!existing || existing.entry.sequence < entry.sequence) entries.set(id, { key, entry });
275​
276function readWriteBatch(entries: EntryMap, batch: Uint8Array) {
277 if (batch.length < 12) fail("write batch too short");
278 const sequence = readUint32(batch, 0) + readUint32(batch, 4) * 0x100000000;
279 const count = readUint32(batch, 8);
280 const reader = new Reader(batch, 12);
281 for (let index = 0; index < count; index++) {
282 const type = reader.byte();
283 const key = reader.lengthPrefixed();
284 if (type === 1) {
285 record(entries, key, { sequence: sequence + index, value: reader.lengthPrefixed() });
286 } else if (type === 0) {
287 record(entries, key, { sequence: sequence + index, value: null });
288 } else {
289 fail(`unknown write batch record type ${type}`);
290 }
291 }
293​
294function readBlock(table: Uint8Array, reader: Reader): Uint8Array {
295 const offset = reader.varint();
296 const size = reader.varint();
297 if (offset + size + BLOCK_TRAILER_SIZE > table.length) fail("block handle out of range");
298 const contents = table.subarray(offset, offset + size);
299 const compression = table[offset + size]!;
300 const checksum = unmaskCrc(readUint32(table, offset + size + 1));
301 if (crc32c(table.subarray(offset, offset + size + 1)) !== checksum) fail("block checksum");
302 if (compression === 0) return contents;
303 if (compression === 1) return decompressSnappy(contents);
304 return fail(`unsupported block compression ${compression}`);
306​
307function* blockEntries(block: Uint8Array): Generator<[Uint8Array, Uint8Array]> {
308 if (block.length < 4) fail("block too short");
309 const restartCount = readUint32(block, block.length - 4);
310 const limit = block.length - 4 - restartCount * 4;
311 if (limit < 0) fail("restart array out of range");
312 const reader = new Reader(block.subarray(0, limit));
313 let key = new Uint8Array(0);
314 while (!reader.done) {
315 const shared = reader.varint();
316 const unshared = reader.varint();
317 const valueLength = reader.varint();
318 if (shared > key.length) fail("block key prefix out of range");
319 const nextKey = new Uint8Array(shared + unshared);
320 nextKey.set(key.subarray(0, shared));
321 nextKey.set(reader.take(unshared), shared);
322 key = nextKey;
323 yield [key, reader.take(valueLength)];
324 }
326​
327function readTable(entries: EntryMap, table: Uint8Array) {
328 if (table.length < TABLE_FOOTER_SIZE) fail("table too short");
329 const footer = new Reader(table, table.length - TABLE_FOOTER_SIZE);
330 footer.varint();
331 footer.varint();
332 const index = readBlock(table, footer);
333 for (const [, handle] of blockEntries(index)) {
334 const block = readBlock(table, new Reader(handle));
335 for (const [internalKey, value] of blockEntries(block)) {
336 if (internalKey.length < 8) fail("internal key too short");
337 const trailerOffset = internalKey.length - 8;
338 const trailer =
339 readUint32(internalKey, trailerOffset) +
340 readUint32(internalKey, trailerOffset + 4) * 0x100000000;
341 const type = trailer % 256;
342 const sequence = Math.floor(trailer / 256);
343 const key = internalKey.subarray(0, trailerOffset);
344 record(entries, key, { sequence, value: type === 1 ? value : null });
345 }
346 }
348​
349/** Chromium prefixes each stored string with 0 (UTF-16LE) or 1 (Latin-1). */
350function decodeChromiumString(bytes: Uint8Array): string | null {
351 if (bytes.length === 0) return null;
352 const body = bytes.subarray(1);
353 if (bytes[0] === 1) return decodeLatin1(body);
354 if (bytes[0] === 0 && body.length % 2 === 0) return textDecoderUtf16.decode(body);
355 return null;
357​
358export class ChromiumLocalStorageReadError extends Schema.TaggedError<ChromiumLocalStorageReadError>()(
359 "ChromiumLocalStorageReadError",
360 {
361 directory: Schema.String,
362 cause: Schema.Defect(),
363 },
364) {
365 override get message() {
366 return `Could not read Chromium Local Storage at ${this.directory}.`;
367 }
369​
370export const readChromiumLocalStorage = Effect.fn("desktop.chromiumLocalStorage.read")(function* (
371 directory: string,
372 origin: string,
373) {
374 const fs = yield* FileSystem.FileSystem;
375 const path = yield* Path.Path;
376 const readFile = (name: string) => fs.readFile(path.join(directory, name));
377 const wrap = Effect.mapError(
378 (cause: PlatformError.PlatformError | LevelDbFormatError) =>
379 new ChromiumLocalStorageReadError({ directory, cause }),
380 );
381 const decode = <A>(run: () => A) =>
382 Effect.try({
383 try: run,
384 catch: (cause) =>
385 isLevelDbFormatError(cause) ? cause : new LevelDbFormatError({ detail: String(cause) }),
386 });
387​
388 const current = textDecoderUtf8.decode(yield* readFile("CURRENT").pipe(wrap)).trim();
389 if (!/^MANIFEST-\d+$/.test(current)) {
390 return yield* new ChromiumLocalStorageReadError({
391 directory,
392 cause: new LevelDbFormatError({ detail: "bad CURRENT" }),
393 });
394 }
395 const manifest = yield* readFile(current).pipe(wrap);
396 const live = yield* decode(() => readManifest(manifest)).pipe(wrap);
397 const logs = (yield* fs.readDirectory(directory).pipe(wrap))
398 .map((name) => /^(\d+)\.log$/.exec(name))
399 .filter((match) => {
400 const number = Number(match?.[1]);
401 return number >= live.logNumber || number === live.previousLogNumber;
402 })
403 .map((match) => match![0]);
404​
405 const entries: EntryMap = new Map();
406 for (const number of live.tables) {
407 const name = String(number).padStart(6, "0");
408 // Newer LevelDB names tables .ldb; older databases may still hold .sst files.
409 const bytes = yield* readFile(`${name}.ldb`).pipe(
410 Effect.catchIf(
411 (error) => error.reason._tag === "NotFound",
412 () => readFile(`${name}.sst`),
413 ),
414 wrap,
415 );
416 yield* decode(() => readTable(entries, bytes)).pipe(wrap);
417 }
418 for (const name of logs) {
419 const bytes = yield* readFile(name).pipe(wrap);
420 yield* decode(() => {
421 for (const batch of readLogRecords(bytes)) readWriteBatch(entries, batch);
422 }).pipe(wrap);
423 }
424​
425 // A flush while another process has the database open can move entries
426 // from a log we read into a table our MANIFEST copy predates. Fail so the
427 // caller retries rather than import a snapshot missing those entries.
428 const currentAfter = textDecoderUtf8.decode(yield* readFile("CURRENT").pipe(wrap)).trim();
429 const manifestAfter = yield* fs.stat(path.join(directory, current)).pipe(wrap);
430 if (currentAfter !== current || Number(manifestAfter.size) !== manifest.length) {
431 return yield* new ChromiumLocalStorageReadError({
432 directory,
433 cause: new LevelDbFormatError({ detail: "database changed while reading" }),
434 });
435 }
436​
437 const prefix = `_${origin}\u0000`;
438 const items = new Map<string, string>();
439 for (const [id, { key: rawKey, entry }] of entries) {
440 if (!id.startsWith(prefix) || entry.value === null) continue;
441 const key = decodeChromiumString(rawKey.subarray(prefix.length));
442 const value = decodeChromiumString(entry.value);
443 if (key !== null && value !== null) items.set(key, value);
444 }
445 return items;
446});