You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

install.js 15KB

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