install.js 14 KB

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