diff --git a/packages/engine/src/utils/notMediaPayload.test.ts b/packages/engine/src/utils/notMediaPayload.test.ts index a707a82b82..d19165c7ca 100644 --- a/packages/engine/src/utils/notMediaPayload.test.ts +++ b/packages/engine/src/utils/notMediaPayload.test.ts @@ -716,3 +716,150 @@ describe.skipIf(process.platform === "win32")("a FIFO with no writer", () => { expect(await playlistLeavesItsFolder(list)).toBe(true); }); }); + +describe("playlistLeavesItsFolder judges the name ffmpeg opens for each entry", () => { + const FFPROBE_8 = /^ffprobe version n?8\./.test( + spawnSync(getFfprobeBinary(), ["-version"], { encoding: "utf-8" }).stdout ?? "", + ); + const segments = (extra = "") => + `#EXTM3U\n#EXT-X-TARGETDURATION:1\n${extra}#EXTINF:1,\nseg.ts\n#EXT-X-ENDLIST\n`; + const kinds: [string, (name: string) => string][] = [ + [ + "segment", + (name) => `#EXTM3U\n#EXT-X-TARGETDURATION:1\n#EXTINF:1,\n${name}\n#EXT-X-ENDLIST\n`, + ], + ["variant", (name) => `#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\n${name}\n`], + [ + "rendition", + (name) => + `#EXTM3U\n#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=a,NAME=a,URI="${name}"\n` + + '#EXT-X-STREAM-INF:BANDWIDTH=1,AUDIO="a"\nv.m3u8\n', + ], + ["key", (name) => segments(`#EXT-X-KEY:METHOD=AES-128,URI="${name}"\n`)], + ["map", (name) => segments(`#EXT-X-MAP:URI="${name}"\n`)], + ]; + const uriKinds = kinds.filter(([kind]) => !["segment", "variant"].includes(kind)); + const outsideList = `#EXTM3U\n#EXT-X-TARGETDURATION:1\n#EXTINF:1,\n${join(tmpdir(), "outside.ts")}\n#EXT-X-ENDLIST\n`; + + /** The list, a harmless file at the suffix's name beside it, and the sibling list ffmpeg opens for the suffix. */ + function withDecoy(list: string, suffix: string): string { + const top = writeTree({ "clip.m3u8": list, "v.m3u8": segments(), "seg.ts": "media" }); + writeFileSync(join(top, "..", suffix.replace(/^%3F/i, "?")), "media"); + if (suffix.startsWith("?")) writeFileSync(`${top}${suffix}`, outsideList); + return top; + } + + const forms = [ + ...(process.platform === "win32" ? [] : ["?x.m3u8", "%3Fx.m3u8"]).flatMap((suffix) => + kinds.map(([kind, list]) => [kind, suffix, list] as const), + ), + ...uriKinds.flatMap(([kind, list]) => [ + [kind, "#x.m3u8", list] as const, + [kind, "", list] as const, + ]), + ]; + + it.each(forms)("refuses a %s entry %j with no path before it", async (_kind, suffix, list) => { + const top = withDecoy(list(suffix), suffix || "decoy"); + expect(await playlistLeavesItsFolder(top)).toBe(true); + expect(await isNotMediaPayload(top)).toBe(true); + await expect(assertMediaPayload(top, "clip")).rejects.toBeInstanceOf(NotMediaPayloadError); + }); + + it.skipIf(process.platform === "win32")( + "refuses a segment line that trims to a query", + async () => { + const top = withDecoy(kinds[0]![1](" ?x.m3u8"), "?x.m3u8"); + expect(await playlistLeavesItsFolder(top)).toBe(true); + }, + ); + + it.skipIf(!FFPROBE_8 || process.platform === "win32")( + "matches ffprobe, which opens the list's own name plus a query-only entry", + async () => { + const top = withDecoy(kinds[0]![1]("?x.ts"), "?x.ts"); + const probe = spawnSync( + getFfprobeBinary(), + ["-loglevel", "debug", "-show_format", "--", top], + { + encoding: "utf-8", + }, + ); + expect(probe.stderr).toContain(`Opening '${top}?x.ts' for reading`); + }, + ); + + it.skipIf(!FFPROBE_8)("matches ffprobe on the name each kind of entry opens", async () => { + for (const [kind, list] of kinds) { + const name = kind === "variant" || kind === "rendition" ? "sub/in.m3u8" : `sub/${kind}.ts`; + const top = writeTree({ "clip.m3u8": list(name), "v.m3u8": segments(), "seg.ts": "media" }); + mkdirSync(join(top, "..", "sub"), { recursive: true }); + writeFileSync(join(top, "..", "sub", "seg.ts"), "media"); + writeFileSync(join(top, "..", name), name.endsWith(".m3u8") ? segments() : "media"); + expect(await playlistLeavesItsFolder(top)).toBe(false); + const probe = spawnSync( + getFfprobeBinary(), + ["-loglevel", "debug", "-show_format", "--", top], + { + encoding: "utf-8", + }, + ); + expect(probe.stderr, kind).toContain(`Opening '${join(top, "..", name)}' for reading`); + } + }); + + it("keeps a query or fragment after a name, as ffmpeg opens it beside the list", async () => { + const names = process.platform === "win32" ? ["seg#1.ts"] : ["seg#1.ts", "seg?v=1.ts"]; + const list = withBeside(writeFixture("clip.m3u8", kinds[0]![1](names.join("\n"))), ...names); + expect(await playlistLeavesItsFolder(list)).toBe(false); + }); +}); + +describe("playlistLeavesItsFolder refuses a list behind an ID3v2 tag", () => { + const tag = (version: number, flags: number, body = 4) => + Buffer.concat([ + Buffer.from([0x49, 0x44, 0x33, version, 0, flags, 0, 0, 0, body]), + Buffer.alloc(body), + ]); + const concat = "ffconcat version 1.0\nfile seg.mp4\n"; + const tags = [2, 3, 4, 5].flatMap((version) => + [0, 0x10].map((flags) => [version, flags] as const), + ); + + it.each(tags)( + "refuses a list behind a v2.%i tag with flags %i, at the top and nested", + async (version, flags) => { + const tagged = Buffer.concat([ + tag(version, flags), + Buffer.alloc(flags ? 10 : 0), + Buffer.from(concat), + ]); + const top = withBeside(writeFixture("clip.mp4", tagged), "seg.mp4"); + expect(await playlistLeavesItsFolder(top)).toBe(true); + expect(await isNotMediaPayload(top)).toBe(true); + const root = mkdtempSync(join(tmpdir(), "hf-playlist-id3-")); + writeFileSync(join(root, "clip.mp4"), "ffconcat version 1.0\nfile inner.mp4\n"); + writeFileSync(join(root, "inner.mp4"), tagged); + writeFileSync(join(root, "seg.mp4"), "media"); + expect(await playlistLeavesItsFolder(join(root, "clip.mp4"))).toBe(true); + }, + ); + + it("refuses a list whose start the tag's footer flag moves", async () => { + // A v2.3 tag with the footer flag: ffmpeg's demuxer reads the list from the tag's end, its probe 10 bytes later. + const root = mkdtempSync(join(tmpdir(), "hf-playlist-id3-")); + writeFileSync(join(root, "clip.mp4"), Buffer.concat([tag(3, 0x10), Buffer.from(concat)])); + writeFileSync(join(root, "seg.mp4"), "media"); + expect(await playlistLeavesItsFolder(join(root, "clip.mp4"))).toBe(true); + }); + + it("keeps a tagged mp3 segment named by a list", async () => { + const list = "#EXTM3U\n#EXT-X-TARGETDURATION:1\n#EXTINF:1,\na.mp3\n#EXT-X-ENDLIST\n"; + const top = writeFixture("clip.m3u8", list); + writeFileSync( + join(top, "..", "a.mp3"), + Buffer.concat([tag(3, 0x10), Buffer.from([0xff, 0xfb, 0x90, 0])]), + ); + expect(await playlistLeavesItsFolder(top)).toBe(false); + }); +}); diff --git a/packages/engine/src/utils/notMediaPayload.ts b/packages/engine/src/utils/notMediaPayload.ts index 5d269475cf..b316859bdb 100644 --- a/packages/engine/src/utils/notMediaPayload.ts +++ b/packages/engine/src/utils/notMediaPayload.ts @@ -319,6 +319,8 @@ const MAX_WALK_ENTRIES = 50_000; const HTTP_URL = /^https?:\/\//i; const COLON_IN_FIRST_SEGMENT = /^[^/\\?#]*:/; const FOLDER_CUT_AT_QUERY_OR_FRAGMENT = /[?#]/; +// ffmpeg reads a name with no path before its query or fragment as the list's own path plus that suffix. +const NO_PATH = /^(?:[?#]|$)/; // ffmpeg reads a list line into a 4096-byte buffer, so a longer line would name something else: it is refused unread. const MAX_LIST_LINE_BYTES = 4095; @@ -345,9 +347,11 @@ function hlsEntries(body: string): Entry[] | true { const line = withoutTrailing(raw, TRAILING_HLS_BLANK); const found = line.startsWith("#") ? attributeUris(line).map((uri) => [uri]) - : [[line, line.trim()]]; - for (const names of found.map((entry) => [...new Set(entry.filter(Boolean))])) { - if (names.length > 0) entries.set(names.join("\n"), names); + : line + ? [[line, line.trim()]] + : []; + for (const names of found.map((entry) => [...new Set(entry)])) { + entries.set(names.join("\n"), names); } } return [...entries.values()]; @@ -428,7 +432,7 @@ function entryLeavesFolder(entry: string, base: string, folder: string): boolean if (HTTP_URL.test(entry)) return false; if (FOLDER_CUT_AT_QUERY_OR_FRAGMENT.test(base)) return true; return [entry, percentDecoded(entry)].some((path) => { - if (COLON_IN_FIRST_SEGMENT.test(path)) return true; + if (NO_PATH.test(path) || COLON_IN_FIRST_SEGMENT.test(path)) return true; if (isAbsolute(path) || path.startsWith("\\")) return true; const inside = relative(folder, resolve(base, path)); return ( @@ -447,7 +451,7 @@ function percentDecoded(value: string): string { /** Paths are walked as latin1 strings, one character per byte, and opened by those bytes. */ const asBytes = (path: string): string => Buffer.from(path).toString("latin1"); -/** A nested name that is not there: ffmpeg would open nothing by it, but the walk may have computed the wrong name. */ +/** A nested name that is not there: ffmpeg opens nothing by it. An entry naming nothing that is there is refused. */ const MISSING = Symbol("missing"); type Verdict = boolean | typeof MISSING; @@ -494,19 +498,51 @@ function isId3Header(head: Buffer): boolean { ); } +const id3End = (head: Buffer, offset: number): number => + offset + 10 + ((head[6]! << 21) | (head[7]! << 14) | (head[8]! << 7) | head[9]!); + /** Where the text starts: ffmpeg skips leading ID3v2 tags before it probes or parses a file. -1 past {@link MAX_ID3_TAGS}. */ async function textStart(fh: FileHandle, first: Buffer): Promise { let offset = 0; let head = first; for (let tags = 0; tags <= MAX_ID3_TAGS; tags++) { if (!isId3Header(head)) return offset; - const size = (head[6]! << 21) | (head[7]! << 14) | (head[8]! << 7) | head[9]!; - offset += 10 + size + (head[5]! & 0x10 ? 10 : 0); + offset = id3End(head, offset) + (head[5]! & 0x10 ? 10 : 0); head = await readAt(fh, 10, offset); } return -1; } +const MAX_TEXT_STARTS = 64; + +/** Every offset a list may be read from: ffmpeg's probe counts a tag's footer, its demuxer only for a clean v2.4 tag. */ +async function textStarts(fh: FileHandle, first: Buffer): Promise { + const starts = new Set(); + let tagged = [0]; + for (let tags = 0; tagged.length > 0; tags++) { + if (tags > MAX_ID3_TAGS || tagged.length + starts.size > MAX_TEXT_STARTS) return null; + tagged = await pastTags(fh, first, tagged, starts); + } + return [...starts]; +} + +async function pastTags( + fh: FileHandle, + first: Buffer, + offsets: number[], + starts: Set, +): Promise { + const next = new Set(); + for (const offset of offsets) { + const head = offset === 0 ? first : await readAt(fh, 10, offset); + if (!isId3Header(head)) starts.add(offset); + else for (const footer of footers(head)) next.add(id3End(head, offset) + footer); + } + return [...next]; +} + +const footers = (head: Buffer): number[] => (head[5]! & 0x10 ? [0, 10] : [0]); + // Encrypted segments and keys open with random bytes, so only a real document signature counts. const MANIFEST_SIGNATURE = /^<(\?xml|MPD\b|!DOCTYPE|html\b|SmoothStreamingMedia\b)/i; @@ -527,18 +563,31 @@ async function readList(path: string, nested: boolean): Promise MAX_PLAYLIST_BYTES ? true : body.toString("latin1"); + return await listText(fh, nested); } finally { await fh.close().catch(() => {}); } } +async function listText(fh: FileHandle, nested: boolean): Promise { + const first = await readAt(fh, SNIFF_BYTES, 0); + const starts = await textStarts(fh, first); + if (!starts) return true; + // ffmpeg's probe and demuxer can read a tagged list from different bytes, so a list behind a tag is refused. + if (starts.length > 1 || starts[0] !== 0) return (await taggedList(fh, starts, nested)) || null; + if (!startsAsPlaylist(first)) return nested && opensAsManifest(first) ? true : null; + const body = await readAt(fh, MAX_PLAYLIST_BYTES + 1, 0); + return body.length > MAX_PLAYLIST_BYTES ? true : body.toString("latin1"); +} + +async function taggedList(fh: FileHandle, starts: number[], nested: boolean): Promise { + for (const start of starts) { + const head = await readAt(fh, SNIFF_BYTES, start); + if (startsAsPlaylist(head) || (nested && opensAsManifest(head))) return true; + } + return false; +} + const isMissing = (error: unknown): boolean => ["ENOENT", "ENOTDIR", "ENAMETOOLONG"].includes( (error as NodeJS.ErrnoException | null)?.code ?? "",