forked from nodegit/nodegit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathacquireOpenSSL.js
More file actions
436 lines (373 loc) · 12.9 KB
/
Copy pathacquireOpenSSL.js
File metadata and controls
436 lines (373 loc) · 12.9 KB
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
const crypto = require("crypto");
const execPromise = require("./execPromise");
// for fs.remove. replace with fs.rm after dropping v12 support
const fse = require("fs-extra");
const fsNonPromise = require("fs");
const { promises: fs } = fsNonPromise;
const path = require("path");
const got = require("got");
const { performance } = require("perf_hooks");
const { promisify } = require("util");
const stream = require("stream");
const tar = require("tar-fs");
const zlib = require("zlib");
const pipeline = promisify(stream.pipeline);
const packageJson = require('../package.json')
const OPENSSL_VERSION = "1.1.1t";
const win32BatPath = path.join(__dirname, "build-openssl.bat");
const vendorPath = path.resolve(__dirname, "..", "vendor");
const opensslPatchPath = path.join(vendorPath, "patches", "openssl");
const extractPath = path.join(vendorPath, "openssl");
const pathsToIncludeForPackage = [
"include", "lib"
];
const getOpenSSLSourceUrl = (version) => `https://www.openssl.org/source/openssl-${version}.tar.gz`;
const getOpenSSLSourceSha256Url = (version) => `${getOpenSSLSourceUrl(version)}.sha256`;
class HashVerify extends stream.Transform {
constructor(algorithm, onFinal) {
super();
this.onFinal = onFinal;
this.hash = crypto.createHash(algorithm);
}
_transform(chunk, encoding, callback) {
this.hash.update(chunk, encoding);
callback(null, chunk);
}
_final(callback) {
const digest = this.hash.digest("hex");
const onFinalResult = this.onFinal(digest);
callback(onFinalResult);
}
}
const makeHashVerifyOnFinal = (expected) => (digest) => {
const digestOk = digest === expected;
return digestOk
? null
: new Error(`Digest not OK: ${digest} !== ${this.expected}`);
};
// currently this only needs to be done on linux
const applyOpenSSLPatches = async (buildCwd, operatingSystem) => {
try {
for (const patchFilename of await fse.readdir(opensslPatchPath)) {
const patchTarget = patchFilename.split("-")[1];
if (patchFilename.split(".").pop() === "patch" && (patchTarget === operatingSystem || patchTarget === "all")) {
console.log(`applying ${patchFilename}`);
await execPromise(`patch -up0 -i ${path.join(opensslPatchPath, patchFilename)}`, {
cwd: buildCwd
}, { pipeOutput: true });
}
}
} catch(e) {
console.log("Patch application failed: ", e);
throw e;
}
}
const buildDarwin = async (buildCwd, macOsDeploymentTarget) => {
if (!macOsDeploymentTarget) {
throw new Error("Expected macOsDeploymentTarget to be specified");
}
const arguments = [
process.arch === "x64" ? "darwin64-x86_64-cc" : "darwin64-arm64-cc",
// speed up ecdh on little-endian platforms with 128bit int support
"enable-ec_nistp_64_gcc_128",
// compile static libraries
"no-shared",
// disable ssl2, ssl3, and compression
"no-ssl2",
"no-ssl3",
"no-comp",
// set install directory
`--prefix="${extractPath}"`,
`--openssldir="${extractPath}"`,
// set macos version requirement
`-mmacosx-version-min=${macOsDeploymentTarget}`
];
await execPromise(`./Configure ${arguments.join(" ")}`, {
cwd: buildCwd
}, { pipeOutput: true });
await applyOpenSSLPatches(buildCwd, "darwin");
// only build the libraries, not the tests/fuzzer or apps
await execPromise("make build_libs", {
cwd: buildCwd
}, { pipeOutput: true });
await execPromise("make test", {
cwd: buildCwd
}, { pipeOutput: true });
await execPromise("make install_sw", {
cwd: buildCwd,
maxBuffer: 10 * 1024 * 1024 // we should really just use spawn
}, { pipeOutput: true });
};
const buildLinux = async (buildCwd) => {
const arguments = [
"linux-x86_64",
// Electron(at least on centos7) imports the libcups library at runtime, which has a
// dependency on the system libssl/libcrypto which causes symbol conflicts and segfaults.
// To fix this we need to hide all the openssl symbols to prevent them from being overridden
// by the runtime linker.
"-fvisibility=hidden",
// compile static libraries
"no-shared",
// disable ssl2, ssl3, and compression
"no-ssl2",
"no-ssl3",
"no-comp",
// set install directory
`--prefix="${extractPath}"`,
`--openssldir="${extractPath}"`
];
await execPromise(`./Configure ${arguments.join(" ")}`, {
cwd: buildCwd
}, { pipeOutput: true });
await applyOpenSSLPatches(buildCwd, "linux");
// only build the libraries, not the tests/fuzzer or apps
await execPromise("make build_libs", {
cwd: buildCwd
}, { pipeOutput: true });
await execPromise("make test", {
cwd: buildCwd
}, { pipeOutput: true });
// only install software, not the docs
await execPromise("make install_sw", {
cwd: buildCwd,
maxBuffer: 10 * 1024 * 1024 // we should really just use spawn
}, { pipeOutput: true });
};
const buildWin32 = async (buildCwd, vsBuildArch) => {
if (!vsBuildArch) {
throw new Error("Expected vsBuildArch to be specified");
}
const programFilesPath = (process.arch === "x64"
? process.env["ProgramFiles(x86)"]
: process.env.ProgramFiles) || "C:\\Program Files";
const vcvarsallPath = process.env.npm_config_vcvarsall_path || `${
programFilesPath
}\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Auxiliary\\Build\\vcvarsall.bat`;
try {
await fs.stat(vcvarsallPath);
} catch {
throw new Error(`vcvarsall.bat not found at ${vcvarsallPath}`);
}
let vcTarget;
switch (vsBuildArch) {
case "x64": {
vcTarget = "VC-WIN64A";
break;
}
case "x86": {
vcTarget = "VC-WIN32";
break;
}
default: {
throw new Error(`Unknown vsBuildArch: ${vsBuildArch}`);
}
}
await execPromise(`"${win32BatPath}" "${vcvarsallPath}" ${vsBuildArch} ${vcTarget}`, {
cwd: buildCwd,
maxBuffer: 10 * 1024 * 1024 // we should really just use spawn
}, { pipeOutput: true });
};
const removeOpenSSLIfOudated = async (openSSLVersion) => {
try {
let openSSLResult;
try {
const openSSLPath = path.join(extractPath, "bin", "openssl");
openSSLResult = await execPromise(`${openSSLPath} version`);
} catch {
/* if we fail to get the version, assume removal not required */
}
if (!openSSLResult) {
return;
}
const versionMatch = openSSLResult.match(/^OpenSSL (\d\.\d\.\d[a-z]*)/);
const installedVersion = versionMatch && versionMatch[1];
if (!installedVersion || installedVersion === openSSLVersion) {
return;
}
console.log("Removing outdated OpenSSL at: ", extractPath);
await fse.remove(extractPath);
console.log("Outdated OpenSSL removed.");
} catch (err) {
console.log("Remove outdated OpenSSL failed: ", err);
}
};
const makeOnStreamDownloadProgress = () => {
let lastReport = performance.now();
return ({ percent, transferred, total }) => {
const currentTime = performance.now();
if (currentTime - lastReport > 1 * 1000) {
lastReport = currentTime;
console.log(`progress: ${transferred}/${total} (${(percent * 100).toFixed(2)}%)`)
}
};
};
const buildOpenSSLIfNecessary = async ({
macOsDeploymentTarget,
openSSLVersion,
vsBuildArch
}) => {
if (process.platform !== "darwin" && process.platform !== "win32" && process.platform !== "linux") {
console.log(`Skipping OpenSSL build, not required on ${process.platform}`);
return;
}
if (process.platform === "linux" && process.env.NODEGIT_OPENSSL_STATIC_LINK !== "1") {
console.log(`Skipping OpenSSL build, NODEGIT_OPENSSL_STATIC_LINK !== 1`);
return;
}
await removeOpenSSLIfOudated(openSSLVersion);
try {
await fs.stat(extractPath);
console.log("Skipping OpenSSL build, dir exists");
return;
} catch {}
const openSSLUrl = getOpenSSLSourceUrl(openSSLVersion);
const openSSLSha256Url = getOpenSSLSourceSha256Url(openSSLVersion);
const openSSLSha256 = (await got(openSSLSha256Url)).body.trim();
const downloadStream = got.stream(openSSLUrl);
downloadStream.on("downloadProgress", makeOnStreamDownloadProgress());
await pipeline(
downloadStream,
new HashVerify("sha256", makeHashVerifyOnFinal(openSSLSha256)),
zlib.createGunzip(),
tar.extract(extractPath)
);
console.log(`OpenSSL ${openSSLVersion} download + extract complete: SHA256 OK.`);
const buildCwd = path.join(extractPath, `openssl-${openSSLVersion}`);
if (process.platform === "darwin") {
await buildDarwin(buildCwd, macOsDeploymentTarget);
} else if (process.platform === "linux") {
await buildLinux(buildCwd);
} else if (process.platform === "win32") {
await buildWin32(buildCwd, vsBuildArch);
} else {
throw new Error(`Unknown platform: ${process.platform}`);
}
console.log("Build finished.");
}
const downloadOpenSSLIfNecessary = async ({
downloadBinUrl,
maybeDownloadSha256,
maybeDownloadSha256Url
}) => {
if (process.platform !== "darwin" && process.platform !== "win32" && process.platform !== "linux") {
console.log(`Skipping OpenSSL download, not required on ${process.platform}`);
return;
}
if (process.platform === "linux" && process.env.NODEGIT_OPENSSL_STATIC_LINK !== "1") {
console.log(`Skipping OpenSSL download, NODEGIT_OPENSSL_STATIC_LINK !== 1`);
return;
}
try {
await fs.stat(extractPath);
console.log("Skipping OpenSSL download, dir exists");
return;
} catch {}
if (maybeDownloadSha256Url) {
maybeDownloadSha256 = (await got(maybeDownloadSha256Url)).body.trim();
}
const downloadStream = got.stream(downloadBinUrl);
downloadStream.on("downloadProgress", makeOnStreamDownloadProgress());
const pipelineSteps = [
downloadStream,
maybeDownloadSha256
? new HashVerify("sha256", makeHashVerifyOnFinal(maybeDownloadSha256))
: null,
zlib.createGunzip(),
tar.extract(extractPath)
].filter(step => step !== null);
await pipeline(
...pipelineSteps
);
console.log(`OpenSSL download + extract complete${maybeDownloadSha256 ? ": SHA256 OK." : "."}`);
console.log("Download finished.");
}
const getOpenSSLPackageName = () => {
let arch = process.arch;
if (process.platform === "win32" && (
process.arch === "ia32" || process.env.NODEGIT_VS_BUILD_ARCH === "x86"
)) {
arch = "x86";
}
return `openssl-${OPENSSL_VERSION}-${process.platform}-${arch}.tar.gz`;
}
const getOpenSSLPackageUrl = () => `${packageJson.binary.host}${getOpenSSLPackageName()}`;
const buildPackage = async () => {
let resolve, reject;
const promise = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
await pipeline(
tar.pack(extractPath, {
entries: pathsToIncludeForPackage,
ignore: (name) => {
// Ignore pkgconfig files
return path.extname(name) === ".pc"
|| path.basename(name) === "pkgconfig";
},
dmode: 0755,
fmode: 0644
}),
zlib.createGzip(),
new HashVerify("sha256", (digest) => {
resolve(digest);
}),
fsNonPromise.createWriteStream(getOpenSSLPackageName())
);
const digest = await promise;
await fs.writeFile(`${getOpenSSLPackageName()}.sha256`, digest);
};
const acquireOpenSSL = async () => {
try {
const downloadBinUrl = process.env.npm_config_openssl_bin_url
|| (['win32', 'darwin'].includes(process.platform) ? getOpenSSLPackageUrl() : undefined);
if (downloadBinUrl && downloadBinUrl !== 'skip' && !process.env.NODEGIT_OPENSSL_BUILD_PACKAGE) {
const downloadOptions = { downloadBinUrl };
if (process.env.npm_config_openssl_bin_sha256 !== 'skip') {
if (process.env.npm_config_openssl_bin_sha256) {
downloadOptions.maybeDownloadSha256 = process.env.npm_config_openssl_bin_sha256;
} else {
downloadOptions.maybeDownloadSha256Url = `${getOpenSSLPackageUrl()}.sha256`;
}
}
await downloadOpenSSLIfNecessary(downloadOptions);
return;
}
let macOsDeploymentTarget;
if (process.platform === "darwin") {
macOsDeploymentTarget = process.argv[2];
if (!macOsDeploymentTarget || !macOsDeploymentTarget.match(/\d+\.\d+/)) {
throw new Error(`Invalid macOsDeploymentTarget: ${macOsDeploymentTarget}`);
}
}
let vsBuildArch;
if (process.platform === "win32") {
vsBuildArch = process.env.NODEGIT_VS_BUILD_ARCH || (process.arch === "x64" ? "x64" : "x86");
if (!["x64", "x86"].includes(vsBuildArch)) {
throw new Error(`Invalid vsBuildArch: ${vsBuildArch}`);
}
}
await buildOpenSSLIfNecessary({
openSSLVersion: OPENSSL_VERSION,
macOsDeploymentTarget,
vsBuildArch
});
if (process.env.NODEGIT_OPENSSL_BUILD_PACKAGE) {
await buildPackage();
}
} catch (err) {
console.error("Acquire failed: ", err);
process.exit(1);
}
};
module.exports = {
acquireOpenSSL,
getOpenSSLPackageName,
OPENSSL_VERSION
};
if (require.main === module) {
acquireOpenSSL().catch((error) => {
console.error("Acquire OpenSSL failed: ", error);
process.exit(1);
});
}