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` [\