install.js 14 KB

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