source: node_modules/node-gyp/lib/install.js@ 62b2964

finki-main main
Last change on this file since 62b2964 was 81bc7da, checked in by Klimentina Efremova <klimentina08642@…>, 3 months ago

Initial commit

  • Property mode set to 100644
File size: 11.8 KB
Line 
1'use strict'
2
3const fs = require('graceful-fs')
4const os = require('os')
5const tar = require('tar')
6const path = require('path')
7const util = require('util')
8const stream = require('stream')
9const crypto = require('crypto')
10const log = require('npmlog')
11const semver = require('semver')
12const fetch = require('make-fetch-happen')
13const processRelease = require('./process-release')
14const win = process.platform === 'win32'
15const streamPipeline = util.promisify(stream.pipeline)
16
17/**
18 * @param {typeof import('graceful-fs')} fs
19 */
20
21async function install (fs, gyp, argv) {
22 const release = processRelease(argv, gyp, process.version, process.release)
23
24 // Determine which node dev files version we are installing
25 log.verbose('install', 'input version string %j', release.version)
26
27 if (!release.semver) {
28 // could not parse the version string with semver
29 throw new Error('Invalid version number: ' + release.version)
30 }
31
32 if (semver.lt(release.version, '0.8.0')) {
33 throw new Error('Minimum target version is `0.8.0` or greater. Got: ' + release.version)
34 }
35
36 // 0.x.y-pre versions are not published yet and cannot be installed. Bail.
37 if (release.semver.prerelease[0] === 'pre') {
38 log.verbose('detected "pre" node version', release.version)
39 if (!gyp.opts.nodedir) {
40 throw new Error('"pre" versions of node cannot be installed, use the --nodedir flag instead')
41 }
42 log.verbose('--nodedir flag was passed; skipping install', gyp.opts.nodedir)
43 return
44 }
45
46 // flatten version into String
47 log.verbose('install', 'installing version: %s', release.versionDir)
48
49 // the directory where the dev files will be installed
50 const devDir = path.resolve(gyp.devDir, release.versionDir)
51
52 // If '--ensure' was passed, then don't *always* install the version;
53 // check if it is already installed, and only install when needed
54 if (gyp.opts.ensure) {
55 log.verbose('install', '--ensure was passed, so won\'t reinstall if already installed')
56 try {
57 await fs.promises.stat(devDir)
58 } catch (err) {
59 if (err.code === 'ENOENT') {
60 log.verbose('install', 'version not already installed, continuing with install', release.version)
61 try {
62 return await go()
63 } catch (err) {
64 return rollback(err)
65 }
66 } else if (err.code === 'EACCES') {
67 return eaccesFallback(err)
68 }
69 throw err
70 }
71 log.verbose('install', 'version is already installed, need to check "installVersion"')
72 const installVersionFile = path.resolve(devDir, 'installVersion')
73 let installVersion = 0
74 try {
75 const ver = await fs.promises.readFile(installVersionFile, 'ascii')
76 installVersion = parseInt(ver, 10) || 0
77 } catch (err) {
78 if (err.code !== 'ENOENT') {
79 throw err
80 }
81 }
82 log.verbose('got "installVersion"', installVersion)
83 log.verbose('needs "installVersion"', gyp.package.installVersion)
84 if (installVersion < gyp.package.installVersion) {
85 log.verbose('install', 'version is no good; reinstalling')
86 try {
87 return await go()
88 } catch (err) {
89 return rollback(err)
90 }
91 }
92 log.verbose('install', 'version is good')
93 } else {
94 try {
95 return await go()
96 } catch (err) {
97 return rollback(err)
98 }
99 }
100
101 async function go () {
102 log.verbose('ensuring nodedir is created', devDir)
103
104 // first create the dir for the node dev files
105 try {
106 const created = await fs.promises.mkdir(devDir, { recursive: true })
107
108 if (created) {
109 log.verbose('created nodedir', created)
110 }
111 } catch (err) {
112 if (err.code === 'EACCES') {
113 return eaccesFallback(err)
114 }
115
116 throw err
117 }
118
119 // now download the node tarball
120 const tarPath = gyp.opts.tarball
121 let extractCount = 0
122 const contentShasums = {}
123 const expectShasums = {}
124
125 // checks if a file to be extracted from the tarball is valid.
126 // only .h header files and the gyp files get extracted
127 function isValid (path) {
128 const isValid = valid(path)
129 if (isValid) {
130 log.verbose('extracted file from tarball', path)
131 extractCount++
132 } else {
133 // invalid
134 log.silly('ignoring from tarball', path)
135 }
136 return isValid
137 }
138
139 // download the tarball and extract!
140
141 if (tarPath) {
142 await tar.extract({
143 file: tarPath,
144 strip: 1,
145 filter: isValid,
146 cwd: devDir
147 })
148 } else {
149 try {
150 const res = await download(gyp, release.tarballUrl)
151
152 if (res.status !== 200) {
153 throw new Error(`${res.status} response downloading ${release.tarballUrl}`)
154 }
155
156 await streamPipeline(
157 res.body,
158 // content checksum
159 new ShaSum((_, checksum) => {
160 const filename = path.basename(release.tarballUrl).trim()
161 contentShasums[filename] = checksum
162 log.verbose('content checksum', filename, checksum)
163 }),
164 tar.extract({
165 strip: 1,
166 cwd: devDir,
167 filter: isValid
168 })
169 )
170 } catch (err) {
171 // something went wrong downloading the tarball?
172 if (err.code === 'ENOTFOUND') {
173 throw new Error('This is most likely not a problem with node-gyp or the package itself and\n' +
174 'is related to network connectivity. In most cases you are behind a proxy or have bad \n' +
175 'network settings.')
176 }
177 throw err
178 }
179 }
180
181 // invoked after the tarball has finished being extracted
182 if (extractCount === 0) {
183 throw new Error('There was a fatal problem while downloading/extracting the tarball')
184 }
185
186 log.verbose('tarball', 'done parsing tarball')
187
188 const installVersionPath = path.resolve(devDir, 'installVersion')
189 await Promise.all([
190 // need to download node.lib
191 ...(win ? downloadNodeLib() : []),
192 // write the "installVersion" file
193 fs.promises.writeFile(installVersionPath, gyp.package.installVersion + '\n'),
194 // Only download SHASUMS.txt if we downloaded something in need of SHA verification
195 ...(!tarPath || win ? [downloadShasums()] : [])
196 ])
197
198 log.verbose('download contents checksum', JSON.stringify(contentShasums))
199 // check content shasums
200 for (const k in contentShasums) {
201 log.verbose('validating download checksum for ' + k, '(%s == %s)', contentShasums[k], expectShasums[k])
202 if (contentShasums[k] !== expectShasums[k]) {
203 throw new Error(k + ' local checksum ' + contentShasums[k] + ' not match remote ' + expectShasums[k])
204 }
205 }
206
207 async function downloadShasums () {
208 log.verbose('check download content checksum, need to download `SHASUMS256.txt`...')
209 log.verbose('checksum url', release.shasumsUrl)
210
211 const res = await download(gyp, release.shasumsUrl)
212
213 if (res.status !== 200) {
214 throw new Error(`${res.status} status code downloading checksum`)
215 }
216
217 for (const line of (await res.text()).trim().split('\n')) {
218 const items = line.trim().split(/\s+/)
219 if (items.length !== 2) {
220 return
221 }
222
223 // 0035d18e2dcf9aad669b1c7c07319e17abfe3762 ./node-v0.11.4.tar.gz
224 const name = items[1].replace(/^\.\//, '')
225 expectShasums[name] = items[0]
226 }
227
228 log.verbose('checksum data', JSON.stringify(expectShasums))
229 }
230
231 function downloadNodeLib () {
232 log.verbose('on Windows; need to download `' + release.name + '.lib`...')
233 const archs = ['ia32', 'x64', 'arm64']
234 return archs.map(async (arch) => {
235 const dir = path.resolve(devDir, arch)
236 const targetLibPath = path.resolve(dir, release.name + '.lib')
237 const { libUrl, libPath } = release[arch]
238 const name = `${arch} ${release.name}.lib`
239 log.verbose(name, 'dir', dir)
240 log.verbose(name, 'url', libUrl)
241
242 await fs.promises.mkdir(dir, { recursive: true })
243 log.verbose('streaming', name, 'to:', targetLibPath)
244
245 const res = await download(gyp, libUrl)
246
247 if (res.status === 403 || res.status === 404) {
248 if (arch === 'arm64') {
249 // Arm64 is a newer platform on Windows and not all node distributions provide it.
250 log.verbose(`${name} was not found in ${libUrl}`)
251 } else {
252 log.warn(`${name} was not found in ${libUrl}`)
253 }
254 return
255 } else if (res.status !== 200) {
256 throw new Error(`${res.status} status code downloading ${name}`)
257 }
258
259 return streamPipeline(
260 res.body,
261 new ShaSum((_, checksum) => {
262 contentShasums[libPath] = checksum
263 log.verbose('content checksum', libPath, checksum)
264 }),
265 fs.createWriteStream(targetLibPath)
266 )
267 })
268 } // downloadNodeLib()
269 } // go()
270
271 /**
272 * Checks if a given filename is "valid" for this installation.
273 */
274
275 function valid (file) {
276 // header files
277 const extname = path.extname(file)
278 return extname === '.h' || extname === '.gypi'
279 }
280
281 async function rollback (err) {
282 log.warn('install', 'got an error, rolling back install')
283 // roll-back the install if anything went wrong
284 await util.promisify(gyp.commands.remove)([release.versionDir])
285 throw err
286 }
287
288 /**
289 * The EACCES fallback is a workaround for npm's `sudo` behavior, where
290 * it drops the permissions before invoking any child processes (like
291 * node-gyp). So what happens is the "nobody" user doesn't have
292 * permission to create the dev dir. As a fallback, make the tmpdir() be
293 * the dev dir for this installation. This is not ideal, but at least
294 * the compilation will succeed...
295 */
296
297 async function eaccesFallback (err) {
298 const noretry = '--node_gyp_internal_noretry'
299 if (argv.indexOf(noretry) !== -1) {
300 throw err
301 }
302 const tmpdir = os.tmpdir()
303 gyp.devDir = path.resolve(tmpdir, '.node-gyp')
304 let userString = ''
305 try {
306 // os.userInfo can fail on some systems, it's not critical here
307 userString = ` ("${os.userInfo().username}")`
308 } catch (e) {}
309 log.warn('EACCES', 'current user%s does not have permission to access the dev dir "%s"', userString, devDir)
310 log.warn('EACCES', 'attempting to reinstall using temporary dev dir "%s"', gyp.devDir)
311 if (process.cwd() === tmpdir) {
312 log.verbose('tmpdir == cwd', 'automatically will remove dev files after to save disk space')
313 gyp.todo.push({ name: 'remove', args: argv })
314 }
315 return util.promisify(gyp.commands.install)([noretry].concat(argv))
316 }
317}
318
319class ShaSum extends stream.Transform {
320 constructor (callback) {
321 super()
322 this._callback = callback
323 this._digester = crypto.createHash('sha256')
324 }
325
326 _transform (chunk, _, callback) {
327 this._digester.update(chunk)
328 callback(null, chunk)
329 }
330
331 _flush (callback) {
332 this._callback(null, this._digester.digest('hex'))
333 callback()
334 }
335}
336
337async function download (gyp, url) {
338 log.http('GET', url)
339
340 const requestOpts = {
341 headers: {
342 'User-Agent': `node-gyp v${gyp.version} (node ${process.version})`,
343 Connection: 'keep-alive'
344 },
345 proxy: gyp.opts.proxy,
346 noProxy: gyp.opts.noproxy
347 }
348
349 const cafile = gyp.opts.cafile
350 if (cafile) {
351 requestOpts.ca = await readCAFile(cafile)
352 }
353
354 const res = await fetch(url, requestOpts)
355 log.http(res.status, res.url)
356
357 return res
358}
359
360async function readCAFile (filename) {
361 // The CA file can contain multiple certificates so split on certificate
362 // boundaries. [\S\s]*? is used to match everything including newlines.
363 const ca = await fs.promises.readFile(filename, 'utf8')
364 const re = /(-----BEGIN CERTIFICATE-----[\S\s]*?-----END CERTIFICATE-----)/g
365 return ca.match(re)
366}
367
368module.exports = function (gyp, argv, callback) {
369 install(fs, gyp, argv).then(callback.bind(undefined, null), callback)
370}
371module.exports.test = {
372 download,
373 install,
374 readCAFile
375}
376module.exports.usage = 'Install node development files for the specified node version.'
Note: See TracBrowser for help on using the repository browser.