diff --git a/doc/api/errors.md b/doc/api/errors.md index 6948ada70cf..b9287936e79 100644 --- a/doc/api/errors.md +++ b/doc/api/errors.md @@ -3263,6 +3263,61 @@ An unspecified or non-specific system error has occurred within the Node.js process. The error object will have an `err.info` object property with additional details. + + +### `ERR_TAR_INVALID_ARCHIVE` + + + +Data that was expected to be a tar archive ends before the end of an entry, or +its compressed form could not be decompressed. + + + +### `ERR_TAR_INVALID_ENTRY` + + + +The header of a tar archive entry has an invalid checksum or an invalid size, +or a pax extended header exceeds the `maxMetaSize` option. The parser skips +such entries and reports them through the `onwarn` option, unless the `strict` +option is set. + +Also thrown when a tar archive is written, for an entry with an invalid field, +or one whose content does not have the size that the entry declares. + + + +### `ERR_TAR_UNSAFE_ENTRY` + + + +A tar archive entry was not extracted because doing so could write outside of +the extraction directory: its path contains `..` or a null byte, is deeper +than the `maxDepth` option, goes through a symbolic link, or would replace the +extraction directory itself. See [`zlib.extractTar()`][]. + + + +### `ERR_TAR_UNSUPPORTED_FEATURE` + + + +A tar archive uses a feature outside of what this implementation supports: +bzip2 or xz compression, or, when extracting, an entry that is not a file, a +directory, a symbolic link or a hard link. Also thrown when a tar archive is +written, for an entry of a type that cannot be written, and by +`zlib.tarFiles()` for what is not a regular file, a directory or a symbolic +link. + ### `ERR_TEST_FAILURE` @@ -4914,6 +4969,7 @@ An error occurred trying to allocate memory. This should never happen. [`util.parseArgs()`]: util.md#utilparseargsconfig [`v8.startupSnapshot.setDeserializeMainFunction()`]: v8.md#v8startupsnapshotsetdeserializemainfunctioncallback-data [`vfs.mount()`]: vfs.md#vfsmount +[`zlib.extractTar()`]: zlib.md#zlibextracttarsource-options [`zlib`]: zlib.md [crypto digest algorithm]: crypto.md#cryptogethashes [debugger]: debugger.md diff --git a/doc/api/zlib.md b/doc/api/zlib.md index 926d2ad76fa..14f5cd1593c 100644 --- a/doc/api/zlib.md +++ b/doc/api/zlib.md @@ -1009,6 +1009,468 @@ changes: Decompress a raw deflate stream. +## Class: `zlib.TarEntry` + + + +> Stability: 1.0 - Early development + +The tar archive API is experimental. Using any part of it (this class among +them) emits an experimental warning the first time; merely importing +`node:zlib` does not. + +An entry of a tar archive, as passed to the callbacks of [`zlib.TarParser`][], +[`zlib.listTar()`][] and [`zlib.extractTar()`][], and as yielded by +[`zlib.tarEntries()`][]. The static methods of this class create the entries +that [`zlib.createTarArchive()`][] writes. + +The v7, ustar, pax and GNU formats are understood. Pax extended headers and GNU +long names are not entries of their own: they are already applied to the entry +that they describe. + +### Static method: `zlib.TarEntry.create(path, data[, options])` + + + +* `path` {string} The path of the entry within the archive. A trailing `/` + makes a directory entry. +* `data` {Buffer|TypedArray|DataView|ArrayBuffer} The whole content of the + entry. Must be empty when `path` names a directory. +* `options` {Object} + * `mode` {integer} The permission bits. **Default:** `0o644` (`0o755` for + directories). + * `mtime` {Date} The modification time. It is written in whole seconds. + **Default:** the current time. + * `uid` {integer} The numeric user id of the owner. **Default:** `0`. + * `gid` {integer} The numeric group id of the owner. **Default:** `0`. + * `uname` {string} The user name of the owner. **Default:** `''`. + * `gname` {string} The group name of the owner. **Default:** `''`. +* Returns: {TarEntry} + +Creates the entry of a file or of a directory. There is no asynchronous work +to do, such as compressing the content, so there is no `Promise`-returning +variant. + +The entry keeps a view of `data`, not a copy: do not change `data` before the +archive is written. An entry created this way can be written to more than one +archive. + +### Static method: `zlib.TarEntry.createLink(path, target[, options])` + + + +* `path` {string} The path of the entry within the archive. +* `target` {string} The path, within the archive, of the entry to link to. +* `options` {Object} See [`zlib.TarEntry.create()`][]. The default `mode` is + `0o644`. +* Returns: {TarEntry} + +Creates the entry of a hard link. The entry that `target` names must come +earlier in the archive, for the link to be created when the archive is +extracted. + +### Static method: `zlib.TarEntry.createStream(path, source, options)` + + + +* `path` {string} The path of the entry within the archive. Must not end with + `/`. +* `source` {AsyncIterable|Iterable} Yields the content of the entry, as + `Uint8Array` chunks. +* `options` {Object} + * `size` {integer} The number of bytes that `source` yields. Required. + * `mode`, `mtime`, `uid`, `gid`, `uname`, `gname`: see + [`zlib.TarEntry.create()`][]. +* Returns: {TarEntry} + +Creates the entry of a file whose content is read from `source` when the +archive is written, without buffering it in memory. In a tar archive the size +of an entry is written before its content, so it must be known up front. +[`zlib.createTarArchive()`][] fails with an [`ERR_TAR_INVALID_ENTRY`][] error +when `source` yields more or fewer bytes than `size`. + +`source` is read once: such an entry can be written to one archive only. +[`zlib.createTarArchiveSync()`][] accepts it only if `source` is a synchronous +`Iterable`. + +Because `source` may hold an operating system resource (a file read stream, +say), the entry is disposable: its `Symbol.dispose` and `Symbol.asyncDispose` +methods destroy `source` if it was not read. An entry given to an archive is +disposed of by that archive (see [`zlib.createTarArchive()`][]); dispose of an +entry directly only when it was created but never given to one. Disposing of +any other kind of entry does nothing. + +### Static method: `zlib.TarEntry.createSymlink(path, target[, options])` + + + +* `path` {string} The path of the entry within the archive. +* `target` {string} The target of the symbolic link. +* `options` {Object} See [`zlib.TarEntry.create()`][]. The default `mode` is + `0o777`. +* Returns: {TarEntry} + +Creates the entry of a symbolic link. `target` is stored as is: when the +archive is read, treat it as untrusted. + +### `tarEntry.atime` + + + +* Type: {Date|null} + +The access time of the entry, or `null` when the archive does not record it. +Only pax and GNU archives can. + +### `tarEntry.body` + + + +* Type: {Object|null} + +The content of the entry. It is only set on the entries yielded by +[`zlib.tarEntries()`][], and is `null` everywhere else. The object is async +iterable, yielding {Buffer} chunks, and has the following members: + +* `buffer()` Returns: {Promise} Fulfills with the whole content as a + {Buffer}. +* `text([encoding])` Returns: {Promise} Fulfills with the whole content as a + string, decoded with `encoding`. **Default:** `'utf8'`. +* `skip()` Returns: {Promise} Fulfills once the rest of the content has been + skipped. +* `done` {boolean} `true` once the content has been read, or skipped, to its + end. + +The content can be read only once: a second call to `buffer()` or `text()`, or +a second iteration, rejects with [`ERR_INVALID_STATE`][]. + +### `tarEntry.ctime` + + + +* Type: {Date|null} + +The status change time of the entry, or `null` when the archive does not +record it. + +### `tarEntry.devmajor` + + + +* Type: {number} + +The major device number of a `'CharacterDevice'` or `'BlockDevice'` entry, and +`0` for any other type. + +### `tarEntry.devminor` + + + +* Type: {number} + +The minor device number of a `'CharacterDevice'` or `'BlockDevice'` entry, and +`0` for any other type. + +### `tarEntry.gid` + + + +* Type: {number} + +The numeric identifier of the group that owns the entry. + +### `tarEntry.gname` + + + +* Type: {string} + +The name of the group that owns the entry, or `''`. + +### `tarEntry.linkpath` + + + +* Type: {string} + +The target of a `'SymbolicLink'` or `'Link'` entry, and `''` for any other +type. The target of a `'Link'` (a hard link) is the path of another entry of +the archive. + +### `tarEntry.mode` + + + +* Type: {number} + +The permission bits of the entry. + +### `tarEntry.mtime` + + + +* Type: {Date|null} + +The modification time of the entry, or `null` when the archive holds a value +that a `Date` cannot represent. + +### `tarEntry.offset` + + + +* Type: {number} + +The position of the header of the entry in the (uncompressed) archive, in +bytes. The content of the entry starts 512 bytes later. + +### `tarEntry.path` + + + +* Type: {string} + +The path of the entry, exactly as the archive stores it: it may be absolute, +contain `..` components, or end with a `/`. Never use it to build a file system +path without checking it. [`zlib.extractTar()`][] does those checks. + +### `tarEntry.pax` + + + +* Type: {Object|null} + +The pax extended header records that apply to the entry, global ones included, +as an object without `Object.prototype` in its prototype chain, whose values +are strings. `null` when there are none. + +### `tarEntry.size` + + + +* Type: {number} + +The size of the content of the entry, in bytes. + +### `tarEntry.type` + + + +* Type: {string} + +The type of the entry: `'File'`, `'Directory'`, `'SymbolicLink'`, `'Link'` +(a hard link), `'CharacterDevice'`, `'BlockDevice'`, `'FIFO'`, +`'ContiguousFile'`, one of the less common `'SolarisACL'`, `'GNUDumpDir'`, +`'Inode'`, `'ContinuationFile'`, `'OldGnuLongPath'`, `'SparseFile'` and +`'TapeVolumeHeader'`, or `'Unsupported'` for anything else. + +### `tarEntry.uid` + + + +* Type: {number} + +The numeric identifier of the user that owns the entry. + +### `tarEntry.uname` + + + +* Type: {string} + +The name of the user that owns the entry, or `''`. + +## Class: `zlib.TarParser` + + + +> Stability: 1.0 - Early development + +The tar archive API is experimental. Using any part of it (this class among +them) emits an experimental warning the first time; merely importing +`node:zlib` does not. + +The push parser that the rest of the tar archive API is built on. It does no +I/O, does not decompress, and creates no streams: it is fed chunks of an +uncompressed archive with [`tarParser.write()`][], and calls back +synchronously for what it finds in them. + +```mjs +import { TarParser } from 'node:zlib'; +import { readFileSync } from 'node:fs'; + +const parser = new TarParser({ + onentry(entry) { + console.log(entry.path, entry.size); + // Only the content of package.json is wanted. + return entry.path === 'package/package.json'; + }, + ondata(chunk, entry) { + console.log(chunk.toString()); + }, +}); +parser.write(readFileSync('package.tar')); +parser.end(); +``` + +```cjs +const { TarParser } = require('node:zlib'); +const { readFileSync } = require('node:fs'); + +const parser = new TarParser({ + onentry(entry) { + console.log(entry.path, entry.size); + // Only the content of package.json is wanted. + return entry.path === 'package/package.json'; + }, + ondata(chunk, entry) { + console.log(chunk.toString()); + }, +}); +parser.write(readFileSync('package.tar')); +parser.end(); +``` + +### `new zlib.TarParser([options])` + + + +* `options` {Object} + * `onentry` {Function} Called with each {TarEntry}. Return `false` to skip + the content of the entry. + * `ondata` {Function} Called with a {Buffer} and the {TarEntry} it belongs + to, for each part of the content of an entry that was not skipped. The + buffer is a view of the chunk given to [`tarParser.write()`][]: copy it to + keep it past the call if the chunk may be reused. Without this callback, + the content of every entry is skipped. + * `onentryend` {Function} Called with the {TarEntry}, after the last part of + its content. It is not called for the entries that were skipped. + * `onwarn` {Function} Called with an {Error} for each problem that the parser + recovers from, such as a header with an invalid checksum + ([`ERR_TAR_INVALID_ENTRY`][]). + * `strict` {boolean} Throw those errors instead. **Default:** `false`. + * `maxMetaSize` {integer} The largest pax extended header or GNU long name + that is kept in memory, in bytes. Larger ones are skipped, with a warning. + **Default:** `1048576` (1 MiB). + +Errors thrown by the callbacks are thrown by [`tarParser.write()`][]. The +parser must not be used after it has thrown. + +### `tarParser.done` + + + +* Type: {boolean} + +`true` once the end of the archive has been found: its end marker, or the end +of the input. What is written afterwards is ignored. + +### `tarParser.end()` + + + +Tells the parser that there is no more input. Throws +[`ERR_TAR_INVALID_ARCHIVE`][] if the archive is truncated. A missing end +marker, and missing padding after the last entry, are accepted. + +### `tarParser.skip(n)` + + + +* `n` {integer} A number of bytes, at most [`tarParser.skippable`][]. + +Tells the parser that the next `n` bytes of the archive will not be written, +because the source of the archive moved past them. + +### `tarParser.skipBody()` + + + +* Returns: {boolean} `false` if no content is being delivered. + +Skips the rest of the content of the entry that is being delivered. `ondata` +and `onentryend` are not called for it anymore. + +### `tarParser.skippable` + + + +* Type: {number} + +The number of bytes that the parser would ignore if they were written next: +what is left of the content of a skipped entry, and its padding. A source that +can seek, such as a file, can jump over them instead of reading them, and call +[`tarParser.skip()`][]. + +### `tarParser.write(chunk)` + + + +* `chunk` {Buffer|TypedArray|DataView} The next part of the uncompressed + archive, of any size. + +Parses `chunk`, calling the callbacks. The parser copies what it needs to keep +between calls, so `chunk` can be reused once the call returns. + ## Class: `zlib.Unzip` + +> Stability: 1.0 - Early development + +The tar archive API is experimental. Using any part of it (this function among +them) emits an experimental warning the first time; merely importing +`node:zlib` does not. + +* `entries` {Iterable|AsyncIterable} of [`TarEntry`][]. +* Returns: {stream.Readable} A byte stream of the archive. + +Writes `entries` to a tar archive. The archive is not compressed: pipe it +through [`zlib.createGzip()`][], for example, to make a `.tar.gz` file. + +```mjs +import { createWriteStream } from 'node:fs'; +import { pipeline } from 'node:stream/promises'; +import { Buffer } from 'node:buffer'; +import { TarEntry, createGzip, createTarArchive } from 'node:zlib'; + +const entries = [ + TarEntry.create('pkg/', Buffer.alloc(0)), + TarEntry.create('pkg/hello.txt', Buffer.from('Hello, world!')), + TarEntry.createSymlink('pkg/link', 'hello.txt'), +]; +await pipeline( + createTarArchive(entries), + createGzip(), + createWriteStream('archive.tar.gz'), +); +``` + +```cjs +const { createWriteStream } = require('node:fs'); +const { pipeline } = require('node:stream/promises'); +const { TarEntry, createGzip, createTarArchive } = require('node:zlib'); + +const entries = [ + TarEntry.create('pkg/', Buffer.alloc(0)), + TarEntry.create('pkg/hello.txt', Buffer.from('Hello, world!')), + TarEntry.createSymlink('pkg/link', 'hello.txt'), +]; +pipeline( + createTarArchive(entries), + createGzip(), + createWriteStream('archive.tar.gz'), +); +``` + +Entries are written in iteration order, as ustar headers. What such a header +cannot hold is written to a pax extended header before it: a path that is too +long or not ASCII, a size of 8 GiB or more, large user and group ids, and +modification times before 1970. Nothing deduplicates paths, and nothing +creates the entries of the parent directories of an entry. + +The fields of an entry can be changed before it is written, and are checked +then. The entries that [`zlib.tarEntries()`][] yields can be written too, as +long as their [`tarEntry.body`][] was not read. This rewrites an archive +without holding it in memory: + +```mjs +import { createWriteStream } from 'node:fs'; +import { pipeline } from 'node:stream/promises'; +import { createTarArchive, tarEntries } from 'node:zlib'; + +async function* withoutTests() { + for await (const entry of tarEntries('package.tgz')) { + if (!entry.path.startsWith('package/test/')) yield entry; + } +} +await pipeline(createTarArchive(withoutTests()), createWriteStream('small.tar')); +``` + +The entries are owned by the returned stream, and must not be reused, except +for the ones that hold their data (see [`zlib.TarEntry.create()`][]). If the +stream is destroyed before its end, or fails, it destroys the source of the +entry that it was writing, and disposes of every entry that is still queued, +so that no file descriptor leaks. An `AsyncIterable` of entries is closed +instead (its `return()` method is called), without being read any further. + +## `zlib.createTarArchiveSync(entries)` + + + +> Stability: 1.0 - Early development + +The tar archive API is experimental. Using any part of it (this function among +them) emits an experimental warning the first time; merely importing +`node:zlib` does not. + +* `entries` {Iterable} of [`TarEntry`][]. +* Returns: {Iterator} of the {Buffer} chunks of the archive. + +The synchronous version of [`zlib.createTarArchive()`][]. An entry created +with [`zlib.TarEntry.createStream()`][] is accepted only if its source is a +synchronous `Iterable`; otherwise an [`ERR_INVALID_STATE`][] error is thrown +when its turn comes. + +```cjs +const { writeFileSync } = require('node:fs'); +const { TarEntry, createTarArchiveSync } = require('node:zlib'); + +const chunks = createTarArchiveSync([ + TarEntry.create('hello.txt', Buffer.from('Hello, world!')), +]); +writeFileSync('archive.tar', Buffer.concat([...chunks])); +``` + +As with [`zlib.createTarArchive()`][], the entries are owned by the returned +iterator: if the iteration stops early, the entry that stopped it and the +ones that are still queued are disposed of. + +## `zlib.createTarExtractStream([options])` + + + +> Stability: 1.0 - Early development + +The tar archive API is experimental. Using any part of it (this function among +them) emits an experimental warning the first time; merely importing +`node:zlib` does not. + +* `options` {Object} The options of [`zlib.extractTar()`][]. Brotli is not + detected: set `compression` to `'brotli'` for it. +* Returns: {stream.Writable} + +Creates a writable stream that extracts the archive written to it. It finishes +once everything has been written to the file system, and is destroyed with the +error if the extraction fails. + +```mjs +import { createTarExtractStream } from 'node:zlib'; +import { pipeline } from 'node:stream/promises'; + +const response = await fetch('https://example.org/archive.tar.gz'); +await pipeline(response.body, createTarExtractStream({ cwd: 'out' })); +``` + +```cjs +const { createTarExtractStream } = require('node:zlib'); +const { pipeline } = require('node:stream/promises'); + +(async () => { + const response = await fetch('https://example.org/archive.tar.gz'); + await pipeline(response.body, createTarExtractStream({ cwd: 'out' })); +})(); +``` + ## `zlib.createUnzip([options])` + +> Stability: 1.0 - Early development + +The tar archive API is experimental. Using any part of it (this function among +them) emits an experimental warning the first time; merely importing +`node:zlib` does not. + +* `source` {string|URL|Buffer|TypedArray|DataView|ArrayBuffer|Blob|ReadableStream|Iterable|AsyncIterable} + The archive. A string or a {URL} is the path of an archive file. Anything + else is the content of the archive: all of it, or its chunks, as an iterable + or an async iterable such as a {stream.Readable}. +* `options` {Object} + * `cwd` {string|URL} The directory to extract into. It is created if needed. + **Default:** `process.cwd()`. + * `compression` {string|boolean} `'gzip'`, `'zstd'` or `'brotli'` to + decompress the archive, `true` for gzip, or `false` for an archive that is + not compressed. **Default:** detected: gzip and zstd from the first bytes + of the archive, brotli from a `source` path ending with `.br` or `.tbr`. + * `strip` {integer} The number of leading path components to remove from + the entry paths. Entries with fewer components are not extracted. + **Default:** `0`. + * `filter` {Function} Called with the path and the {TarEntry} of each entry. + Return `false` to leave the entry out. + * `onentry` {Function} Called with each {TarEntry} that passed the filter, + before it is extracted. + * `onwarn` {Function} Called with an {Error} and, when there is one, the + {TarEntry} that it is about, for each problem that does not stop the + extraction. See below. + * `strict` {boolean} Fail on those problems instead. **Default:** `false`. + * `keep` {boolean} Do not replace the files that already exist. + **Default:** `false`. + * `newer` {boolean} Replace the files that already exist only when the entry + is newer. **Default:** `false`. + * `noMtime` {boolean} Do not set the modification times from the archive. + **Default:** `false`. + * `preserveOwner` {boolean} Set the owner of what is extracted from the + numeric identifiers in the archive. **Default:** `true` when the process + runs as root, `false` otherwise. + * `uid` {integer} Set this user as the owner of everything that is extracted. + * `gid` {integer} Set this group as the owner of everything that is + extracted. + * `chmod` {boolean} Set the modes exactly as `umask` gives them, rather than + letting the umask of the process apply. **Default:** `false`. + * `umask` {integer|string} The bits to remove from the modes. + **Default:** `process.umask()`. + * `fmode` {integer|string} The mode of the files whose entry has none. + **Default:** `0o666`. + * `dmode` {integer|string} The mode of the directories whose entry has none, + and of the directories that no entry describes. **Default:** `0o777`. + * `maxDepth` {number} The deepest path that is extracted, in components. + **Default:** `1024`. + * `preservePaths` {boolean} Allow absolute paths, `..` components and + extraction through symbolic links. Never set it for an archive that is not + trusted. **Default:** `false`. + * `maxMetaSize` {integer} See [`new zlib.TarParser()`][]. + * `jobs` {integer} The most files that are written at the same time. + **Default:** `64`. + * `highWaterMark` {integer} How much file content may wait in memory to be + written, in bytes, before the archive stops being read. + **Default:** `33554432` (32 MiB). +* Returns: {Promise} Fulfills with `undefined` once the archive is extracted. + +Extracts a tar archive into a directory. Regular files, directories, symbolic +links and hard links are extracted; entries of any other type are reported +with [`ERR_TAR_UNSUPPORTED_FEATURE`][] and left out. What already exists at +the path of an entry is replaced, unless `keep` or `newer` says otherwise. + +```mjs +import { extractTar } from 'node:zlib'; + +// The compression is detected. +await extractTar('package.tgz', { cwd: 'out', strip: 1 }); + +// From a stream. +const response = await fetch('https://example.org/archive.tar.zst'); +await extractTar(response.body, { + cwd: 'out', + filter: (path) => !path.endsWith('.map'), + onwarn: (err, entry) => console.warn(entry?.path, err.message), +}); +``` + +```cjs +const { extractTar } = require('node:zlib'); + +(async () => { + // The compression is detected. + await extractTar('package.tgz', { cwd: 'out', strip: 1 }); + + // From a stream. + const response = await fetch('https://example.org/archive.tar.zst'); + await extractTar(response.body, { + cwd: 'out', + filter: (path) => !path.endsWith('.map'), + onwarn: (err, entry) => console.warn(entry?.path, err.message), + }); +})(); +``` + +Archives are untrusted input. Unless `preservePaths` is set, extraction never +writes outside of `cwd`: + +* entries whose path contains a `..` component are not extracted + ([`ERR_TAR_UNSAFE_ENTRY`][]), and absolute paths are made relative to `cwd`; +* nothing is written through a symbolic link, whether the archive made it or it + was there before: files are created exclusively (an existing file, link or + symbolic link is removed first), and every directory on the way to an entry + must be a real directory; +* hard links to a target outside of `cwd`, or to a target reached through a + symbolic link, are not made; +* paths deeper than `maxDepth` are not extracted. + +Symbolic links are made with the target that the archive gives, which can be +anywhere: what reads the extracted tree afterwards has to take that into +account. The sizes of the entries are not bounded either. Use `filter` to +enforce a policy on them. + +A problem with one entry (an unsafe path, an unsupported type, a file system +error) does not stop the extraction: it is passed to `onwarn`, and the +extraction goes on with the next entry. With `strict`, the first such problem +rejects the promise instead; an absolute path that was made relative is the +exception, and is still only passed to `onwarn`. A truncated or corrupt archive +always rejects with [`ERR_TAR_INVALID_ARCHIVE`][]. In both cases, what was +extracted before the failure is left in place. + +The archive is decompressed and parsed on the main thread, in slices, while the +file system operations run concurrently in the libuv thread pool. The order of +the entries is kept wherever it matters, so the result is the same as +extracting them one after the other. + +## `zlib.extractTarSync(source[, options])` + + + +> Stability: 1.0 - Early development + +The tar archive API is experimental. Using any part of it (this function among +them) emits an experimental warning the first time; merely importing +`node:zlib` does not. + +* `source` {string|URL|Buffer|TypedArray|DataView|ArrayBuffer|Iterable} The + archive. A string or a {URL} is the path of an archive file. Anything else + is the content of the archive: all of it, or an iterable of its chunks. +* `options` {Object} The options of [`zlib.extractTar()`][], except `jobs` and + `highWaterMark`. + +The synchronous version of [`zlib.extractTar()`][], with the same guarantees. +Problems that stop the extraction are thrown. As with the synchronous +`node:fs` APIs, it blocks the Node.js event loop until the archive is +extracted. + +```mjs +import { extractTarSync } from 'node:zlib'; + +extractTarSync('archive.tar', { cwd: 'out' }); +``` + +```cjs +const { extractTarSync } = require('node:zlib'); + +extractTarSync('archive.tar', { cwd: 'out' }); +``` + ## `zlib.getMaxZipContentSize()` + +> Stability: 1.0 - Early development + +The tar archive API is experimental. Using any part of it (this function among +them) emits an experimental warning the first time; merely importing +`node:zlib` does not. + +* `source` {string|URL|Buffer|TypedArray|DataView|ArrayBuffer|Blob|ReadableStream|Iterable|AsyncIterable} + The archive. See [`zlib.extractTar()`][]. +* `options` {Object} + * `compression` {string|boolean} See [`zlib.extractTar()`][]. + * `filter` {Function} Called with the path and the {TarEntry} of each entry. + Return `false` to leave the entry out. + * `onentry` {Function} Called with each {TarEntry} that passed the filter, + as it is found. When it is given, the entries are not collected. + * `onwarn` {Function} Called with an {Error} for each problem that the + parser recovers from. See [`new zlib.TarParser()`][]. + * `strict` {boolean} Reject on those problems instead. **Default:** `false`. + * `maxMetaSize` {integer} See [`new zlib.TarParser()`][]. +* Returns: {Promise} Fulfills with a {TarEntry\[]}, or with `undefined` when + `onentry` is given. + +Lists the entries of a tar archive, without reading their content. When +`source` is the path of an archive that is not compressed, the content of the +entries is not even read from the file. + +```mjs +import { listTar } from 'node:zlib'; + +for (const entry of await listTar('archive.tar.gz')) { + console.log(entry.type, entry.size, entry.path); +} +``` + +```cjs +const { listTar } = require('node:zlib'); + +(async () => { + for (const entry of await listTar('archive.tar.gz')) { + console.log(entry.type, entry.size, entry.path); + } +})(); +``` + +## `zlib.listTarSync(source[, options])` + + + +> Stability: 1.0 - Early development + +The tar archive API is experimental. Using any part of it (this function among +them) emits an experimental warning the first time; merely importing +`node:zlib` does not. + +* `source` {string|URL|Buffer|TypedArray|DataView|ArrayBuffer|Iterable} The + archive. See [`zlib.extractTarSync()`][]. +* `options` {Object} The options of [`zlib.listTar()`][]. +* Returns: {TarEntry\[]|undefined} `undefined` when `onentry` is given. + +The synchronous version of [`zlib.listTar()`][]. + ## `zlib.setMaxZipContentSize(size)` + +> Stability: 1.0 - Early development + +The tar archive API is experimental. Using any part of it (this function among +them) emits an experimental warning the first time; merely importing +`node:zlib` does not. + +* `source` {string|URL|Buffer|TypedArray|DataView|ArrayBuffer|Blob|ReadableStream|Iterable|AsyncIterable} + The archive. See [`zlib.extractTar()`][]. +* `options` {Object} + * `compression` {string|boolean} See [`zlib.extractTar()`][]. + * `filter` {Function} Called with the path and the {TarEntry} of each entry. + Return `false` to leave the entry out. + * `onwarn` {Function} Called with an {Error} for each problem that the + parser recovers from. See [`new zlib.TarParser()`][]. + * `strict` {boolean} Fail on those problems instead. **Default:** `false`. + * `maxMetaSize` {integer} See [`new zlib.TarParser()`][]. +* Returns: {AsyncIterator} of {TarEntry}, each with its + [`body`][`tarEntry.body`]. + +Reads the entries of a tar archive one at a time, with their content. The +archive is read as the iteration goes on, and no further than needed: the +content of an entry has to be read before asking for the next entry, and what +is left unread is skipped. + +```mjs +import { tarEntries } from 'node:zlib'; + +for await (const entry of tarEntries('package.tgz')) { + if (entry.path === 'package/package.json') { + console.log(JSON.parse(await entry.body.text()).version); + break; + } +} +``` + +```cjs +const { tarEntries } = require('node:zlib'); + +(async () => { + for await (const entry of tarEntries('package.tgz')) { + if (entry.path === 'package/package.json') { + console.log(JSON.parse(await entry.body.text()).version); + break; + } + } +})(); +``` + +Leaving the loop early, as above, stops reading the archive and releases it. +An iterator that is driven by hand has to be closed with its `return()` method +for that, unless it is run to its end. + +## `zlib.tarFiles(files[, options])` + + + +> Stability: 1.0 - Early development + +The tar archive API is experimental. Using any part of it (this function among +them) emits an experimental warning the first time; merely importing +`node:zlib` does not. + +* `files` {Iterable|AsyncIterable} of `[sourcePath, entryPath]` pairs: an + array, a `Map`, the result of `Object.entries()`, a generator, and so on. +* `options` {Object} + * `followSymlinks` {boolean} When `true`, a symbolic link is archived as the + file or directory that it points to. When `false`, it is archived as a + symbolic link. **Default:** `true`. +* Returns: {stream.Readable} A byte stream of the archive. + +Creates an archive from files on disk, with [`zlib.createTarArchive()`][]. +Each entry records the permission bits, the modification time and the numeric +owner of its file. The content of a regular file is streamed, not buffered in +memory. A directory becomes a directory entry: what it contains is not added, +so list every file to archive. + +Anything other than a regular file, a directory or a symbolic link (a FIFO or +a device, for example) fails the archive with an +[`ERR_TAR_UNSUPPORTED_FEATURE`][] error. So does a file that gets shorter +while it is read, with an [`ERR_TAR_INVALID_ENTRY`][] error; a file that grows +is archived up to the size that it had when it was opened. + +```mjs +import { createWriteStream } from 'node:fs'; +import { pipeline } from 'node:stream/promises'; +import { createGzip, tarFiles } from 'node:zlib'; + +await pipeline( + tarFiles([ + ['./build', 'app'], + ['./build/index.js', 'app/index.js'], + ['./README.md', 'app/README.md'], + ]), + createGzip(), + createWriteStream('app.tar.gz'), +); +``` + ## Convenience methods @@ -3552,6 +4514,10 @@ Create a Zstandard decompression transform. [`DeflateRaw`]: #class-zlibdeflateraw [`Deflate`]: #class-zlibdeflate [`ERR_INVALID_STATE`]: errors.md#err_invalid_state +[`ERR_TAR_INVALID_ARCHIVE`]: errors.md#err_tar_invalid_archive +[`ERR_TAR_INVALID_ENTRY`]: errors.md#err_tar_invalid_entry +[`ERR_TAR_UNSAFE_ENTRY`]: errors.md#err_tar_unsafe_entry +[`ERR_TAR_UNSUPPORTED_FEATURE`]: errors.md#err_tar_unsupported_feature [`ERR_ZIP_ARCHIVE_TOO_LARGE`]: errors.md#err_zip_archive_too_large [`ERR_ZIP_ENTRY_CORRUPT`]: errors.md#err_zip_entry_corrupt [`ERR_ZIP_ENTRY_NOT_FOUND`]: errors.md#err_zip_entry_not_found @@ -3563,6 +4529,7 @@ Create a Zstandard decompression transform. [`Gzip`]: #class-zlibgzip [`InflateRaw`]: #class-zlibinflateraw [`Inflate`]: #class-zlibinflate +[`TarEntry`]: #class-zlibtarentry [`Unzip`]: #class-zlibunzip [`ZipBuffer`]: #class-zlibzipbuffer [`ZipEntry`]: #class-zlibzipentry @@ -3572,11 +4539,16 @@ Create a Zstandard decompression transform. [`ZstdDecompress`]: #class-zlibzstddecompress [`buffer.kMaxLength`]: buffer.md#bufferkmaxlength [`deflateInit2` and `inflateInit2`]: https://zlib.net/manual.html#Advanced +[`new zlib.TarParser()`]: #new-zlibtarparseroptions [`node:stream/iter`]: stream_iter.md [`pipeTo()`]: stream_iter.md#pipetosource-transforms-writer-options [`pipeline()`]: stream.md#streampipelinesource-transforms-destination-callback [`pull()`]: stream_iter.md#pullsource-transforms-options [`stream.Transform`]: stream.md#class-streamtransform +[`tarEntry.body`]: #tarentrybody +[`tarParser.skip()`]: #tarparserskipn +[`tarParser.skippable`]: #tarparserskippable +[`tarParser.write()`]: #tarparserwritechunk [`zipBuffer.add()`]: #zipbufferaddfilename-data-options [`zipBuffer.addSync()`]: #zipbufferaddsyncfilename-data-options [`zipBuffer.comment`]: #zipbuffercomment @@ -3605,15 +4577,25 @@ Create a Zstandard decompression transform. [`zipFile.get()`]: #zipfilegetname [`zipFile.stream()`]: #zipfilestreamname-options [`zipFile.values()`]: #zipfilevalues +[`zlib.TarEntry.create()`]: #static-method-zlibtarentrycreatepath-data-options +[`zlib.TarEntry.createStream()`]: #static-method-zlibtarentrycreatestreampath-source-options +[`zlib.TarParser`]: #class-zlibtarparser [`zlib.ZipEntry.create()`]: #static-method-zlibzipentrycreatefilename-data-options [`zlib.ZipEntry.createStream()`]: #static-method-zlibzipentrycreatestreamfilename-source-options [`zlib.ZipEntry.createSymlink()`]: #static-method-zlibzipentrycreatesymlinkfilename-target-options [`zlib.ZipEntry.createSync()`]: #static-method-zlibzipentrycreatesyncfilename-data-options [`zlib.ZipFile.open()`]: #static-method-zlibzipfileopenfilename-options [`zlib.crc32()`]: #zlibcrc32data-value +[`zlib.createGzip()`]: #zlibcreategzipoptions +[`zlib.createTarArchive()`]: #zlibcreatetararchiveentries +[`zlib.createTarArchiveSync()`]: #zlibcreatetararchivesyncentries [`zlib.createZipArchive()`]: #zlibcreateziparchiveentries-options [`zlib.createZipArchiveSync()`]: #zlibcreateziparchivesyncentries-options +[`zlib.extractTar()`]: #zlibextracttarsource-options +[`zlib.extractTarSync()`]: #zlibextracttarsyncsource-options [`zlib.getMaxZipContentSize()`]: #zlibgetmaxzipcontentsize +[`zlib.listTar()`]: #zliblisttarsource-options +[`zlib.tarEntries()`]: #zlibtarentriessource-options [`zlib.zstdCompress()`]: #zlibzstdcompressbuffer-options-callback [convenience methods]: #convenience-methods [zlib documentation]: https://zlib.net/manual.html#Constants diff --git a/doc/type-map.json b/doc/type-map.json index c6ba3940258..c42ccdd4b27 100644 --- a/doc/type-map.json +++ b/doc/type-map.json @@ -135,6 +135,8 @@ "SyncHeapProfileHandle": "v8.html#class-syncheapprofilehandle", "SyncShare": "stream_iter.html#class-syncshare", "SyncShareable": "stream_iter.html#interface-syncshareable", + "TarEntry": "zlib.html#class-zlibtarentry", + "TarParser": "zlib.html#class-zlibtarparser", "TestContext": "test.html#class-testcontext", "TestsStream": "test.html#class-testsstream", "TextDecoderStream": "webstreams.html#class-textdecoderstream", diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 711ceb4b109..b9b3b3fa79b 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -1850,6 +1850,10 @@ E('ERR_STREAM_WRAP', 'Stream has StringDecoder set or is in objectMode', Error); E('ERR_STREAM_WRITE_AFTER_END', 'write after end', Error, TypeError); E('ERR_SYNTHETIC', 'JavaScript Callstack', Error); E('ERR_SYSTEM_ERROR', 'A system error occurred', SystemError, HideStackFramesError); +E('ERR_TAR_INVALID_ARCHIVE', 'invalid tar archive: %s', Error); +E('ERR_TAR_INVALID_ENTRY', 'invalid tar entry: %s', Error); +E('ERR_TAR_UNSAFE_ENTRY', 'refusing to extract tar entry: %s', Error); +E('ERR_TAR_UNSUPPORTED_FEATURE', 'unsupported tar feature: %s', Error); E('ERR_TEST_FAILURE', function(error, failureType) { hideInternalStackFrames(this); assert(typeof failureType === 'string' || typeof failureType === 'symbol', diff --git a/lib/internal/tar.js b/lib/internal/tar.js new file mode 100644 index 00000000000..6c7f51d88bd --- /dev/null +++ b/lib/internal/tar.js @@ -0,0 +1,47 @@ +'use strict'; + +// Public entry point for tar archive support in `node:zlib`. The +// implementation is split across `internal/tar/`: +// +// entry TarEntry, and the factories for the entries to write +// header decoding of 512-byte header blocks +// pax pax extended header records +// parser TarParser, the push parser everything else is built on +// decompress compression detection and synchronous decompression +// pool recycled read and decompression buffers +// source feeding files, buffers, streams and iterables to a parser +// entries tarEntries(), the pull-based reader +// paths sanitizing of entry paths for extraction +// unpack-common what synchronous and asynchronous extraction share +// unpack-sync extractTarSync() +// unpack extractTar() and createTarExtractStream() +// archive createTarArchive() and tarFiles(), the writing side +// api argument validation and wiring +// +// This barrel re-exports only the surface `lib/zlib.js` consumes. + +const { TarEntry } = require('internal/tar/entry'); +const { TarParser } = require('internal/tar/parser'); +const { createTarArchive, createTarArchiveSync, tarFiles } = require('internal/tar/archive'); +const { + createTarExtractStream, + extractTar, + extractTarSync, + listTar, + listTarSync, + tarEntries, +} = require('internal/tar/api'); + +module.exports = { + TarEntry, + TarParser, + createTarArchive, + createTarArchiveSync, + createTarExtractStream, + extractTar, + extractTarSync, + listTar, + listTarSync, + tarEntries, + tarFiles, +}; diff --git a/lib/internal/tar/api.js b/lib/internal/tar/api.js new file mode 100644 index 00000000000..7fbb9cf4e49 --- /dev/null +++ b/lib/internal/tar/api.js @@ -0,0 +1,314 @@ +'use strict'; + +// The public functions: argument validation, and the wiring of a source, a +// parser and (for extraction) an unpacker. + +const { + ArrayPrototypePush, + PromisePrototypeThen, +} = primordials; + +const { + parseFileMode, + validateBoolean, + validateFunction, + validateInteger, + validateNumber, + validateObject, + validateOneOf, + validateString, +} = require('internal/validators'); +const { kEmptyObject } = require('internal/util'); +const { isURL, toPathIfFileURL } = require('internal/url'); +const { Writable } = require('stream'); +const { Parser, validateParserOptions } = require('internal/tar/parser'); +const { + Sink, + closeFile, + feedFd, + feedFile, + feedFileSync, + feedInput, + feedInputSync, + openFile, +} = require('internal/tar/source'); +const { tarEntries: createEntriesIterator } = require('internal/tar/entries'); +const { Unpack } = require('internal/tar/unpack'); +const { UnpackSync } = require('internal/tar/unpack-sync'); + +const kMaxId = 2 ** 32 - 2; +const kCompressions = [true, false, 'gzip', 'zstd', 'brotli']; + +function validateCommonOptions(options) { + validateObject(options, 'options'); + const { compression, filter, onentry } = options; + if (compression !== undefined) validateOneOf(compression, 'options.compression', kCompressions); + if (filter !== undefined) validateFunction(filter, 'options.filter'); + if (onentry !== undefined) validateFunction(onentry, 'options.onentry'); + // The options shared with TarParser. + validateParserOptions({ + __proto__: null, + onwarn: options.onwarn, + strict: options.strict, + maxMetaSize: options.maxMetaSize, + }); +} + +function validateExtractOptions(options) { + validateCommonOptions(options); + const { + strip, keep, newer, noMtime, preserveOwner, preservePaths, chmod, + uid, gid, maxDepth, jobs, highWaterMark, + } = options; + if (strip !== undefined) validateInteger(strip, 'options.strip', 0); + if (keep !== undefined) validateBoolean(keep, 'options.keep'); + if (newer !== undefined) validateBoolean(newer, 'options.newer'); + if (noMtime !== undefined) validateBoolean(noMtime, 'options.noMtime'); + if (preserveOwner !== undefined) validateBoolean(preserveOwner, 'options.preserveOwner'); + if (preservePaths !== undefined) validateBoolean(preservePaths, 'options.preservePaths'); + if (chmod !== undefined) validateBoolean(chmod, 'options.chmod'); + if (uid !== undefined) validateInteger(uid, 'options.uid', 0, kMaxId); + if (gid !== undefined) validateInteger(gid, 'options.gid', 0, kMaxId); + if (maxDepth !== undefined) validateNumber(maxDepth, 'options.maxDepth', 0); + if (jobs !== undefined) validateInteger(jobs, 'options.jobs', 1); + if (highWaterMark !== undefined) validateInteger(highWaterMark, 'options.highWaterMark', 0); + + let cwd = options.cwd; + if (cwd !== undefined) { + cwd = toPathIfFileURL(cwd); + validateString(cwd, 'options.cwd'); + } + // A copy: the modes are parsed, and later changes to `options` are not + // seen. + return { + __proto__: null, + cwd, + compression: options.compression, + filter: options.filter, + onentry: options.onentry, + onwarn: options.onwarn, + strict: options.strict, + maxMetaSize: options.maxMetaSize, + strip, + keep, + newer, + noMtime, + preserveOwner, + preservePaths, + chmod, + uid, + gid, + umask: options.umask === undefined ? undefined : parseFileMode(options.umask, 'options.umask'), + fmode: options.fmode === undefined ? undefined : parseFileMode(options.fmode, 'options.fmode'), + dmode: options.dmode === undefined ? undefined : parseFileMode(options.dmode, 'options.dmode'), + maxDepth, + jobs, + highWaterMark, + }; +} + +// A string or a URL is the path of an archive file; anything else is the +// archive itself. +function isFileSource(source) { + return typeof source === 'string' || isURL(source); +} + +function sourceOptions(options, file) { + return { + __proto__: null, + compression: options.compression, + // Brotli is detected from the file name. + file: typeof file === 'string' ? file : undefined, + }; +} + +function listCallbacks(options) { + const { filter, onentry } = options; + const entries = onentry === undefined ? [] : undefined; + return { + __proto__: null, + entries, + strict: options.strict, + maxMetaSize: options.maxMetaSize, + onwarn: options.onwarn, + onentry(entry) { + if (filter !== undefined && !filter(entry.path, entry)) return false; + if (onentry !== undefined) onentry(entry); + else ArrayPrototypePush(entries, entry); + return false; + }, + }; +} + +// Lists the entries of an archive. Resolves with the entries, or with +// undefined when `onentry` is given. +async function listTar(source, options = kEmptyObject) { + validateCommonOptions(options); + const callbacks = listCallbacks(options); + const parser = new Parser(callbacks); + if (isFileSource(source)) { + const file = toPathIfFileURL(source); + const so = sourceOptions(options, file); + // Listing keeps no chunks: buffers can be reused right away, and bodies + // are jumped over. + so.reuse = true; + so.seek = true; + await feedFile(file, parser, so); + } else { + const so = sourceOptions(options); + so.reuse = true; + await feedInput(source, parser, so); + } + return callbacks.entries; +} + +function listTarSync(source, options = kEmptyObject) { + validateCommonOptions(options); + const callbacks = listCallbacks(options); + const parser = new Parser(callbacks); + if (isFileSource(source)) { + const file = toPathIfFileURL(source); + const so = sourceOptions(options, file); + so.seek = true; + feedFileSync(file, parser, so); + } else { + feedInputSync(source, parser, sourceOptions(options)); + } + return callbacks.entries; +} + +function unpackParser(u, options) { + return new Parser({ + __proto__: null, + strict: options.strict, + maxMetaSize: options.maxMetaSize, + onentry: (entry) => u.onentry(entry), + ondata: (chunk) => u.ondata(chunk), + onentryend: (entry) => u.onentryend(entry), + onwarn: (err) => u.warn(err, undefined), + }); +} + +// Extracts an archive into `options.cwd`. +async function extractTar(source, options = kEmptyObject) { + options = validateExtractOptions(options); + const isFile = isFileSource(source); + const file = isFile ? toPathIfFileURL(source) : undefined; + const u = new Unpack(options); + await u.init(); + const parser = unpackParser(u, options); + const so = sourceOptions(options, file); + so.wait = () => u.wait(); + so.pool = u.pool; + + let fd = -1; + try { + if (isFile) { + fd = await openFile(file); + so.seek = true; + so.ondetect = (kind) => { + // Uncompressed: bodies can be read in place. Large files are copied + // by their own jobs, in parallel, while the parser jumps over them. + if (kind === null) u.setSource(fd); + }; + await feedFd(fd, parser, so); + } else { + await feedInput(source, parser, so); + } + await u.finish(); + } catch (err) { + await u.abort(); + throw u.fatal ?? err; + } finally { + if (fd !== -1) await closeFile(fd); + } +} + +function extractTarSync(source, options = kEmptyObject) { + options = validateExtractOptions(options); + const u = new UnpackSync(options); + const parser = unpackParser(u, options); + try { + if (isFileSource(source)) { + const file = toPathIfFileURL(source); + const so = sourceOptions(options, file); + so.seek = true; + feedFileSync(file, parser, so); + } else { + feedInputSync(source, parser, sourceOptions(options)); + } + u.finish(); + } catch (err) { + u.abort(); + throw err; + } +} + +// A Writable that extracts the archive written to it: +// await pipeline(source, createTarExtractStream({ cwd })) +function createTarExtractStream(options = kEmptyObject) { + options = validateExtractOptions(options); + const u = new Unpack(options); + const parser = unpackParser(u, options); + const so = sourceOptions(options); + so.wait = () => u.wait(); + so.pool = u.pool; + const sink = new Sink(parser, so); + + return new Writable({ + __proto__: null, + construct(cb) { + PromisePrototypeThen(u.init(), () => cb(), cb); + }, + write(chunk, encoding, cb) { + let p; + try { + sink.write(chunk); + p = sink.pause(); + } catch (err) { + return cb(err); + } + if (p === null) cb(); + else PromisePrototypeThen(p, () => cb(), cb); + }, + final(cb) { + try { + sink.end(); + } catch (err) { + PromisePrototypeThen(u.abort(), () => cb(err), cb); + return; + } + PromisePrototypeThen(u.finish(), () => cb(), cb); + }, + destroy(err, cb) { + sink.close(); + // Nothing is left to wait for after final(). Otherwise, the file being + // written is closed, and the running jobs are waited for. + PromisePrototypeThen(u.abort(), () => cb(err ? (u.fatal ?? err) : null), cb); + }, + }); +} + +// An async iterator of the entries of an archive, each with its body. +function tarEntries(source, options = kEmptyObject) { + validateCommonOptions(options); + const isFile = isFileSource(source); + if (isFile) source = toPathIfFileURL(source); + return createEntriesIterator(source, isFile, { + __proto__: null, + compression: options.compression, + filter: options.filter, + onwarn: options.onwarn, + strict: options.strict, + maxMetaSize: options.maxMetaSize, + }); +} + +module.exports = { + createTarExtractStream, + extractTar, + extractTarSync, + listTar, + listTarSync, + tarEntries, +}; diff --git a/lib/internal/tar/archive.js b/lib/internal/tar/archive.js new file mode 100644 index 00000000000..bba5db8a365 --- /dev/null +++ b/lib/internal/tar/archive.js @@ -0,0 +1,539 @@ +'use strict'; + +// Archive serialization: `createTarArchive()`, `createTarArchiveSync()` and +// the `tarFiles()` on-disk variant. Entries are written as ustar headers, +// preceded by a pax extended header for what ustar cannot hold: long or +// non-ASCII names, large sizes and identifiers, times out of range. + +const { + ArrayPrototypePush, + DatePrototypeGetTime, + MathFloor, + NumberIsSafeInteger, + StringPrototypeEndsWith, + StringPrototypeIncludes, + SymbolAsyncDispose, + SymbolAsyncIterator, + SymbolDispose, + SymbolIterator, +} = primordials; + +const { + codes: { + ERR_INVALID_ARG_TYPE, + ERR_INVALID_STATE, + ERR_TAR_INVALID_ENTRY, + ERR_TAR_UNSUPPORTED_FEATURE, + }, +} = require('internal/errors'); +const { + validateBoolean, + validateObject, + validateString, +} = require('internal/validators'); +const { isUint8Array } = require('internal/util/types'); +const { Buffer } = require('buffer'); +const { + TarEntry, + getData, + hasSource, + hasSyncSource, + isTarEntry, + takeSource, +} = require('internal/tar/entry'); + +const BLOCK_SIZE = 512; +const NAME_LEN = 100; +const PREFIX_LEN = 155; +const LINKNAME_LEN = 100; +const USER_LEN = 32; +// The largest values of the 8 and 12 byte octal fields. +const MAX_OCTAL_8 = 0o7777777; +const MAX_OCTAL_12 = 0o77777777777; + +const TYPE_FILE = 0x30; +const TYPE_PAX = 0x78; +const typeFlags = { + __proto__: null, + File: TYPE_FILE, + ContiguousFile: TYPE_FILE, + Link: 0x31, + SymbolicLink: 0x32, + CharacterDevice: 0x33, + BlockDevice: 0x34, + Directory: 0x35, + FIFO: 0x36, +}; + +let fs; +let Readable; + +function isAscii(buf) { + for (let i = 0; i < buf.length; i++) { + if (buf[i] >= 0x80) return false; + } + return true; +} + +// Writes an octal field, or GNU base-256 when the value does not fit (a pax +// record then holds it too). +function writeNumber(block, off, len, value) { + const max = len === 8 ? MAX_OCTAL_8 : MAX_OCTAL_12; + if (value < 0) value = 0; + if (value <= max) { + let i = off + len - 2; + while (i >= off) { + block[i--] = 0x30 + (value % 8); + value = MathFloor(value / 8); + } + return; + } + block[off] = 0x80; + for (let i = off + len - 1; i > off && value > 0; i--) { + block[i] = value % 256; + value = MathFloor(value / 256); + } +} + +function writeChecksum(block) { + let sum = 8 * 0x20; + for (let i = 0; i < BLOCK_SIZE; i++) sum += block[i]; + for (let i = 153; i >= 148; i--) { + block[i] = 0x30 + (sum % 8); + sum = MathFloor(sum / 8); + } + block[154] = 0; + block[155] = 0x20; +} + +function writeMagic(block) { + block.write('ustar\x0000', 257, 'latin1'); +} + +// One pax record: " =\n", where the length counts the +// whole record, its own digits included. +function paxRecord(key, value) { + const body = Buffer.from(` ${key}=${value}\n`); + let length = body.length + 1; + while (`${length}`.length + body.length !== length) { + length = `${length}`.length + body.length; + } + return Buffer.concat([Buffer.from(`${length}`), body]); +} + +function invalidEntry(entry, reason) { + return new ERR_TAR_INVALID_ENTRY(`${reason} (${typeof entry.path === 'string' ? entry.path : 'entry'})`); +} + +function checkString(entry, name, allowEmpty) { + const value = entry[name]; + if (typeof value !== 'string' || (!allowEmpty && value === '') || StringPrototypeIncludes(value, '\0')) { + throw invalidEntry(entry, `invalid ${name}`); + } + return value; +} + +function checkNumber(entry, name) { + const value = entry[name]; + if (!NumberIsSafeInteger(value) || value < 0) { + throw invalidEntry(entry, `invalid ${name}`); + } + return value; +} + +// The header blocks of an entry whose content is `size` bytes: a ustar +// header, after a pax extended header when one is needed. +function encodeHeader(entry, size) { + const flag = typeFlags[entry.type]; + if (flag === undefined) { + throw new ERR_TAR_UNSUPPORTED_FEATURE(`cannot write an entry of type ${entry.type}`); + } + let path = checkString(entry, 'path', false); + if (flag === 0x35 && !StringPrototypeEndsWith(path, '/')) path += '/'; + const hasLink = flag === 0x31 || flag === 0x32; + const linkpath = hasLink ? checkString(entry, 'linkpath', false) : ''; + const uname = checkString(entry, 'uname', true); + const gname = checkString(entry, 'gname', true); + const uid = checkNumber(entry, 'uid'); + const gid = checkNumber(entry, 'gid'); + const mode = checkNumber(entry, 'mode') & 0o7777; + const mtime = entry.mtime; + // Whole seconds; a time that the parser could not represent is the epoch. + const seconds = mtime === null ? 0 : MathFloor(DatePrototypeGetTime(mtime) / 1000); + if (!NumberIsSafeInteger(seconds)) throw invalidEntry(entry, 'invalid mtime'); + + const block = Buffer.alloc(BLOCK_SIZE); + const records = []; + + const pathBytes = Buffer.from(path); + let fits = false; + if (isAscii(pathBytes)) { + if (pathBytes.length <= NAME_LEN) { + pathBytes.copy(block, 0); + fits = true; + } else { + // Split at a slash: what comes before goes to the prefix field. + const min = pathBytes.length - NAME_LEN - 1; + for (let i = min > 1 ? min : 1; i <= PREFIX_LEN && i < pathBytes.length - 1; i++) { + if (pathBytes[i] === 0x2f) { + pathBytes.copy(block, 345, 0, i); + pathBytes.copy(block, 0, i + 1); + fits = true; + break; + } + } + } + } + if (!fits) { + ArrayPrototypePush(records, paxRecord('path', path)); + pathBytes.copy(block, 0, 0, NAME_LEN); + } + + if (hasLink) { + const linkBytes = Buffer.from(linkpath); + if (linkBytes.length > LINKNAME_LEN || !isAscii(linkBytes)) { + ArrayPrototypePush(records, paxRecord('linkpath', linkpath)); + } + linkBytes.copy(block, 157, 0, LINKNAME_LEN); + } + + const unameBytes = Buffer.from(uname); + if (unameBytes.length > USER_LEN || !isAscii(unameBytes)) { + ArrayPrototypePush(records, paxRecord('uname', uname)); + } + unameBytes.copy(block, 265, 0, USER_LEN); + const gnameBytes = Buffer.from(gname); + if (gnameBytes.length > USER_LEN || !isAscii(gnameBytes)) { + ArrayPrototypePush(records, paxRecord('gname', gname)); + } + gnameBytes.copy(block, 297, 0, USER_LEN); + + if (uid > MAX_OCTAL_8) ArrayPrototypePush(records, paxRecord('uid', uid)); + if (gid > MAX_OCTAL_8) ArrayPrototypePush(records, paxRecord('gid', gid)); + if (size > MAX_OCTAL_12) ArrayPrototypePush(records, paxRecord('size', size)); + if (seconds < 0 || seconds > MAX_OCTAL_12) ArrayPrototypePush(records, paxRecord('mtime', seconds)); + + writeNumber(block, 100, 8, mode); + writeNumber(block, 108, 8, uid); + writeNumber(block, 116, 8, gid); + writeNumber(block, 124, 12, size); + writeNumber(block, 136, 12, seconds); + block[156] = flag; + writeMagic(block); + if (flag === 0x33 || flag === 0x34) { + writeNumber(block, 329, 8, checkNumber(entry, 'devmajor')); + writeNumber(block, 337, 8, checkNumber(entry, 'devminor')); + } else { + writeNumber(block, 329, 8, 0); + writeNumber(block, 337, 8, 0); + } + writeChecksum(block); + + if (records.length === 0) return block; + + const data = Buffer.concat(records); + const pax = Buffer.alloc(BLOCK_SIZE); + // Readers that know pax ignore this name; the others extract the records + // as a file with it. + const name = Buffer.from(`PaxHeader/${path}`).subarray(0, NAME_LEN); + for (let i = 0; i < name.length; i++) pax[i] = name[i] < 0x80 ? name[i] : 0x5f; + writeNumber(pax, 100, 8, 0o644); + writeNumber(pax, 108, 8, 0); + writeNumber(pax, 116, 8, 0); + writeNumber(pax, 124, 12, data.length); + writeNumber(pax, 136, 12, seconds > MAX_OCTAL_12 ? 0 : seconds); + pax[156] = TYPE_PAX; + writeMagic(pax); + writeNumber(pax, 329, 8, 0); + writeNumber(pax, 337, 8, 0); + writeChecksum(pax); + return Buffer.concat([pax, data, padding(data.length), block]); +} + +// What completes `size` bytes to a whole block. A new buffer each time: the +// chunks are handed to the consumer. +function padding(size) { + const rest = size % BLOCK_SIZE; + return Buffer.alloc(rest === 0 ? 0 : BLOCK_SIZE - rest); +} + +const CONTENT_NONE = 0; +const CONTENT_DATA = 1; +const CONTENT_SOURCE = 2; +const CONTENT_BODY = 3; + +// Where the content of an entry comes from. Only files have content. +function contentKind(entry) { + if (!isTarEntry(entry)) { + throw new ERR_INVALID_ARG_TYPE('entry', 'TarEntry', entry); + } + if (typeFlags[entry.type] !== TYPE_FILE) return CONTENT_NONE; + if (getData(entry) !== null) return CONTENT_DATA; + if (hasSource(entry)) return CONTENT_SOURCE; + if (entry.size === 0) return CONTENT_NONE; + // An entry read by tarEntries(), whose body was not consumed. + const body = entry.body; + if (body !== null && typeof body === 'object' && typeof body[SymbolAsyncIterator] === 'function' && + body.done === false) { + return CONTENT_BODY; + } + throw new ERR_INVALID_STATE(`The entry has no content to serialize (${entry.path})`); +} + +function checkChunk(entry, chunk, written, size) { + if (!isUint8Array(chunk)) { + throw new ERR_INVALID_ARG_TYPE('chunk', ['Buffer', 'Uint8Array'], chunk); + } + if (written + chunk.length > size) { + throw invalidEntry(entry, `content is larger than its size of ${size} bytes`); + } +} + +function checkEnd(entry, written, size) { + if (written !== size) { + throw invalidEntry(entry, `content is ${written} bytes, expected ${size}`); + } +} + +function endOfArchive() { + return Buffer.alloc(2 * BLOCK_SIZE); +} + +// Disposes of the entries that an interrupted serialization did not reach. +// Entries given to an archive are owned by it, and a streaming entry may hold +// a file descriptor. A lazy asynchronous source is told to stop instead: +// pulling its remaining entries could open as many files just to close them. +async function disposeQueuedEntries(iterator, isAsync) { + if (isAsync) { + if (typeof iterator.return === 'function') await iterator.return(); + return; + } + for (let next = iterator.next(); !next.done; next = iterator.next()) { + const entry = next.value; + if (typeof entry?.[SymbolAsyncDispose] === 'function') await entry[SymbolAsyncDispose](); + } +} + +// The iterator is driven by hand, so that the `finally` can dispose of every +// entry that was not serialized when the consumer stops early. The source of +// the entry being serialized is closed by its `for await` loop. +async function* generateTarArchive(entries) { + const isAsync = entries[SymbolAsyncIterator] !== undefined; + const iterator = isAsync ? entries[SymbolAsyncIterator]() : entries[SymbolIterator](); + let completed = false; + let current = null; + try { + while (true) { + const next = isAsync ? await iterator.next() : iterator.next(); + if (next.done) break; + current = next.value; + const kind = contentKind(current); + if (kind === CONTENT_DATA) { + const data = getData(current); + yield encodeHeader(current, data.length); + if (data.length > 0) { + yield data; + const pad = padding(data.length); + if (pad.length > 0) yield pad; + } + } else if (kind === CONTENT_NONE) { + yield encodeHeader(current, 0); + } else { + const size = checkNumber(current, 'size'); + yield encodeHeader(current, size); + const entry = current; + const source = kind === CONTENT_SOURCE ? takeSource(entry) : entry.body; + current = null; + let written = 0; + for await (const chunk of source) { + checkChunk(entry, chunk, written, size); + if (chunk.length === 0) continue; + written += chunk.length; + yield chunk; + } + checkEnd(entry, written, size); + const pad = padding(size); + if (pad.length > 0) yield pad; + } + current = null; + } + yield endOfArchive(); + completed = true; + } finally { + if (!completed) { + if (typeof current?.[SymbolAsyncDispose] === 'function') await current[SymbolAsyncDispose](); + await disposeQueuedEntries(iterator, isAsync); + } + } +} + +function* generateTarArchiveSync(entries) { + const iterator = entries[SymbolIterator](); + let completed = false; + let current = null; + try { + for (let next = iterator.next(); !next.done; next = iterator.next()) { + current = next.value; + const kind = contentKind(current); + if (kind === CONTENT_DATA) { + const data = getData(current); + yield encodeHeader(current, data.length); + if (data.length > 0) { + yield data; + const pad = padding(data.length); + if (pad.length > 0) yield pad; + } + } else if (kind === CONTENT_NONE) { + yield encodeHeader(current, 0); + } else { + if (kind === CONTENT_BODY || !hasSyncSource(current)) { + throw new ERR_INVALID_STATE( + `An entry with an asynchronous source cannot be serialized synchronously (${current.path})`); + } + const size = checkNumber(current, 'size'); + yield encodeHeader(current, size); + const entry = current; + const source = takeSource(entry); + current = null; + let written = 0; + for (const chunk of source) { + checkChunk(entry, chunk, written, size); + if (chunk.length === 0) continue; + written += chunk.length; + yield chunk; + } + checkEnd(entry, written, size); + const pad = padding(size); + if (pad.length > 0) yield pad; + } + current = null; + } + yield endOfArchive(); + completed = true; + } finally { + if (!completed) { + if (typeof current?.[SymbolDispose] === 'function') current[SymbolDispose](); + for (let next = iterator.next(); !next.done; next = iterator.next()) { + const entry = next.value; + if (typeof entry?.[SymbolDispose] === 'function') entry[SymbolDispose](); + } + } + } +} + +/** + * Serializes `entries` into a `Readable` stream of the bytes of a tar + * archive. The archive is not compressed: pipe it through `createGzip()`, + * for example. + * @param {Iterable | AsyncIterable} entries + * @returns {import('stream').Readable} + */ +function createTarArchive(entries) { + if (entries == null || + (typeof entries[SymbolAsyncIterator] !== 'function' && typeof entries[SymbolIterator] !== 'function')) { + throw new ERR_INVALID_ARG_TYPE('entries', ['Iterable', 'AsyncIterable'], entries); + } + Readable ??= require('stream').Readable; + return Readable.from(generateTarArchive(entries), { objectMode: false }); +} + +/** + * The synchronous counterpart of `createTarArchive()`. + * @param {Iterable} entries + * @returns {Iterator} + */ +function createTarArchiveSync(entries) { + if (entries == null || typeof entries[SymbolIterator] !== 'function') { + throw new ERR_INVALID_ARG_TYPE('entries', 'Iterable', entries); + } + return generateTarArchiveSync(entries); +} + +/** + * Creates an archive from files on disk. `files` is an iterable of + * `[sourcePath, entryPath]` pairs. + * @param {Iterable<[string, string]> | AsyncIterable<[string, string]>} files + * @param {{ followSymlinks?: boolean }} [options] + * @returns {import('stream').Readable} + */ +function tarFiles(files, options) { + if (files == null || + (typeof files[SymbolAsyncIterator] !== 'function' && typeof files[SymbolIterator] !== 'function')) { + throw new ERR_INVALID_ARG_TYPE('files', ['Iterable', 'AsyncIterable'], files); + } + if (options !== undefined) validateObject(options, 'options'); + const followSymlinks = options?.followSymlinks ?? true; + validateBoolean(followSymlinks, 'options.followSymlinks'); + return createTarArchive(fileEntries(files, followSymlinks)); +} + +async function* fileEntries(files, followSymlinks) { + fs ??= require('fs'); + for await (const pair of files) { + const sourcePath = pair?.[0]; + const path = pair?.[1]; + validateString(sourcePath, 'sourcePath'); + validateString(path, 'path'); + const stats = await (followSymlinks ? fs.promises.stat(sourcePath) : fs.promises.lstat(sourcePath)); + const options = { + __proto__: null, + mode: stats.mode & 0o7777, + mtime: stats.mtime, + uid: stats.uid, + gid: stats.gid, + }; + if (stats.isSymbolicLink()) { + yield TarEntry.createSymlink(path, await fs.promises.readlink(sourcePath), options); + } else if (stats.isDirectory()) { + yield TarEntry.create(StringPrototypeEndsWith(path, '/') ? path : `${path}/`, Buffer.alloc(0), options); + } else { + // The file is opened here, and read from that descriptor: opening it + // again by path would let a symbolic link swapped in after the stat + // above redirect the read. O_NOFOLLOW refuses a link when links are + // not followed, and O_NONBLOCK keeps the open from blocking on a FIFO, + // so that the fstat can refuse what is not a regular file. + const flags = fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK || 0) | + (followSymlinks ? 0 : (fs.constants.O_NOFOLLOW || 0)); + const handle = await fs.promises.open(sourcePath, flags); + let ownsHandle = true; + try { + const stat = await handle.stat(); + if (!stat.isFile()) { + throw new ERR_TAR_UNSUPPORTED_FEATURE(`cannot archive ${sourcePath}: not a regular file`); + } + const fileOptions = { + __proto__: null, + mode: stat.mode & 0o7777, + mtime: stat.mtime, + uid: stat.uid, + gid: stat.gid, + size: stat.size, + }; + if (stat.size === 0) { + yield TarEntry.create(path, Buffer.alloc(0), fileOptions); + continue; + } + // The header holds the size, so exactly that much is read: a file + // that grows meanwhile is cut there, one that shrinks is an error. + // The stream closes the handle when it ends or is destroyed. + const stream = fs.createReadStream(undefined, { fd: handle, start: 0, end: stat.size - 1 }); + ownsHandle = false; + let handedOff = false; + try { + yield TarEntry.createStream(path, stream, fileOptions); + handedOff = true; + } finally { + if (!handedOff) stream.destroy(); + } + } finally { + if (ownsHandle) await handle.close(); + } + } + } +} + +module.exports = { + createTarArchive, + createTarArchiveSync, + tarFiles, +}; diff --git a/lib/internal/tar/decompress.js b/lib/internal/tar/decompress.js new file mode 100644 index 00000000000..41757773f23 --- /dev/null +++ b/lib/internal/tar/decompress.js @@ -0,0 +1,200 @@ +'use strict'; + +// Compression detection and synchronous, streaming decompression. + +const { + ArrayPrototypePop, + ArrayPrototypePush, + RegExpPrototypeExec, +} = primordials; + +const { + codes: { + ERR_TAR_INVALID_ARCHIVE, + ERR_TAR_UNSUPPORTED_FEATURE, + }, +} = require('internal/errors'); +const { Buffer } = require('buffer'); + +// `internal/tar` is required from `lib/zlib.js`, so it must not require the +// public `zlib` facade at load time (its module.exports is not yet +// populated). Decompression is only needed once an archive is read, well +// after `zlib.js` has finished loading. +let zlib; +function lazyZlib() { + zlib ??= require('zlib'); + return zlib; +} + +const GZIP = 'gzip'; +const ZSTD = 'zstd'; +const BROTLI = 'brotli'; + +// Bytes needed by detect(). +const DETECT_LENGTH = 6; + +const kBrotliName = /\.(?:tbr|br)$/i; + +// Detects the compression of an archive from its first bytes. Returns null +// for (apparently) uncompressed data. +function detect(head, file) { + if (head.length >= 2 && head[0] === 0x1f && head[1] === 0x8b) { + return GZIP; + } + if (head.length >= 4 && head[0] === 0x28 && head[1] === 0xb5 && head[2] === 0x2f && head[3] === 0xfd) { + return ZSTD; + } + if (head.length >= 3 && head[0] === 0x42 && head[1] === 0x5a && head[2] === 0x68) { + throw new ERR_TAR_UNSUPPORTED_FEATURE('bzip2 compression'); + } + if (head.length >= 6 && head[0] === 0xfd && head[1] === 0x37 && head[2] === 0x7a && + head[3] === 0x58 && head[4] === 0x5a && head[5] === 0x00) { + throw new ERR_TAR_UNSUPPORTED_FEATURE('xz compression'); + } + // Brotli has no magic number: rely on the file name. + if (typeof file === 'string' && RegExpPrototypeExec(kBrotliName, file) !== null) { + return BROTLI; + } + return null; +} + +function resolveCompression(option, head, file) { + if (option === false) return null; + if (option === GZIP || option === ZSTD || option === BROTLI) return option; + if (option === true) return GZIP; + return detect(head, file); +} + +const OUT_CHUNK = 256 * 1024; + +// Output buffers of the `reuse` decompressors, kept for the next ones: a +// fresh buffer costs as much as decompressing a small archive. +const spareOut = []; +const MAX_SPARE_OUT = 2; + +function createDecompressStream(kind) { + const options = { __proto__: null, chunkSize: OUT_CHUNK }; + switch (kind) { + case GZIP: + return lazyZlib().createGunzip(options); + case ZSTD: + return lazyZlib().createZstdDecompress(options); + default: + return lazyZlib().createBrotliDecompress(options); + } +} + +// A synchronous, streaming decompressor. The public zlib API only offers +// one-shot synchronous decompression, which needs the whole input and output +// in memory and concatenates the output. This drives the zlib handle of a +// decompression stream directly instead. Output buffers are: +// - with `reuse`, a single buffer: `onchunk` gets views of it that are valid +// only during the call; +// - with `pool`, buffers from the pool, filled up before moving on; +// - otherwise, fresh buffers, filled up before moving on. +class SyncDecompressor { + constructor(kind, onchunk, reuse, pool = null) { + this.kind = kind; + this.onchunk = onchunk; + this.reuse = reuse; + this.pool = pool; + this.stream = createDecompressStream(kind); + this.handle = this.stream._handle; + this.state = this.stream._writeState; + this.flushFlag = this.stream._defaultFlushFlag; + this.finishFlag = this.stream._finishFlushFlag; + this.out = null; + this.outOff = 0; + this.error = null; + this.ended = false; + // Bytes produced so far. + this.produced = 0; + // Errors are reported synchronously by writeSync() through onerror. + this.handle.onerror = (message) => { + this.error = new ERR_TAR_INVALID_ARCHIVE(`${kind} decompression failed: ${message}`); + }; + this.#nextOut(); + } + + write(input) { + this.#run(input, this.flushFlag); + } + + end() { + if (this.ended) return; + this.ended = true; + try { + this.#run(Buffer.alloc(0), this.finishFlag); + } finally { + this.close(); + } + } + + close() { + if (this.handle !== null) { + this.handle.onerror = null; + this.handle = null; + this.stream.close(); + } + if (this.out !== null) { + if (this.pool !== null) this.pool.release(this.out); + else if (this.reuse && spareOut.length < MAX_SPARE_OUT) ArrayPrototypePush(spareOut, this.out); + this.out = null; + } + } + + #nextOut() { + if (this.pool !== null) { + if (this.out !== null) this.pool.release(this.out); + this.out = this.pool.get(); + } else { + this.out = (this.reuse ? ArrayPrototypePop(spareOut) : undefined) ?? Buffer.allocUnsafeSlow(OUT_CHUNK); + } + this.outOff = this.produced & 511; + } + + #run(input, flag) { + const handle = this.handle; + const state = this.state; + let inOff = 0; + let inLen = input.length; + for (;;) { + const out = this.out; + const off = this.outOff; + const room = out.length - off; + handle.writeSync(flag, input, inOff, inLen, out, off, room); + if (this.error !== null) { + const err = this.error; + this.close(); + throw err; + } + const availOut = state[0]; + const availIn = state[1]; + const have = room - availOut; + inOff += inLen - availIn; + inLen = availIn; + if (have > 0) { + this.produced += have; + // Reused, the buffer is filled again from the start, at the same + // offset modulo 512 as the output in the archive: headers stay + // aligned in memory, which makes them faster to check. + this.outOff = this.reuse ? this.produced & 511 : off + have; + this.onchunk(have === out.length ? out : out.subarray(off, off + have)); + // The consumer may have closed the decompressor. + if (this.handle === null) return; + } + if (availOut === 0) { + // Output full: there may be more. + if (!this.reuse) this.#nextOut(); + continue; + } + break; + } + } +} + +module.exports = { + DETECT_LENGTH, + SyncDecompressor, + resolveCompression, +}; diff --git a/lib/internal/tar/entries.js b/lib/internal/tar/entries.js new file mode 100644 index 00000000000..4b613f49409 --- /dev/null +++ b/lib/internal/tar/entries.js @@ -0,0 +1,312 @@ +'use strict'; + +// Pull-based reading: an async iterator of entries, each with its body. +// +// for await (const entry of tarEntries('x.tar')) { +// const data = await entry.body.buffer(); +// } +// +// A body must be read before moving to the next entry; what is left of it is +// skipped. + +const { + ArrayPrototypePush, + ArrayPrototypeSlice, + Promise, + PromisePrototypeThen, + PromiseReject, + SymbolAsyncIterator, +} = primordials; + +const { + codes: { + ERR_INVALID_STATE, + }, +} = require('internal/errors'); +const { Buffer } = require('buffer'); +const { Parser } = require('internal/tar/parser'); +const { feedFile, feedInput } = require('internal/tar/source'); + +const HIGH_WATER_MARK = 8 * 1024 * 1024; + +const ITEM_ENTRY = 0; +const ITEM_DATA = 1; +const ITEM_END = 2; +const ITEM_NONE = -1; + +// A body smaller than this share of the buffer it is a view of is copied by +// buffer(), so that keeping it does not keep the whole buffer. +const COPY_RATIO = 4; + +class Reader { + constructor(source, isFile, options) { + this.source = source; + this.isFile = isFile; + this.options = options; + // Pairs of (item type, value). + this.queue = []; + this.head = 0; + this.queuedBytes = 0; + this.finished = false; + this.error = null; + this.notify = null; + this.resume = null; + this.stopped = false; + this.value = undefined; + this.parser = null; + // The entry whose body the parser is delivering. + this.delivering = null; + } + + start() { + const options = this.options; + const filter = options.filter; + this.parser = new Parser({ + __proto__: null, + strict: options.strict, + maxMetaSize: options.maxMetaSize, + onwarn: options.onwarn, + onentry: (entry) => { + if (filter !== undefined && !filter(entry.path, entry)) return false; + this.delivering = entry; + this.#push(ITEM_ENTRY, entry); + return true; + }, + ondata: (chunk) => { + this.queuedBytes += chunk.length; + this.#push(ITEM_DATA, chunk); + }, + onentryend: () => { + this.delivering = null; + this.#push(ITEM_END, null); + }, + }); + const so = { + __proto__: null, + compression: options.compression, + file: this.isFile && typeof this.source === 'string' ? this.source : undefined, + // Bodies that are skipped while they are read are jumped over. + seek: true, + wait: () => this.#wait(), + }; + const done = this.isFile ? feedFile(this.source, this.parser, so) : feedInput(this.source, this.parser, so); + PromisePrototypeThen(done, () => { + this.finished = true; + this.#wake(); + }, (err) => { + if (!this.stopped) this.error = err; + this.finished = true; + this.#wake(); + }); + } + + #push(type, value) { + ArrayPrototypePush(this.queue, type, value); + this.#wake(); + } + + #wake() { + if (this.notify !== null) { + const fn = this.notify; + this.notify = null; + fn(); + } + } + + #wait() { + if (this.stopped) return PromiseReject(new ERR_INVALID_STATE('The iterator was closed')); + if (this.queuedBytes < HIGH_WATER_MARK) return null; + return new Promise((resolve) => { + this.resume = resolve; + }); + } + + // Takes the next queued item: returns its type (its value is in + // `this.value`), or ITEM_NONE when the queue is empty. + take() { + if (this.head === this.queue.length) return ITEM_NONE; + const queue = this.queue; + const type = queue[this.head]; + this.value = queue[this.head + 1]; + queue[this.head + 1] = undefined; + this.head += 2; + if (this.head > 2048 && this.head * 2 > queue.length) { + this.queue = ArrayPrototypeSlice(queue, this.head); + this.head = 0; + } + if (type === ITEM_DATA) { + this.queuedBytes -= this.value.length; + if (this.resume !== null && this.queuedBytes < HIGH_WATER_MARK / 2) { + const fn = this.resume; + this.resume = null; + fn(); + } + } + return type; + } + + // A promise for when an item is queued or the producer is done, or null + // when there is no need to wait. + available() { + if (this.head < this.queue.length || this.finished) return null; + return new Promise((resolve) => { + this.notify = resolve; + }); + } + + // The next item's type (ITEM_NONE at the end), waiting if needed. + async next() { + for (;;) { + const type = this.take(); + if (type !== ITEM_NONE) return type; + if (this.finished) { + if (this.error !== null) throw this.error; + return ITEM_NONE; + } + await this.available(); + } + } + + stop() { + this.stopped = true; + if (this.resume !== null) { + const fn = this.resume; + this.resume = null; + fn(); + } + } +} + +class TarEntryBody { + #reader; + #entry; + #done; + #locked = false; + + constructor(reader, entry) { + this.#reader = reader; + this.#entry = entry; + this.#done = entry.size === 0; + } + + // Whether the body was read or skipped to its end. + get done() { + return this.#done; + } + + #lock() { + if (this.#locked) throw new ERR_INVALID_STATE('The body was already read'); + this.#locked = true; + } + + async *[SymbolAsyncIterator]() { + this.#lock(); + const reader = this.#reader; + while (!this.#done) { + const type = await reader.next(); + if (type === ITEM_DATA) { + yield reader.value; + } else { + this.#done = true; + } + } + } + + // The whole body in one Buffer. + async buffer() { + this.#lock(); + const reader = this.#reader; + let first = null; + let chunks = null; + let length = 0; + while (!this.#done) { + const type = await reader.next(); + if (type !== ITEM_DATA) { + this.#done = true; + break; + } + const chunk = reader.value; + length += chunk.length; + if (first === null) { + first = chunk; + } else { + chunks ??= [first]; + ArrayPrototypePush(chunks, chunk); + } + } + if (chunks !== null) return Buffer.concat(chunks, length); + if (first === null) return Buffer.alloc(0); + // A view of a small part of a larger buffer: copied, so that keeping the + // body does not keep the rest. + return first.length * COPY_RATIO < first.buffer.byteLength ? Buffer.from(first) : first; + } + + async text(encoding = 'utf8') { + return (await this.buffer()).toString(encoding); + } + + // Skips the rest of the body. + async skip() { + this.#locked = true; + const reader = this.#reader; + while (!this.#done) { + const type = reader.take(); + if (type === ITEM_DATA) continue; + if (type !== ITEM_NONE) { + this.#done = true; + } else if (reader.finished) { + if (reader.error !== null) throw reader.error; + this.#done = true; + } else if (reader.delivering === this.#entry && reader.parser.skipBody()) { + // The rest of the body is not read yet: the parser drops it. + reader.delivering = null; + this.#done = true; + } else { + await reader.available(); + } + } + } +} + +function tarEntries(source, isFile, options) { + const reader = new Reader(source, isFile, options); + let started = false; + let closed = false; + let body = null; + return { + async next() { + if (closed) return { __proto__: null, value: undefined, done: true }; + if (!started) { + started = true; + reader.start(); + } + if (body !== null && !body.done) await body.skip(); + body = null; + for (;;) { + const type = await reader.next(); + if (type === ITEM_NONE) { + closed = true; + return { __proto__: null, value: undefined, done: true }; + } + if (type === ITEM_ENTRY) { + const entry = reader.value; + body = new TarEntryBody(reader, entry); + entry.body = body; + return { __proto__: null, value: entry, done: false }; + } + } + }, + async return() { + closed = true; + if (started) reader.stop(); + return { __proto__: null, value: undefined, done: true }; + }, + [SymbolAsyncIterator]() { + return this; + }, + }; +} + +module.exports = { + tarEntries, +}; diff --git a/lib/internal/tar/entry.js b/lib/internal/tar/entry.js new file mode 100644 index 00000000000..40d50523bf7 --- /dev/null +++ b/lib/internal/tar/entry.js @@ -0,0 +1,210 @@ +'use strict'; + +// `TarEntry`: what the parser hands out for each entry of an archive it +// reads, and what `createTarArchive()` serializes. An entry made by one of +// the static factories carries its content: a buffer, or a source that is +// drained when the entry is serialized. + +const { + Date, + DatePrototypeGetTime, + NumberIsNaN, + NumberMAX_SAFE_INTEGER, + StringPrototypeEndsWith, + StringPrototypeIncludes, + SymbolAsyncDispose, + SymbolAsyncIterator, + SymbolDispose, + SymbolIterator, +} = primordials; + +const { + codes: { + ERR_INVALID_ARG_TYPE, + ERR_INVALID_ARG_VALUE, + }, +} = require('internal/errors'); +const { + validateInteger, + validateObject, + validateString, +} = require('internal/validators'); +const { kEmptyObject } = require('internal/util'); +const { isAnyArrayBuffer, isArrayBufferView, isDate } = require('internal/util/types'); +const { Buffer } = require('buffer'); + +// Accessors for the content of an entry, for the serializer. +let getData; +let hasSource; +let hasSyncSource; +let isTarEntry; +let takeSource; + +function validatePath(path, name) { + validateString(path, name); + if (path === '' || StringPrototypeIncludes(path, '\0')) { + throw new ERR_INVALID_ARG_VALUE(name, path, 'must be a non-empty string without null bytes'); + } +} + +// Applies the metadata options that every factory takes. +function applyOptions(entry, options, defaultMode) { + validateObject(options, 'options'); + const { mode = defaultMode, mtime, uid = 0, gid = 0, uname = '', gname = '' } = options; + validateInteger(mode, 'options.mode', 0, 0o7777); + validateInteger(uid, 'options.uid', 0, NumberMAX_SAFE_INTEGER); + validateInteger(gid, 'options.gid', 0, NumberMAX_SAFE_INTEGER); + validateString(uname, 'options.uname'); + validateString(gname, 'options.gname'); + if (mtime !== undefined) { + if (!isDate(mtime)) { + throw new ERR_INVALID_ARG_TYPE('options.mtime', 'Date', mtime); + } + if (NumberIsNaN(DatePrototypeGetTime(mtime))) { + throw new ERR_INVALID_ARG_VALUE('options.mtime', mtime); + } + } + entry.mode = mode; + entry.uid = uid; + entry.gid = gid; + entry.uname = uname; + entry.gname = gname; + entry.mtime = mtime ?? new Date(); +} + +class TarEntry { + #data = null; + #source = null; + + static { + getData = (entry) => entry.#data; + hasSource = (entry) => entry.#source !== null; + hasSyncSource = (entry) => typeof entry.#source?.[SymbolIterator] === 'function'; + isTarEntry = (value) => value !== null && typeof value === 'object' && #source in value; + takeSource = (entry) => { + const source = entry.#source; + entry.#source = null; + return source; + }; + } + + constructor() { + this.path = ''; + this.type = 'File'; + this.size = 0; + this.mode = 0; + this.uid = 0; + this.gid = 0; + this.mtime = null; + this.atime = null; + this.ctime = null; + this.linkpath = ''; + this.uname = ''; + this.gname = ''; + this.devmajor = 0; + this.devminor = 0; + this.pax = null; + // Offset of the header block in the archive. + this.offset = 0; + // The body reader, with tarEntries(). + this.body = null; + } + + // A file with `data` as its content, or a directory when `path` ends with + // a slash. The entry keeps a view of `data`, not a copy. + static create(path, data, options = kEmptyObject) { + validatePath(path, 'path'); + let content; + if (isArrayBufferView(data)) { + content = Buffer.from(data.buffer, data.byteOffset, data.byteLength); + } else if (isAnyArrayBuffer(data)) { + content = Buffer.from(data); + } else { + throw new ERR_INVALID_ARG_TYPE('data', ['Buffer', 'TypedArray', 'DataView', 'ArrayBuffer'], data); + } + const isDirectory = StringPrototypeEndsWith(path, '/'); + if (isDirectory && content.length > 0) { + throw new ERR_INVALID_ARG_VALUE('data', data, 'must be empty for a directory entry'); + } + const entry = new TarEntry(); + applyOptions(entry, options, isDirectory ? 0o755 : 0o644); + entry.path = path; + if (isDirectory) { + entry.type = 'Directory'; + } else { + entry.size = content.length; + entry.#data = content; + } + return entry; + } + + // A file whose content is drained from `source` when the entry is + // serialized. A tar header comes before the content and holds its size, so + // the size must be known up front. + static createStream(path, source, options) { + validatePath(path, 'path'); + if (StringPrototypeEndsWith(path, '/')) { + throw new ERR_INVALID_ARG_VALUE('path', path, 'a directory entry cannot be streamed'); + } + if (source == null || + (typeof source[SymbolAsyncIterator] !== 'function' && typeof source[SymbolIterator] !== 'function')) { + throw new ERR_INVALID_ARG_TYPE('source', ['AsyncIterable', 'Iterable'], source); + } + validateObject(options, 'options'); + validateInteger(options.size, 'options.size', 0, NumberMAX_SAFE_INTEGER); + const entry = new TarEntry(); + applyOptions(entry, options, 0o644); + entry.path = path; + entry.size = options.size; + entry.#source = source; + return entry; + } + + static createSymlink(path, target, options = kEmptyObject) { + return TarEntry.#createLink('SymbolicLink', path, target, options, 0o777); + } + + // A hard link to `target`, the path of an earlier entry of the archive. + static createLink(path, target, options = kEmptyObject) { + return TarEntry.#createLink('Link', path, target, options, 0o644); + } + + static #createLink(type, path, target, options, defaultMode) { + validatePath(path, 'path'); + validatePath(target, 'target'); + const entry = new TarEntry(); + applyOptions(entry, options, defaultMode); + entry.path = path; + entry.type = type; + entry.linkpath = target; + return entry; + } + + // Releases the source of a streaming entry that was never serialized. An + // entry given to an archive is disposed of by the archive. + [SymbolDispose]() { + const source = this.#source; + this.#source = null; + if (source === null) return; + if (typeof source.destroy === 'function') source.destroy(); + else if (typeof source.return === 'function') source.return(); + } + + async [SymbolAsyncDispose]() { + const source = this.#source; + this.#source = null; + if (source === null) return; + if (typeof source[SymbolAsyncDispose] === 'function') await source[SymbolAsyncDispose](); + else if (typeof source.destroy === 'function') source.destroy(); + else if (typeof source.return === 'function') await source.return(); + } +} + +module.exports = { + TarEntry, + getData, + hasSource, + hasSyncSource, + isTarEntry, + takeSource, +}; diff --git a/lib/internal/tar/header.js b/lib/internal/tar/header.js new file mode 100644 index 00000000000..ef4f88810de --- /dev/null +++ b/lib/internal/tar/header.js @@ -0,0 +1,346 @@ +'use strict'; + +// Decoding of 512-byte tar header blocks (v7, ustar, GNU and the header part +// of pax archives). Everything here works on raw bytes: no intermediate +// strings are allocated for numeric fields. + +const { + Date, + DatePrototypeGetTime, + Int32Array, + NumberIsNaN, + Uint8Array, +} = primordials; + +const { Buffer } = require('buffer'); + +const BLOCK_SIZE = 512; + +// Field offsets and lengths, from the ustar specification. +const NAME = 0; +const NAME_LEN = 100; +const MODE = 100; +const UID = 108; +const GID = 116; +const SIZE = 124; +const MTIME = 136; +const CHKSUM = 148; +const TYPEFLAG = 156; +const LINKNAME = 157; +const MAGIC = 257; +const UNAME = 265; +const UNAME_LEN = 32; +const GNAME = 297; +const DEVMAJOR = 329; +const DEVMINOR = 337; +const PREFIX = 345; +const PREFIX_LEN = 155; +const GNU_ATIME = 345; +const GNU_CTIME = 357; + +// Header formats, detected from the magic field. +const FORMAT_V7 = 0; +const FORMAT_USTAR = 1; +const FORMAT_GNU = 2; + +const TYPE_PAX = 0x78; +const TYPE_PAX_GLOBAL = 0x67; +const TYPE_GNU_LONG_PATH = 0x4c; +const TYPE_GNU_LONG_LINK = 0x4b; +const TYPE_OLD_PAX = 0x58; + +// Type flag byte -> type name. Names follow the common tar vocabulary. +const typeNames = []; +for (let i = 0; i < 256; i++) typeNames[i] = 'Unsupported'; +typeNames[0] = 'File'; +typeNames[0x30] = 'File'; // '0' +typeNames[0x31] = 'Link'; // '1' +typeNames[0x32] = 'SymbolicLink'; // '2' +typeNames[0x33] = 'CharacterDevice'; // '3' +typeNames[0x34] = 'BlockDevice'; // '4' +typeNames[0x35] = 'Directory'; // '5' +typeNames[0x36] = 'FIFO'; // '6' +typeNames[0x37] = 'ContiguousFile'; // '7' +typeNames[TYPE_PAX_GLOBAL] = 'GlobalExtendedHeader'; // 'g' +typeNames[TYPE_PAX] = 'ExtendedHeader'; // 'x' +typeNames[0x41] = 'SolarisACL'; // 'A' +typeNames[0x44] = 'GNUDumpDir'; // 'D' +typeNames[0x49] = 'Inode'; // 'I' +typeNames[TYPE_GNU_LONG_LINK] = 'NextFileHasLongLinkpath'; // 'K' +typeNames[TYPE_GNU_LONG_PATH] = 'NextFileHasLongPath'; // 'L' +typeNames[0x4d] = 'ContinuationFile'; // 'M' +typeNames[0x4e] = 'OldGnuLongPath'; // 'N' +typeNames[0x53] = 'SparseFile'; // 'S' +typeNames[0x56] = 'TapeVolumeHeader'; // 'V' +typeNames[TYPE_OLD_PAX] = 'OldExtendedHeader'; // 'X' + +// Result codes of verifyChecksum(). +const BLOCK_OK = 1; +const BLOCK_ZERO = 0; +const BLOCK_INVALID = -1; + +// A Date for a number of seconds since the epoch, or null when it is not +// representable: headers are untrusted, and an invalid Date must never reach +// the file system calls. +function toDate(seconds) { + const date = new Date(seconds * 1000); + return NumberIsNaN(DatePrototypeGetTime(date)) ? null : date; +} + +// The last string read from a field. User and group names are mostly the same +// from one header to the next: comparing bytes is cheaper than making a +// string. +class StringCache { + constructor(size) { + this.bytes = new Uint8Array(size); + this.length = -1; + this.value = ''; + } + + read(buf, off, max) { + const bytes = this.bytes; + const len = this.length; + let i = 0; + while (i < len && buf[off + i] === bytes[i]) i++; + if (i === len && (len === max || buf[off + len] === 0)) { + return this.value; + } + const value = readString(buf, off, max); + let n = 0; + while (n < max && buf[off + n] !== 0) { + bytes[n] = buf[off + n]; + n++; + } + this.length = n; + this.value = value; + return value; + } +} + +// State kept from one header to the next, by each parser (so that none keeps +// a buffer alive): an Int32Array over the last ArrayBuffer seen, to sum +// header bytes four at a time (sources mostly reuse a few buffers), and the +// last user and group names. +class HeaderCache { + constructor() { + this.of = null; + this.words = null; + this.uname = new StringCache(UNAME_LEN); + this.gname = new StringCache(UNAME_LEN); + // Where blocks that are not 4-byte aligned are copied to be summed. + this.scratch = Buffer.allocUnsafeSlow(BLOCK_SIZE); + this.scratchWords = new Int32Array(this.scratch.buffer, 0, BLOCK_SIZE >>> 2); + } + + get(ab) { + if (ab !== this.of) { + this.words = new Int32Array(ab, 0, ab.byteLength >>> 2); + this.of = ab; + } + return this.words; + } +} + +// Sum of the bytes of the 128 words at `base` of `w`. Bytes are added in +// pairs of 16-bit lanes ("SIMD within a register"): 128 words of 4 bytes +// cannot overflow a lane. The result does not depend on the byte order. +function sumWords(w, base) { + let a = 0; + let b = 0; + const end = base + 128; + for (let i = base; i < end; i += 4) { + const x = w[i]; + const y = w[i + 1]; + const z = w[i + 2]; + const t = w[i + 3]; + a = (a + (x & 0x00ff00ff) + (y & 0x00ff00ff) + (z & 0x00ff00ff) + (t & 0x00ff00ff)) | 0; + b = (b + ((x >>> 8) & 0x00ff00ff) + ((y >>> 8) & 0x00ff00ff) + + ((z >>> 8) & 0x00ff00ff) + ((t >>> 8) & 0x00ff00ff)) | 0; + } + return (a & 0xffff) + (a >>> 16) + (b & 0xffff) + (b >>> 16); +} + +// Sum of the 512 bytes at `off`. +function sumBlock(buf, off, cache) { + const start = buf.byteOffset + off; + if ((start & 3) === 0) return sumWords(cache.get(buf.buffer), start >>> 2); + // Not aligned (chunks from arbitrary streams): copying is cheaper than + // summing bytes one by one. + buf.copy(cache.scratch, 0, off, off + BLOCK_SIZE); + return sumWords(cache.scratchWords, 0); +} + +// Checks the header checksum. The checksum field itself counts as if it were +// filled with spaces. Some old implementations used signed bytes, which are +// accepted too. +function verifyChecksum(buf, off, cache) { + let sum = sumBlock(buf, off, cache); + if (sum === 0) { + return BLOCK_ZERO; + } + const end = off + BLOCK_SIZE; + + const cs = off + CHKSUM; + let field = 0; + for (let i = cs; i < cs + 8; i++) { + field += buf[i]; + } + sum = sum - field + 8 * 0x20; + + const expected = readOctal(buf, cs, 8); + if (expected === sum) { + return BLOCK_OK; + } + + // Signed variant. + let signed = 0; + for (let i = off; i < end; i++) { + const b = buf[i]; + signed += b > 127 ? b - 256 : b; + } + for (let i = cs; i < cs + 8; i++) { + const b = buf[i]; + signed -= b > 127 ? b - 256 : b; + } + signed += 8 * 0x20; + return expected === signed ? BLOCK_OK : BLOCK_INVALID; +} + +// The type flag of a header block. +function readTypeflag(buf, off) { + return buf[off + TYPEFLAG]; +} + +// The size field of a header block. +function readSize(buf, off) { + return readOctal(buf, off + SIZE, 12); +} + +// Reads a numeric field: octal ASCII, optionally padded with spaces or NULs, +// or GNU base-256 when the high bit of the first byte is set. +function readOctal(buf, off, len) { + const first = buf[off]; + if (first & 0x80) { + return readBase256(buf, off, len); + } + const end = off + len; + let i = off; + // Leading padding. + while (i < end) { + const c = buf[i]; + if (c !== 0x20 && c !== 0x30 && c !== 0) break; + i++; + } + let n = 0; + while (i < end) { + const c = buf[i]; + if (c < 0x30 || c > 0x37) break; + n = n * 8 + (c - 0x30); + i++; + } + return n; +} + +// GNU base-256: 0x80 prefix for positive values, 0xff for negative ones +// (two's complement over the whole field). +function readBase256(buf, off, len) { + const end = off + len; + if (buf[off] === 0xff) { + // Negative: invert and add one. + let n = 0; + for (let i = off; i < end; i++) { + n = n * 256 + (0xff - buf[i]); + } + return -(n + 1); + } + let n = buf[off] & 0x7f; + for (let i = off + 1; i < end; i++) { + n = n * 256 + buf[i]; + } + return n; +} + +// Reads a NUL-terminated (or field-length) string. ASCII-only strings take the +// faster latin1 path; anything else is decoded as UTF-8. +function readString(buf, off, len) { + const max = off + len; + let end = off; + let high = 0; + while (end < max) { + const c = buf[end]; + if (c === 0) break; + high |= c; + end++; + } + if (end === off) { + return ''; + } + return (high & 0x80) === 0 ? buf.latin1Slice(off, end) : buf.utf8Slice(off, end); +} + +// Decodes a verified header block into `entry`. Pax/GNU overrides are applied +// later by the parser. +function decodeHeader(buf, off, entry, cache) { + const flag = buf[off + TYPEFLAG]; + entry.type = typeNames[flag]; + entry.mode = readOctal(buf, off + MODE, 8); + entry.uid = readOctal(buf, off + UID, 8); + entry.gid = readOctal(buf, off + GID, 8); + entry.size = readOctal(buf, off + SIZE, 12); + entry.mtime = toDate(readOctal(buf, off + MTIME, 12)); + entry.linkpath = buf[off + LINKNAME] === 0 ? '' : readString(buf, off + LINKNAME, 100); + + // "ustar\0" + "00" is POSIX, "ustar \0" is GNU, anything else is v7. + const m = off + MAGIC; + let format = FORMAT_V7; + if (buf[m] === 0x75 && buf[m + 1] === 0x73 && buf[m + 2] === 0x74 && + buf[m + 3] === 0x61 && buf[m + 4] === 0x72) { + format = buf[m + 5] === 0 ? FORMAT_USTAR : FORMAT_GNU; + } + + let path = readString(buf, off + NAME, NAME_LEN); + if (format !== FORMAT_V7) { + entry.uname = cache.uname.read(buf, off + UNAME, UNAME_LEN); + entry.gname = cache.gname.read(buf, off + GNAME, UNAME_LEN); + // Only devices have device numbers. + if (flag === 0x33 || flag === 0x34) { + entry.devmajor = readOctal(buf, off + DEVMAJOR, 8); + entry.devminor = readOctal(buf, off + DEVMINOR, 8); + } + if (format === FORMAT_USTAR) { + if (buf[off + PREFIX] !== 0) { + const prefix = readString(buf, off + PREFIX, PREFIX_LEN); + path = `${prefix}/${path}`; + } + } else { + // GNU stores access and change time where ustar has the prefix. + if (buf[off + GNU_ATIME] !== 0) { + entry.atime = toDate(readOctal(buf, off + GNU_ATIME, 12)); + } + if (buf[off + GNU_CTIME] !== 0) { + entry.ctime = toDate(readOctal(buf, off + GNU_CTIME, 12)); + } + } + } + entry.path = path; +} + +module.exports = { + BLOCK_SIZE, + BLOCK_OK, + BLOCK_ZERO, + BLOCK_INVALID, + TYPE_PAX, + TYPE_PAX_GLOBAL, + TYPE_GNU_LONG_PATH, + TYPE_GNU_LONG_LINK, + TYPE_OLD_PAX, + HeaderCache, + decodeHeader, + readOctal, + readSize, + readString, + readTypeflag, + toDate, + verifyChecksum, +}; diff --git a/lib/internal/tar/parser.js b/lib/internal/tar/parser.js new file mode 100644 index 00000000000..949739c0656 --- /dev/null +++ b/lib/internal/tar/parser.js @@ -0,0 +1,464 @@ +'use strict'; + +// A push parser for tar streams. +// +// The parser is a plain state machine: it does no I/O and creates no streams. +// Feed it chunks with write(), and it calls back synchronously: +// +// onentry(entry) for every entry. Return false to skip its body. +// ondata(chunk, entry) for each part of the body of a wanted entry. +// `chunk` is a view into the written chunk. +// onentryend(entry) after the last part of a wanted body. +// +// When no `ondata` callback is given, every body is skipped. A skipped body is +// reported by `skippable`, so that sources that can seek (files) can jump over +// it instead of reading it: see skip(). + +const { + NumberIsSafeInteger, + ObjectAssign, +} = primordials; + +const { + codes: { + ERR_INVALID_ARG_TYPE, + ERR_OUT_OF_RANGE, + ERR_TAR_INVALID_ARCHIVE, + ERR_TAR_INVALID_ENTRY, + }, +} = require('internal/errors'); +const { + validateBoolean, + validateFunction, + validateInteger, + validateObject, +} = require('internal/validators'); +const { Buffer } = require('buffer'); +const { isArrayBufferView } = require('internal/util/types'); +const { + BLOCK_SIZE, + BLOCK_OK, + BLOCK_ZERO, + TYPE_PAX, + TYPE_PAX_GLOBAL, + TYPE_GNU_LONG_PATH, + TYPE_GNU_LONG_LINK, + TYPE_OLD_PAX, + HeaderCache, + decodeHeader, + readSize, + readString, + readTypeflag, + verifyChecksum, +} = require('internal/tar/header'); +const { PaxRecords, applyPax, parsePax } = require('internal/tar/pax'); +const { TarEntry } = require('internal/tar/entry'); + +const S_HEADER = 0; +const S_BODY = 1; +const S_SKIP = 2; +const S_META = 3; +const S_END = 4; + +const DEFAULT_MAX_META_SIZE = 1024 * 1024; + +function noop() {} + +function paddingOf(size) { + return (BLOCK_SIZE - (size % BLOCK_SIZE)) % BLOCK_SIZE; +} + +// The internal parser. Its options are trusted and its chunks must be +// Buffers: see TarParser for the public, validating variant. +class Parser { + #onentry; + #ondata; + #onentryend; + #onwarn; + #strict; + #maxMetaSize; + + #state = S_HEADER; + // Bytes left in the current body, skipped area or meta entry. + #remaining = 0; + // Padding after the current body. + #padding = 0; + #entry = null; + // Absolute position in the archive. + #position = 0; + #ended = false; + #sawZeroBlock = false; + + // A header block split across chunks. + #block = null; + #blockLength = 0; + // Body of a pax or GNU long name entry split across chunks. + #meta = null; + #metaLength = 0; + #metaType = 0; + + #globalPax = null; + #nextPax = null; + #longPath = null; + #longLink = null; + #cache = new HeaderCache(); + + constructor(options) { + this.#onentry = options.onentry ?? noop; + this.#ondata = options.ondata ?? null; + this.#onentryend = options.onentryend ?? noop; + this.#onwarn = options.onwarn ?? noop; + this.#strict = options.strict === true; + this.#maxMetaSize = options.maxMetaSize ?? DEFAULT_MAX_META_SIZE; + } + + // Bytes that the parser will discard without looking at them. + get skippable() { + return this.#state === S_SKIP ? this.#remaining : 0; + } + + // True when the archive end marker has been seen. + get done() { + return this.#state === S_END; + } + + // Tells the parser that the source jumped over `n` skippable bytes. + skip(n) { + this.#remaining -= n; + this.#position += n; + if (this.#remaining === 0) { + this.#state = S_HEADER; + } + } + + // Skips the rest of the body being delivered: no more ondata() nor + // onentryend() for it. Returns false when no body is being delivered. + skipBody() { + if (this.#state !== S_BODY) return false; + this.#entry = null; + this.#remaining += this.#padding; + this.#state = S_SKIP; + return true; + } + + write(chunk) { + const len = chunk.length; + let pos = 0; + while (pos < len) { + switch (this.#state) { + case S_HEADER: { + const have = this.#blockLength; + if (have === 0 && len - pos >= BLOCK_SIZE) { + this.#header(chunk, pos); + pos += BLOCK_SIZE; + break; + } + // Copied: the source may reuse its buffer. + const block = this.#block ??= Buffer.allocUnsafeSlow(BLOCK_SIZE); + const need = BLOCK_SIZE - have; + if (len - pos < need) { + chunk.copy(block, have, pos, len); + this.#blockLength = have + len - pos; + pos = len; + } else { + chunk.copy(block, have, pos, pos + need); + pos += need; + this.#blockLength = 0; + this.#header(block, 0); + } + break; + } + case S_BODY: { + const avail = len - pos; + const remaining = this.#remaining; + if (avail >= remaining) { + const end = pos + remaining; + this.#position += remaining; + this.#remaining = 0; + this.#ondata(pos === 0 && end === len ? chunk : chunk.subarray(pos, end), this.#entry); + pos = end; + // The callback may have called skipBody(). + if (this.#state === S_BODY) this.#endBody(); + } else { + this.#remaining = remaining - avail; + this.#position += avail; + this.#ondata(pos === 0 ? chunk : chunk.subarray(pos), this.#entry); + pos = len; + } + break; + } + case S_SKIP: { + const avail = len - pos; + const remaining = this.#remaining; + if (avail >= remaining) { + pos += remaining; + this.#position += remaining; + this.#remaining = 0; + this.#state = S_HEADER; + } else { + this.#remaining = remaining - avail; + this.#position += avail; + pos = len; + } + break; + } + case S_META: { + const avail = len - pos; + const remaining = this.#remaining; + if (avail >= remaining) { + const end = pos + remaining; + let data; + if (this.#meta === null) { + data = chunk.subarray(pos, end); + } else { + data = this.#meta; + chunk.copy(data, this.#metaLength, pos, end); + this.#meta = null; + this.#metaLength = 0; + } + pos = end; + this.#position += remaining; + this.#remaining = 0; + this.#endMeta(data); + } else { + // Copied: the source may reuse its buffer. The size was checked + // against maxMetaSize. + this.#meta ??= Buffer.allocUnsafeSlow(remaining); + chunk.copy(this.#meta, this.#metaLength, pos, len); + this.#metaLength += avail; + this.#remaining = remaining - avail; + this.#position += avail; + pos = len; + } + break; + } + default: + // After the end marker: ignore trailing data (usually zeros). + this.#position += len - pos; + pos = len; + } + } + } + + end() { + if (this.#ended) return; + this.#ended = true; + // Drop the references to the last buffers seen. + this.#cache = new HeaderCache(); + this.#block = null; + this.#meta = null; + if (this.#state === S_END) return; + if (this.#state === S_HEADER && this.#blockLength === 0) { + // EOF on a block boundary without the end marker: accepted. + if (this.#nextPax !== null || this.#longPath !== null || this.#longLink !== null) { + throw new ERR_TAR_INVALID_ARCHIVE('unexpected end of archive after an extended header'); + } + this.#state = S_END; + return; + } + // Trailing padding of the last entry missing: tolerated. + if (this.#state === S_SKIP && this.#entry === null && this.#remaining <= this.#padding) { + this.#state = S_END; + return; + } + throw truncatedArchive(this.#position, this.#entry?.path); + } + + #warn(message, position, path) { + const err = new ERR_TAR_INVALID_ENTRY(message); + err.position = position; + if (path !== undefined) err.path = path; + if (this.#strict) { + throw err; + } + this.#onwarn(err); + } + + #header(buf, off) { + const offset = this.#position; + this.#position += BLOCK_SIZE; + const check = verifyChecksum(buf, off, this.#cache); + if (check !== BLOCK_OK) { + if (check === BLOCK_ZERO) { + if (this.#sawZeroBlock) { + this.#state = S_END; + } else { + this.#sawZeroBlock = true; + } + return; + } + this.#warn('invalid header checksum', offset); + return; + } + this.#sawZeroBlock = false; + + const flag = readTypeflag(buf, off); + if (flag === TYPE_PAX || flag === TYPE_PAX_GLOBAL || flag === TYPE_GNU_LONG_PATH || + flag === TYPE_GNU_LONG_LINK || flag === TYPE_OLD_PAX) { + this.#startMeta(buf, off, flag, offset); + return; + } + + const entry = new TarEntry(); + decodeHeader(buf, off, entry, this.#cache); + entry.offset = offset; + const globalPax = this.#globalPax; + const nextPax = this.#nextPax; + if (globalPax !== null) { + applyPax(entry, globalPax); + } + if (nextPax !== null) { + applyPax(entry, nextPax); + entry.pax = globalPax !== null ? ObjectAssign(new PaxRecords(), globalPax, nextPax) : nextPax; + this.#nextPax = null; + } else if (globalPax !== null) { + entry.pax = globalPax; + } + if (this.#longPath !== null) { + entry.path = this.#longPath; + this.#longPath = null; + } + if (this.#longLink !== null) { + entry.linkpath = this.#longLink; + this.#longLink = null; + } + + const size = entry.size; + if (size < 0 || !NumberIsSafeInteger(size)) { + this.#warn('invalid entry size', offset, entry.path); + return; + } + const padding = paddingOf(size); + + if (this.#onentry(entry) === false || this.#ondata === null) { + this.#entry = null; + this.#remaining = size + padding; + this.#padding = padding; + this.#state = this.#remaining > 0 ? S_SKIP : S_HEADER; + return; + } + + this.#entry = entry; + this.#padding = padding; + if (size === 0) { + this.#endBody(); + } else { + this.#remaining = size; + this.#state = S_BODY; + } + } + + #endBody() { + const entry = this.#entry; + this.#entry = null; + this.#afterBody(); + this.#onentryend(entry); + } + + #afterBody() { + if (this.#padding > 0) { + this.#remaining = this.#padding; + this.#state = S_SKIP; + } else { + this.#state = S_HEADER; + } + } + + #startMeta(buf, off, flag, offset) { + const size = readSize(buf, off); + const padding = paddingOf(size); + this.#entry = null; + if (size > this.#maxMetaSize || size < 0 || !NumberIsSafeInteger(size)) { + if (size < 0 || !NumberIsSafeInteger(size)) { + this.#warn('invalid extended header size', offset); + return; + } + this.#padding = padding; + this.#remaining = size + padding; + this.#state = this.#remaining > 0 ? S_SKIP : S_HEADER; + this.#warn('extended header too large', offset); + return; + } + this.#padding = padding; + this.#metaType = flag; + if (size === 0) { + this.#endMeta(Buffer.alloc(0)); + return; + } + this.#remaining = size; + this.#state = S_META; + } + + #endMeta(data) { + switch (this.#metaType) { + case TYPE_PAX: + case TYPE_OLD_PAX: + this.#nextPax = parsePax(data, this.#nextPax ?? new PaxRecords()); + break; + case TYPE_PAX_GLOBAL: + // Later global headers add to (and override) earlier ones. + this.#globalPax = parsePax( + data, + this.#globalPax !== null ? ObjectAssign(new PaxRecords(), this.#globalPax) : new PaxRecords()); + break; + case TYPE_GNU_LONG_PATH: + this.#longPath = readString(data, 0, data.length); + break; + case TYPE_GNU_LONG_LINK: + this.#longLink = readString(data, 0, data.length); + break; + } + this.#afterBody(); + } +} + +function truncatedArchive(position, path) { + const err = new ERR_TAR_INVALID_ARCHIVE('unexpected end of archive'); + err.position = position; + if (path !== undefined) err.path = path; + return err; +} + +function validateParserOptions(options) { + const { onentry, ondata, onentryend, onwarn, strict, maxMetaSize } = options; + if (onentry !== undefined) validateFunction(onentry, 'options.onentry'); + if (ondata !== undefined) validateFunction(ondata, 'options.ondata'); + if (onentryend !== undefined) validateFunction(onentryend, 'options.onentryend'); + if (onwarn !== undefined) validateFunction(onwarn, 'options.onwarn'); + if (strict !== undefined) validateBoolean(strict, 'options.strict'); + if (maxMetaSize !== undefined) validateInteger(maxMetaSize, 'options.maxMetaSize', 0); +} + +// The public parser: validates its options and its input. +class TarParser extends Parser { + constructor(options = { __proto__: null }) { + validateObject(options, 'options'); + validateParserOptions(options); + super(options); + } + + skip(n) { + validateInteger(n, 'n', 0); + if (n > this.skippable) { + throw new ERR_OUT_OF_RANGE('n', `<= ${this.skippable}`, n); + } + super.skip(n); + } + + write(chunk) { + if (!isArrayBufferView(chunk)) { + throw new ERR_INVALID_ARG_TYPE('chunk', ['Buffer', 'TypedArray', 'DataView'], chunk); + } + if (!Buffer.isBuffer(chunk)) { + chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength); + } + super.write(chunk); + } +} + +module.exports = { + Parser, + TarParser, + truncatedArchive, + validateParserOptions, +}; diff --git a/lib/internal/tar/paths.js b/lib/internal/tar/paths.js new file mode 100644 index 00000000000..63e88c8a2b1 --- /dev/null +++ b/lib/internal/tar/paths.js @@ -0,0 +1,154 @@ +'use strict'; + +// Path handling for extraction: stripping, sanitizing and joining. + +const { + ArrayPrototypeJoin, + ArrayPrototypePop, + ArrayPrototypePush, + ArrayPrototypeShift, + ArrayPrototypeSlice, + RegExpPrototypeExec, + StringPrototypeCharCodeAt, + StringPrototypeEndsWith, + StringPrototypeIndexOf, + StringPrototypeLastIndexOf, + StringPrototypeReplaceAll, + StringPrototypeSlice, + StringPrototypeSplit, + StringPrototypeStartsWith, +} = primordials; + +const { resolve } = require('path'); + +const isWindows = process.platform === 'win32'; + +// Anything that needs the slow path: absolute paths, empty, "." or ".." +// components, backslashes, drive letters. +const kNeedsNormalize = /(?:^|\/)\.{1,2}(?:\/|$)|\/\/|^\/|\\|^[a-zA-Z]:/; +const kDriveLetter = /^[a-zA-Z]:$/; +const kDriveRoot = /^[a-zA-Z]:\//; + +function normalizeCwd(cwd) { + let abs = resolve(cwd); + if (isWindows) abs = StringPrototypeReplaceAll(abs, '\\', '/'); + if (abs.length > 1 && StringPrototypeEndsWith(abs, '/')) abs = StringPrototypeSlice(abs, 0, -1); + return abs; +} + +function parentOf(abs) { + const i = StringPrototypeLastIndexOf(abs, '/'); + if (i <= 0) return '/'; + // Windows drive root: "C:/x" -> "C:/" + if (i === 2 && StringPrototypeCharCodeAt(abs, 1) === 58) return StringPrototypeSlice(abs, 0, 3); + return StringPrototypeSlice(abs, 0, i); +} + +// Result of sanitize() when the entry must be skipped. +const SKIP = null; + +// Turns an archive path into a clean relative path ('' is the root). Returns +// SKIP (null) when the path must not be extracted, after calling +// warn(message, info), unless the path is only stripped away. +function sanitize(path, strip, preservePaths, maxDepth, warn) { + if (StringPrototypeIndexOf(path, '\0') !== -1) { + warn('path contains a null byte', false); + return SKIP; + } + if (isWindows) path = StringPrototypeReplaceAll(path, '\\', '/'); + + if (strip === 0 && RegExpPrototypeExec(kNeedsNormalize, path) === null) { + // Fast path: already clean, maybe with a trailing slash. + const clean = StringPrototypeCharCodeAt(path, path.length - 1) === 47 ? + StringPrototypeSlice(path, 0, -1) : path; + if (maxDepth !== Infinity && depthOf(clean) > maxDepth) { + warn(`path exceeds the maximum depth of ${maxDepth}`, false); + return SKIP; + } + return clean; + } + + let parts = StringPrototypeSplit(path, '/'); + if (strip > 0) { + // Leading empty components of absolute paths count, like the other + // components. + if (parts.length <= strip) return SKIP; + parts = ArrayPrototypeSlice(parts, strip); + } + + if (!preservePaths) { + // Absolute paths become relative. + let absolute = false; + if (parts.length > 0 && RegExpPrototypeExec(kDriveLetter, parts[0]) !== null) { + ArrayPrototypeShift(parts); + absolute = true; + } + while (parts.length > 0 && parts[0] === '') { + ArrayPrototypeShift(parts); + absolute = true; + } + if (absolute) { + warn('absolute path made relative', true); + } + } + + const out = []; + for (let i = 0; i < parts.length; i++) { + const p = parts[i]; + if (p === '' || p === '.') continue; + if (p === '..') { + if (!preservePaths) { + warn("path contains '..'", false); + return SKIP; + } + if (out.length === 0 || out[out.length - 1] === '..') { + ArrayPrototypePush(out, '..'); + } else { + ArrayPrototypePop(out); + } + continue; + } + ArrayPrototypePush(out, p); + } + + if (out.length > maxDepth) { + warn(`path exceeds the maximum depth of ${maxDepth}`, false); + return SKIP; + } + + // With preservePaths, absolute paths stay absolute. + if (preservePaths && strip === 0) { + if (StringPrototypeCharCodeAt(path, 0) === 47) { + return { __proto__: null, absolute: `/${ArrayPrototypeJoin(out, '/')}` }; + } + if (RegExpPrototypeExec(kDriveRoot, path) !== null) { + // The drive is the first component of `out`. + return { __proto__: null, absolute: out.length === 1 ? `${out[0]}/` : ArrayPrototypeJoin(out, '/') }; + } + } + return ArrayPrototypeJoin(out, '/'); +} + +function depthOf(p) { + if (p === '') return 0; + let n = 1; + let i = -1; + while ((i = StringPrototypeIndexOf(p, '/', i + 1)) !== -1) n++; + return n; +} + +// Joins a sanitized path (string, or { absolute }) with the base dir. +function join(cwd, rel) { + if (typeof rel !== 'string') return rel.absolute; + if (rel === '') return cwd; + if (StringPrototypeStartsWith(rel, '..')) return normalizeCwd(`${cwd}/${rel}`); + return cwd === '/' ? `/${rel}` : `${cwd}/${rel}`; +} + +module.exports = { + SKIP, + join, + normalizeCwd, + parentOf, + sanitize, +}; diff --git a/lib/internal/tar/pax.js b/lib/internal/tar/pax.js new file mode 100644 index 00000000000..64a52e1b88a --- /dev/null +++ b/lib/internal/tar/pax.js @@ -0,0 +1,141 @@ +'use strict'; + +// POSIX pax extended header records: " =\n". + +const { + ArrayPrototypePush, + Number, + NumberIsFinite, + NumberIsSafeInteger, + StringPrototypeCharCodeAt, +} = primordials; + +const { toDate } = require('internal/tar/header'); + +// The records of a pax header. Object.prototype is not in its prototype +// chain, so that any key is safe ('__proto__' included). Unlike a plain +// null-prototype object, V8 keeps these objects in fast mode, which makes +// them several times faster to fill and to read. +function PaxRecords() {} +PaxRecords.prototype = { __proto__: null }; + +// Keys that are common enough to be compared rather than decoded, by length. +const KNOWN_KEYS = [ + 'path', 'linkpath', 'size', 'uid', 'gid', 'uname', 'gname', 'mtime', + 'atime', 'ctime', 'charset', 'comment', 'hdrcharset', + 'GNU.sparse.name', 'GNU.sparse.major', 'GNU.sparse.minor', + 'GNU.sparse.realsize', 'GNU.sparse.size', 'GNU.sparse.numblocks', + 'SCHILY.dev', 'SCHILY.ino', 'SCHILY.nlink', 'SCHILY.fflags', + 'LIBARCHIVE.creationtime', +]; +const keysByLength = []; +for (let i = 0; i < KNOWN_KEYS.length; i++) { + const key = KNOWN_KEYS[i]; + while (keysByLength.length <= key.length) ArrayPrototypePush(keysByLength, null); + keysByLength[key.length] ??= []; + ArrayPrototypePush(keysByLength[key.length], key); +} + +function matches(buf, start, key) { + for (let i = 0; i < key.length; i++) { + if (buf[start + i] !== StringPrototypeCharCodeAt(key, i)) return false; + } + return true; +} + +function readKey(buf, start, end) { + const length = end - start; + const keys = length < keysByLength.length ? keysByLength[length] : null; + if (keys !== null) { + for (let k = 0; k < keys.length; k++) { + if (matches(buf, start, keys[k])) return keys[k]; + } + } + return buf.utf8Slice(start, end); +} + +// Parses the records of a pax extended header. Malformed trailing data +// (including NUL padding) stops the parse; what was read so far is kept. +function parsePax(buf, into = new PaxRecords()) { + const len = buf.length; + let i = 0; + while (i < len) { + let j = i; + let recLen = 0; + while (j < len) { + const c = buf[j]; + if (c < 0x30 || c > 0x39) break; + recLen = recLen * 10 + (c - 0x30); + j++; + } + if (j === i || buf[j] !== 0x20 || recLen <= j - i + 1 || i + recLen > len) { + break; + } + const recEnd = i + recLen; + let eq = j + 1; + while (eq < recEnd && buf[eq] !== 0x3d) eq++; + if (eq >= recEnd) { + break; + } + const key = readKey(buf, j + 1, eq); + // The record ends with a newline that is not part of the value. + const valueEnd = buf[recEnd - 1] === 0x0a ? recEnd - 1 : recEnd; + into[key] = buf.utf8Slice(eq + 1, valueEnd); + i = recEnd; + } + return into; +} + +function paxDate(value) { + const n = Number(value); + return NumberIsFinite(n) ? toDate(n) : null; +} + +function paxInt(value) { + const n = Number(value); + return NumberIsSafeInteger(n) && n >= 0 ? n : -1; +} + +// Applies pax records to an entry. Empty values mean "no override". +function applyPax(entry, pax) { + let v = pax.path; + if (v) entry.path = v; + v = pax['GNU.sparse.name']; + if (v) entry.path = v; + v = pax.linkpath; + if (v) entry.linkpath = v; + v = pax.size; + if (v) { + const n = paxInt(v); + if (n >= 0) entry.size = n; + } + v = pax.uid; + if (v) { + const n = paxInt(v); + if (n >= 0) entry.uid = n; + } + v = pax.gid; + if (v) { + const n = paxInt(v); + if (n >= 0) entry.gid = n; + } + v = pax.uname; + if (v) entry.uname = v; + v = pax.gname; + if (v) entry.gname = v; + v = pax.mtime; + if (v) { + const d = paxDate(v); + if (d !== null) entry.mtime = d; + } + v = pax.atime; + if (v) entry.atime = paxDate(v); + v = pax.ctime; + if (v) entry.ctime = paxDate(v); +} + +module.exports = { + PaxRecords, + applyPax, + parsePax, +}; diff --git a/lib/internal/tar/pool.js b/lib/internal/tar/pool.js new file mode 100644 index 00000000000..4e905b3dc04 --- /dev/null +++ b/lib/internal/tar/pool.js @@ -0,0 +1,69 @@ +'use strict'; + +// A pool of large buffers, recycled once every view of them is released. +// +// Fresh multi-megabyte buffers are expensive: the kernel maps their pages on +// first touch, and the GC must track them. The readers take buffers from +// here; each pending write of a view holds a reference to its buffer; a +// buffer goes back to the pool when the reader and every write are done with +// it. + +const { + ArrayPrototypePop, + ArrayPrototypePush, + SafeMap, +} = primordials; + +const { Buffer } = require('buffer'); + +class Slot { + constructor(buf) { + this.buf = buf; + this.refs = 0; + } +} + +class BufferPool { + constructor(size, max = 64) { + this.size = size; + this.max = max; + this.free = []; + // ArrayBuffer -> Slot, for the buffers in use. + this.used = new SafeMap(); + } + + // A buffer, held by the caller until release(). + get() { + const buf = ArrayPrototypePop(this.free) ?? Buffer.allocUnsafeSlow(this.size); + let slot = this.used.get(buf.buffer); + if (slot === undefined) { + slot = new Slot(buf); + this.used.set(buf.buffer, slot); + } + slot.refs = 1; + return buf; + } + + // Takes a reference on the buffer behind `view`, if it is pooled. + ref(view) { + const slot = this.used.get(view.buffer); + if (slot !== undefined) slot.refs++; + } + + // Drops a reference taken by get() or ref(). + release(view) { + const slot = this.used.get(view.buffer); + if (slot === undefined) return; + if (--slot.refs === 0) { + if (this.free.length < this.max) { + ArrayPrototypePush(this.free, slot.buf); + } else { + this.used.delete(view.buffer); + } + } + } +} + +module.exports = { + BufferPool, +}; diff --git a/lib/internal/tar/source.js b/lib/internal/tar/source.js new file mode 100644 index 00000000000..a26df267eb1 --- /dev/null +++ b/lib/internal/tar/source.js @@ -0,0 +1,690 @@ +'use strict'; + +// Feeding archive bytes into a Parser, from files, buffers, streams and +// iterables, with transparent decompression. +// +// Uncompressed files are read with positional reads. When the parser is +// skipping a body (because nobody wants it), the reader jumps over it instead +// of reading it. +// +// Decompression is done with SyncDecompressor, also by the async readers: it +// is several times faster than zlib streams. The async readers feed it in +// slices and yield to the event loop regularly. +// +// Options of the feeders: +// - compression: true/'gzip'/'zstd'/'brotli' to force, false to disable, +// undefined to detect; +// - file: the name of the archive, to detect brotli; +// - seek: jump over skipped bodies (files only); +// - reuse: chunks are not retained by the consumer, so read buffers can be +// reused right away; +// - pool: a BufferPool for the read buffers, when chunks are retained; +// - wait(): returns a promise when the consumer needs the reader to slow +// down, or null; +// - ondetect(kind): called with the compression found in a file, before +// anything is parsed. + +const { + ArrayPrototypePop, + ArrayPrototypePush, + MathFloor, + MathMax, + MathMin, + Promise, + PromisePrototypeThen, + SymbolAsyncIterator, + SymbolIterator, +} = primordials; + +const { + codes: { + ERR_INVALID_ARG_TYPE, + ERR_TAR_INVALID_ARCHIVE, + }, +} = require('internal/errors'); +const { Buffer } = require('buffer'); +const fs = require('fs'); +const { setImmediate } = require('timers'); +const { isAnyArrayBuffer, isArrayBufferView } = require('internal/util/types'); +const { + DETECT_LENGTH, + SyncDecompressor, + resolveCompression, +} = require('internal/tar/decompress'); +const { truncatedArchive } = require('internal/tar/parser'); + +// Reads after a seek start this small (often only a header is needed)... +const MIN_CHUNK = 4 * 1024; +// ...but the first one is larger: small archives are then read at once. +const FIRST_CHUNK = 64 * 1024; +// ...and once they have grown back to this size, the async readers read the +// next chunk while the current one is parsed. +const AHEAD_MIN = 64 * 1024; +// ...and seeks are only worth it over this many bytes. +const SEEK_MIN = 128 * 1024; +const MAX_CHUNK = 1024 * 1024; +// Compressed input is fed to the decompressor in slices, sized from the +// compression ratio so that each makes about SLICE_OUTPUT bytes (an archive +// can compress a thousand times)... +const INPUT_SLICE = 64 * 1024; +const MAX_INPUT_SLICE = 1024 * 1024; +const SLICE_OUTPUT = 4 * 1024 * 1024; +// ...yielding to the event loop after this much output. +const YIELD_EVERY = 8 * 1024 * 1024; + +function noop() {} + +// Blobs are rarely the source of an archive: their module is not loaded with +// `node:zlib`. +let isBlob; +function lazyIsBlob(value) { + isBlob ??= require('internal/blob').isBlob; + return isBlob(value); +} + +// Read buffers kept for the next calls, for the readers whose chunks are not +// retained (the async ones use two at a time). +const spares = []; +const MAX_SPARES = 2; + +function takeBuffer() { + return ArrayPrototypePop(spares) ?? Buffer.allocUnsafeSlow(MAX_CHUNK); +} + +function giveBack(buf) { + if (spares.length < MAX_SPARES) ArrayPrototypePush(spares, buf); +} + +function toBuffer(chunk) { + if (Buffer.isBuffer(chunk)) return chunk; + if (isArrayBufferView(chunk)) return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength); + if (isAnyArrayBuffer(chunk)) return Buffer.from(chunk); + throw new ERR_INVALID_ARG_TYPE('chunk', ['Buffer', 'TypedArray', 'DataView', 'ArrayBuffer'], chunk); +} + +function isBufferSource(input) { + return isArrayBufferView(input) || isAnyArrayBuffer(input); +} + +// A decompressor that writes into `parser`, until the end of the archive. +function decompressorFor(kind, parser, reuse, pool) { + return new SyncDecompressor(kind, (chunk) => { + if (!parser.done) parser.write(chunk); + }, reuse, pool); +} + +function nextTurn() { + return new Promise((resolve) => setImmediate(resolve)); +} + +// Detects the compression from the first bytes, then feeds the parser, +// directly or through a decompressor. +class Sink { + constructor(parser, opts) { + this.parser = parser; + this.opts = opts; + this.head = null; + this.decided = false; + this.dec = null; + this.lastYield = 0; + } + + write(chunk) { + if (!this.decided) { + this.head = this.head === null ? chunk : Buffer.concat([this.head, chunk]); + if (this.head.length < DETECT_LENGTH) return; + chunk = this.head; + this.head = null; + this.#decide(chunk); + } + if (this.dec === null) { + this.parser.write(chunk); + return; + } + for (let off = 0; off < chunk.length; off += INPUT_SLICE) { + this.dec.write(chunk.length <= INPUT_SLICE ? chunk : chunk.subarray(off, off + INPUT_SLICE)); + if (this.parser.done) return; + } + } + + #decide(head) { + this.decided = true; + const opts = this.opts; + const kind = resolveCompression(opts.compression, head, opts.file); + if (kind !== null) { + this.dec = decompressorFor(kind, this.parser, opts.reuse === true, opts.pool); + } + } + + // A promise when the reader should wait before the next chunk, or null. + pause() { + const wait = this.opts.wait; + if (wait !== undefined) { + const p = wait(); + if (p !== null) return p; + } + if (this.dec !== null && this.dec.produced - this.lastYield > YIELD_EVERY) { + this.lastYield = this.dec.produced; + return nextTurn(); + } + return null; + } + + end() { + try { + if (!this.decided && this.head !== null) { + const head = this.head; + this.head = null; + this.#decide(head); + this.write(head); + } + if (this.dec !== null && !this.parser.done) this.dec.end(); + } finally { + this.close(); + } + this.parser.end(); + } + + close() { + if (this.dec !== null) this.dec.close(); + } +} + +// --------------------------------------------------------------------------- +// Sync + +// Feeds a whole file into `parser`. The parser (and its consumers) must not +// retain the chunks: the read buffer is reused. +function feedFileSync(file, parser, opts) { + const fd = fs.openSync(file, 'r'); + try { + feedFdSync(fd, parser, opts); + } finally { + fs.closeSync(fd); + } +} + +function feedFdSync(fd, parser, opts) { + const seek = opts.seek === true; + const buf = takeBuffer(); + const chunkSize = buf.length; + try { + let len = seek ? FIRST_CHUNK : chunkSize; + let n = fs.readSync(fd, buf, 0, len, 0); + let pos = n; + const kind = resolveCompression(opts.compression, buf.subarray(0, MathMin(n, DETECT_LENGTH)), opts.file); + + if (kind !== null) { + const dec = decompressorFor(kind, parser, true); + try { + while (n > 0) { + dec.write(buf.subarray(0, n)); + if (parser.done) break; + n = fs.readSync(fd, buf, 0, chunkSize, pos); + pos += n; + } + if (!parser.done) dec.end(); + } finally { + dec.close(); + } + parser.end(); + return; + } + + // Skips are blind; the file size is only checked at the end. + let skipped = false; + while (n > 0) { + parser.write(n === chunkSize ? buf : buf.subarray(0, n)); + if (parser.done) break; + skipped = false; + if (seek) { + const skip = parser.skippable; + if (skip >= SEEK_MIN) { + parser.skip(skip); + pos += skip; + skipped = true; + len = MIN_CHUNK; + } else if (len < chunkSize) { + len *= 2; + } + } + n = fs.readSync(fd, buf, 0, len, pos); + pos += n; + } + if (skipped && fs.fstatSync(fd).size < pos) throw truncatedArchive(pos); + parser.end(); + } finally { + giveBack(buf); + } +} + +// Feeds a Buffer/TypedArray/ArrayBuffer, or an iterable of them. +function feedInputSync(input, parser, opts) { + if (isBufferSource(input)) { + input = toBuffer(input); + const kind = resolveCompression(opts.compression, input.subarray(0, DETECT_LENGTH), opts.file); + if (kind !== null) { + const dec = decompressorFor(kind, parser, true); + try { + dec.write(input); + if (!parser.done) dec.end(); + } finally { + dec.close(); + } + } else { + parser.write(input); + } + parser.end(); + return; + } + if (input == null || typeof input[SymbolIterator] !== 'function') { + throw new ERR_INVALID_ARG_TYPE( + 'source', ['string', 'URL', 'Buffer', 'TypedArray', 'DataView', 'ArrayBuffer', 'Iterable'], input); + } + const sink = new Sink(parser, { __proto__: null, compression: opts.compression, file: opts.file, reuse: true }); + try { + for (const chunk of input) { + sink.write(toBuffer(chunk)); + if (parser.done) break; + } + sink.end(); + } finally { + sink.close(); + } +} + +// --------------------------------------------------------------------------- +// Async + +function read(fd, buf, length, position) { + return new Promise((resolve, reject) => { + fs.read(fd, buf, 0, length, position, (err, n) => { + if (err) reject(err); + else resolve(n); + }); + }); +} + +// A read whose result is the byte count or the error, never rejected: a read +// ahead may end up not being awaited before something throws. +function readAhead(fd, buf, length, position) { + return new Promise((resolve) => { + fs.read(fd, buf, 0, length, position, (err, n) => resolve(err ?? n)); + }); +} + +function openFile(file) { + return new Promise((resolve, reject) => { + fs.open(file, 'r', (err, fd) => { + if (err) reject(err); + else resolve(fd); + }); + }); +} + +function closeFile(fd) { + return new Promise((resolve) => fs.close(fd, () => resolve())); +} + +function fstat(fd) { + return new Promise((resolve, reject) => { + fs.fstat(fd, (err, st) => { + if (err) reject(err); + else resolve(st); + }); + }); +} + +async function feedFile(file, parser, opts) { + const fd = await openFile(file); + try { + await feedFd(fd, parser, opts); + } finally { + // Read-only: nothing to wait for. + fs.close(fd, noop); + } +} + +// Reads an open file into `parser`. +async function feedFd(fd, parser, opts) { + const reuse = opts.reuse === true; + const pool = reuse ? null : (opts.pool ?? null); + const chunkSize = pool !== null ? pool.size : MAX_CHUNK; + const wait = opts.wait; + const seek = opts.seek === true; + + function take() { + if (reuse) return takeBuffer(); + return pool !== null ? pool.get() : Buffer.allocUnsafeSlow(chunkSize); + } + + function release(b) { + if (reuse) giveBack(b); + else if (pool !== null) pool.release(b); + } + + let len = seek ? MathMin(FIRST_CHUNK, chunkSize) : chunkSize; + let buf = take(); + let n; + let kind; + try { + n = await read(fd, buf, len, 0); + kind = resolveCompression(opts.compression, buf.subarray(0, MathMin(n, DETECT_LENGTH)), opts.file); + if (opts.ondetect !== undefined) opts.ondetect(kind); + } catch (err) { + release(buf); + throw err; + } + let pos = n; + + if (kind !== null) { + // The decompressor is done with a chunk when it asks for the next one: + // two buffers take turns, the next chunk being read while the current one + // is decompressed. + // A short read is the end of a file: nothing is read ahead then (it would + // only find the end), but what follows is still read if asked for (pipes + // have short reads too). + let other = take(); + let ahead = n === len ? readAhead(fd, other, chunkSize, pos) : null; + let first = buf.subarray(0, n); + try { + await feedCompressed(kind, async () => { + if (first !== null) { + const f = first; + first = null; + return f.length === 0 ? null : f; + } + let r; + if (ahead !== null) { + r = await ahead; + ahead = null; + if (typeof r !== 'number') throw r; + } else { + r = await read(fd, other, chunkSize, pos); + } + if (r === 0) return null; + pos += r; + const cur = other; + other = buf; + buf = cur; + if (r === chunkSize) ahead = readAhead(fd, other, chunkSize, pos); + return cur.subarray(0, r); + }, parser, opts); + } finally { + if (ahead !== null) await ahead; + release(buf); + release(other); + } + return; + } + + let skipped = false; + // Whether the current chunk followed another one: reads are only made ahead + // then, not right after opening or seeking (an archive of large files is + // about to seek again). + let sequential = false; + for (;;) { + if (n === 0) { + release(buf); + break; + } + // Sequential reads: the next chunk is read while this one is parsed. If + // the parser then skips past it, it is dropped. + const nextLen = seek && len < chunkSize ? len * 2 : len; + let aheadBuf = null; + let ahead = null; + if (nextLen >= AHEAD_MIN && n === len && sequential) { + aheadBuf = take(); + ahead = readAhead(fd, aheadBuf, nextLen, pos); + } + try { + try { + parser.write(n === buf.length ? buf : buf.subarray(0, n)); + } finally { + if (!reuse) release(buf); + } + if (!parser.done && wait !== undefined) { + const p = wait(); + if (p !== null) await p; + } + } catch (err) { + if (reuse) release(buf); + if (ahead !== null) { + await ahead; + release(aheadBuf); + } + throw err; + } + if (parser.done) { + if (reuse) release(buf); + if (ahead !== null) { + await ahead; + release(aheadBuf); + } + break; + } + skipped = false; + const skip = seek ? parser.skippable : 0; + if (ahead !== null) { + const r = await ahead; + if (typeof r !== 'number') { + if (reuse) release(buf); + release(aheadBuf); + throw r; + } + if (skip < SEEK_MIN || skip < r) { + // The parser goes on into the chunk read ahead. + if (reuse) release(buf); + buf = aheadBuf; + n = r; + pos += r; + len = nextLen; + sequential = true; + continue; + } + // All of it is to be skipped: the buffer is used for the next read. + if (reuse) release(buf); + buf = aheadBuf; + } else if (!reuse) { + buf = take(); + } + if (skip >= SEEK_MIN) { + parser.skip(skip); + pos += skip; + skipped = true; + sequential = false; + len = MIN_CHUNK; + } else { + sequential = true; + len = nextLen; + } + try { + n = await read(fd, buf, len, pos); + } catch (err) { + release(buf); + throw err; + } + pos += n; + } + if (skipped && (await fstat(fd)).size < pos) throw truncatedArchive(pos); + parser.end(); +} + +// Decompresses chunks returned by `next()` (null at the end) into the parser, +// in slices, yielding to the event loop now and then. +async function feedCompressed(kind, next, parser, opts) { + const wait = opts.wait; + const dec = decompressorFor(kind, parser, opts.reuse === true, opts.pool); + let lastYield = 0; + let slice = INPUT_SLICE; + try { + for (;;) { + const chunk = await next(); + if (chunk === null) break; + for (let off = 0; off < chunk.length;) { + const end = MathMin(off + slice, chunk.length); + const before = dec.produced; + dec.write(off === 0 && end === chunk.length ? chunk : chunk.subarray(off, end)); + const made = dec.produced - before; + slice = made <= 0 ? + INPUT_SLICE : + MathMax(INPUT_SLICE, MathMin(MAX_INPUT_SLICE, MathFloor(SLICE_OUTPUT * (end - off) / made))); + off = end; + if (parser.done) break; + if (wait !== undefined) { + const p = wait(); + if (p !== null) await p; + } + if (dec.produced - lastYield > YIELD_EVERY) { + lastYield = dec.produced; + await nextTurn(); + } + } + if (parser.done) break; + } + if (!parser.done) dec.end(); + } finally { + dec.close(); + } + parser.end(); +} + +// Feeds a buffer, a Blob, a Node.js Readable, a web ReadableStream, or an +// async or sync iterable of chunks. +async function feedInput(input, parser, opts) { + if (isBufferSource(input)) { + const buf = toBuffer(input); + const kind = resolveCompression(opts.compression, buf.subarray(0, DETECT_LENGTH), opts.file); + if (kind === null) { + parser.write(buf); + parser.end(); + return; + } + let done = false; + await feedCompressed(kind, async () => { + if (done) return null; + done = true; + return buf; + }, parser, opts); + return; + } + + if (lazyIsBlob(input)) { + input = input.stream(); + } + if (input == null || + (typeof input[SymbolAsyncIterator] !== 'function' && typeof input[SymbolIterator] !== 'function')) { + throw new ERR_INVALID_ARG_TYPE( + 'source', + ['string', 'URL', 'Buffer', 'TypedArray', 'DataView', 'ArrayBuffer', 'Blob', 'ReadableStream', + 'stream.Readable', 'Iterable', 'AsyncIterable'], + input); + } + if (typeof input.on === 'function' && typeof input.pause === 'function') { + await feedReadable(input, parser, opts); + return; + } + + const iterator = typeof input[SymbolAsyncIterator] === 'function' ? + input[SymbolAsyncIterator]() : input[SymbolIterator](); + const sink = new Sink(parser, opts); + let finished = false; + try { + for (;;) { + const { value, done } = await iterator.next(); + if (done) { + finished = true; + break; + } + sink.write(toBuffer(value)); + if (parser.done) break; + const p = sink.pause(); + if (p !== null) await p; + } + sink.end(); + } finally { + sink.close(); + if (!finished && typeof iterator.return === 'function') await iterator.return(); + } +} + +// Feeds a Node.js readable stream, with 'data' events (faster than async +// iteration) and pause()/resume() for backpressure. +function feedReadable(stream, parser, opts) { + return new Promise((resolve, reject) => { + const sink = new Sink(parser, opts); + let settled = false; + const cleanup = () => { + stream.off('data', ondata); + stream.off('end', onend); + stream.off('error', fail); + stream.off('close', onclose); + }; + + function fail(err) { + if (settled) return; + settled = true; + cleanup(); + sink.close(); + stream.destroy(); + reject(err); + } + + function ondata(chunk) { + if (settled) return; + try { + sink.write(toBuffer(chunk)); + if (parser.done) { + settled = true; + cleanup(); + stream.destroy(); + sink.end(); + resolve(); + return; + } + const p = sink.pause(); + if (p !== null) { + stream.pause(); + PromisePrototypeThen(p, () => { + if (!settled) stream.resume(); + }, fail); + } + } catch (err) { + fail(err); + } + } + + function onend() { + if (settled) return; + settled = true; + cleanup(); + try { + sink.end(); + resolve(); + } catch (err) { + reject(err); + } + } + + function onclose() { + fail(new ERR_TAR_INVALID_ARCHIVE('the source stream closed before its end')); + } + stream.on('data', ondata); + stream.on('end', onend); + stream.on('error', fail); + stream.on('close', onclose); + // Errors after the end of the archive are not ours to report. + stream.on('error', noop); + }); +} + +module.exports = { + Sink, + closeFile, + feedFd, + feedFile, + feedFileSync, + feedInput, + feedInputSync, + openFile, +}; diff --git a/lib/internal/tar/unpack-common.js b/lib/internal/tar/unpack-common.js new file mode 100644 index 00000000000..b2ba052bf06 --- /dev/null +++ b/lib/internal/tar/unpack-common.js @@ -0,0 +1,256 @@ +'use strict'; + +// What sync and async extraction share: options, warnings and the decision of +// what to do with each entry. + +const { + Date, + DatePrototypeGetTime, + NumberIsInteger, + StringPrototypeIndexOf, +} = primordials; + +const { + codes: { + ERR_TAR_UNSAFE_ENTRY, + ERR_TAR_UNSUPPORTED_FEATURE, + }, +} = require('internal/errors'); +const { constants: { O_CREAT, O_EXCL, O_WRONLY } } = require('fs'); +const { SKIP, join, normalizeCwd, sanitize } = require('internal/tar/paths'); + +const KIND_FILE = 1; +const KIND_DIR = 2; +const KIND_SYMLINK = 3; +const KIND_LINK = 4; + +// O_EXCL makes open() fail on any existing path, symlinks included, so a file +// is never written through a pre-existing link. +const CREATE_FLAGS = O_CREAT | O_EXCL | O_WRONLY; + +const DEFAULT_MAX_DEPTH = 1024; +const MAX_ID = 2 ** 32 - 2; + +function isValidId(id) { + return NumberIsInteger(id) && id >= 0 && id <= MAX_ID; +} + +function makeOptions(options) { + const isRoot = typeof process.getuid === 'function' && process.getuid() === 0; + return { + __proto__: null, + cwd: normalizeCwd(options.cwd ?? process.cwd()), + strip: options.strip ?? 0, + filter: options.filter ?? null, + onentry: options.onentry ?? null, + onwarn: options.onwarn ?? null, + strict: options.strict === true, + preservePaths: options.preservePaths === true, + keep: options.keep === true, + newer: options.newer === true, + noMtime: options.noMtime === true, + preserveOwner: options.preserveOwner ?? isRoot, + uid: options.uid ?? null, + gid: options.gid ?? null, + chmod: options.chmod === true, + umask: options.umask ?? process.umask(), + fmode: options.fmode ?? 0o666, + dmode: options.dmode ?? 0o777, + maxDepth: options.maxDepth ?? DEFAULT_MAX_DEPTH, + now: new Date(), + }; +} + +class Plan { + constructor(kind, entry, abs, linkAbs) { + this.kind = kind; + this.entry = entry; + this.abs = abs; + this.linkAbs = linkAbs; + } +} + +function unsafeEntry(message, entry) { + const err = new ERR_TAR_UNSAFE_ENTRY(message); + err.path = entry.path; + return err; +} + +function throughSymlink(symlink, entry) { + return unsafeEntry(`cannot extract through symbolic link '${symlink}'`, entry); +} + +// Base class with the per-entry decision logic. +class UnpackBase { + constructor(options) { + this.o = makeOptions(options); + this.cwd = this.o.cwd; + this.fatal = null; + } + + // Reports a recoverable problem: thrown when strict (unless it is only + // informative), passed to onwarn() otherwise. + warn(err, entry, info = false) { + const o = this.o; + if (o.strict && !info) { + throw err; + } + if (o.onwarn !== null) { + o.onwarn(err, entry); + } + } + + // Reports a file system error for an entry: a warning, or fatal when + // strict. + entryError(err, entry) { + if (this.o.strict) { + this.fatal ??= err; + return; + } + if (this.o.onwarn !== null) { + // This runs in file system callbacks: what onwarn() throws stops the + // extraction, like what it throws from warn(). + try { + this.o.onwarn(err, entry); + } catch (err) { + this.fatal ??= err; + } + } + } + + // Decides what to do with an entry. Returns a Plan, or null to skip. + plan(entry) { + const o = this.o; + if (o.filter !== null && !o.filter(entry.path, entry)) { + return null; + } + if (o.onentry !== null) { + o.onentry(entry); + } + + let kind; + switch (entry.type) { + case 'File': + case 'ContiguousFile': + kind = KIND_FILE; + break; + case 'Directory': + case 'GNUDumpDir': + kind = KIND_DIR; + break; + case 'SymbolicLink': + kind = KIND_SYMLINK; + break; + case 'Link': + kind = KIND_LINK; + break; + default: { + const err = new ERR_TAR_UNSUPPORTED_FEATURE(`entry type '${entry.type}'`); + err.path = entry.path; + this.warn(err, entry); + return null; + } + } + + const warn = (message, info) => this.warn(unsafeEntry(message, entry), entry, info); + const rel = sanitize(entry.path, o.strip, o.preservePaths, o.maxDepth, warn); + if (rel === SKIP) { + return null; + } + const abs = join(this.cwd, rel); + if (abs === this.cwd && kind !== KIND_DIR) { + warn('it would replace the extraction directory', false); + return null; + } + + let linkAbs = null; + if (kind === KIND_LINK) { + const lrel = sanitize(entry.linkpath, o.strip, o.preservePaths, o.maxDepth, warn); + if (lrel === SKIP || lrel === '') { + if (lrel === '') warn('invalid hard link target', false); + return null; + } + linkAbs = join(this.cwd, lrel); + } else if (kind === KIND_SYMLINK && + (entry.linkpath === '' || StringPrototypeIndexOf(entry.linkpath, '\0') !== -1)) { + warn('invalid symbolic link target', false); + return null; + } + return new Plan(kind, entry, abs, linkAbs); + } + + fileMode(entry) { + return (entry.mode & 0o7777) || this.o.fmode; + } + + dirMode(entry) { + // Owner rwx is needed to fill the directory; the real mode is set at the + // end when it lacks them. + return ((entry.mode & 0o7777) || this.o.dmode) | 0o700; + } + + // The deferred mode of a directory, or -1 when mkdir already set it. + dirFinalMode(entry) { + const mode = (entry.mode & 0o7777) || this.o.dmode; + if (this.o.chmod || (mode & 0o700) !== 0o700) { + return mode & ~this.o.umask; + } + return -1; + } + + // The deferred mode of a directory that was made before its entry, with the + // default mode. + implicitDirFinalMode(entry) { + const mode = ((entry.mode & 0o7777) || this.o.dmode) & ~this.o.umask; + return mode === (this.o.dmode & ~this.o.umask) ? -1 : mode; + } + + // The [uid, gid] to give to an entry, or null to leave the owner alone. + // Identifiers come from untrusted headers: the ones that the file system + // calls would not accept are ignored. + owner(entry) { + const o = this.o; + let uid; + let gid; + if (o.uid !== null || o.gid !== null) { + uid = o.uid ?? entry.uid; + gid = o.gid ?? entry.gid; + } else if (o.preserveOwner) { + uid = entry.uid; + gid = entry.gid; + } else { + return null; + } + return isValidId(uid) && isValidId(gid) ? [uid, gid] : null; + } + + atime(entry) { + return entry.atime ?? this.o.now; + } +} + +function isEntryNewer(entry, st) { + return entry.mtime !== null && DatePrototypeGetTime(entry.mtime) > st.mtimeMs; +} + +class DeferredDir { + constructor(abs, entry, mode) { + this.abs = abs; + this.entry = entry; + this.mode = mode; + } +} + +module.exports = { + CREATE_FLAGS, + DEFAULT_MAX_DEPTH, + KIND_DIR, + KIND_FILE, + KIND_LINK, + KIND_SYMLINK, + DeferredDir, + UnpackBase, + isEntryNewer, + throughSymlink, + unsafeEntry, +}; diff --git a/lib/internal/tar/unpack-sync.js b/lib/internal/tar/unpack-sync.js new file mode 100644 index 00000000000..1ff8f88a001 --- /dev/null +++ b/lib/internal/tar/unpack-sync.js @@ -0,0 +1,319 @@ +'use strict'; + +// Synchronous extraction. + +const { + SafeSet, + StringPrototypeStartsWith, +} = primordials; + +const fs = require('fs'); +const { parentOf } = require('internal/tar/paths'); +const { + CREATE_FLAGS, + KIND_DIR, + KIND_FILE, + KIND_LINK, + KIND_SYMLINK, + DeferredDir, + UnpackBase, + isEntryNewer, + throughSymlink, + unsafeEntry, +} = require('internal/tar/unpack-common'); + +// Where link() follows a symbolic link given as its target. +const followsLinks = process.platform !== 'linux'; + +class UnpackSync extends UnpackBase { + constructor(options) { + super(options); + fs.mkdirSync(this.cwd, { __proto__: null, recursive: true }); + // Directories known to be real directories (not symlinks). + this.dirs = new SafeSet([this.cwd]); + // Directories made as parents of other entries, with the default mode. + this.madeImplicit = new SafeSet(); + this.deferred = []; + this.fd = -1; + this.current = null; + } + + // Parser callback. Returns true when the body must be delivered. + onentry(entry) { + const plan = this.plan(entry); + if (plan === null) return false; + try { + switch (plan.kind) { + case KIND_FILE: + return this.#openFile(plan); + case KIND_DIR: + this.#makeDir(plan); + return false; + case KIND_SYMLINK: + this.#symlink(plan); + return false; + case KIND_LINK: + this.#link(plan); + return false; + } + } catch (err) { + this.#error(err, entry); + } + return false; + } + + ondata(chunk) { + const fd = this.fd; + if (fd < 0) return; + try { + const len = chunk.length; + let off = fs.writeSync(fd, chunk, 0, len); + while (off < len) { + off += fs.writeSync(fd, chunk, off, len - off); + } + } catch (err) { + this.#closeCurrent(); + this.#error(err, this.current); + } + } + + onentryend(entry) { + const fd = this.fd; + if (fd < 0) return; + this.fd = -1; + const o = this.o; + try { + if (!o.noMtime && entry.mtime !== null) { + fs.futimesSync(fd, this.atime(entry), entry.mtime); + } + const owner = this.owner(entry); + if (owner !== null) { + fs.fchownSync(fd, owner[0], owner[1]); + } + if (o.chmod) { + fs.fchmodSync(fd, this.fileMode(entry) & ~o.umask); + } + } catch (err) { + this.#error(err, entry); + } finally { + fs.closeSync(fd); + } + } + + // Applies deferred directory attributes. Call after the last entry. + finish() { + this.#closeCurrent(); + const o = this.o; + const list = this.deferred; + this.deferred = []; + // Deepest first: a mode can forbid access to children. + for (let i = list.length - 1; i >= 0; i--) { + const d = list[i]; + try { + const owner = this.owner(d.entry); + if (owner !== null) { + fs.chownSync(d.abs, owner[0], owner[1]); + } + if (!o.noMtime && d.entry.mtime !== null) { + fs.utimesSync(d.abs, this.atime(d.entry), d.entry.mtime); + } + if (d.mode !== -1) { + fs.chmodSync(d.abs, d.mode); + } + } catch (err) { + this.#error(err, d.entry); + } + } + } + + // Releases resources after a failure. + abort() { + this.#closeCurrent(); + } + + #closeCurrent() { + if (this.fd >= 0) { + const fd = this.fd; + this.fd = -1; + try { + fs.closeSync(fd); + } catch { + // Nothing more can be done with it. + } + } + } + + #error(err, entry) { + this.entryError(err, entry); + if (this.fatal !== null) { + throw this.fatal; + } + } + + #openFile(plan) { + const { abs, entry } = plan; + const parent = parentOf(abs); + if (!this.dirs.has(parent)) { + this.#ensureDir(parent, entry); + } + this.#evict(abs); + const mode = this.fileMode(entry); + let fd; + try { + fd = fs.openSync(abs, CREATE_FLAGS, mode); + } catch (err) { + if (err.code === 'ENOENT') { + // A cached parent was removed under us. + this.#evict(parent); + this.#ensureDir(parent, entry); + fd = fs.openSync(abs, CREATE_FLAGS, mode); + } else if (err.code === 'EEXIST') { + if (!this.#replace(abs, entry)) return false; + fd = fs.openSync(abs, CREATE_FLAGS, mode); + } else { + throw err; + } + } + this.fd = fd; + this.current = entry; + return true; + } + + // Removes an existing path that an entry replaces. Returns false when the + // existing path must be kept. + #replace(abs, entry) { + const o = this.o; + if (o.keep) return false; + const st = fs.lstatSync(abs); + if (o.newer && !isEntryNewer(entry, st)) return false; + if (st.isDirectory()) { + fs.rmdirSync(abs); + this.#evict(abs); + } else { + fs.unlinkSync(abs); + } + return true; + } + + #makeDir(plan) { + const { abs, entry } = plan; + let mode; + if (!this.dirs.has(abs)) { + const parent = parentOf(abs); + if (!this.dirs.has(parent)) { + this.#ensureDir(parent, entry); + } + this.#mkdir(abs, this.dirMode(entry), true, entry); + this.dirs.add(abs); + mode = this.dirFinalMode(entry); + } else { + mode = this.madeImplicit.has(abs) ? this.implicitDirFinalMode(entry) : this.dirFinalMode(entry); + } + if (mode !== -1 || !this.o.noMtime || this.owner(entry) !== null) { + this.deferred[this.deferred.length] = new DeferredDir(abs, entry, mode); + } + } + + #symlink(plan) { + const { abs, entry } = plan; + const parent = parentOf(abs); + if (!this.dirs.has(parent)) { + this.#ensureDir(parent, entry); + } + this.#evict(abs); + try { + fs.symlinkSync(entry.linkpath, abs); + } catch (err) { + if (err.code !== 'EEXIST') throw err; + if (!this.#replace(abs, entry)) return; + fs.symlinkSync(entry.linkpath, abs); + } + const owner = this.owner(entry); + if (owner !== null) { + fs.lchownSync(abs, owner[0], owner[1]); + } + if (!this.o.noMtime && entry.mtime !== null) { + fs.lutimesSync(abs, this.atime(entry), entry.mtime); + } + } + + #link(plan) { + const { abs, entry, linkAbs } = plan; + const parent = parentOf(abs); + if (!this.dirs.has(parent)) { + this.#ensureDir(parent, entry); + } + if (!this.o.preservePaths) { + this.#verifyDir(parentOf(linkAbs), entry); + if (followsLinks && fs.lstatSync(linkAbs).isSymbolicLink()) { + throw throughSymlink(linkAbs, entry); + } + } + this.#evict(abs); + try { + fs.linkSync(linkAbs, abs); + } catch (err) { + if (err.code !== 'EEXIST') throw err; + if (!this.#replace(abs, entry)) return; + fs.linkSync(linkAbs, abs); + } + } + + // mkdir -p, refusing to go through symlinks. + #ensureDir(dir, entry) { + if (this.dirs.has(dir)) return; + const parent = parentOf(dir); + if (parent !== dir && !this.dirs.has(parent)) { + this.#ensureDir(parent, entry); + } + if (this.#mkdir(dir, this.o.dmode, false, entry)) { + this.madeImplicit.add(dir); + } + this.dirs.add(dir); + } + + // Checks that `dir` and its parents are real directories. + #verifyDir(dir, entry) { + if (this.dirs.has(dir)) return; + const parent = parentOf(dir); + if (parent !== dir) this.#verifyDir(parent, entry); + const st = fs.lstatSync(dir); + if (st.isSymbolicLink()) throw throughSymlink(dir, entry); + if (!st.isDirectory()) throw unsafeEntry(`'${dir}' is not a directory`, entry); + this.dirs.add(dir); + } + + // Creates one directory. `leaf` is true for the directory of a Directory + // entry, which replaces whatever is in its place. Returns true when the + // directory was made. + #mkdir(dir, mode, leaf, entry) { + try { + fs.mkdirSync(dir, mode); + return true; + } catch (err) { + if (err.code !== 'EEXIST') throw err; + } + const st = fs.lstatSync(dir); + if (st.isDirectory()) return false; + if (st.isSymbolicLink() && !leaf) { + if (this.o.preservePaths && fs.statSync(dir).isDirectory()) return false; + throw throughSymlink(dir, entry); + } + fs.unlinkSync(dir); + fs.mkdirSync(dir, mode); + return true; + } + + // Forgets `abs` and everything under it as known directories. + #evict(abs) { + if (!this.dirs.has(abs)) return; + const prefix = `${abs}/`; + this.dirs.forEach((d) => { + if (d === abs || StringPrototypeStartsWith(d, prefix)) this.dirs.delete(d); + }); + } +} + +module.exports = { + UnpackSync, +}; diff --git a/lib/internal/tar/unpack.js b/lib/internal/tar/unpack.js new file mode 100644 index 00000000000..9c91482c4cb --- /dev/null +++ b/lib/internal/tar/unpack.js @@ -0,0 +1,937 @@ +'use strict'; + +// Asynchronous extraction. +// +// Entries are turned into jobs that run concurrently on the libuv thread +// pool. Ordering is kept where it matters: +// - a job waits for the previous job on the same path; +// - a job waits for its parent directory; +// - a directory is only (re)created after the jobs on its path, so a symlink +// extracted in place of a directory is detected before anything is written +// below it. +// The number of open files is bounded (`jobs`), and so is the amount of data +// buffered in memory, through wait(). + +const { + ArrayPrototypePop, + ArrayPrototypePush, + ArrayPrototypeShift, + ArrayPrototypeSlice, + MathMin, + Promise, + PromisePrototypeThen, + PromiseReject, + PromiseResolve, + SafeMap, + SafePromiseAllReturnVoid, + SafeSet, + StringPrototypeStartsWith, +} = primordials; + +const fs = require('fs'); +const { BLOCK_SIZE } = require('internal/tar/header'); +const { truncatedArchive } = require('internal/tar/parser'); +const { parentOf } = require('internal/tar/paths'); +const { BufferPool } = require('internal/tar/pool'); +const { + CREATE_FLAGS, + KIND_DIR, + KIND_FILE, + KIND_LINK, + KIND_SYMLINK, + DeferredDir, + UnpackBase, + isEntryNewer, + throughSymlink, + unsafeEntry, +} = require('internal/tar/unpack-common'); + +// Where link() follows a symbolic link given as its target. +const followsLinks = process.platform !== 'linux'; + +const DEFAULT_JOBS = 64; +const HIGH_WATER_MARK = 32 * 1024 * 1024; +const LOW_WATER_MARK = 4 * 1024 * 1024; +const MAX_PENDING_JOBS = 4096; +// Files at least this large are copied by their own job when the archive is +// a file, see CopyJob. +const COPY_MIN_SIZE = 1024 * 1024; +const COPY_JOBS = 8; +const COPY_CHUNK_SIZE = 2 * 1024 * 1024; +const CHUNK_SIZE = 1024 * 1024; +// Smaller parts of a body are buffered up to this size before writing. +const FLUSH_SIZE = 512 * 1024; + +function lstat(path) { + return new Promise((resolve, reject) => { + fs.lstat(path, (err, st) => (err ? reject(err) : resolve(st))); + }); +} + +function stat(path) { + return new Promise((resolve, reject) => { + fs.stat(path, (err, st) => (err ? reject(err) : resolve(st))); + }); +} + +function mkdir(path, mode) { + return new Promise((resolve, reject) => { + fs.mkdir(path, mode, (err) => (err ? reject(err) : resolve())); + }); +} + +function unlink(path) { + return new Promise((resolve, reject) => { + fs.unlink(path, (err) => (err ? reject(err) : resolve())); + }); +} + +function chown(path, uid, gid) { + return new Promise((resolve, reject) => { + fs.chown(path, uid, gid, (err) => (err ? reject(err) : resolve())); + }); +} + +function utimes(path, atime, mtime) { + return new Promise((resolve, reject) => { + fs.utimes(path, atime, mtime, (err) => (err ? reject(err) : resolve())); + }); +} + +function chmod(path, mode) { + return new Promise((resolve, reject) => { + fs.chmod(path, mode, (err) => (err ? reject(err) : resolve())); + }); +} + +class Job { + constructor(u, plan) { + this.u = u; + this.plan = plan; + this.done = false; + this.error = null; + // Outstanding dependencies, plus one held by schedule(). + this.deps = 1; + this.waiters = null; + } + + hold() { + this.deps++; + } + + release(err) { + if (err && this.error === null) this.error = err; + if (--this.deps === 0) { + if (this.error !== null) { + this.fail(this.error); + return; + } + // Paths and attributes come from the archive: the file system calls + // may refuse them synchronously. + try { + this.start(); + } catch (err) { + this.fail(err); + } + } + } + + fail(err) { + this.finish(err); + } + + // Calls fn when the job is done. + whenDone(fn) { + if (this.done) { + fn(); + } else if (this.waiters === null) { + this.waiters = [fn]; + } else { + ArrayPrototypePush(this.waiters, fn); + } + } + + promise() { + return new Promise((resolve) => this.whenDone(resolve)); + } + + finish(err) { + if (this.done) return; + this.done = true; + const u = this.u; + if (err) u.entryError(err, this.plan.entry); + const abs = this.plan.abs; + if (u.busy.get(abs) === this) u.busy.delete(abs); + const waiters = this.waiters; + if (waiters !== null) { + this.waiters = null; + for (let i = 0; i < waiters.length; i++) waiters[i](); + } + u.jobDone(); + } + + // Removes what is at the path of this job, when the job may replace it. + // Calls back with true to go on, false to keep what is there. + replace(cb) { + const u = this.u; + const o = u.o; + const { abs, entry } = this.plan; + if (o.keep) return cb(null, false); + fs.lstat(abs, (err, st) => { + if (err) return cb(err.code === 'ENOENT' ? null : err, err.code === 'ENOENT'); + if (o.newer && !isEntryNewer(entry, st)) return cb(null, false); + if (st.isDirectory()) { + u.evict(abs); + fs.rmdir(abs, (err) => cb(err, !err)); + } else { + fs.unlink(abs, (err) => cb(err && err.code !== 'ENOENT' ? err : null, true)); + } + }); + } +} + +class FileJob extends Job { + constructor(u, plan) { + super(u, plan); + this.fd = -1; + this.chunks = []; + this.bytes = 0; + this.position = 0; + this.writing = false; + this.ended = false; + this.discard = false; + this.retried = false; + this.slot = false; + } + + start() { + this.u.acquire(this); + } + + // Called by the unpacker when a file descriptor slot is free. + open() { + try { + fs.open(this.plan.abs, CREATE_FLAGS, this.u.fileMode(this.plan.entry), (err, fd) => this.#onopen(err, fd)); + } catch (err) { + this.fail(err); + } + } + + #onopen(err, fd) { + if (err) { + if (!this.retried && err.code === 'EEXIST') { + this.retried = true; + this.replace((err, go) => { + if (err) return this.fail(err); + if (!go) return this.fail(null); + this.open(); + }); + return; + } + if (!this.retried && err.code === 'ENOENT') { + // The parent directory went away: make it again. + this.retried = true; + const u = this.u; + const parent = parentOf(this.plan.abs); + u.evict(parent); + PromisePrototypeThen(u.ensureDir(parent, this.plan.entry), () => this.open(), (err) => this.fail(err)); + return; + } + this.fail(err); + return; + } + this.fd = fd; + this.opened(); + } + + opened() { + if (this.chunks.length > 0 && (this.ended || this.bytes >= FLUSH_SIZE)) { + this.#flush(); + } else if (this.ended) { + this.finalize(); + } + } + + push(chunk) { + if (this.discard) return; + const u = this.u; + u.pool.ref(chunk); + ArrayPrototypePush(this.chunks, chunk); + this.bytes += chunk.length; + u.buffered += chunk.length; + // Small pieces of a large body are written together. + if (this.fd >= 0 && !this.writing && this.bytes >= FLUSH_SIZE) { + this.#flush(); + } + } + + end() { + this.ended = true; + if (this.discard) { + if (this.fd < 0 && !this.writing) this.finish(this.error); + return; + } + if (this.fd >= 0 && !this.writing) { + if (this.chunks.length > 0) this.#flush(); + else this.finalize(); + } + } + + #flush() { + this.writing = true; + const chunks = this.chunks; + const bytes = this.bytes; + this.chunks = []; + this.bytes = 0; + const cb = (err, written) => this.#onwrite(err, written, chunks, bytes); + if (chunks.length === 1) { + fs.write(this.fd, chunks[0], 0, bytes, this.position, cb); + } else { + fs.writev(this.fd, chunks, this.position, cb); + } + } + + #onwrite(err, written, chunks, bytes) { + this.writing = false; + const u = this.u; + const pool = u.pool; + if (err) { + u.buffered -= bytes; + for (let i = 0; i < chunks.length; i++) pool.release(chunks[i]); + this.fail(err); + u.checkDrain(); + return; + } + this.position += written; + if (written < bytes) { + // Short write: put the rest back in front of the queue. + let skip = written; + const rest = []; + for (let i = 0; i < chunks.length; i++) { + const c = chunks[i]; + if (skip >= c.length) { + skip -= c.length; + pool.release(c); + } else { + ArrayPrototypePush(rest, skip > 0 ? c.subarray(skip) : c); + skip = 0; + } + } + u.buffered -= written; + for (let i = 0; i < this.chunks.length; i++) ArrayPrototypePush(rest, this.chunks[i]); + this.chunks = rest; + this.bytes += bytes - written; + } else { + u.buffered -= bytes; + for (let i = 0; i < chunks.length; i++) pool.release(chunks[i]); + } + if (this.discard) { + // Failed while writing: fail() left the descriptor to us. + this.fail(null); + } else if (this.chunks.length > 0 && (this.ended || this.bytes >= FLUSH_SIZE)) { + this.#flush(); + } else if (this.ended) { + this.finalize(); + } + u.checkDrain(); + } + + finalize() { + const u = this.u; + const o = u.o; + const entry = this.plan.entry; + const fd = this.fd; + const owner = u.owner(entry); + const close = (err) => { + this.fd = -1; + fs.close(fd, (err2) => { + this.releaseSlot(); + this.finish(err || err2); + }); + }; + const chmod = (err) => { + if (err || !o.chmod) return close(err); + fs.fchmod(fd, u.fileMode(entry) & ~o.umask, close); + }; + const chown = (err) => { + if (err || owner === null) return chmod(err); + fs.fchown(fd, owner[0], owner[1], chmod); + }; + if (!o.noMtime && entry.mtime !== null) { + fs.futimes(fd, u.atime(entry), entry.mtime, chown); + } else { + chown(null); + } + } + + // Stops writing: the rest of the body is dropped. + fail(err) { + const u = this.u; + this.discard = true; + if (this.chunks.length > 0) { + u.buffered -= this.bytes; + for (let i = 0; i < this.chunks.length; i++) u.pool.release(this.chunks[i]); + this.bytes = 0; + this.chunks = []; + u.checkDrain(); + } + if (err) this.error ??= err; + // A write in flight still uses the descriptor: its callback comes back + // here. + if (this.writing) return; + if (this.fd >= 0) { + const fd = this.fd; + this.fd = -1; + fs.close(fd, () => { + this.releaseSlot(); + if (this.ended) this.finish(this.error); + }); + return; + } + this.releaseSlot(); + if (this.ended) this.finish(this.error); + } + + releaseSlot() { + if (this.slot) { + this.slot = false; + this.u.releaseSlot(); + } + } +} + +// A file whose body is copied straight from the archive file, by the job +// itself, while the parser jumps over it. Large files are extracted this way, +// in parallel. Two buffers: the next read runs during the write. +class CopyJob extends FileJob { + constructor(u, plan, srcFd) { + super(u, plan); + this.srcFd = srcFd; + this.srcPos = plan.entry.offset + BLOCK_SIZE; + this.toRead = plan.entry.size; + this.toWrite = plan.entry.size; + this.ended = true; + this.free = null; + this.filled = []; + this.reading = false; + this.copying = false; + this.stopped = false; + } + + opened() { + this.u.copySlots.acquire(() => { + const pool = this.u.copyPool; + this.free = [pool.get(), pool.get()]; + this.#readNext(); + }); + } + + #readNext() { + if (this.stopped || this.toRead === 0 || this.reading || this.free.length === 0) return; + const buf = ArrayPrototypePop(this.free); + const len = MathMin(buf.length, this.toRead); + const pos = this.srcPos; + this.toRead -= len; + this.srcPos += len; + this.reading = true; + fs.read(this.srcFd, buf, 0, len, pos, (err, n) => { + this.reading = false; + if (!err && n !== len) { + err = truncatedArchive(pos + n, this.plan.entry.path); + } + if (this.stopped || err) { + this.#drop(buf); + return this.#stop(err); + } + ArrayPrototypePush(this.filled, buf, n); + this.#writeNext(); + this.#readNext(); + }); + } + + #writeNext() { + if (this.stopped || this.copying || this.filled.length === 0) return; + const buf = ArrayPrototypeShift(this.filled); + const n = ArrayPrototypeShift(this.filled); + this.copying = true; + this.#write(buf, 0, n); + } + + #write(buf, off, n) { + fs.write(this.fd, buf, off, n, this.position, (err, w) => { + if (this.stopped || err) { + this.copying = false; + this.#drop(buf); + return this.#stop(err); + } + this.position += w; + if (w < n) return this.#write(buf, off + w, n - w); + this.copying = false; + this.toWrite -= off + n; + ArrayPrototypePush(this.free, buf); + if (this.toWrite === 0) { + this.#release(); + this.finalize(); + return; + } + this.#writeNext(); + this.#readNext(); + }); + } + + #drop(buf) { + this.u.copyPool.release(buf); + } + + // Gives back the buffers and the copy slot, once nothing is in flight. + #release() { + if (this.free === null) return; + const pool = this.u.copyPool; + for (let i = 0; i < this.free.length; i++) pool.release(this.free[i]); + for (let i = 0; i < this.filled.length; i += 2) pool.release(this.filled[i]); + this.free = null; + this.filled = []; + this.u.copySlots.release(); + } + + #stop(err) { + if (!this.stopped) { + this.stopped = true; + this.error = err ?? this.error; + } + if (this.reading || this.copying) return; + this.#release(); + this.fail(this.error); + } +} + +class Semaphore { + constructor(max) { + this.max = max; + this.active = 0; + this.queue = []; + this.head = 0; + } + + acquire(fn) { + if (this.active < this.max) { + this.active++; + fn(); + } else { + ArrayPrototypePush(this.queue, fn); + } + } + + release() { + if (this.head < this.queue.length) { + const fn = this.queue[this.head]; + this.queue[this.head++] = undefined; + if (this.head > 1024 && this.head * 2 > this.queue.length) { + this.queue = ArrayPrototypeSlice(this.queue, this.head); + this.head = 0; + } + fn(); + } else { + this.active--; + } + } +} + +class DirJob extends Job { + start() { + const u = this.u; + const { abs, entry } = this.plan; + PromisePrototypeThen(u.ensureDir(abs, entry, u.dirMode(entry), true), () => { + const mode = u.madeImplicit.has(abs) ? u.implicitDirFinalMode(entry) : u.dirFinalMode(entry); + if (mode !== -1 || !u.o.noMtime || u.owner(entry) !== null) { + ArrayPrototypePush(u.deferred, new DeferredDir(abs, entry, mode)); + } + this.finish(null); + }, (err) => this.finish(err)); + } +} + +class SymlinkJob extends Job { + start() { + const { abs, entry } = this.plan; + const make = (retry) => { + fs.symlink(entry.linkpath, abs, (err) => { + if (err) { + if (retry && err.code === 'EEXIST') { + return this.replace((err, go) => { + if (err) return this.finish(err); + if (!go) return this.finish(null); + make(false); + }); + } + return this.finish(err); + } + const u = this.u; + const times = (err) => { + if (err || u.o.noMtime || entry.mtime === null) return this.finish(err); + fs.lutimes(abs, u.atime(entry), entry.mtime, (err) => this.finish(err)); + }; + const owner = u.owner(entry); + if (owner === null) return times(null); + fs.lchown(abs, owner[0], owner[1], times); + }); + }; + make(true); + } +} + +class LinkJob extends Job { + start() { + const u = this.u; + const { abs, entry, linkAbs } = this.plan; + const make = (retry) => { + fs.link(linkAbs, abs, (err) => { + if (err) { + if (retry && err.code === 'EEXIST') { + return this.replace((err, go) => { + if (err) return this.finish(err); + if (!go) return this.finish(null); + make(false); + }); + } + return this.finish(err); + } + this.finish(null); + }); + }; + if (u.o.preservePaths) return make(true); + const verified = PromisePrototypeThen(u.verifyDir(parentOf(linkAbs), entry), async () => { + if (followsLinks && (await lstat(linkAbs)).isSymbolicLink()) { + throw throughSymlink(linkAbs, entry); + } + }); + PromisePrototypeThen(verified, () => make(true), (err) => this.finish(err)); + } +} + +class Unpack extends UnpackBase { + constructor(options) { + super(options); + // abs -> true (a real directory), or a promise while it is made. + this.dirs = new SafeMap(); + // Directories made as parents of other entries, not from their own entry + // (yet): their mode is the default one. + this.madeImplicit = new SafeSet(); + // abs -> the last job on that path, while it runs. + this.busy = new SafeMap(); + this.deferred = []; + this.pending = 0; + this.buffered = 0; + this.maxOpen = options.jobs ?? DEFAULT_JOBS; + // Data waiting to be written, past which the reader waits. More lets the + // writes of consecutive files overlap. + this.highWaterMark = options.highWaterMark ?? HIGH_WATER_MARK; + this.lowWaterMark = MathMin(LOW_WATER_MARK, this.highWaterMark / 4); + this.slots = 0; + this.slotQueue = []; + this.slotHead = 0; + this.current = null; + this.drain = null; + this.drainResolve = null; + this.idle = null; + this.idleResolve = null; + this.ready = null; + this.pool = new BufferPool(CHUNK_SIZE); + this.copySlots = new Semaphore(COPY_JOBS); + this.copyPool = new BufferPool(COPY_CHUNK_SIZE, COPY_JOBS * 2); + // The archive file descriptor, when bodies can be read from it. + this.source = -1; + } + + // Lets large file bodies be read from the uncompressed archive `fd`. + setSource(fd) { + this.source = fd; + } + + // Makes the extraction directory. Must be awaited before parsing. + init() { + this.ready ??= new Promise((resolve, reject) => { + fs.mkdir(this.cwd, { __proto__: null, recursive: true }, (err) => { + if (err) return reject(err); + this.dirs.set(this.cwd, true); + resolve(); + }); + }); + return this.ready; + } + + // Parser callbacks. + + onentry(entry) { + if (this.fatal !== null) return false; + const plan = this.plan(entry); + if (plan === null) return false; + switch (plan.kind) { + case KIND_FILE: { + if (this.source !== -1 && entry.size >= COPY_MIN_SIZE) { + this.#schedule(new CopyJob(this, plan, this.source)); + return false; + } + const job = new FileJob(this, plan); + this.current = job; + this.#schedule(job); + return true; + } + case KIND_DIR: + // Directories are ordered by ensureDir() itself, which must see the + // directory right away so that later entries wait for it. + this.pending++; + new DirJob(this, plan).release(null); + return false; + case KIND_SYMLINK: + this.#schedule(new SymlinkJob(this, plan)); + return false; + case KIND_LINK: + this.#schedule(new LinkJob(this, plan)); + return false; + } + return false; + } + + ondata(chunk) { + this.current.push(chunk); + } + + onentryend() { + const job = this.current; + this.current = null; + job.end(); + } + + #schedule(job) { + this.pending++; + const { abs, kind, linkAbs, entry } = job.plan; + if (kind !== KIND_DIR) { + // A directory still being made here (directories are not in `busy`): + // let it be made first, or it would replace this entry. + const making = this.dirs.get(abs); + if (making !== undefined && making !== true) { + job.hold(); + PromisePrototypeThen(making, () => job.release(null), () => job.release(null)); + } + // Whatever was a known directory here is about to be replaced. + this.evict(abs); + } + const prev = this.busy.get(abs); + this.busy.set(abs, job); + if (prev !== undefined && !prev.done) { + job.hold(); + prev.whenDone(() => job.release(null)); + } + const parent = parentOf(abs); + if (this.dirs.get(parent) !== true) { + job.hold(); + PromisePrototypeThen(this.ensureDir(parent, entry), () => job.release(null), (err) => job.release(err)); + } + if (linkAbs !== null) { + const target = this.busy.get(linkAbs); + if (target !== undefined && !target.done && target !== job) { + job.hold(); + target.whenDone(() => job.release(null)); + } + } + job.release(null); + } + + // Directory creation, shared by all the jobs that need a directory. + // `entry` is the entry that needs it. + ensureDir(dir, entry, mode = this.o.dmode, leaf = false) { + const known = this.dirs.get(dir); + if (known !== undefined) { + return known === true ? PromiseResolve() : known; + } + const parent = parentOf(dir); + const steps = []; + if (parent !== dir && this.dirs.get(parent) !== true) { + ArrayPrototypePush(steps, this.ensureDir(parent, entry)); + } + // Something else is being extracted at this path: let it finish, then + // look at what it left there. + const job = this.busy.get(dir); + if (job !== undefined && !job.done && job.plan.kind !== KIND_DIR) { + ArrayPrototypePush(steps, job.promise()); + } + const made = steps.length === 0 ? + this.#mkdir(dir, mode, leaf, entry) : + PromisePrototypeThen(SafePromiseAllReturnVoid(steps), () => this.#mkdir(dir, mode, leaf, entry)); + const p = PromisePrototypeThen(made, () => { + if (this.dirs.get(dir) === p) this.dirs.set(dir, true); + }, (err) => { + if (this.dirs.get(dir) === p) this.dirs.delete(dir); + throw err; + }); + // Every user of the directory handles the rejection too. + PromisePrototypeThen(p, undefined, () => {}); + this.dirs.set(dir, p); + return p; + } + + async #mkdir(dir, mode, leaf, entry) { + try { + await mkdir(dir, mode); + if (!leaf) this.madeImplicit.add(dir); + return; + } catch (err) { + if (err.code !== 'EEXIST') throw err; + } + const st = await lstat(dir); + if (st.isDirectory()) return; + if (st.isSymbolicLink() && !leaf) { + if (this.o.preservePaths && (await stat(dir)).isDirectory()) return; + throw throughSymlink(dir, entry); + } + await unlink(dir); + await mkdir(dir, mode); + } + + // Checks that `dir` and its parents are real directories, without making + // anything. + async verifyDir(dir, entry) { + const known = this.dirs.get(dir); + if (known === true) return; + if (known !== undefined) { + await known; + return; + } + const parent = parentOf(dir); + if (parent !== dir) await this.verifyDir(parent, entry); + const st = await lstat(dir); + if (st.isSymbolicLink()) throw throughSymlink(dir, entry); + if (!st.isDirectory()) throw unsafeEntry(`'${dir}' is not a directory`, entry); + } + + // Forgets `abs` and everything under it as known directories. + evict(abs) { + if (!this.dirs.has(abs)) return; + const prefix = `${abs}/`; + this.dirs.forEach((_, d) => { + if (d === abs || StringPrototypeStartsWith(d, prefix)) this.dirs.delete(d); + }); + } + + // File descriptor slots. + + acquire(job) { + if (this.slots < this.maxOpen) { + this.slots++; + job.slot = true; + job.open(); + } else { + ArrayPrototypePush(this.slotQueue, job); + } + } + + releaseSlot() { + if (this.slotHead < this.slotQueue.length) { + const next = this.slotQueue[this.slotHead]; + this.slotQueue[this.slotHead++] = undefined; + if (this.slotHead > 1024 && this.slotHead * 2 > this.slotQueue.length) { + this.slotQueue = ArrayPrototypeSlice(this.slotQueue, this.slotHead); + this.slotHead = 0; + } + next.slot = true; + next.open(); + } else { + this.slots--; + } + } + + // Flow control. + + // A promise to await before feeding more data, or null. + wait() { + if (this.fatal !== null) return PromiseReject(this.fatal); + if (this.buffered < this.highWaterMark && this.pending < MAX_PENDING_JOBS) return null; + this.drain ??= new Promise((resolve) => { + this.drainResolve = resolve; + }); + return this.drain; + } + + checkDrain() { + if (this.drain !== null && + ((this.buffered < this.lowWaterMark && this.pending < MAX_PENDING_JOBS / 2) || this.fatal !== null)) { + const resolve = this.drainResolve; + this.drain = null; + this.drainResolve = null; + resolve(); + } + } + + jobDone() { + this.pending--; + this.checkDrain(); + if (this.pending === 0 && this.idleResolve !== null) { + const resolve = this.idleResolve; + this.idle = null; + this.idleResolve = null; + resolve(); + } + } + + async #idle() { + while (this.pending > 0) { + this.idle ??= new Promise((resolve) => { + this.idleResolve = resolve; + }); + await this.idle; + } + } + + // Waits for all the jobs, then applies deferred directory attributes. + async finish() { + await this.#idle(); + if (this.fatal !== null) throw this.fatal; + + const o = this.o; + const list = this.deferred; + this.deferred = []; + // Owners and times can be set in any order. + let i = 0; + const worker = async () => { + while (i < list.length) { + const d = list[i++]; + try { + const owner = this.owner(d.entry); + if (owner !== null) await chown(d.abs, owner[0], owner[1]); + if (!o.noMtime && d.entry.mtime !== null) await utimes(d.abs, this.atime(d.entry), d.entry.mtime); + } catch (err) { + this.entryError(err, d.entry); + } + } + }; + const workers = []; + for (let w = 0; w < MathMin(this.maxOpen, list.length); w++) ArrayPrototypePush(workers, worker()); + await SafePromiseAllReturnVoid(workers); + // Modes last, deepest first: a mode can forbid access to children. + for (let i = list.length - 1; i >= 0; i--) { + const d = list[i]; + if (d.mode === -1) continue; + try { + await chmod(d.abs, d.mode); + } catch (err) { + this.entryError(err, d.entry); + } + } + if (this.fatal !== null) throw this.fatal; + } + + // Stops after a failure: waits for the running jobs. + async abort() { + if (this.current !== null) { + const job = this.current; + this.current = null; + job.end(); + } + await this.#idle(); + } +} + +module.exports = { + Unpack, +}; diff --git a/lib/zlib.js b/lib/zlib.js index 2230913d534..d161d1f623d 100644 --- a/lib/zlib.js +++ b/lib/zlib.js @@ -86,6 +86,19 @@ const { getMaxZipContentSize, setMaxZipContentSize, } = require('internal/zip'); +const { + TarEntry, + TarParser, + createTarArchive, + createTarArchiveSync, + createTarExtractStream, + extractTar, + extractTarSync, + listTar, + listTarSync, + tarEntries, + tarFiles, +} = require('internal/tar'); const kFlushFlag = Symbol('kFlushFlag'); const kError = Symbol('kError'); @@ -1269,6 +1282,41 @@ for (const { 0: Wrapper, 1: Raw, 2: factories } of [ ObjectDefineProperty(Wrapper, 'name', { __proto__: null, value: Raw.name }); } +// Tar archive support is experimental too, and gated the same way. +function emitTarExperimentalWarning() { + emitExperimentalWarning('The zlib tar archive API'); +} + +function experimentalTarFunction(fn) { + return assignFunctionName(fn.name, function(...args) { + emitTarExperimentalWarning(); + return ReflectApply(fn, this, args); + }); +} + +class ExperimentalTarParser extends TarParser { + static [SymbolHasInstance](instance) { return instance instanceof TarParser; } + constructor(options) { emitTarExperimentalWarning(); super(options); } +} +ObjectDefineProperty(ExperimentalTarParser, 'name', { __proto__: null, value: TarParser.name }); + +class ExperimentalTarEntry extends TarEntry { + static [SymbolHasInstance](instance) { return instance instanceof TarEntry; } +} +for (const name of ['create', 'createStream', 'createSymlink', 'createLink']) { + const factory = TarEntry[name]; + ObjectDefineProperty(ExperimentalTarEntry, name, { + __proto__: null, + configurable: true, + writable: true, + value: assignFunctionName(name, function(...args) { + emitTarExperimentalWarning(); + return ReflectApply(factory, TarEntry, args); + }), + }); +} +ObjectDefineProperty(ExperimentalTarEntry, 'name', { __proto__: null, value: TarEntry.name }); + function crc32(data, value = 0) { if (typeof data !== 'string' && !isArrayBufferView(data)) { throw new ERR_INVALID_ARG_TYPE('data', ['Buffer', 'TypedArray', 'DataView', 'string'], data); @@ -1376,6 +1424,19 @@ ObjectDefineProperties(module.exports, { zipFiles: experimentalZipProperty(experimentalZipFunction(zipFiles)), getMaxZipContentSize: experimentalZipProperty(experimentalZipFunction(getMaxZipContentSize)), setMaxZipContentSize: experimentalZipProperty(experimentalZipFunction(setMaxZipContentSize)), + + // Tar archive support (experimental). + TarEntry: experimentalZipProperty(ExperimentalTarEntry), + TarParser: experimentalZipProperty(ExperimentalTarParser), + createTarArchive: experimentalZipProperty(experimentalTarFunction(createTarArchive)), + createTarArchiveSync: experimentalZipProperty(experimentalTarFunction(createTarArchiveSync)), + createTarExtractStream: experimentalZipProperty(experimentalTarFunction(createTarExtractStream)), + extractTar: experimentalZipProperty(experimentalTarFunction(extractTar)), + extractTarSync: experimentalZipProperty(experimentalTarFunction(extractTarSync)), + listTar: experimentalZipProperty(experimentalTarFunction(listTar)), + listTarSync: experimentalZipProperty(experimentalTarFunction(listTarSync)), + tarEntries: experimentalZipProperty(experimentalTarFunction(tarEntries)), + tarFiles: experimentalZipProperty(experimentalTarFunction(tarFiles)), }); // These should be considered deprecated diff --git a/test/common/README.md b/test/common/README.md index ee13afcb4c7..043041a67a6 100644 --- a/test/common/README.md +++ b/test/common/README.md @@ -45,6 +45,7 @@ several other tasks: * [ongc module](#ongc-module) * [process-exit-code-test-cases module](#process-exit-code-test-cases-module) * [Report module](#report-module) +* [tar module](#tar-module) * [tick module](#tick-module) * [tmpdir module](#tmpdir-module) * [UDP pair helper](#udp-pair-helper) @@ -1119,6 +1120,43 @@ into `targetExecutable` and sign it if necessary. If `verifyWorkflow` is false (default) and any of the steps fails, it skips the tests. Otherwise, an error is thrown. +## tar module + +The `tar` module is a minimal tar writer for crafting archives in tests, +including broken and malicious ones. + +### `header(fields)` + +* `fields` [\][] The fields of the header: `name`, `type`, + `size`, `mode`, `uid`, `gid`, `mtime`, `linkname`, `uname`, `gname`, + `prefix`, `format` (`'ustar'`, `'gnu'` or `'v7'`), and `rawSize` and + `rawMtime` to set the bytes of those fields. +* Returns: [\][] A 512-byte header block. + +### `makeTar(entries[, options])` + +* `entries` [\][] The fields of each entry, as for + `header()`, with its content as `data`. `pax` and `globalPax` (objects), + `gnuLongPath` and `gnuLongLink` (strings) add the matching extended header + before the entry. `raw` (a `Buffer`) is added as is. +* `options` [\][] + * `end` [\][] Add the end marker. **Default:** `true`. +* Returns: [\][] The archive. + +### `paxRecords(records)` + +* `records` [\][] +* Returns: [\][] The content of a pax extended header. + +### `randomChunks(buffer[, seed[, max]])` + +* Returns: [\][] `buffer`, split in chunks of at most `max` + bytes, deterministically. + +### `tempDir()` + +* Returns: [\][] A new directory under `tmpdir.path`. + ## tick module The `tick` module provides a helper function that can be used to call a callback diff --git a/test/common/tar.js b/test/common/tar.js new file mode 100644 index 00000000000..9e14fb4c82b --- /dev/null +++ b/test/common/tar.js @@ -0,0 +1,163 @@ +'use strict'; + +// A minimal tar writer for crafting archives in tests, including broken and +// malicious ones. + +const { mkdtempSync } = require('node:fs'); +const { join } = require('node:path'); +const tmpdir = require('./tmpdir'); + +function octal(buf, off, len, value) { + const s = value.toString(8).padStart(len - 1, '0'); + buf.write(s, off, len - 1, 'ascii'); + buf[off + len - 1] = 0; +} + +function checksum(block) { + block.fill(0x20, 148, 156); + let sum = 0; + for (let i = 0; i < 512; i++) sum += block[i]; + block.write(`${sum.toString(8).padStart(6, '0')}\0 `, 148, 8, 'ascii'); +} + +const TYPE_FLAGS = { + file: '0', + link: '1', + symlink: '2', + char: '3', + block: '4', + dir: '5', + fifo: '6', + pax: 'x', + globalPax: 'g', + gnuLongPath: 'L', + gnuLongLink: 'K', +}; + +// One header block. `name` must fit in 100 bytes (use pax otherwise). +function header({ + name, + type = 'file', + size = 0, + mode = type === 'dir' ? 0o755 : 0o644, + uid = 1000, + gid = 1000, + mtime = 1700000000, + linkname = '', + uname = 'user', + gname = 'group', + prefix = '', + format = 'ustar', + rawSize = null, + rawMtime = null, +}) { + const block = Buffer.alloc(512); + block.write(name, 0, 100, 'utf8'); + octal(block, 100, 8, mode); + octal(block, 108, 8, uid); + octal(block, 116, 8, gid); + if (rawSize !== null) { + rawSize.copy(block, 124); + } else { + octal(block, 124, 12, size); + } + if (rawMtime !== null) { + rawMtime.copy(block, 136); + } else { + octal(block, 136, 12, mtime); + } + block.write(TYPE_FLAGS[type] ?? type, 156, 1, 'ascii'); + block.write(linkname, 157, 100, 'utf8'); + if (format === 'ustar') { + block.write('ustar\0', 257, 6, 'ascii'); + block.write('00', 263, 2, 'ascii'); + } else if (format === 'gnu') { + block.write('ustar \0', 257, 8, 'ascii'); + } + if (format !== 'v7') { + block.write(uname, 265, 32, 'utf8'); + block.write(gname, 297, 32, 'utf8'); + octal(block, 329, 8, 0); + octal(block, 337, 8, 0); + } + if (prefix) block.write(prefix, 345, 155, 'utf8'); + checksum(block); + return block; +} + +function pad(data) { + const rem = data.length % 512; + return rem === 0 ? data : Buffer.concat([data, Buffer.alloc(512 - rem)]); +} + +function paxRecords(records) { + let out = ''; + for (const [key, value] of Object.entries(records)) { + const body = ` ${key}=${value}\n`; + const len = Buffer.byteLength(body); + let total = len + String(len).length; + if (String(total).length !== String(len).length) total = len + String(total).length; + out += total + body; + } + return Buffer.from(out); +} + +// Builds an archive from entry descriptions: +// { name, type, data, linkname, mode, mtime, pax: {...}, gnuLongPath, ... } +function makeTar(entries, { end = true } = {}) { + const parts = []; + for (const e of entries) { + if (e.raw) { + parts.push(e.raw); + continue; + } + if (e.globalPax) { + const body = paxRecords(e.globalPax); + parts.push(header({ name: 'pax_global_header', type: 'globalPax', size: body.length }), pad(body)); + } + if (e.pax) { + const body = paxRecords(e.pax); + parts.push(header({ name: 'PaxHeader/x', type: 'pax', size: body.length }), pad(body)); + } + if (e.gnuLongPath) { + const body = Buffer.from(`${e.gnuLongPath}\0`); + parts.push(header({ name: '././@LongLink', type: 'gnuLongPath', size: body.length, format: 'gnu' }), pad(body)); + } + if (e.gnuLongLink) { + const body = Buffer.from(`${e.gnuLongLink}\0`); + parts.push(header({ name: '././@LongLink', type: 'gnuLongLink', size: body.length, format: 'gnu' }), pad(body)); + } + const data = e.data === undefined ? Buffer.alloc(0) : Buffer.from(e.data); + parts.push(header({ ...e, size: e.size ?? data.length })); + if (data.length > 0) parts.push(pad(data)); + } + if (end) parts.push(Buffer.alloc(1024)); + return Buffer.concat(parts); +} + +// A new directory under the test's temporary directory, which the caller +// must have refreshed. +function tempDir() { + return mkdtempSync(join(tmpdir.path, 'tar-')); +} + +// Splits a buffer in chunks of random sizes, deterministically. +function randomChunks(buf, seed = 1, max = 700) { + const chunks = []; + let i = 0; + while (i < buf.length) { + seed = (seed * 1103515245 + 12345) & 0x7fffffff; + const n = 1 + (seed % max); + chunks.push(buf.subarray(i, i + n)); + i += n; + } + return chunks; +} + +module.exports = { + header, + makeTar, + paxRecords, + randomChunks, + tempDir, +}; diff --git a/test/parallel/test-zlib-tar-create.js b/test/parallel/test-zlib-tar-create.js new file mode 100644 index 00000000000..fb977375161 --- /dev/null +++ b/test/parallel/test-zlib-tar-create.js @@ -0,0 +1,417 @@ +'use strict'; + +// Writing tar archives: TarEntry factories, createTarArchive(), +// createTarArchiveSync() and tarFiles(). + +const common = require('../common'); + +const assert = require('node:assert'); +const fs = require('node:fs'); +const { join } = require('node:path'); +const { Readable } = require('node:stream'); +const { pipeline } = require('node:stream/promises'); +const { spawnSync } = require('node:child_process'); +const { test } = require('node:test'); +const zlib = require('node:zlib'); +const { tempDir } = require('../common/tar'); +const tmpdir = require('../common/tmpdir'); + +tmpdir.refresh(); + +const { TarEntry } = zlib; + +async function collect(stream) { + const chunks = []; + for await (const chunk of stream) chunks.push(chunk); + return Buffer.concat(chunks); +} + +function archiveSync(entries) { + return Buffer.concat([...zlib.createTarArchiveSync(entries)]); +} + +const mtime = new Date(1_700_000_000_000); + +test('the factories set the fields of the entry', () => { + const options = { mode: 0o600, mtime, uid: 1, gid: 2, uname: 'u', gname: 'g' }; + const file = TarEntry.create('a.txt', Buffer.from('abc'), options); + assert.ok(file instanceof TarEntry); + assert.deepStrictEqual( + [file.path, file.type, file.size, file.mode, file.mtime, file.uid, file.gid, file.uname, file.gname], + ['a.txt', 'File', 3, 0o600, mtime, 1, 2, 'u', 'g']); + const dir = TarEntry.create('d/', new Uint8Array(0)); + assert.deepStrictEqual([dir.type, dir.size, dir.mode], ['Directory', 0, 0o755]); + assert.ok(dir.mtime instanceof Date); + const link = TarEntry.createSymlink('l', '../target'); + assert.deepStrictEqual([link.type, link.linkpath, link.mode], ['SymbolicLink', '../target', 0o777]); + const hard = TarEntry.createLink('h', 'a.txt'); + assert.deepStrictEqual([hard.type, hard.linkpath, hard.mode], ['Link', 'a.txt', 0o644]); + const stream = TarEntry.createStream('s', [Buffer.from('x')], { size: 1 }); + assert.deepStrictEqual([stream.type, stream.size, stream.mode], ['File', 1, 0o644]); + assert.strictEqual(TarEntry.create('ab', new Uint16Array([1, 2]).buffer).size, 4); + assert.strictEqual(TarEntry.create('dv', new DataView(new ArrayBuffer(8), 2, 3)).size, 3); +}); + +test('the factories validate their arguments', () => { + const type = { code: 'ERR_INVALID_ARG_TYPE' }; + const value = { code: 'ERR_INVALID_ARG_VALUE' }; + const range = { code: 'ERR_OUT_OF_RANGE' }; + const b = Buffer.alloc(1); + assert.throws(() => TarEntry.create(1, b), type); + assert.throws(() => TarEntry.create('', b), value); + assert.throws(() => TarEntry.create('a\0b', b), value); + assert.throws(() => TarEntry.create('a', 'string'), type); + assert.throws(() => TarEntry.create('d/', b), value); + assert.throws(() => TarEntry.create('a', b, null), type); + assert.throws(() => TarEntry.create('a', b, { mode: 0o10000 }), range); + assert.throws(() => TarEntry.create('a', b, { mode: '644' }), type); + assert.throws(() => TarEntry.create('a', b, { uid: -1 }), range); + assert.throws(() => TarEntry.create('a', b, { gid: 1.5 }), range); + assert.throws(() => TarEntry.create('a', b, { uname: 1 }), type); + assert.throws(() => TarEntry.create('a', b, { gname: 1 }), type); + assert.throws(() => TarEntry.create('a', b, { mtime: 0 }), type); + assert.throws(() => TarEntry.create('a', b, { mtime: new Date(NaN) }), value); + assert.throws(() => TarEntry.createStream('a', [b]), type); + assert.throws(() => TarEntry.createStream('a', [b], {}), type); + assert.throws(() => TarEntry.createStream('a', [b], { size: -1 }), range); + assert.throws(() => TarEntry.createStream('a', null, { size: 1 }), type); + assert.throws(() => TarEntry.createStream('a', {}, { size: 1 }), type); + assert.throws(() => TarEntry.createStream('d/', [b], { size: 1 }), value); + assert.throws(() => TarEntry.createSymlink('a', ''), value); + assert.throws(() => TarEntry.createSymlink('a', 'b\0'), value); + assert.throws(() => TarEntry.createLink('a', 1), type); + assert.throws(() => zlib.createTarArchive(null), type); + assert.throws(() => zlib.createTarArchive({}), type); + assert.throws(() => zlib.createTarArchiveSync(Readable.from([])), type); + assert.throws(() => zlib.tarFiles(1), type); + assert.throws(() => zlib.tarFiles([], 1), type); + assert.throws(() => zlib.tarFiles([], { followSymlinks: 1 }), type); +}); + +test('an archive round-trips through the reader', async () => { + const entries = () => [ + TarEntry.create('dir/', Buffer.alloc(0), { mtime, mode: 0o700 }), + TarEntry.create('dir/a.txt', Buffer.from('hello'), + { mtime, mode: 0o640, uid: 501, gid: 20, uname: 'me', gname: 'us' }), + TarEntry.create('empty', Buffer.alloc(0), { mtime }), + TarEntry.create('block', Buffer.alloc(512, 1), { mtime }), + TarEntry.createSymlink('dir/link', 'a.txt', { mtime }), + TarEntry.createLink('dir/hard', 'dir/a.txt', { mtime }), + TarEntry.createStream('stream', [Buffer.from('ab'), new Uint8Array(0), new Uint8Array([99])], { size: 3, mtime }), + ]; + const expected = [ + ['Directory', 'dir/', 0, 0o700, '', 0, ''], + ['File', 'dir/a.txt', 5, 0o640, '', 501, 'me'], + ['File', 'empty', 0, 0o644, '', 0, ''], + ['File', 'block', 512, 0o644, '', 0, ''], + ['SymbolicLink', 'dir/link', 0, 0o777, 'a.txt', 0, ''], + ['Link', 'dir/hard', 0, 0o644, 'dir/a.txt', 0, ''], + ['File', 'stream', 3, 0o644, '', 0, ''], + ]; + const sync = archiveSync(entries()); + const async = await collect(zlib.createTarArchive(entries())); + assert.ok(sync.equals(async)); + // Three blocks of content, and the two empty blocks of the end. + assert.strictEqual(sync.length, (7 + 3 + 2) * 512); + const listed = zlib.listTarSync(sync); + assert.deepStrictEqual(listed.map((e) => [e.type, e.path, e.size, e.mode, e.linkpath, e.uid, e.uname]), expected); + for (const entry of listed) { + assert.strictEqual(entry.mtime.getTime(), mtime.getTime()); + assert.strictEqual(entry.pax, null); + } + const contents = {}; + for await (const entry of zlib.tarEntries(async)) { + if (entry.type === 'File') contents[entry.path] = await entry.body.text(); + } + assert.deepStrictEqual(contents, { + 'dir/a.txt': 'hello', 'empty': '', 'block': '\x01'.repeat(512), 'stream': 'abc', + }); +}); + +test('an asynchronous iterable of entries, and asynchronous sources', async () => { + async function* source() { + yield Buffer.from('12'); + yield Buffer.from('345'); + } + + async function* entries() { + yield TarEntry.create('a', Buffer.from('a')); + yield TarEntry.createStream('b', source(), { size: 5 }); + yield TarEntry.createStream('c', Readable.from([Buffer.from('cc')]), { size: 2 }); + } + const tar = await collect(zlib.createTarArchive(entries())); + assert.deepStrictEqual(zlib.listTarSync(tar).map((e) => [e.path, e.size]), [['a', 1], ['b', 5], ['c', 2]]); +}); + +test('what ustar cannot hold goes to a pax header', () => { + const split = 'p/'.repeat(60) + 'n'.repeat(90); + const long = ('y'.repeat(120) + '/').repeat(3) + 'z'; + const exact = 'e'.repeat(100); + const unsplittable = 'u'.repeat(101); + const list = zlib.listTarSync(archiveSync([ + TarEntry.create(exact, Buffer.alloc(0)), + TarEntry.create(split, Buffer.alloc(0)), + TarEntry.create(long, Buffer.from('x')), + TarEntry.create(unsplittable, Buffer.alloc(0)), + TarEntry.create('ünï/côdé', Buffer.alloc(0), { uname: 'üser', gname: 'g'.repeat(40) }), + TarEntry.create('ids', Buffer.alloc(0), { uid: 2 ** 31, gid: 2 ** 40 }), + TarEntry.create('old', Buffer.alloc(0), { mtime: new Date(-5000) }), + TarEntry.createSymlink('link', 't'.repeat(200)), + TarEntry.createLink('hard', 'lïnk'), + TarEntry.create('dir', Buffer.alloc(0)), + ])); + assert.deepStrictEqual(list.map((e) => e.path), + [exact, split, long, unsplittable, 'ünï/côdé', 'ids', 'old', 'link', 'hard', 'dir']); + assert.deepStrictEqual(list.map((e) => (e.pax === null ? null : Object.keys(e.pax))), [ + null, null, ['path'], ['path'], ['path', 'uname', 'gname'], ['uid', 'gid'], ['mtime'], ['linkpath'], ['linkpath'], + null, + ]); + assert.strictEqual(list[2].size, 1); + assert.deepStrictEqual([list[4].uname, list[4].gname], ['üser', 'g'.repeat(40)]); + assert.deepStrictEqual([list[5].uid, list[5].gid], [2 ** 31, 2 ** 40]); + assert.strictEqual(list[6].mtime.getTime(), -5000); + assert.strictEqual(list[7].linkpath, 't'.repeat(200)); + assert.strictEqual(list[8].linkpath, 'lïnk'); +}); + +test('a large size is written to the header and to a pax record', () => { + const size = 2 ** 33 + 5; + const it = zlib.createTarArchiveSync([TarEntry.createStream('big', [], { size })]); + const header = it.next().value; + it.return(); + let seen = null; + const parser = new zlib.TarParser({ onentry: (entry) => { seen = entry; } }); + parser.write(header); + assert.strictEqual(seen.size, size); + assert.strictEqual(seen.pax.size, `${size}`); + // GNU base-256 in the ustar header itself. + assert.strictEqual(header[1024 + 124], 0x80); + assert.strictEqual(header.readUIntBE(1024 + 130, 6), size); +}); + +test('entries changed after their creation are checked when written', () => { + const invalid = { code: 'ERR_TAR_INVALID_ENTRY' }; + const make = (change) => { + const entry = TarEntry.create('a', Buffer.from('a')); + change(entry); + return [entry]; + }; + assert.throws(() => archiveSync(make((e) => { e.path = ''; })), invalid); + assert.throws(() => archiveSync(make((e) => { e.path = 'a\0'; })), invalid); + assert.throws(() => archiveSync(make((e) => { e.uid = -1; })), invalid); + assert.throws(() => archiveSync(make((e) => { e.mode = 'x'; })), invalid); + assert.throws(() => archiveSync(make((e) => { e.uname = null; })), invalid); + assert.throws(() => archiveSync(make((e) => { e.mtime = new Date(NaN); })), invalid); + assert.throws(() => archiveSync(make((e) => { e.type = 'Link'; })), invalid); + assert.throws(() => archiveSync(make((e) => { e.type = 'SparseFile'; })), { code: 'ERR_TAR_UNSUPPORTED_FEATURE' }); + assert.throws(() => archiveSync([{ path: 'a' }]), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => archiveSync([null]), { code: 'ERR_INVALID_ARG_TYPE' }); + // The size of an entry with data is the size of its data. + const [entry] = zlib.listTarSync(archiveSync(make((e) => { e.size = 100; }))); + assert.strictEqual(entry.size, 1); + // A directory is written with a slash, and without content. + const [dir] = zlib.listTarSync(archiveSync(make((e) => { e.type = 'Directory'; }))); + assert.deepStrictEqual([dir.path, dir.size], ['a/', 0]); +}); + +test('a source that does not match its size fails the archive', async () => { + const invalid = { code: 'ERR_TAR_INVALID_ENTRY' }; + for (const { 0: size, 1: message } of [[5, /content is 3 bytes, expected 5/], [2, /larger than its size of 2 bytes/]]) { + assert.throws(() => archiveSync([TarEntry.createStream('a', [Buffer.from('abc')], { size })]), + { ...invalid, message }); + const source = Readable.from([Buffer.from('abc')]); + await assert.rejects(collect(zlib.createTarArchive([TarEntry.createStream('a', source, { size })])), + { ...invalid, message }); + assert.strictEqual(source.destroyed, true); + } + await assert.rejects(collect(zlib.createTarArchive([TarEntry.createStream('a', ['abc'], { size: 3 })])), + { code: 'ERR_INVALID_ARG_TYPE' }); +}); + +test('an entry is serialized once, unless it holds its data', async () => { + const data = TarEntry.create('a', Buffer.from('a')); + assert.ok(archiveSync([data]).equals(archiveSync([data]))); + const stream = TarEntry.createStream('s', [Buffer.from('s')], { size: 1 }); + archiveSync([stream]); + assert.throws(() => archiveSync([stream]), { code: 'ERR_INVALID_STATE' }); + await assert.rejects(collect(zlib.createTarArchive([stream])), { code: 'ERR_INVALID_STATE' }); + // An entry of an archive that was listed has no content. + const [listed] = zlib.listTarSync(archiveSync([data])); + assert.throws(() => archiveSync([listed]), { code: 'ERR_INVALID_STATE' }); +}); + +test('createTarArchiveSync() refuses asynchronous sources, and disposes of the entries', () => { + const first = Readable.from([Buffer.from('a')]); + const second = Readable.from([Buffer.from('b')]); + assert.throws(() => archiveSync([ + TarEntry.createStream('a', first, { size: 1 }), + TarEntry.createStream('b', second, { size: 1 }), + ]), { code: 'ERR_INVALID_STATE' }); + assert.strictEqual(first.destroyed, true); + assert.strictEqual(second.destroyed, true); +}); + +test('an archive that is destroyed disposes of the entries it did not write', async () => { + const sources = [1, 2, 3].map(() => new Readable({ read() {} })); + sources[0].push(Buffer.alloc(100)); + const archive = zlib.createTarArchive(sources.map((s, i) => TarEntry.createStream(`f${i}`, s, { size: 1000 }))); + const closed = new Promise((resolve) => archive.on('close', resolve)); + let received = 0; + archive.on('data', (chunk) => { + received += chunk.length; + if (received === 612) archive.destroy(); + }); + await closed; + assert.strictEqual(received, 612); + assert.deepStrictEqual(sources.map((s) => s.destroyed), [true, true, true]); +}); + +test('an asynchronous iterable of entries is told to stop when the archive fails', async () => { + let finalized = false; + let produced = 0; + async function* entries() { + try { + while (true) { + produced++; + yield TarEntry.createStream(`f${produced}`, [Buffer.from('ab')], { size: 1 }); + } + } finally { + finalized = true; + } + } + await assert.rejects(collect(zlib.createTarArchive(entries())), { code: 'ERR_TAR_INVALID_ENTRY' }); + assert.strictEqual(produced, 1); + assert.strictEqual(finalized, true); +}); + +test('an entry that was never written can be disposed of', async () => { + const a = Readable.from([Buffer.from('a')]); + const b = Readable.from([Buffer.from('b')]); + const first = TarEntry.createStream('a', a, { size: 1 }); + const second = TarEntry.createStream('b', b, { size: 1 }); + first[Symbol.dispose](); + first[Symbol.dispose](); + await second[Symbol.asyncDispose](); + assert.strictEqual(a.destroyed, true); + assert.strictEqual(b.destroyed, true); + assert.throws(() => archiveSync([first]), { code: 'ERR_INVALID_STATE' }); + // Entries without a source: nothing to do. + TarEntry.create('c', Buffer.from('c'))[Symbol.dispose](); + await TarEntry.createSymlink('l', 't')[Symbol.asyncDispose](); +}); + +test('entries read with tarEntries() can be written to another archive', async () => { + const original = archiveSync([ + TarEntry.create('keep.txt', Buffer.from('keep'), { mtime, mode: 0o600 }), + TarEntry.create('drop.txt', Buffer.from('drop'), { mtime }), + TarEntry.create('dir/', Buffer.alloc(0), { mtime }), + TarEntry.create('dir/big', Buffer.alloc(100_000, 7), { mtime }), + TarEntry.createSymlink('dir/link', 'big', { mtime }), + ]); + async function* filtered() { + for await (const entry of zlib.tarEntries(zlib.gzipSync(original))) { + if (entry.path === 'drop.txt') continue; + entry.path = `renamed/${entry.path}`; + yield entry; + } + } + const copy = await collect(zlib.createTarArchive(filtered())); + const contents = []; + for await (const entry of zlib.tarEntries(copy)) { + contents.push([entry.type, entry.path, entry.mode, entry.linkpath, (await entry.body.buffer()).length]); + } + assert.deepStrictEqual(contents, [ + ['File', 'renamed/keep.txt', 0o600, '', 4], + ['Directory', 'renamed/dir/', 0o755, '', 0], + ['File', 'renamed/dir/big', 0o644, '', 100_000], + ['SymbolicLink', 'renamed/dir/link', 0o777, 'big', 0], + ]); +}); + +test('tarFiles() archives files, directories and symbolic links', async (t) => { + const dir = tempDir(t); + fs.mkdirSync(join(dir, 'src/sub'), { recursive: true }); + fs.writeFileSync(join(dir, 'src/a.txt'), 'aaa', { mode: 0o640 }); + fs.writeFileSync(join(dir, 'src/empty'), ''); + fs.writeFileSync(join(dir, 'src/sub/big.bin'), Buffer.alloc(200_000, 3)); + fs.utimesSync(join(dir, 'src/a.txt'), 1_600_000_000, 1_600_000_000); + let symlinks = true; + try { + fs.symlinkSync('a.txt', join(dir, 'src/link')); + } catch { + symlinks = false; + } + const files = new Map([ + [join(dir, 'src/sub'), 'pkg/sub'], + [join(dir, 'src/a.txt'), 'pkg/a.txt'], + [join(dir, 'src/empty'), 'pkg/empty'], + [join(dir, 'src/sub/big.bin'), 'pkg/sub/big.bin'], + ]); + if (symlinks) files.set(join(dir, 'src/link'), 'pkg/link'); + + const followed = await collect(zlib.tarFiles(files)); + const list = zlib.listTarSync(followed); + assert.deepStrictEqual(list.map((e) => [e.type, e.path, e.size]), [ + ['Directory', 'pkg/sub/', 0], + ['File', 'pkg/a.txt', 3], + ['File', 'pkg/empty', 0], + ['File', 'pkg/sub/big.bin', 200_000], + ...(symlinks ? [['File', 'pkg/link', 3]] : []), + ]); + assert.strictEqual(list[1].mtime.getTime(), 1_600_000_000_000); + if (!common.isWindows) { + assert.strictEqual(list[1].mode, 0o640); + assert.strictEqual(list[1].uid, process.getuid()); + } + + const out = join(dir, 'out'); + await pipeline(zlib.tarFiles(files, { followSymlinks: false }), zlib.createGzip(), + fs.createWriteStream(join(dir, 'out.tgz'))); + await zlib.extractTar(join(dir, 'out.tgz'), { cwd: out, strict: true }); + assert.strictEqual(fs.readFileSync(join(out, 'pkg/a.txt'), 'utf8'), 'aaa'); + assert.ok(fs.readFileSync(join(out, 'pkg/sub/big.bin')).equals(Buffer.alloc(200_000, 3))); + if (symlinks) assert.strictEqual(fs.readlinkSync(join(out, 'pkg/link')), 'a.txt'); +}); + +test('tarFiles() fails on what it cannot archive, and closes what it opened', async (t) => { + const dir = tempDir(t); + fs.writeFileSync(join(dir, 'a'), 'a'); + await assert.rejects(collect(zlib.tarFiles([[join(dir, 'a'), 'a'], [join(dir, 'missing'), 'm']])), + { code: 'ENOENT' }); + await assert.rejects(collect(zlib.tarFiles([[join(dir, 'a')]])), { code: 'ERR_INVALID_ARG_TYPE' }); + await assert.rejects(collect(zlib.tarFiles([null])), { code: 'ERR_INVALID_ARG_TYPE' }); + // Destroyed while the first file is open. + fs.writeFileSync(join(dir, 'big'), Buffer.alloc(1_000_000)); + const archive = zlib.tarFiles([[join(dir, 'big'), 'big'], [join(dir, 'a'), 'a']]); + const closed = new Promise((resolve) => archive.on('close', resolve)); + archive.once('data', () => archive.destroy()); + await closed; + fs.rmSync(join(dir, 'big')); +}); + +test('tarFiles() refuses what is not a regular file', { skip: common.isWindows }, async (t) => { + const dir = tempDir(t); + const fifo = join(dir, 'fifo'); + if (spawnSync('mkfifo', [fifo]).status !== 0) return t.skip('mkfifo is not available'); + await assert.rejects(collect(zlib.tarFiles([[fifo, 'fifo']])), { code: 'ERR_TAR_UNSUPPORTED_FEATURE' }); +}); + +test('the system tar reads what createTarArchive() writes', async (t) => { + if (spawnSync('tar', ['--version']).status !== 0) return t.skip('tar is not available'); + const dir = tempDir(t); + const long = ('long-directory-name/'.repeat(10)) + 'file.txt'; + const file = join(dir, 'a.tar'); + await pipeline(zlib.createTarArchive([ + TarEntry.create('pkg/', Buffer.alloc(0)), + TarEntry.create('pkg/a.txt', Buffer.from('hello')), + TarEntry.create(`pkg/${long}`, Buffer.from('long')), + TarEntry.createStream('pkg/s.bin', [Buffer.alloc(70_000, 9)], { size: 70_000 }), + ]), fs.createWriteStream(file)); + const out = join(dir, 'out'); + fs.mkdirSync(out); + const r = spawnSync('tar', ['-xf', 'a.tar', '-C', 'out'], { cwd: dir, encoding: 'utf8' }); + assert.strictEqual(r.status, 0, r.stderr); + assert.strictEqual(fs.readFileSync(join(out, 'pkg/a.txt'), 'utf8'), 'hello'); + assert.strictEqual(fs.readFileSync(join(out, 'pkg', long), 'utf8'), 'long'); + assert.ok(fs.readFileSync(join(out, 'pkg/s.bin')).equals(Buffer.alloc(70_000, 9))); +}); diff --git a/test/parallel/test-zlib-tar-experimental-warning.js b/test/parallel/test-zlib-tar-experimental-warning.js new file mode 100644 index 00000000000..2fe340015e5 --- /dev/null +++ b/test/parallel/test-zlib-tar-experimental-warning.js @@ -0,0 +1,82 @@ +'use strict'; + +// The zlib tar archive API is experimental and must warn when it is *used*, +// but importing or requiring node:zlib - or merely accessing a tar export, as +// the ESM loader does when building its named-export bindings - must not +// warn. See lib/zlib.js. + +require('../common'); + +const assert = require('node:assert'); +const { spawnSync } = require('node:child_process'); +const { test } = require('node:test'); + +const WARNING = /ExperimentalWarning: The zlib tar archive API/; + +function run(...args) { + return spawnSync(process.execPath, args, { encoding: 'utf8' }); +} + +test('importing node:zlib (ESM) does not emit the tar experimental warning', () => { + const src = "import 'node:zlib';\n" + + "import { TarParser, TarEntry, listTar, extractTar } from 'node:zlib';\n" + + 'void TarParser; void TarEntry; void listTar; void extractTar;'; + const r = run('--input-type=module', '-e', src); + assert.strictEqual(r.status, 0, r.stderr); + assert.doesNotMatch(r.stderr, WARNING); +}); + +test('requiring node:zlib and only reading tar exports does not warn', () => { + const src = "const z = require('zlib');\n" + + 'void z.TarParser; void z.TarEntry; void z.listTar; void z.tarEntries;\n' + + 'void ({} instanceof z.TarParser);'; // The instanceof check must not warn. + const r = run('-e', src); + assert.strictEqual(r.status, 0, r.stderr); + assert.doesNotMatch(r.stderr, WARNING); +}); + +for (const use of [ + 'z.listTarSync(Buffer.alloc(1024))', + 'z.listTar(Buffer.alloc(1024))', + 'z.extractTarSync(Buffer.alloc(1024))', + 'z.extractTar(Buffer.alloc(1024))', + 'z.createTarExtractStream().destroy()', + 'z.tarEntries(Buffer.alloc(1024))', + 'new z.TarParser()', + "z.TarEntry.create('a', Buffer.alloc(0))", + "z.TarEntry.createStream('a', [], { size: 0 })", + "z.TarEntry.createSymlink('a', 'b')", + "z.TarEntry.createLink('a', 'b')", + 'z.createTarArchive([]).destroy()', + 'z.createTarArchiveSync([])', + 'z.tarFiles([]).destroy()', +]) { + test(`${use} emits the experimental warning`, () => { + const r = run('-e', `const z = require('zlib'); ${use};`); + assert.strictEqual(r.status, 0, r.stderr); + assert.match(r.stderr, WARNING); + assert.strictEqual(r.stderr.match(/ExperimentalWarning/g).length, 1); + }); +} + +test('using a tar export emits the experimental warning (ESM)', () => { + const src = "import { listTarSync } from 'node:zlib';\nlistTarSync(Buffer.alloc(1024));"; + const r = run('--input-type=module', '-e', src); + assert.strictEqual(r.status, 0, r.stderr); + assert.match(r.stderr, WARNING); +}); + +test('the exports keep their names and identity', () => { + const zlib = require('node:zlib'); + for (const name of ['listTar', 'listTarSync', 'extractTar', 'extractTarSync', 'createTarExtractStream', + 'tarEntries', 'TarParser', 'TarEntry', 'createTarArchive', 'createTarArchiveSync', + 'tarFiles']) { + assert.strictEqual(zlib[name].name, name); + } + const parser = new zlib.TarParser(); + assert.ok(parser instanceof zlib.TarParser); + assert.strictEqual(zlib.TarEntry.create.name, 'create'); + assert.ok(zlib.listTarSync(Buffer.alloc(1024)).every((e) => e instanceof zlib.TarEntry)); + assert.ok(zlib.TarEntry.createSymlink('a', 'b') instanceof zlib.TarEntry); + assert.ok(Object.keys(zlib).includes('extractTar')); +}); diff --git a/test/parallel/test-zlib-tar-extract.js b/test/parallel/test-zlib-tar-extract.js new file mode 100644 index 00000000000..d06681cbea7 --- /dev/null +++ b/test/parallel/test-zlib-tar-extract.js @@ -0,0 +1,459 @@ +'use strict'; + +// zlib.extractTar(), zlib.extractTarSync() and zlib.createTarExtractStream(). + +const common = require('../common'); + +const assert = require('node:assert'); +const fs = require('node:fs'); +const zlib = require('node:zlib'); +const { join } = require('node:path'); +const { pathToFileURL } = require('node:url'); +const { Readable } = require('node:stream'); +const { pipeline } = require('node:stream/promises'); +const { test } = require('node:test'); +const { isMainThread } = require('node:worker_threads'); +const tmpdir = require('../common/tmpdir'); +const { makeTar, tempDir, randomChunks } = require('../common/tar'); + +const { extractTar, extractTarSync, createTarExtractStream } = zlib; + +tmpdir.refresh(); + +const big = Buffer.alloc(3 * 1024 * 1024 + 123); +for (let i = 0; i < big.length; i++) big[i] = (i * 31) & 0xff; + +const deep = `pkg/${'d'.repeat(120)}/f.txt`; +const sample = makeTar([ + { name: 'pkg/', type: 'dir', mode: 0o755, mtime: 1600000000 }, + { name: 'pkg/a.txt', data: 'hello', mode: 0o640, mtime: 1500000000 }, + { name: 'pkg/bin/run.sh', data: '#!/bin/sh\n', mode: 0o755 }, + { name: 'pkg/empty.txt' }, + { name: 'pkg/big.bin', data: big }, + { name: 'pkg/hard', type: 'link', linkname: 'pkg/a.txt' }, + { name: 'pkg/long', pax: { path: deep }, data: 'deep' }, + { name: 'pkg/ünï.txt', data: 'unicode' }, + { name: 'pkg/private/', type: 'dir', mode: 0o700 }, + // Making symbolic links needs a privilege on Windows. + ...(common.canCreateSymLink() ? [{ name: 'pkg/link', type: 'symlink', linkname: 'a.txt' }] : []), +]); +const sampleEntries = common.canCreateSymLink() ? 10 : 9; + +function check(dir) { + const p = (x) => join(dir, 'pkg', x); + assert.strictEqual(fs.readFileSync(p('a.txt'), 'utf8'), 'hello'); + assert.strictEqual(fs.statSync(p('a.txt')).mtimeMs, 1500000000 * 1000); + assert.strictEqual(fs.readFileSync(p('bin/run.sh'), 'utf8'), '#!/bin/sh\n'); + assert.strictEqual(fs.readFileSync(p('empty.txt')).length, 0); + assert.ok(fs.readFileSync(p('big.bin')).equals(big)); + assert.strictEqual(fs.statSync(p('hard')).ino, fs.statSync(p('a.txt')).ino); + assert.strictEqual(fs.readFileSync(join(dir, deep), 'utf8'), 'deep'); + assert.strictEqual(fs.readFileSync(p('ünï.txt'), 'utf8'), 'unicode'); + assert.strictEqual(fs.statSync(join(dir, 'pkg')).mtimeMs, 1600000000 * 1000); + if (common.canCreateSymLink()) { + assert.strictEqual(fs.readlinkSync(p('link')), 'a.txt'); + } + if (!common.isWindows) { + assert.strictEqual(fs.statSync(p('a.txt')).mode & 0o777, 0o640 & ~process.umask()); + assert.strictEqual(fs.statSync(p('bin/run.sh')).mode & 0o100, 0o100); + assert.strictEqual(fs.statSync(p('private')).mode & 0o777, 0o700); + } +} + +// Every way to extract: (source, options), where source is a path or a +// Buffer. +const modes = { + async: (source, options) => extractTar(source, options), + sync: async (source, options) => extractTarSync(source, options), + stream: (source, options) => { + const data = typeof source === 'string' ? fs.readFileSync(source) : source; + return pipeline(Readable.from(randomChunks(data, 7, 9000)), createTarExtractStream(options)); + }, + readable: (source, options) => { + const data = typeof source === 'string' ? fs.readFileSync(source) : source; + return extractTar(Readable.from(randomChunks(data, 3, 70000)), options); + }, +}; + +for (const { 0: name, 1: run } of Object.entries(modes)) { + test(`${name}: extracts a file archive`, async () => { + const dir = tempDir(); + const file = join(dir, 'a.tar'); + fs.writeFileSync(file, sample); + const out = join(dir, 'out'); + await run(file, { cwd: out }); + check(out); + }); + + test(`${name}: extracts a buffer`, async () => { + const dir = tempDir(); + await run(sample, { cwd: dir }); + check(dir); + }); + + for (const { 0: kind, 1: compress } of [ + ['gzip', zlib.gzipSync], ['brotli', zlib.brotliCompressSync], ['zstd', zlib.zstdCompressSync], + ]) { + test(`${name}: extracts ${kind}`, async () => { + const dir = tempDir(); + const ext = { gzip: 'tgz', brotli: 'tar.br', zstd: 'tar.zst' }[kind]; + const file = join(dir, `a.${ext}`); + fs.writeFileSync(file, compress(sample)); + const out = join(dir, 'out'); + await run(file, { cwd: out, compression: kind === 'brotli' ? 'brotli' : undefined }); + check(out); + }); + } + + test(`${name}: strip and filter`, async () => { + const dir = tempDir(); + await run(sample, { cwd: dir, strip: 1, filter: (path) => !path.includes('big') }); + assert.strictEqual(fs.readFileSync(join(dir, 'a.txt'), 'utf8'), 'hello'); + assert.strictEqual(fs.existsSync(join(dir, 'big.bin')), false); + assert.strictEqual(fs.statSync(join(dir, 'hard')).ino, fs.statSync(join(dir, 'a.txt')).ino); + }); + + test(`${name}: replaces existing files, keep and newer`, async () => { + const dir = tempDir(); + fs.mkdirSync(join(dir, 'pkg')); + fs.writeFileSync(join(dir, 'pkg/a.txt'), 'old content'); + await run(sample, { cwd: dir }); + assert.strictEqual(fs.readFileSync(join(dir, 'pkg/a.txt'), 'utf8'), 'hello'); + + fs.writeFileSync(join(dir, 'pkg/a.txt'), 'mine'); + await run(sample, { cwd: dir, keep: true }); + assert.strictEqual(fs.readFileSync(join(dir, 'pkg/a.txt'), 'utf8'), 'mine'); + + // The file on disk is newer than the archive entry. + await run(sample, { cwd: dir, newer: true }); + assert.strictEqual(fs.readFileSync(join(dir, 'pkg/a.txt'), 'utf8'), 'mine'); + fs.utimesSync(join(dir, 'pkg/a.txt'), 1000, 1000); + await run(sample, { cwd: dir, newer: true }); + assert.strictEqual(fs.readFileSync(join(dir, 'pkg/a.txt'), 'utf8'), 'hello'); + }); + + test(`${name}: an entry replaces a different kind of entry`, async () => { + const dir = tempDir(); + const tar = makeTar([ + { name: 'x', data: 'file' }, + { name: 'x/', type: 'dir' }, + { name: 'x/inner', data: 'inner' }, + { name: 'y/', type: 'dir' }, + { name: 'y', data: 'now a file' }, + ]); + await run(tar, { cwd: dir }); + assert.strictEqual(fs.readFileSync(join(dir, 'x/inner'), 'utf8'), 'inner'); + assert.strictEqual(fs.readFileSync(join(dir, 'y'), 'utf8'), 'now a file'); + }); + + test(`${name}: a file replaces a symbolic link`, { skip: !common.canCreateSymLink() }, async () => { + const dir = tempDir(); + const tar = makeTar([ + { name: 'z', type: 'symlink', linkname: 'nowhere' }, + { name: 'z', data: 'replaced link' }, + ]); + await run(tar, { cwd: dir }); + assert.strictEqual(fs.lstatSync(join(dir, 'z')).isFile(), true); + }); + + test(`${name}: a file replaces a directory that is still being made`, async () => { + const dir = tempDir(); + const list = []; + for (let i = 0; i < 300; i++) { + list.push({ name: `d${i}/`, type: 'dir' }, { name: `d${i}`, data: `file ${i}` }); + } + await run(makeTar(list), { cwd: dir }); + for (let i = 0; i < 300; i++) { + assert.strictEqual(fs.readFileSync(join(dir, `d${i}`), 'utf8'), `file ${i}`); + } + }); + + test(`${name}: noMtime`, async () => { + const dir = tempDir(); + const before = Date.now() - 10_000; + await run(sample, { cwd: dir, noMtime: true }); + assert.ok(fs.statSync(join(dir, 'pkg/a.txt')).mtimeMs > before); + }); + + test(`${name}: unsupported entries are warnings`, async () => { + const dir = tempDir(); + const warnings = []; + const tar = makeTar([{ name: 'fifo', type: 'fifo' }, { name: 'ok', data: 'x' }]); + await run(tar, { cwd: dir, onwarn: (err, entry) => warnings.push([err.code, err.message, err.path, entry.path]) }); + assert.deepStrictEqual(warnings, [ + ['ERR_TAR_UNSUPPORTED_FEATURE', "unsupported tar feature: entry type 'FIFO'", 'fifo', 'fifo'], + ]); + assert.strictEqual(fs.readFileSync(join(dir, 'ok'), 'utf8'), 'x'); + }); + + test(`${name}: truncated archives fail`, async () => { + const dir = tempDir(); + const tar = makeTar([{ name: 'a', data: 'x'.repeat(3000) }], { end: false }).subarray(0, 2000); + await assert.rejects(run(tar, { cwd: dir }), { code: 'ERR_TAR_INVALID_ARCHIVE' }); + const file = join(dir, 'trunc.tar'); + fs.writeFileSync(file, makeTar([{ name: 'a', data: big }], { end: false }).subarray(0, 100000)); + await assert.rejects(run(file, { cwd: join(dir, 'o') }), { code: 'ERR_TAR_INVALID_ARCHIVE' }); + }); + + test(`${name}: corrupt compressed data fails`, async () => { + const dir = tempDir(); + const gz = zlib.gzipSync(sample); + gz[gz.length >> 1] ^= 0xff; + gz[(gz.length >> 1) + 1] ^= 0xff; + await assert.rejects(run(gz, { cwd: dir }), { code: 'ERR_TAR_INVALID_ARCHIVE' }); + }); + + test(`${name}: many files`, async () => { + const dir = tempDir(); + const entries = []; + for (let d = 0; d < 20; d++) { + for (let f = 0; f < 50; f++) entries.push({ name: `d${d}/sub/f${f}.txt`, data: `${d}-${f}` }); + } + await run(makeTar(entries), { cwd: dir }); + for (let d = 0; d < 20; d++) { + for (let f = 0; f < 50; f++) { + assert.strictEqual(fs.readFileSync(join(dir, `d${d}/sub/f${f}.txt`), 'utf8'), `${d}-${f}`); + } + } + }); + + test(`${name}: strict mode fails on the first problem`, async () => { + const dir = tempDir(); + const tar = makeTar([{ name: '../evil', data: 'x' }, { name: 'after', data: 'y' }]); + await assert.rejects(run(tar, { cwd: dir, strict: true }), { + code: 'ERR_TAR_UNSAFE_ENTRY', + message: "refusing to extract tar entry: path contains '..'", + path: '../evil', + }); + const bad = makeTar([{ raw: Buffer.alloc(512, 7) }, { name: 'after', data: 'y' }]); + await assert.rejects(run(bad, { cwd: dir, strict: true }), { code: 'ERR_TAR_INVALID_ENTRY' }); + // File system errors are fatal too. + fs.mkdirSync(join(dir, 'full')); + fs.writeFileSync(join(dir, 'full/file'), ''); + const clash = makeTar([{ name: 'full', data: 'cannot replace a directory that is not empty' }]); + await assert.rejects(run(clash, { cwd: dir, strict: true }), { code: /^(ENOTEMPTY|EEXIST|EPERM)$/ }); + const warnings = []; + await run(clash, { cwd: dir, onwarn: (err, entry) => warnings.push([err.code, entry.path]) }); + assert.strictEqual(warnings.length, 1); + assert.strictEqual(warnings[0][1], 'full'); + }); + + test(`${name}: errors thrown by the callbacks stop the extraction`, async () => { + const dir = tempDir(); + fs.mkdirSync(join(dir, 'full')); + fs.writeFileSync(join(dir, 'full/file'), ''); + const boom = new Error('boom'); + const thrower = () => { throw boom; }; + // A warning from the parser, from the planning of an entry, and from a + // file system operation. + for (const entries of [ + [{ raw: Buffer.alloc(512, 7) }], + [{ name: '../evil', data: 'x' }], + [{ name: 'full', data: 'cannot replace a directory that is not empty' }, { name: 'after', data: 'y' }], + ]) { + await assert.rejects(run(makeTar(entries), { cwd: dir, onwarn: thrower }), boom); + } + await assert.rejects(run(sample, { cwd: dir, filter: thrower }), boom); + await assert.rejects(run(sample, { cwd: dir, onentry: thrower }), boom); + }); + + test(`${name}: headers cannot make the file system calls throw`, async () => { + const dir = tempDir(); + const rawMtime = Buffer.alloc(12, 0xee); + rawMtime[0] = 0x80; + const warnings = []; + const tar = makeTar([ + { name: 'time', rawMtime, data: 'a' }, + { name: 'paxtime', pax: { mtime: '1e300', atime: '-1e300' }, data: 'b' }, + { name: 'nul', pax: { path: 'nul\0byte' }, data: 'c' }, + { name: 'owner', pax: { uid: '99999999999999', gid: '99999999999999' }, data: 'd' }, + { name: 'last', data: 'e' }, + ]); + await run(tar, { + cwd: dir, + preserveOwner: true, + onwarn: (err) => warnings.push(err.message), + }); + assert.strictEqual(fs.readFileSync(join(dir, 'time'), 'utf8'), 'a'); + assert.strictEqual(fs.readFileSync(join(dir, 'paxtime'), 'utf8'), 'b'); + assert.strictEqual(fs.readFileSync(join(dir, 'owner'), 'utf8'), 'd'); + assert.strictEqual(fs.readFileSync(join(dir, 'last'), 'utf8'), 'e'); + // The owners of the other files may not be settable (not root). + assert.ok(warnings.includes('refusing to extract tar entry: path contains a null byte')); + }); +} + +test('extractTar with jobs: 1 and a small highWaterMark still works', async () => { + const dir = tempDir(); + await extractTar(sample, { cwd: dir, jobs: 1, highWaterMark: 1 }); + check(dir); +}); + +test('extracts from an fs.ReadStream, a URL, a web ReadableStream, a Blob and iterables', async () => { + const dir = tempDir(); + const file = join(dir, 'a.tar'); + fs.writeFileSync(file, sample); + await extractTar(fs.createReadStream(file), { cwd: join(dir, 'stream') }); + check(join(dir, 'stream')); + await extractTar(pathToFileURL(file), { cwd: pathToFileURL(join(dir, 'url')) }); + check(join(dir, 'url')); + extractTarSync(pathToFileURL(file), { cwd: pathToFileURL(join(dir, 'url-sync')) }); + check(join(dir, 'url-sync')); + await extractTar(new Blob([sample]), { cwd: join(dir, 'blob') }); + check(join(dir, 'blob')); + await extractTar(Readable.toWeb(Readable.from(randomChunks(sample, 5, 5000))), { cwd: join(dir, 'web') }); + check(join(dir, 'web')); + await extractTar(randomChunks(zlib.gzipSync(sample), 5, 5000), { cwd: join(dir, 'iterable') }); + check(join(dir, 'iterable')); + extractTarSync(randomChunks(sample, 5, 5000), { cwd: join(dir, 'iterable-sync') }); + check(join(dir, 'iterable-sync')); + async function* generate() { + yield* randomChunks(sample, 6, 50000); + } + await extractTar(generate(), { cwd: join(dir, 'generator') }); + check(join(dir, 'generator')); +}); + +test('large files of an uncompressed archive file are copied in place', async () => { + // Enough large files to queue for the copy slots, between small ones. + const dir = tempDir(); + const list = []; + for (let i = 0; i < 12; i++) { + list.push({ name: `big/${i}.bin`, data: Buffer.alloc(1024 * 1024 + i * 1000, i + 1), mtime: 1500000000 + i }); + list.push({ name: `small/${i}.txt`, data: `small ${i}` }); + } + const file = join(dir, 'a.tar'); + fs.writeFileSync(file, makeTar(list)); + await extractTar(file, { cwd: join(dir, 'out') }); + for (let i = 0; i < 12; i++) { + const data = fs.readFileSync(join(dir, 'out/big', `${i}.bin`)); + assert.strictEqual(data.length, 1024 * 1024 + i * 1000); + assert.ok(data.every((b) => b === i + 1)); + assert.strictEqual(fs.statSync(join(dir, 'out/big', `${i}.bin`)).mtimeMs, (1500000000 + i) * 1000); + assert.strictEqual(fs.readFileSync(join(dir, 'out/small', `${i}.txt`), 'utf8'), `small ${i}`); + } + // Truncated inside a large file. + const truncated = join(dir, 'truncated.tar'); + fs.writeFileSync(truncated, fs.readFileSync(file).subarray(0, 512 + 600 * 1024)); + await assert.rejects(extractTar(truncated, { cwd: join(dir, 'out2') }), { code: 'ERR_TAR_INVALID_ARCHIVE' }); +}); + +test('onentry sees every extracted entry', async () => { + const dir = tempDir(); + const paths = []; + await extractTar(sample, { cwd: dir, onentry: (e) => paths.push(e.path) }); + assert.strictEqual(paths.length, sampleEntries); + const filtered = []; + extractTarSync(sample, { cwd: dir, filter: (p) => p.endsWith('/'), onentry: (e) => filtered.push(e.path) }); + assert.deepStrictEqual(filtered, ['pkg/', 'pkg/private/']); +}); + +test('cwd defaults to the current directory', { skip: !isMainThread }, async () => { + const dir = tempDir(); + const previous = process.cwd(); + process.chdir(dir); + try { + extractTarSync(makeTar([{ name: 'sync.txt', data: 's' }])); + await extractTar(makeTar([{ name: 'async.txt', data: 'a' }])); + } finally { + process.chdir(previous); + } + assert.strictEqual(fs.readFileSync(join(dir, 'sync.txt'), 'utf8'), 's'); + assert.strictEqual(fs.readFileSync(join(dir, 'async.txt'), 'utf8'), 'a'); +}); + +test('arguments are validated', async () => { + const cwd = tmpdir.path; + for (const source of [undefined, null, 1, {}]) { + await assert.rejects(extractTar(source, { cwd }), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => extractTarSync(source, { cwd }), { code: 'ERR_INVALID_ARG_TYPE' }); + } + const invalid = [ + [{ cwd: 1 }, 'ERR_INVALID_ARG_TYPE'], + [{ strip: -1 }, 'ERR_OUT_OF_RANGE'], + [{ strip: '1' }, 'ERR_INVALID_ARG_TYPE'], + [{ keep: 1 }, 'ERR_INVALID_ARG_TYPE'], + [{ newer: 1 }, 'ERR_INVALID_ARG_TYPE'], + [{ noMtime: 1 }, 'ERR_INVALID_ARG_TYPE'], + [{ preserveOwner: 1 }, 'ERR_INVALID_ARG_TYPE'], + [{ preservePaths: 1 }, 'ERR_INVALID_ARG_TYPE'], + [{ chmod: 1 }, 'ERR_INVALID_ARG_TYPE'], + [{ uid: -1 }, 'ERR_OUT_OF_RANGE'], + [{ gid: 2 ** 32 }, 'ERR_OUT_OF_RANGE'], + [{ umask: 'rwx' }, 'ERR_INVALID_ARG_VALUE'], + [{ fmode: -1 }, 'ERR_OUT_OF_RANGE'], + [{ dmode: {} }, 'ERR_INVALID_ARG_TYPE'], + [{ maxDepth: -1 }, 'ERR_OUT_OF_RANGE'], + [{ jobs: 0 }, 'ERR_OUT_OF_RANGE'], + [{ highWaterMark: -1 }, 'ERR_OUT_OF_RANGE'], + [{ compression: 'xz' }, 'ERR_INVALID_ARG_VALUE'], + [{ filter: 1 }, 'ERR_INVALID_ARG_TYPE'], + [{ onentry: 1 }, 'ERR_INVALID_ARG_TYPE'], + [{ onwarn: 1 }, 'ERR_INVALID_ARG_TYPE'], + [{ strict: 1 }, 'ERR_INVALID_ARG_TYPE'], + [{ maxMetaSize: -1 }, 'ERR_OUT_OF_RANGE'], + [null, 'ERR_INVALID_ARG_TYPE'], + ]; + for (const { 0: options, 1: code } of invalid) { + await assert.rejects(extractTar(sample, options), { code }); + assert.throws(() => extractTarSync(sample, options), { code }); + assert.throws(() => createTarExtractStream(options), { code }); + } +}); + +for (const { 0: name, 1: run } of [['async', extractTar], ['sync', async (s, o) => extractTarSync(s, o)]]) { + test(`${name}: uid/gid, chmod and default modes`, { skip: common.isWindows }, async () => { + const dir = tempDir(); + const uid = process.getuid(); + const gid = process.getgid(); + const tar = makeTar([ + { name: 'd/', type: 'dir', mode: 0o777 }, + { name: 'd/f', data: 'x', mode: 0o666 }, + { name: 'd/nomode', data: 'y', mode: 0 }, + { name: 'd/l', type: 'symlink', linkname: 'f' }, + { name: 'ro/', type: 'dir', mode: 0o555 }, + { name: 'ro/inside', data: 'z' }, + ]); + await run(tar, { cwd: dir, uid, gid, chmod: true, umask: 0o022, fmode: '600' }); + assert.strictEqual(fs.statSync(join(dir, 'd/f')).uid, uid); + assert.strictEqual(fs.statSync(join(dir, 'd/f')).mode & 0o777, 0o644); + assert.strictEqual(fs.statSync(join(dir, 'd')).mode & 0o777, 0o755); + assert.strictEqual(fs.statSync(join(dir, 'd/nomode')).mode & 0o777, 0o600); + assert.strictEqual(fs.lstatSync(join(dir, 'd/l')).uid, uid); + // Read-only directories get their mode at the end. + assert.strictEqual(fs.statSync(join(dir, 'ro')).mode & 0o777, 0o555); + assert.strictEqual(fs.readFileSync(join(dir, 'ro/inside'), 'utf8'), 'z'); + // So that the temporary directory can be removed. + fs.chmodSync(join(dir, 'ro'), 0o755); + }); +} + +test('symbolic links get their mtime', { skip: !common.canCreateSymLink() || common.isWindows }, async () => { + const dir = tempDir(); + const tar = makeTar([{ name: 'l', type: 'symlink', linkname: 'nowhere', mtime: 1400000000 }]); + await extractTar(tar, { cwd: join(dir, 'a') }); + extractTarSync(tar, { cwd: join(dir, 'b') }); + assert.strictEqual(fs.lstatSync(join(dir, 'a/l')).mtimeMs, 1400000000 * 1000); + assert.strictEqual(fs.lstatSync(join(dir, 'b/l')).mtimeMs, 1400000000 * 1000); +}); + +test('destroying the extract stream without an error closes the file being written', async () => { + const dir = tempDir(); + const stream = createTarExtractStream({ cwd: dir }); + const closed = new Promise((resolve) => stream.on('close', resolve)); + // The header of pkg/big.bin and a part of its content. + stream.write(sample.subarray(0, 512 * 7 + 100000), common.mustCall(() => stream.destroy())); + await closed; + assert.strictEqual(fs.statSync(join(dir, 'pkg/big.bin')).size, 100000); +}); + +test('destroying the extract stream stops the extraction', async () => { + const dir = tempDir(); + const stream = createTarExtractStream({ cwd: dir }); + const closed = new Promise((resolve) => stream.on('close', resolve)); + stream.on('error', common.mustCall((err) => assert.strictEqual(err.message, 'stop'))); + stream.write(sample.subarray(0, 512 * 3), common.mustCall(() => stream.destroy(new Error('stop')))); + await closed; + assert.strictEqual(fs.readFileSync(join(dir, 'pkg/a.txt'), 'utf8'), 'hello'); + assert.strictEqual(fs.existsSync(join(dir, 'pkg/big.bin')), false); +}); diff --git a/test/parallel/test-zlib-tar-internals.js b/test/parallel/test-zlib-tar-internals.js new file mode 100644 index 00000000000..697ac050417 --- /dev/null +++ b/test/parallel/test-zlib-tar-internals.js @@ -0,0 +1,181 @@ +// Flags: --expose-internals +'use strict'; + +// Building blocks of the tar implementation that the public API does not +// reach directly. + +require('../common'); + +const assert = require('node:assert'); +const zlib = require('node:zlib'); +const { randomBytes } = require('node:crypto'); +const { test } = require('node:test'); +const { header, paxRecords } = require('../common/tar'); + +const { + BLOCK_OK, BLOCK_ZERO, BLOCK_INVALID, HeaderCache, readOctal, readString, verifyChecksum, +} = require('internal/tar/header'); +const { PaxRecords, parsePax } = require('internal/tar/pax'); +const { SyncDecompressor } = require('internal/tar/decompress'); +const { BufferPool } = require('internal/tar/pool'); +const { sanitize } = require('internal/tar/paths'); + +test('readOctal parses octal with padding', () => { + assert.strictEqual(readOctal(Buffer.from('0000644\0'), 0, 8), 0o644); + assert.strictEqual(readOctal(Buffer.from(' 644 \0'), 0, 8), 0o644); + assert.strictEqual(readOctal(Buffer.from('\0\0\0\0\0\0\0\0'), 0, 8), 0); + assert.strictEqual(readOctal(Buffer.from('77777777777\0'), 0, 12), 8589934591); +}); + +test('readOctal parses base-256 numbers', () => { + const pos = Buffer.alloc(12); + pos[0] = 0x80; + pos.writeUIntBE(2 ** 40 + 5, 6, 6); + assert.strictEqual(readOctal(pos, 0, 12), 2 ** 40 + 5); + + const neg = Buffer.alloc(8, 0xff); + assert.strictEqual(readOctal(neg, 0, 8), -1); + neg[7] = 0xfe; + assert.strictEqual(readOctal(neg, 0, 8), -2); +}); + +test('readString stops at NUL and decodes UTF-8', () => { + const b = Buffer.alloc(20); + b.write('héllo'); + assert.strictEqual(readString(b, 0, 20), 'héllo'); + assert.strictEqual(readString(Buffer.from('abcdef'), 0, 3), 'abc'); + assert.strictEqual(readString(Buffer.alloc(4), 0, 4), ''); +}); + +test('verifyChecksum, at any alignment', () => { + const cache = new HeaderCache(); + const block = header({ name: 'a.txt', size: 3 }); + for (let shift = 0; shift < 8; shift++) { + const buf = Buffer.alloc(1024 + shift); + block.copy(buf, shift); + assert.strictEqual(verifyChecksum(buf, shift, cache), BLOCK_OK); + assert.strictEqual(verifyChecksum(buf, shift + 512, cache), BLOCK_ZERO); + buf[shift] = 0x62; + assert.strictEqual(verifyChecksum(buf, shift, cache), BLOCK_INVALID); + } + // A block of the largest bytes does not overflow the sum. + assert.strictEqual(verifyChecksum(Buffer.alloc(512, 0xff), 0, cache), BLOCK_INVALID); +}); + +test('parsePax', () => { + const records = parsePax(paxRecords({ 'path': 'ünï/côdé', 'size': '12', 'custom.key': 'a=b\nc' })); + assert.ok(records instanceof PaxRecords); + assert.deepStrictEqual({ ...records }, { 'path': 'ünï/côdé', 'size': '12', 'custom.key': 'a=b\nc' }); + // Malformed data stops the parse; what was read is kept. + for (const junk of ['', '\0\0\0', 'x', '2 a=b\n', '0 a=b\n', '999 a=b\n', '6 abc\n']) { + const buf = Buffer.concat([paxRecords({ uid: '7' }), Buffer.from(junk)]); + assert.deepStrictEqual({ ...parsePax(buf) }, { uid: '7' }, JSON.stringify(junk)); + } +}); + +test('sanitize', () => { + const warnings = []; + const run = (path, strip = 0, preservePaths = false, maxDepth = 1024) => + sanitize(path, strip, preservePaths, maxDepth, (message) => warnings.push(message)); + assert.strictEqual(run('a/b/c'), 'a/b/c'); + assert.strictEqual(run('a/b/'), 'a/b'); + assert.strictEqual(run('./a//b/./c/'), 'a/b/c'); + assert.strictEqual(run('a/b/c', 1), 'b/c'); + assert.strictEqual(run('a/b/c', 3), null); + assert.strictEqual(run('a', 1), null); + assert.strictEqual(run(''), ''); + assert.strictEqual(run('.'), ''); + assert.deepStrictEqual(warnings, []); + assert.strictEqual(run('/a/b'), 'a/b'); + assert.strictEqual(run('c:/a/b'), 'a/b'); + assert.strictEqual(run('a/../b'), null); + assert.strictEqual(run('..'), null); + assert.strictEqual(run('a/b/c', 0, false, 2), null); + assert.strictEqual(run('a\0b'), null); + assert.strictEqual(warnings.length, 6); + assert.strictEqual(run('a/../b', 0, true), 'b'); + assert.strictEqual(run('../../b', 0, true), '../../b'); + assert.deepStrictEqual({ ...run('/a/./b', 0, true) }, { absolute: '/a/b' }); + assert.deepStrictEqual({ ...run('c:/a/b', 0, true) }, { absolute: 'c:/a/b' }); + // Names that only look like dots. + assert.strictEqual(run('...'), '...'); + assert.strictEqual(run('a/..b/c..'), 'a/..b/c..'); +}); + +// Compressible and incompressible parts, so that output chunks end at all +// sorts of offsets. +const data = Buffer.concat([ + randomBytes(100_003), Buffer.alloc(700_001, 'a'), randomBytes(300_007), Buffer.alloc(5_000_011, 'b'), +]); +const gz = zlib.gzipSync(data); + +for (const mode of ['reuse', 'pool', 'fresh']) { + test(`SyncDecompressor (${mode}): output is complete and stays aligned with its position`, () => { + const parts = []; + let produced = 0; + const pool = mode === 'pool' ? new BufferPool(1024 * 1024) : null; + let misaligned = 0; + const dec = new SyncDecompressor('gzip', (chunk) => { + // The output is at the same offset modulo 512 in memory as in the + // stream, so that tar headers are always aligned. + if ((chunk.byteOffset - produced) % 512 !== 0) misaligned++; + parts.push(Buffer.from(chunk)); + produced += chunk.length; + }, mode === 'reuse', pool); + // Odd input slices. + for (let off = 0; off < gz.length; off += 777) dec.write(gz.subarray(off, off + 777)); + dec.end(); + assert.strictEqual(misaligned, 0); + assert.ok(Buffer.concat(parts).equals(data)); + assert.strictEqual(dec.produced, data.length); + }); +} + +test('SyncDecompressor: every format, early close and errors', () => { + const run = (kind, input) => { + const parts = []; + const dec = new SyncDecompressor(kind, (c) => parts.push(Buffer.from(c)), true); + try { + dec.write(input); + dec.end(); + } finally { + dec.close(); + } + return Buffer.concat(parts); + }; + const a = Buffer.alloc(300_000, 'x'); + const b = randomBytes(50_000); + const kinds = { gzip: zlib.gzipSync, brotli: zlib.brotliCompressSync, zstd: zlib.zstdCompressSync }; + for (const { 0: kind, 1: compress } of Object.entries(kinds)) { + for (let i = 0; i < 3; i++) { + assert.ok(run(kind, compress(a)).equals(a), kind); + assert.ok(run(kind, compress(b)).equals(b), kind); + // Closed half way: the next one is not affected. + const half = new SyncDecompressor(kind, () => {}, true); + half.write(compress(b).subarray(0, 1000)); + half.close(); + half.close(); + assert.ok(run(kind, compress(b)).equals(b), kind); + } + // Corrupt data fails, and the next one still works. (Corrupt random data + // may not fail: brotli and zstd store it as is, unchecked.) + const bad = compress(Buffer.from('lorem ipsum dolor sit amet '.repeat(20000))); + bad.fill(0xff, 4, bad.length - 4); + assert.throws(() => run(kind, bad), { code: 'ERR_TAR_INVALID_ARCHIVE' }); + assert.ok(run(kind, compress(a)).equals(a), kind); + } +}); + +test('BufferPool recycles a buffer once every reference is dropped', () => { + const pool = new BufferPool(1024, 1); + const a = pool.get(); + const view = a.subarray(10, 20); + pool.ref(view); + pool.release(a); + assert.notStrictEqual(pool.get(), a); + pool.release(view); + assert.strictEqual(pool.get(), a); + // Buffers that are not from the pool are ignored. + pool.ref(Buffer.alloc(1)); + pool.release(Buffer.alloc(1)); +}); diff --git a/test/parallel/test-zlib-tar-list.js b/test/parallel/test-zlib-tar-list.js new file mode 100644 index 00000000000..2338c976eb0 --- /dev/null +++ b/test/parallel/test-zlib-tar-list.js @@ -0,0 +1,318 @@ +'use strict'; + +// zlib.listTar(), zlib.listTarSync() and zlib.tarEntries(). + +const common = require('../common'); + +const assert = require('node:assert'); +const fs = require('node:fs'); +const zlib = require('node:zlib'); +const { join } = require('node:path'); +const { pathToFileURL } = require('node:url'); +const { Readable } = require('node:stream'); +const { test } = require('node:test'); +const tmpdir = require('../common/tmpdir'); +const { makeTar, tempDir, randomChunks } = require('../common/tar'); + +const { listTar, listTarSync, tarEntries } = zlib; + +tmpdir.refresh(); + +const big = Buffer.alloc(2 * 1024 * 1024 + 7, 'b'); +const sample = makeTar([ + { name: 'a/', type: 'dir' }, + { name: 'a/small.txt', data: 'small' }, + { name: 'a/big.bin', data: big }, + { name: 'a/after.txt', data: 'after' }, + { name: 'a/link', type: 'symlink', linkname: 'small.txt' }, +]); +const paths = ['a/', 'a/small.txt', 'a/big.bin', 'a/after.txt', 'a/link']; +const pathsOf = (entries) => entries.map((e) => e.path); + +test('listTar and listTarSync, from files and inputs', async () => { + const dir = tempDir(); + const file = join(dir, 'a.tar'); + fs.writeFileSync(file, sample); + const gz = join(dir, 'a.tgz'); + fs.writeFileSync(gz, zlib.gzipSync(sample)); + const zst = join(dir, 'a.tar.zst'); + fs.writeFileSync(zst, zlib.zstdCompressSync(sample)); + const br = join(dir, 'a.tar.br'); + fs.writeFileSync(br, zlib.brotliCompressSync(sample)); + for (const f of [file, gz, zst, br, pathToFileURL(file)]) { + assert.deepStrictEqual(pathsOf(await listTar(f)), paths); + assert.deepStrictEqual(pathsOf(listTarSync(f)), paths); + } + assert.deepStrictEqual(pathsOf(await listTar(sample)), paths); + assert.deepStrictEqual(pathsOf(listTarSync(sample)), paths); + assert.deepStrictEqual(pathsOf(listTarSync(new Uint8Array(sample))), paths); + assert.deepStrictEqual(pathsOf(await listTar(new Uint8Array(sample).buffer)), paths); + assert.deepStrictEqual(pathsOf(listTarSync(randomChunks(sample, 3, 3000))), paths); + assert.deepStrictEqual(pathsOf(listTarSync(randomChunks(zlib.gzipSync(sample), 3, 3))), paths); + assert.deepStrictEqual(pathsOf(await listTar(randomChunks(sample, 3, 3000))), paths); + assert.deepStrictEqual(pathsOf(await listTar(Readable.from(randomChunks(zlib.gzipSync(sample), 3, 100)))), paths); + assert.deepStrictEqual(pathsOf(await listTar(fs.createReadStream(file))), paths); + assert.deepStrictEqual(pathsOf(await listTar(fs.createReadStream(gz))), paths); + assert.deepStrictEqual(pathsOf(await listTar(new Blob([sample]))), paths); + assert.deepStrictEqual(pathsOf(await listTar(new Blob([sample]).stream())), paths); +}); + +test('the compression option', async () => { + const br = zlib.brotliCompressSync(sample); + assert.deepStrictEqual(pathsOf(await listTar(br, { compression: 'brotli' })), paths); + assert.deepStrictEqual(pathsOf(listTarSync(br, { compression: 'brotli' })), paths); + assert.deepStrictEqual(pathsOf(listTarSync(zlib.gzipSync(sample), { compression: true })), paths); + assert.deepStrictEqual(pathsOf(listTarSync(zlib.zstdCompressSync(sample), { compression: 'zstd' })), paths); + // Not decompressed: the gzip data is not a tar archive. + assert.deepStrictEqual( + listTarSync(zlib.gzipSync(sample, { level: 0 }).subarray(0, 512 * 20), { compression: false, onwarn() {} }), []); +}); + +test('listTar with onentry and filter', async () => { + const seen = []; + const res = await listTar(sample, { filter: (p) => p.endsWith('.txt'), onentry: (e) => seen.push(e.path) }); + assert.strictEqual(res, undefined); + assert.deepStrictEqual(seen, ['a/small.txt', 'a/after.txt']); + assert.deepStrictEqual(pathsOf(listTarSync(sample, { filter: (p, e) => e.type === 'SymbolicLink' })), ['a/link']); +}); + +test('arguments are validated', async () => { + for (const source of [undefined, null, 1, {}, true]) { + await assert.rejects(listTar(source), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => listTarSync(source), { code: 'ERR_INVALID_ARG_TYPE' }); + } + // Sync functions do not take async sources. + assert.throws(() => listTarSync(Readable.from([sample])), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => listTarSync(sample, null), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => listTarSync(sample, { compression: 'bzip2' }), { code: 'ERR_INVALID_ARG_VALUE' }); + assert.throws(() => listTarSync(sample, { filter: 1 }), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => listTarSync(sample, { onentry: 1 }), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => listTarSync(sample, { onwarn: 1 }), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => listTarSync(sample, { strict: 1 }), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => listTarSync(sample, { maxMetaSize: 1.5 }), { code: 'ERR_OUT_OF_RANGE' }); + await assert.rejects(listTar(sample, { compression: 1 }), { code: 'ERR_INVALID_ARG_VALUE' }); + assert.throws(() => tarEntries(sample, { strict: 'yes' }), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => listTarSync(['string']), { code: 'ERR_INVALID_ARG_TYPE' }); + await assert.rejects(listTar(Readable.from(['string'])), { code: 'ERR_INVALID_ARG_TYPE' }); +}); + +test('missing files are reported', async () => { + const file = join(tmpdir.path, 'does-not-exist.tar'); + await assert.rejects(listTar(file), { code: 'ENOENT' }); + assert.throws(() => listTarSync(file), { code: 'ENOENT' }); + await assert.rejects(tarEntries(file).next(), { code: 'ENOENT' }); +}); + +test('listTar detects truncated files even when seeking', async () => { + const file = join(tempDir(), 't.tar'); + fs.writeFileSync(file, sample.subarray(0, 512 * 4 + 100000)); + await assert.rejects(listTar(file), { code: 'ERR_TAR_INVALID_ARCHIVE' }); + assert.throws(() => listTarSync(file), { code: 'ERR_TAR_INVALID_ARCHIVE' }); +}); + +test('listTar reads ahead, and drops what it then skips', async () => { + // Small entries make the reads grow until they read ahead; large ones are + // then skipped, partly or entirely inside a chunk read ahead. + const list = []; + const sizes = [0, 100, 3000, 200 * 1024, 70 * 1024, 129 * 1024, 5 * 1024 * 1024, 1, 600 * 1024, 2 * 1024 * 1024 + 3]; + for (let round = 0; round < 3; round++) { + for (let i = 0; i < 300; i++) list.push({ name: `r${round}/small-${i}`, data: 'x'.repeat(i * 7) }); + for (const size of sizes) list.push({ name: `r${round}/big-${size}`, data: Buffer.alloc(size, round) }); + } + const archive = makeTar(list); + const file = join(tempDir(), 'a.tar'); + fs.writeFileSync(file, archive); + const expected = list.map((e) => [e.name, e.data.length]); + assert.deepStrictEqual((await listTar(file)).map((e) => [e.path, e.size]), expected); + assert.deepStrictEqual(listTarSync(file).map((e) => [e.path, e.size]), expected); + assert.deepStrictEqual((await listTar(fs.createReadStream(file))).map((e) => [e.path, e.size]), expected); + + // Truncated in the middle of a large entry, at several places. + for (const cut of [archive.length - 2 * 1024 * 1024, archive.length - 1024 * 1024 - 1, + Math.floor(archive.length / 2)]) { + fs.writeFileSync(file, archive.subarray(0, cut - (cut % 512))); + await assert.rejects(listTar(file), { code: 'ERR_TAR_INVALID_ARCHIVE' }); + assert.throws(() => listTarSync(file), { code: 'ERR_TAR_INVALID_ARCHIVE' }); + } +}); + +test('unsupported compressions are rejected', async () => { + await assert.rejects(listTar(Buffer.from('BZh91AY&SY')), { + code: 'ERR_TAR_UNSUPPORTED_FEATURE', + message: 'unsupported tar feature: bzip2 compression', + }); + assert.throws(() => listTarSync(Buffer.from([0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00, 0x00])), + { code: 'ERR_TAR_UNSUPPORTED_FEATURE' }); +}); + +test('corrupt and truncated compressed data is rejected', async () => { + const gz = zlib.gzipSync(sample); + const truncated = gz.subarray(0, gz.length >> 1); + await assert.rejects(listTar(truncated), { code: 'ERR_TAR_INVALID_ARCHIVE' }); + assert.throws(() => listTarSync(truncated), { code: 'ERR_TAR_INVALID_ARCHIVE' }); + const corrupt = Buffer.from(gz); + corrupt.fill(0xff, 20, 40); + await assert.rejects(listTar(corrupt), { code: 'ERR_TAR_INVALID_ARCHIVE', message: /gzip decompression failed/ }); + assert.throws(() => listTarSync(corrupt), { code: 'ERR_TAR_INVALID_ARCHIVE' }); + await assert.rejects(listTar(Readable.from([corrupt])), { code: 'ERR_TAR_INVALID_ARCHIVE' }); +}); + +test('highly compressed archives are listed without buffering them', async () => { + // 64 MiB of zeros in one entry, a few dozen KiB compressed. + const tar = makeTar([{ name: 'zeros', data: Buffer.alloc(64 * 1024 * 1024) }, { name: 'end', data: 'x' }]); + const gz = zlib.gzipSync(tar); + assert.deepStrictEqual(pathsOf(await listTar(gz)), ['zeros', 'end']); + assert.deepStrictEqual(pathsOf(listTarSync(gz)), ['zeros', 'end']); + assert.deepStrictEqual(pathsOf(await listTar(Readable.from(randomChunks(gz, 2, 5000)))), ['zeros', 'end']); +}); + +test('errors of the source stream are reported', async () => { + const failing = new Readable({ + read() { + this.push(sample.subarray(0, 1000)); + this.destroy(new Error('boom')); + }, + }); + await assert.rejects(listTar(failing), { message: 'boom' }); + const closed = new Readable({ + read() { + this.push(sample.subarray(0, 1000)); + this.destroy(); + }, + }); + await assert.rejects(listTar(closed), { code: 'ERR_TAR_INVALID_ARCHIVE' }); +}); + +test('matches the system tar', { skip: !hasTar() }, async () => { + const dir = tempDir(); + const src = join(dir, 'src'); + fs.mkdirSync(join(src, 'x'.repeat(120), 'y'.repeat(120)), { recursive: true }); + fs.writeFileSync(join(src, 'x'.repeat(120), 'y'.repeat(120), 'z'.repeat(110)), 'long'); + fs.writeFileSync(join(src, 'plain'), 'u'); + fs.symlinkSync('plain', join(src, 'l'.repeat(150))); + fs.linkSync(join(src, 'plain'), join(src, 'hardlink')); + const { execFileSync } = require('node:child_process'); + let checked = 0; + for (const format of ['gnu', 'gnutar', 'pax', 'ustar', 'v7']) { + const file = join(dir, `${format}.tar`); + try { + // COPYFILE_DISABLE: no AppleDouble entries on macOS, which `tar -t` hides. + execFileSync('tar', ['-cf', file, `--format=${format}`, '-C', src, '.'], + { stdio: 'ignore', env: { ...process.env, COPYFILE_DISABLE: '1' } }); + } catch { + // Not every tar knows every format, and ustar and v7 cannot store the + // long names. + continue; + } + const expected = execFileSync('tar', ['-tf', file], { encoding: 'utf8' }).trim().split('\n'); + assert.deepStrictEqual(pathsOf(await listTar(file)), expected, format); + checked++; + } + assert.ok(checked > 0); +}); + +function hasTar() { + if (common.isWindows) return false; + try { + require('node:child_process').execFileSync('tar', ['--version'], { stdio: 'ignore' }); + return true; + } catch { + return false; + } +} + +test('tarEntries() gives the bodies', async () => { + const got = []; + for await (const entry of tarEntries(Readable.from(randomChunks(sample, 9, 40000)))) { + if (entry.path === 'a/big.bin') { + const data = await entry.body.buffer(); + assert.ok(data.equals(big)); + got.push([entry.path, data.length]); + } else if (entry.path === 'a/after.txt') { + got.push([entry.path, await entry.body.text()]); + } else { + // Not read: skipped. + got.push([entry.path]); + } + } + assert.deepStrictEqual( + got, [['a/'], ['a/small.txt'], ['a/big.bin', big.length], ['a/after.txt', 'after'], ['a/link']]); +}); + +test('tarEntries() reads files, skipping what is not read', async () => { + const file = join(tempDir(), 'a.tar'); + fs.writeFileSync(file, sample); + const got = []; + for await (const entry of tarEntries(file)) { + got.push([entry.path, entry.path.endsWith('.txt') ? await entry.body.text('latin1') : null]); + } + assert.deepStrictEqual( + got, [['a/', null], ['a/small.txt', 'small'], ['a/big.bin', null], ['a/after.txt', 'after'], ['a/link', null]]); + assert.deepStrictEqual(pathsOf(await Array.fromAsync(tarEntries(pathToFileURL(file)))), paths); + assert.deepStrictEqual( + pathsOf(await Array.fromAsync(tarEntries(file, { filter: (p) => p.includes('big') }))), ['a/big.bin']); +}); + +test('tarEntries() can stop early', async () => { + const file = join(tempDir(), 'a.tar'); + fs.writeFileSync(file, sample); + let n = 0; + const iterator = tarEntries(file); + for await (const entry of iterator) { + n++; + if (entry.path === 'a/small.txt') break; + } + assert.strictEqual(n, 2); + assert.deepStrictEqual(await iterator.next(), { __proto__: null, value: undefined, done: true }); + // Never started. + assert.deepStrictEqual(await tarEntries(file).return(), { __proto__: null, value: undefined, done: true }); +}); + +test('tarEntries() streams a body in chunks', async () => { + let total = 0; + for await (const entry of tarEntries(zlib.gzipSync(sample))) { + for await (const chunk of entry.body) total += chunk.length; + } + assert.strictEqual(total, 5 + big.length + 5); +}); + +test('a body can only be read once', async () => { + for await (const entry of tarEntries(sample)) { + if (entry.path !== 'a/small.txt') continue; + assert.strictEqual(entry.body.done, false); + assert.strictEqual(await entry.body.text(), 'small'); + assert.strictEqual(entry.body.done, true); + await assert.rejects(entry.body.buffer(), { code: 'ERR_INVALID_STATE' }); + await assert.rejects(entry.body.text(), { code: 'ERR_INVALID_STATE' }); + await assert.rejects(entry.body[Symbol.asyncIterator]().next(), { code: 'ERR_INVALID_STATE' }); + await entry.body.skip(); + } +}); + +test('a partly read body is skipped', async () => { + const got = []; + for await (const entry of tarEntries(Readable.from(randomChunks(sample, 4, 9000)))) { + got.push(entry.path); + if (entry.path === 'a/big.bin') { + for await (const chunk of entry.body) { + assert.ok(chunk.length > 0); + break; + } + } + } + assert.deepStrictEqual(got, paths); +}); + +test('tarEntries() reports errors', async () => { + await assert.rejects(async () => { + for await (const entry of tarEntries(sample.subarray(0, 3000))) { + await entry.body.buffer(); + } + }, { code: 'ERR_TAR_INVALID_ARCHIVE' }); + const bad = makeTar([{ name: 'ok' }, { raw: Buffer.alloc(512, 1) }]); + await assert.rejects(Array.fromAsync(tarEntries(bad, { strict: true })), { code: 'ERR_TAR_INVALID_ENTRY' }); + const warnings = []; + assert.deepStrictEqual( + pathsOf(await Array.fromAsync(tarEntries(bad, { onwarn: (err) => warnings.push(err.code) }))), ['ok']); + assert.deepStrictEqual(warnings, ['ERR_TAR_INVALID_ENTRY']); +}); diff --git a/test/parallel/test-zlib-tar-parser.js b/test/parallel/test-zlib-tar-parser.js new file mode 100644 index 00000000000..170b4038988 --- /dev/null +++ b/test/parallel/test-zlib-tar-parser.js @@ -0,0 +1,335 @@ +'use strict'; + +// zlib.TarParser: the push parser that the rest of the tar API is built on. + +require('../common'); + +const assert = require('node:assert'); +const { test } = require('node:test'); +const { TarParser, TarEntry } = require('node:zlib'); +const { makeTar, header, randomChunks } = require('../common/tar'); + +function parseAll(chunks, opts = {}) { + const entries = []; + const warnings = []; + let current = null; + const { skip, ...options } = opts; + const parser = new TarParser({ + onwarn: (err) => warnings.push(err.code), + ...options, + onentry(entry) { + current = { entry, data: [] }; + entries.push(current); + return skip ? !skip(entry) : true; + }, + ondata(chunk) { + current.data.push(Buffer.from(chunk)); + }, + onentryend() { + current.ended = true; + }, + }); + for (const c of chunks) parser.write(c); + parser.end(); + return { entries: entries.map((e) => ({ ...e, body: Buffer.concat(e.data).toString() })), warnings }; +} + +const sample = makeTar([ + { name: 'dir/', type: 'dir' }, + { name: 'dir/a.txt', data: 'hello world' }, + { name: 'dir/empty' }, + { name: 'dir/big.bin', data: Buffer.alloc(5000, 'x') }, + { name: 'link', type: 'symlink', linkname: 'dir/a.txt' }, + { name: 'hard', type: 'link', linkname: 'dir/a.txt' }, + { name: 'long', pax: { path: `${'p'.repeat(300)}/file` }, data: 'pax path' }, + { name: 'gnu', gnuLongPath: 'g'.repeat(200), gnuLongLink: 'l'.repeat(150), type: 'symlink', linkname: 'short' }, + { name: 'after', data: 'last' }, +]); + +test('parses all entry kinds', () => { + const { entries, warnings } = parseAll([sample]); + assert.deepStrictEqual(warnings, []); + assert.deepStrictEqual(entries.map((e) => e.entry.path), [ + 'dir/', 'dir/a.txt', 'dir/empty', 'dir/big.bin', 'link', 'hard', `${'p'.repeat(300)}/file`, 'g'.repeat(200), + 'after', + ]); + assert.deepStrictEqual(entries.map((e) => e.entry.type), [ + 'Directory', 'File', 'File', 'File', 'SymbolicLink', 'Link', 'File', 'SymbolicLink', 'File', + ]); + assert.strictEqual(entries[1].body, 'hello world'); + assert.strictEqual(entries[3].body, 'x'.repeat(5000)); + assert.strictEqual(entries[6].body, 'pax path'); + assert.strictEqual(entries[6].entry.pax.path, `${'p'.repeat(300)}/file`); + assert.strictEqual(entries[7].entry.linkpath, 'l'.repeat(150)); + assert.strictEqual(entries[8].body, 'last'); + assert.ok(entries.every((e) => e.ended)); + assert.ok(entries.every((e) => e.entry instanceof TarEntry)); +}); + +test('entries carry the header fields', () => { + const tar = makeTar([ + { name: 'f', data: 'abc', mode: 0o640, uid: 12, gid: 34, mtime: 1500000000, uname: 'me', gname: 'us' }, + { name: 'old', format: 'v7', data: 'x' }, + { name: 'name', prefix: 'some/prefix', data: 'y' }, + ]); + const { entries } = parseAll([tar]); + const e = entries[0].entry; + assert.strictEqual(e.size, 3); + assert.strictEqual(e.mode, 0o640); + assert.strictEqual(e.uid, 12); + assert.strictEqual(e.gid, 34); + assert.strictEqual(e.uname, 'me'); + assert.strictEqual(e.gname, 'us'); + assert.strictEqual(e.mtime.getTime(), 1500000000 * 1000); + assert.strictEqual(e.atime, null); + assert.strictEqual(e.ctime, null); + assert.strictEqual(e.linkpath, ''); + assert.strictEqual(e.pax, null); + assert.strictEqual(e.offset, 0); + assert.strictEqual(entries[1].entry.uname, ''); + assert.strictEqual(entries[1].entry.offset, 1024); + assert.strictEqual(entries[2].entry.path, 'some/prefix/name'); +}); + +test('results do not depend on chunk boundaries', () => { + const expected = parseAll([sample]).entries.map((e) => [e.entry.path, e.body]); + for (let seed = 1; seed < 30; seed++) { + const got = parseAll(randomChunks(sample, seed, seed * 37)).entries.map((e) => [e.entry.path, e.body]); + assert.deepStrictEqual(got, expected, `seed ${seed}`); + } + const bytes = []; + for (let i = 0; i < sample.length; i++) bytes.push(sample.subarray(i, i + 1)); + assert.deepStrictEqual(parseAll(bytes).entries.map((e) => [e.entry.path, e.body]), expected); +}); + +test('chunks may be reused by the source after write()', () => { + // The parser must copy whatever it keeps across write() calls. + const expected = parseAll([sample]).entries.map((e) => [e.entry.path, e.body]); + const entries = []; + let cur = null; + const parser = new TarParser({ + onentry(e) { + cur = [e.path, '']; + entries.push(cur); + }, + ondata(c) { + cur[1] += c.toString(); + }, + }); + const scratch = Buffer.alloc(333); + for (let i = 0; i < sample.length; i += 333) { + const n = sample.copy(scratch, 0, i, i + 333); + parser.write(scratch.subarray(0, n)); + scratch.fill(0xaa); + } + parser.end(); + assert.deepStrictEqual(entries, expected); +}); + +test('accepts any ArrayBufferView, and nothing else', () => { + const paths = []; + const parser = new TarParser({ onentry: (e) => { paths.push(e.path); } }); + const copy = new Uint8Array(sample); + parser.write(copy.subarray(0, 1000)); + parser.write(new DataView(copy.buffer, 1000)); + parser.end(); + assert.strictEqual(paths.length, 9); + assert.throws(() => parser.write('string'), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => parser.write(copy.buffer), { code: 'ERR_INVALID_ARG_TYPE' }); +}); + +test('validates its options', () => { + assert.throws(() => new TarParser(null), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => new TarParser({ onentry: 1 }), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => new TarParser({ ondata: 'x' }), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => new TarParser({ onentryend: {} }), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => new TarParser({ onwarn: true }), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => new TarParser({ strict: 1 }), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => new TarParser({ maxMetaSize: -1 }), { code: 'ERR_OUT_OF_RANGE' }); + new TarParser().end(); +}); + +test('without ondata every body is skippable', () => { + const paths = []; + const parser = new TarParser({ onentry: (e) => { paths.push(e.path); } }); + parser.write(sample.subarray(0, 512 * 2)); + // dir/, then the header of dir/a.txt: its body is skippable. + assert.strictEqual(parser.skippable, 512); + assert.throws(() => parser.skip(513), { code: 'ERR_OUT_OF_RANGE' }); + assert.throws(() => parser.skip(-1), { code: 'ERR_OUT_OF_RANGE' }); + parser.skip(512); + assert.strictEqual(parser.skippable, 0); + parser.write(sample.subarray(512 * 3)); + parser.end(); + assert.strictEqual(paths.length, 9); +}); + +test('onentry returning false skips the body', () => { + const { entries } = parseAll([sample], { skip: (e) => e.path === 'dir/a.txt' }); + assert.strictEqual(entries[1].body, ''); + assert.strictEqual(entries[1].ended, undefined); + assert.strictEqual(entries[3].body, 'x'.repeat(5000)); +}); + +test('skipBody() drops the rest of a body', () => { + for (const size of [3, 512, 5000]) { + for (const step of [100, 512, 100000]) { + const tar = makeTar([{ name: 'a', data: 'a'.repeat(size) }, { name: 'b', data: 'bb' }]); + const seen = []; + const ended = []; + const skipped = []; + const parser = new TarParser({ + onentry: (e) => { seen.push([e.path, 0]); }, + ondata(chunk, entry) { + seen.at(-1)[1] += chunk.length; + if (entry.path === 'a') skipped.push(parser.skipBody()); + }, + onentryend: (e) => ended.push(e.path), + }); + assert.strictEqual(parser.skipBody(), false); + for (let i = 0; i < tar.length; i += step) parser.write(tar.subarray(i, i + step)); + parser.end(); + // The first part of the body is what follows the header in its chunk. + const first = 512 % step === 0 ? step : step - (512 % step); + assert.strictEqual(seen[0][1], Math.min(size, first), `${size}/${step}`); + assert.deepStrictEqual(seen[1], ['b', 2]); + assert.deepStrictEqual(ended, ['b']); + assert.deepStrictEqual(skipped, [true]); + } + } +}); + +test('global pax headers apply to the following entries', () => { + const tar = makeTar([ + { name: 'a', globalPax: { uname: 'everyone', mtime: '1000' } }, + { name: 'b', pax: { mtime: '2000' } }, + { name: 'c' }, + ]); + const { entries } = parseAll([tar]); + assert.deepStrictEqual(entries.map((e) => e.entry.uname), ['everyone', 'everyone', 'everyone']); + assert.deepStrictEqual(entries.map((e) => e.entry.mtime.getTime()), [1000000, 2000000, 1000000]); + assert.strictEqual(Object.getPrototypeOf(Object.getPrototypeOf(entries[1].entry.pax)), null); + assert.deepStrictEqual({ ...entries[1].entry.pax }, { uname: 'everyone', mtime: '2000' }); +}); + +test('pax records cannot pollute prototypes', () => { + const pax = Object.fromEntries([['__proto__', 'polluted'], ['constructor', 'x']]); + const tar = makeTar([{ name: 'a', pax }]); + const { entries } = parseAll([tar]); + assert.strictEqual(Object.getOwnPropertyDescriptor(entries[0].entry.pax, '__proto__').value, 'polluted'); + assert.strictEqual(entries[0].entry.pax.constructor, 'x'); + assert.strictEqual({}.polluted, undefined); +}); + +test('pax size overrides the header size', () => { + const tar = makeTar([{ name: 'a', pax: { size: '3' }, size: 0, data: 'abc' }, { name: 'b', data: 'x' }]); + // The header says 0 but pax says 3: the body is 3 bytes. + const { entries } = parseAll([tar]); + assert.strictEqual(entries[0].entry.size, 3); + assert.strictEqual(entries[0].body, 'abc'); + assert.strictEqual(entries[1].body, 'x'); +}); + +test('times that are not representable are null', () => { + const rawMtime = Buffer.alloc(12, 0xee); + rawMtime[0] = 0x80; + const tar = makeTar([ + { name: 'a', rawMtime }, + { name: 'b', pax: { mtime: '1e300', atime: 'junk', ctime: '12.5' } }, + ]); + const { entries } = parseAll([tar]); + assert.strictEqual(entries[0].entry.mtime, null); + assert.strictEqual(entries[1].entry.mtime.getTime(), 1700000000 * 1000); + assert.strictEqual(entries[1].entry.atime, null); + assert.strictEqual(entries[1].entry.ctime.getTime(), 12500); +}); + +test('truncated archives throw', () => { + const tar = makeTar([{ name: 'a', data: 'x'.repeat(1000) }], { end: false }); + assert.throws(() => parseAll([tar.subarray(0, 900)]), { + code: 'ERR_TAR_INVALID_ARCHIVE', + message: 'invalid tar archive: unexpected end of archive', + path: 'a', + position: 900, + }); + assert.throws(() => parseAll([tar.subarray(0, 300)]), { code: 'ERR_TAR_INVALID_ARCHIVE' }); + const pax = makeTar([{ name: 'a', pax: { path: 'b' } }], { end: false }); + assert.throws(() => parseAll([pax.subarray(0, 1024)]), { code: 'ERR_TAR_INVALID_ARCHIVE' }); +}); + +test('a missing end marker is accepted', () => { + const tar = makeTar([{ name: 'a', data: 'x' }], { end: false }); + assert.strictEqual(parseAll([tar]).entries.length, 1); +}); + +test('a missing final padding is accepted', () => { + const tar = makeTar([{ name: 'a', data: 'xyz' }], { end: false }); + assert.strictEqual(parseAll([tar.subarray(0, 515)]).entries[0].body, 'xyz'); +}); + +test('invalid headers are reported and skipped', () => { + const bad = header({ name: 'bad' }); + bad[0] = 0x63; + const tar = makeTar([{ name: 'first' }, { raw: bad }, { name: 'good', data: 'ok' }]); + const errors = []; + const { entries } = parseAll([tar], { onwarn: (err) => errors.push(err) }); + assert.strictEqual(errors.length, 1); + assert.strictEqual(errors[0].code, 'ERR_TAR_INVALID_ENTRY'); + assert.strictEqual(errors[0].position, 512); + assert.deepStrictEqual(entries.map((e) => e.entry.path), ['first', 'good']); +}); + +test('strict mode turns warnings into errors', () => { + const bad = header({ name: 'bad' }); + bad[0] = 0x63; + assert.throws(() => parseAll([makeTar([{ raw: bad }])], { strict: true }), { code: 'ERR_TAR_INVALID_ENTRY' }); +}); + +test('oversized meta entries are skipped', () => { + const tar = makeTar([{ name: 'a', pax: { path: 'x'.repeat(2000) }, data: 'body' }]); + for (const chunks of [[tar], randomChunks(tar, 5, 300)]) { + const { entries, warnings } = parseAll(chunks, { maxMetaSize: 100 }); + assert.deepStrictEqual(warnings, ['ERR_TAR_INVALID_ENTRY']); + assert.strictEqual(entries[0].entry.path, 'a'); + assert.strictEqual(entries[0].body, 'body'); + } +}); + +test('invalid sizes are reported', () => { + const rawSize = Buffer.alloc(12, 0xff); + const tar = makeTar([{ name: 'neg', rawSize }, { name: 'meta', type: 'pax', rawSize }, { name: 'ok', data: 'x' }]); + const { entries, warnings } = parseAll([tar]); + assert.deepStrictEqual(warnings, ['ERR_TAR_INVALID_ENTRY', 'ERR_TAR_INVALID_ENTRY']); + assert.deepStrictEqual(entries.map((e) => [e.entry.path, e.body]), [['ok', 'x']]); +}); + +test('data after the end marker is ignored', () => { + const tar = Buffer.concat([makeTar([{ name: 'a', data: 'x' }]), Buffer.from('trailing garbage')]); + const parser = new TarParser({ onentry() {} }); + assert.strictEqual(parser.done, false); + parser.write(tar); + assert.strictEqual(parser.done, true); + parser.end(); + parser.end(); +}); + +test('base-256 sizes', () => { + const raw = Buffer.alloc(12); + raw[0] = 0x80; + raw.writeUInt32BE(5, 8); + const tar = makeTar([{ name: 'a', rawSize: raw, data: '12345' }, { name: 'b' }]); + const { entries } = parseAll([tar]); + assert.strictEqual(entries[0].body, '12345'); + assert.strictEqual(entries[1].entry.path, 'b'); +}); + +test('headers with signed checksums are accepted', () => { + const block = header({ name: 'ünï' }); + let signed = 0; + block.fill(0x20, 148, 156); + for (let i = 0; i < 512; i++) signed += block[i] > 127 ? block[i] - 256 : block[i]; + block.write(`${signed.toString(8).padStart(6, '0')}\0 `, 148, 8, 'ascii'); + const { entries, warnings } = parseAll([makeTar([{ raw: block }])]); + assert.deepStrictEqual(warnings, []); + assert.strictEqual(entries[0].entry.path, 'ünï'); +}); diff --git a/test/parallel/test-zlib-tar-security.js b/test/parallel/test-zlib-tar-security.js new file mode 100644 index 00000000000..2634dd44d10 --- /dev/null +++ b/test/parallel/test-zlib-tar-security.js @@ -0,0 +1,189 @@ +'use strict'; + +// Extraction must never write outside of the extraction directory, whatever +// the archive says. + +const common = require('../common'); + +if (!common.canCreateSymLink()) { + common.skip('insufficient privileges to create symbolic links'); +} + +const assert = require('node:assert'); +const fs = require('node:fs'); +const { join } = require('node:path'); +const { Readable } = require('node:stream'); +const { pipeline } = require('node:stream/promises'); +const { test } = require('node:test'); +const { extractTar, extractTarSync, createTarExtractStream } = require('node:zlib'); +const tmpdir = require('../common/tmpdir'); +const { makeTar, tempDir } = require('../common/tar'); + +tmpdir.refresh(); + +const modes = { + async: (tar, options) => extractTar(tar, options), + sync: async (tar, options) => extractTarSync(tar, options), + stream: (tar, options) => pipeline(Readable.from([tar]), createTarExtractStream(options)), +}; + +function setup() { + const root = tempDir(); + const cwd = join(root, 'cwd'); + const outside = join(root, 'outside'); + fs.mkdirSync(cwd); + fs.mkdirSync(outside); + return { root, cwd, outside }; +} + +const kUnsafe = 'ERR_TAR_UNSAFE_ENTRY'; + +for (const { 0: name, 1: run } of Object.entries(modes)) { + test(`${name}: '..' paths are refused`, async () => { + const { root, cwd } = setup(); + const warnings = []; + const tar = makeTar([ + { name: '../escape.txt', data: 'x' }, + { name: 'a/../../escape2.txt', data: 'x' }, + { name: 'long', pax: { path: 'b/../../escape3.txt' }, data: 'x' }, + { name: 'long', gnuLongPath: '../escape4.txt', data: 'x' }, + ]); + await run(tar, { cwd, onwarn: (err) => warnings.push(err.code) }); + for (const file of ['escape.txt', 'escape2.txt', 'escape3.txt', 'escape4.txt']) { + assert.strictEqual(fs.existsSync(join(root, file)), false); + } + assert.deepStrictEqual(fs.readdirSync(cwd), []); + assert.deepStrictEqual(warnings, [kUnsafe, kUnsafe, kUnsafe, kUnsafe]); + }); + + test(`${name}: absolute paths are made relative`, async () => { + const { root, cwd } = setup(); + const target = join(root, 'abs.txt'); + const warnings = []; + await run(makeTar([{ name: 'x', pax: { path: target }, data: 'x' }]), + { cwd, onwarn: (err) => warnings.push(err.message) }); + assert.strictEqual(fs.existsSync(target), false); + assert.strictEqual(fs.readFileSync(join(cwd, target.replace(/^[a-zA-Z]:/, '')), 'utf8'), 'x'); + assert.deepStrictEqual(warnings, ['refusing to extract tar entry: absolute path made relative']); + // Informative: it is not an error when strict. + const { cwd: cwd2 } = setup(); + await run(makeTar([{ name: 'x', pax: { path: target }, data: 'x' }]), { cwd: cwd2, strict: true }); + assert.strictEqual(fs.existsSync(target), false); + }); + + test(`${name}: no writing through a symlink from the archive`, async () => { + const { cwd, outside } = setup(); + const warnings = []; + await run(makeTar([ + { name: 'evil', type: 'symlink', linkname: outside }, + { name: 'evil/pwned.txt', data: 'gotcha' }, + { name: 'evil/sub/pwned.txt', data: 'gotcha' }, + { name: 'evil/dir/', type: 'dir' }, + ]), { cwd, onwarn: (err) => warnings.push(err.code) }); + assert.deepStrictEqual(fs.readdirSync(outside), []); + assert.deepStrictEqual(warnings, [kUnsafe, kUnsafe, kUnsafe]); + }); + + test(`${name}: no writing through a symlink replacing a directory`, async () => { + const { cwd, outside } = setup(); + await run(makeTar([ + { name: 'd/', type: 'dir' }, + { name: 'd', type: 'symlink', linkname: outside }, + { name: 'd/pwned.txt', data: 'gotcha' }, + ]), { cwd }); + assert.deepStrictEqual(fs.readdirSync(outside), []); + }); + + test(`${name}: no writing through a pre-existing symlink`, async () => { + const { cwd, outside } = setup(); + fs.symlinkSync(outside, join(cwd, 'pre')); + fs.writeFileSync(join(outside, 'target.txt'), 'original'); + fs.symlinkSync(join(outside, 'target.txt'), join(cwd, 'leaf')); + await run(makeTar([ + { name: 'pre/pwned.txt', data: 'gotcha' }, + { name: 'leaf', data: 'overwritten?' }, + ]), { cwd }); + assert.strictEqual(fs.existsSync(join(outside, 'pwned.txt')), false); + assert.strictEqual(fs.readFileSync(join(outside, 'target.txt'), 'utf8'), 'original'); + // The leaf symlink itself was replaced by a regular file. + assert.strictEqual(fs.lstatSync(join(cwd, 'leaf')).isFile(), true); + }); + + test(`${name}: hard links cannot point outside`, async () => { + const { cwd, outside } = setup(); + fs.writeFileSync(join(outside, 'secret'), 'secret'); + await run(makeTar([ + { name: 'h1', type: 'link', linkname: '../outside/secret' }, + { name: 'h2', type: 'link', gnuLongLink: join(outside, 'secret') }, + ]), { cwd }); + assert.strictEqual(fs.existsSync(join(cwd, 'h1')), false); + // Absolute targets are made relative to cwd, where they do not exist. + assert.strictEqual(fs.existsSync(join(cwd, 'h2')), false); + }); + + test(`${name}: hard links cannot go through symlinks`, async () => { + const { cwd, outside } = setup(); + fs.writeFileSync(join(outside, 'secret'), 'secret'); + await run(makeTar([ + { name: 's', type: 'symlink', linkname: outside }, + { name: 'h', type: 'link', linkname: 's/secret' }, + { name: 'h', data: 'overwrite' }, + { name: 'direct', type: 'symlink', linkname: join(outside, 'secret') }, + { name: 'h2', type: 'link', linkname: 'direct' }, + { name: 'h2', data: 'overwrite' }, + ]), { cwd }); + assert.strictEqual(fs.readFileSync(join(outside, 'secret'), 'utf8'), 'secret'); + }); + + test(`${name}: writing a file over an existing hard link does not change the other link`, async () => { + const { cwd, outside } = setup(); + fs.writeFileSync(join(outside, 'shared'), 'shared'); + fs.linkSync(join(outside, 'shared'), join(cwd, 'f')); + await run(makeTar([{ name: 'f', data: 'new' }]), { cwd }); + assert.strictEqual(fs.readFileSync(join(outside, 'shared'), 'utf8'), 'shared'); + assert.strictEqual(fs.readFileSync(join(cwd, 'f'), 'utf8'), 'new'); + }); + + test(`${name}: maxDepth`, async () => { + const { cwd } = setup(); + const warnings = []; + await run(makeTar([{ name: 'a/b/c/d/e.txt', data: 'x' }, { name: 'a/./b//c/../c/d/e.txt', data: 'x' }]), + { cwd, maxDepth: 3, preservePaths: true, onwarn: (err) => warnings.push(err.code) }); + assert.strictEqual(fs.existsSync(join(cwd, 'a')), false); + assert.deepStrictEqual(warnings, [kUnsafe, kUnsafe]); + }); + + test(`${name}: an entry cannot replace cwd`, async () => { + const { cwd } = setup(); + const warnings = []; + await run(makeTar([{ name: './', type: 'symlink', linkname: '/' }, { name: '.', data: 'x' }]), + { cwd, onwarn: (err) => warnings.push(err.code) }); + assert.strictEqual(fs.lstatSync(cwd).isDirectory(), true); + assert.deepStrictEqual(warnings, [kUnsafe, kUnsafe]); + }); + + test(`${name}: null bytes in paths and link targets are refused`, async () => { + const { cwd } = setup(); + const warnings = []; + await run(makeTar([ + { name: 'x', pax: { path: 'a\0b' }, data: 'x' }, + { name: 'l', type: 'symlink', linkname: 'x', pax: { linkpath: 'a\0b' } }, + { name: 'h', type: 'link', linkname: 'x', pax: { linkpath: 'a\0b' } }, + { name: 'empty', type: 'symlink', linkname: '' }, + ]), { cwd, onwarn: (err) => warnings.push(err.code) }); + assert.deepStrictEqual(fs.readdirSync(cwd), []); + assert.deepStrictEqual(warnings, [kUnsafe, kUnsafe, kUnsafe, kUnsafe]); + }); +} + +test('preservePaths allows absolute paths and ..', async () => { + const { root, cwd } = setup(); + const target = join(root, 'abs.txt'); + await extractTar(makeTar([{ name: 'x', pax: { path: target }, data: 'x' }]), { cwd, preservePaths: true }); + assert.strictEqual(fs.readFileSync(target, 'utf8'), 'x'); + const target2 = join(root, 'abs2.txt'); + extractTarSync(makeTar([{ name: 'x', pax: { path: target2 }, data: 'y' }]), { cwd, preservePaths: true }); + assert.strictEqual(fs.readFileSync(target2, 'utf8'), 'y'); + await extractTar(makeTar([{ name: '../up.txt', data: 'z' }]), { cwd, preservePaths: true }); + assert.strictEqual(fs.readFileSync(join(root, 'up.txt'), 'utf8'), 'z'); +});