-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathtgzUtils.ts
225 lines (169 loc) Β· 7.46 KB
/
tgzUtils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import {Configuration, nodeUtils} from '@yarnpkg/core';
import {FakeFS, PortablePath, NodeFS, ppath, xfs, npath, constants, statUtils} from '@yarnpkg/fslib';
import {ZipCompression, ZipFS} from '@yarnpkg/libzip';
import {PassThrough, Readable} from 'stream';
import tar from 'tar';
import {AsyncPool, TaskPool, WorkerPool} from './TaskPool';
import * as miscUtils from './miscUtils';
import {getContent as getZipWorkerSource} from './worker-zip';
export type ConvertToZipPayload = {
tmpFile: PortablePath;
tgz: Buffer | Uint8Array;
extractBufferOpts: ExtractBufferOptions;
compressionLevel: ZipCompression;
};
export type ZipWorkerPool = TaskPool<ConvertToZipPayload, PortablePath>;
function createTaskPool(poolMode: string, poolSize: number): ZipWorkerPool {
switch (poolMode) {
case `async`:
return new AsyncPool(convertToZipWorker, {poolSize});
case `workers`:
return new WorkerPool(getZipWorkerSource(), {poolSize});
default: {
throw new Error(`Assertion failed: Unknown value ${poolMode} for taskPoolMode`);
}
}
}
let defaultWorkerPool: ZipWorkerPool | undefined;
export function getDefaultTaskPool() {
if (typeof defaultWorkerPool === `undefined`)
defaultWorkerPool = createTaskPool(`workers`, nodeUtils.availableParallelism());
return defaultWorkerPool;
}
const workerPools = new WeakMap<Configuration, ZipWorkerPool>();
export function getTaskPoolForConfiguration(configuration: Configuration | void): ZipWorkerPool {
if (typeof configuration === `undefined`)
return getDefaultTaskPool();
return miscUtils.getFactoryWithDefault(workerPools, configuration, () => {
const poolMode = configuration.get(`taskPoolMode`);
const poolSize = configuration.get(`taskPoolConcurrency`);
switch (poolMode) {
case `async`:
return new AsyncPool(convertToZipWorker, {poolSize});
case `workers`:
return new WorkerPool(getZipWorkerSource(), {poolSize});
default: {
throw new Error(`Assertion failed: Unknown value ${poolMode} for taskPoolMode`);
}
}
});
}
export async function convertToZipWorker(data: ConvertToZipPayload) {
const {tmpFile, tgz, compressionLevel, extractBufferOpts} = data;
const zipFs = new ZipFS(tmpFile, {create: true, level: compressionLevel, stats: statUtils.makeDefaultStats()});
// Buffers sent through Node are turned into regular Uint8Arrays
const tgzBuffer = Buffer.from(tgz.buffer, tgz.byteOffset, tgz.byteLength);
await extractArchiveTo(tgzBuffer, zipFs, extractBufferOpts);
zipFs.saveAndClose();
return tmpFile;
}
export interface MakeArchiveFromDirectoryOptions {
baseFs?: FakeFS<PortablePath>;
prefixPath?: PortablePath | null;
compressionLevel?: ZipCompression;
inMemory?: boolean;
}
export async function makeArchiveFromDirectory(source: PortablePath, {baseFs = new NodeFS(), prefixPath = PortablePath.root, compressionLevel, inMemory = false}: MakeArchiveFromDirectoryOptions = {}): Promise<ZipFS> {
let zipFs;
if (inMemory) {
zipFs = new ZipFS(null, {level: compressionLevel});
} else {
const tmpFolder = await xfs.mktempPromise();
const tmpFile = ppath.join(tmpFolder, `archive.zip`);
zipFs = new ZipFS(tmpFile, {create: true, level: compressionLevel});
}
const target = ppath.resolve(PortablePath.root, prefixPath!);
await zipFs.copyPromise(target, source, {baseFs, stableTime: true, stableSort: true});
return zipFs;
}
export interface ExtractBufferOptions {
prefixPath?: PortablePath;
stripComponents?: number;
}
export interface ConvertToZipOptions extends ExtractBufferOptions {
configuration?: Configuration;
compressionLevel?: ZipCompression;
taskPool?: ZipWorkerPool;
}
export async function convertToZip(tgz: Buffer, opts: ConvertToZipOptions = {}) {
const tmpFolder = await xfs.mktempPromise();
const tmpFile = ppath.join(tmpFolder, `archive.zip`);
const compressionLevel = opts.compressionLevel
?? opts.configuration?.get(`compressionLevel`)
?? `mixed`;
const extractBufferOpts: ExtractBufferOptions = {
prefixPath: opts.prefixPath,
stripComponents: opts.stripComponents,
};
const taskPool = opts.taskPool ?? getTaskPoolForConfiguration(opts.configuration);
await taskPool.run({tmpFile, tgz, compressionLevel, extractBufferOpts});
return new ZipFS(tmpFile, {level: opts.compressionLevel});
}
async function * parseTar(tgz: Buffer) {
// @ts-expect-error - Types are wrong about what this function returns
const parser: tar.ParseStream = new tar.Parse();
const passthrough = new PassThrough({objectMode: true, autoDestroy: true, emitClose: true});
parser.on(`entry`, (entry: tar.ReadEntry) => {
passthrough.write(entry);
});
parser.on(`error`, error => {
passthrough.destroy(error);
});
parser.on(`close`, () => {
if (!passthrough.destroyed) {
passthrough.end();
}
});
parser.end(tgz);
for await (const entry of passthrough) {
const it = entry as tar.ReadEntry;
yield it;
it.resume();
}
}
export async function extractArchiveTo<T extends FakeFS<PortablePath>>(tgz: Buffer, targetFs: T, {stripComponents = 0, prefixPath = PortablePath.dot}: ExtractBufferOptions = {}): Promise<T> {
function ignore(entry: tar.ReadEntry) {
// Disallow absolute paths; might be malicious (ex: /etc/passwd)
if (entry.path[0] === `/`)
return true;
const parts = entry.path.split(/\//g);
// We also ignore paths that could lead to escaping outside the archive
if (parts.some((part: string) => part === `..`))
return true;
if (parts.length <= stripComponents)
return true;
return false;
}
for await (const entry of parseTar(tgz)) {
if (ignore(entry))
continue;
const parts = ppath.normalize(npath.toPortablePath(entry.path)).replace(/\/$/, ``).split(/\//g);
if (parts.length <= stripComponents)
continue;
const slicePath = parts.slice(stripComponents).join(`/`) as PortablePath;
const mappedPath = ppath.join(prefixPath, slicePath);
let mode = 0o644;
// If a single executable bit is set, normalize so that all are
if (entry.type === `Directory` || ((entry.mode ?? 0) & 0o111) !== 0)
mode |= 0o111;
switch (entry.type) {
case `Directory`: {
targetFs.mkdirpSync(ppath.dirname(mappedPath), {chmod: 0o755, utimes: [constants.SAFE_TIME, constants.SAFE_TIME]});
targetFs.mkdirSync(mappedPath, {mode});
targetFs.utimesSync(mappedPath, constants.SAFE_TIME, constants.SAFE_TIME);
} break;
case `OldFile`:
case `File`: {
targetFs.mkdirpSync(ppath.dirname(mappedPath), {chmod: 0o755, utimes: [constants.SAFE_TIME, constants.SAFE_TIME]});
targetFs.writeFileSync(mappedPath, await miscUtils.bufferStream(entry as unknown as Readable), {mode});
targetFs.utimesSync(mappedPath, constants.SAFE_TIME, constants.SAFE_TIME);
} break;
case `SymbolicLink`: {
targetFs.mkdirpSync(ppath.dirname(mappedPath), {chmod: 0o755, utimes: [constants.SAFE_TIME, constants.SAFE_TIME]});
targetFs.symlinkSync((entry as any).linkpath, mappedPath);
targetFs.lutimesSync(mappedPath, constants.SAFE_TIME, constants.SAFE_TIME);
} break;
}
}
return targetFs;
}