install.js 15 KB

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