2 module.exports = exports = install
4 module.exports.test = { download: download, readCAFile: readCAFile }
6 exports.usage = 'Install node development files for the specified node version.'
12 var fs = require('graceful-fs')
13 , osenv = require('osenv')
14 , tar = require('tar')
15 , rm = require('rimraf')
16 , path = require('path')
17 , crypto = require('crypto')
18 , zlib = require('zlib')
19 , log = require('npmlog')
20 , semver = require('semver')
21 , fstream = require('fstream')
22 , request = require('request')
23 , minimatch = require('minimatch')
24 , mkdir = require('mkdirp')
25 , processRelease = require('./process-release')
26 , win = process.platform == 'win32'
28 function install (gyp, argv, callback) {
30 var release = processRelease(argv, gyp, process.version, process.release)
32 // ensure no double-callbacks happen
37 log.warn('install', 'got an error, rolling back install')
38 // roll-back the install if anything went wrong
39 gyp.commands.remove([ release.versionDir ], function (err2) {
43 callback(null, release.version)
47 // Determine which node dev files version we are installing
48 log.verbose('install', 'input version string %j', release.version)
50 if (!release.semver) {
51 // could not parse the version string with semver
52 return callback(new Error('Invalid version number: ' + release.version))
55 if (semver.lt(release.version, '0.8.0')) {
56 return callback(new Error('Minimum target version is `0.8.0` or greater. Got: ' + release.version))
59 // 0.x.y-pre versions are not published yet and cannot be installed. Bail.
60 if (release.semver.prerelease[0] === 'pre') {
61 log.verbose('detected "pre" node version', release.version)
62 if (gyp.opts.nodedir) {
63 log.verbose('--nodedir flag was passed; skipping install', gyp.opts.nodedir)
66 callback(new Error('"pre" versions of node cannot be installed, use the --nodedir flag instead'))
71 // flatten version into String
72 log.verbose('install', 'installing version: %s', release.versionDir)
74 // the directory where the dev files will be installed
75 var devDir = path.resolve(gyp.devDir, release.versionDir)
77 // If '--ensure' was passed, then don't *always* install the version;
78 // check if it is already installed, and only install when needed
79 if (gyp.opts.ensure) {
80 log.verbose('install', '--ensure was passed, so won\'t reinstall if already installed')
81 fs.stat(devDir, function (err, stat) {
83 if (err.code == 'ENOENT') {
84 log.verbose('install', 'version not already installed, continuing with install', release.version)
86 } else if (err.code == 'EACCES') {
93 log.verbose('install', 'version is already installed, need to check "installVersion"')
94 var installVersionFile = path.resolve(devDir, 'installVersion')
95 fs.readFile(installVersionFile, 'ascii', function (err, ver) {
96 if (err && err.code != 'ENOENT') {
99 var installVersion = parseInt(ver, 10) || 0
100 log.verbose('got "installVersion"', installVersion)
101 log.verbose('needs "installVersion"', gyp.package.installVersion)
102 if (installVersion < gyp.package.installVersion) {
103 log.verbose('install', 'version is no good; reinstalling')
106 log.verbose('install', 'version is good')
115 function getContentSha(res, callback) {
116 var shasum = crypto.createHash('sha256')
117 res.on('data', function (chunk) {
119 }).on('end', function () {
120 callback(null, shasum.digest('hex'))
126 log.verbose('ensuring nodedir is created', devDir)
128 // first create the dir for the node dev files
129 mkdir(devDir, function (err, created) {
131 if (err.code == 'EACCES') {
140 log.verbose('created nodedir', created)
143 // now download the node tarball
144 var tarPath = gyp.opts.tarball
145 var badDownload = false
147 , gunzip = zlib.createGunzip()
148 , extracter = tar.Extract({ path: devDir, strip: 1, filter: isValid })
150 var contentShasums = {}
151 var expectShasums = {}
153 // checks if a file to be extracted from the tarball is valid.
154 // only .h header files and the gyp files get extracted
155 function isValid () {
156 var name = this.path.substring(devDir.length + 1)
157 var isValid = valid(name)
158 if (name === '' && this.type === 'Directory') {
159 // the first directory entry is ok
163 log.verbose('extracted file from tarball', name)
167 log.silly('ignoring from tarball', name)
172 gunzip.on('error', cb)
173 extracter.on('error', cb)
174 extracter.on('end', afterTarball)
176 // download the tarball, gunzip and extract!
179 var input = fs.createReadStream(tarPath)
180 input.pipe(gunzip).pipe(extracter)
185 var req = download(gyp, process.env, release.tarballUrl)
190 // something went wrong downloading the tarball?
191 req.on('error', function (err) {
192 if (err.code === 'ENOTFOUND') {
193 return cb(new Error('This is most likely not a problem with node-gyp or the package itself and\n' +
194 'is related to network connectivity. In most cases you are behind a proxy or have bad \n' +
195 'network settings.'))
201 req.on('close', function () {
202 if (extractCount === 0) {
203 cb(new Error('Connection closed while downloading tarball file'))
207 req.on('response', function (res) {
208 if (res.statusCode !== 200) {
210 cb(new Error(res.statusCode + ' response downloading ' + release.tarballUrl))
214 getContentSha(res, function (_, checksum) {
215 var filename = path.basename(release.tarballUrl).trim()
216 contentShasums[filename] = checksum
217 log.verbose('content checksum', filename, checksum)
220 // start unzipping and untaring
221 req.pipe(gunzip).pipe(extracter)
224 // invoked after the tarball has finished being extracted
225 function afterTarball () {
226 if (badDownload) return
227 if (extractCount === 0) {
228 return cb(new Error('There was a fatal problem while downloading/extracting the tarball'))
230 log.verbose('tarball', 'done parsing tarball')
234 // need to download node.lib
236 downloadNodeLib(deref)
239 // write the "installVersion" file
241 var installVersionPath = path.resolve(devDir, 'installVersion')
242 fs.writeFile(installVersionPath, gyp.package.installVersion + '\n', deref)
244 // Only download SHASUMS.txt if not using tarPath override
246 // download SHASUMS.txt
248 downloadShasums(deref)
252 // no async tasks required
256 function deref (err) {
257 if (err) return cb(err)
261 log.verbose('download contents checksum', JSON.stringify(contentShasums))
262 // check content shasums
263 for (var k in contentShasums) {
264 log.verbose('validating download checksum for ' + k, '(%s == %s)', contentShasums[k], expectShasums[k])
265 if (contentShasums[k] !== expectShasums[k]) {
266 cb(new Error(k + ' local checksum ' + contentShasums[k] + ' not match remote ' + expectShasums[k]))
275 function downloadShasums(done) {
276 log.verbose('check download content checksum, need to download `SHASUMS256.txt`...')
277 var shasumsPath = path.resolve(devDir, 'SHASUMS256.txt')
279 log.verbose('checksum url', release.shasumsUrl)
281 var req = download(gyp, process.env, release.shasumsUrl)
286 req.on('error', done)
287 req.on('response', function (res) {
288 if (res.statusCode !== 200) {
289 done(new Error(res.statusCode + ' status code downloading checksum'))
294 res.on('data', function (chunk) {
297 res.on('end', function () {
298 var lines = Buffer.concat(chunks).toString().trim().split('\n')
299 lines.forEach(function (line) {
300 var items = line.trim().split(/\s+/)
301 if (items.length !== 2) return
303 // 0035d18e2dcf9aad669b1c7c07319e17abfe3762 ./node-v0.11.4.tar.gz
304 var name = items[1].replace(/^\.\//, '')
305 expectShasums[name] = items[0]
308 log.verbose('checksum data', JSON.stringify(expectShasums))
314 function downloadNodeLib (done) {
315 log.verbose('on Windows; need to download `' + release.name + '.lib`...')
316 var dir32 = path.resolve(devDir, 'ia32')
317 , dir64 = path.resolve(devDir, 'x64')
318 , libPath32 = path.resolve(dir32, release.name + '.lib')
319 , libPath64 = path.resolve(dir64, release.name + '.lib')
321 log.verbose('32-bit ' + release.name + '.lib dir', dir32)
322 log.verbose('64-bit ' + release.name + '.lib dir', dir64)
323 log.verbose('`' + release.name + '.lib` 32-bit url', release.libUrl32)
324 log.verbose('`' + release.name + '.lib` 64-bit url', release.libUrl64)
327 mkdir(dir32, function (err) {
328 if (err) return done(err)
329 log.verbose('streaming 32-bit ' + release.name + '.lib to:', libPath32)
332 var req = download(gyp, process.env, release.libUrl32, cb)
337 req.on('error', done)
338 req.on('response', function (res) {
339 if (res.statusCode !== 200) {
340 done(new Error(res.statusCode + ' status code downloading 32-bit ' + release.name + '.lib'))
344 getContentSha(res, function (_, checksum) {
345 contentShasums[release.libPath32] = checksum
346 log.verbose('content checksum', release.libPath32, checksum)
349 var ws = fs.createWriteStream(libPath32)
353 req.on('end', function () {
357 mkdir(dir64, function (err) {
358 if (err) return done(err)
359 log.verbose('streaming 64-bit ' + release.name + '.lib to:', libPath64)
362 var req = download(gyp, process.env, release.libUrl64, cb)
367 req.on('error', done)
368 req.on('response', function (res) {
369 if (res.statusCode !== 200) {
370 done(new Error(res.statusCode + ' status code downloading 64-bit ' + release.name + '.lib'))
374 getContentSha(res, function (_, checksum) {
375 contentShasums[release.libPath64] = checksum
376 log.verbose('content checksum', release.libPath64, checksum)
379 var ws = fs.createWriteStream(libPath64)
383 req.on('end', function () {
387 } // downloadNodeLib()
394 * Checks if a given filename is "valid" for this installation.
397 function valid (file) {
399 return minimatch(file, '*.h', { matchBase: true }) ||
400 minimatch(file, '*.gypi', { matchBase: true })
404 * The EACCES fallback is a workaround for npm's `sudo` behavior, where
405 * it drops the permissions before invoking any child processes (like
406 * node-gyp). So what happens is the "nobody" user doesn't have
407 * permission to create the dev dir. As a fallback, make the tmpdir() be
408 * the dev dir for this installation. This is not ideal, but at least
409 * the compilation will succeed...
412 function eaccesFallback () {
413 var tmpdir = osenv.tmpdir()
414 gyp.devDir = path.resolve(tmpdir, '.node-gyp')
415 log.warn('EACCES', 'user "%s" does not have permission to access the dev dir "%s"', osenv.user(), devDir)
416 log.warn('EACCES', 'attempting to reinstall using temporary dev dir "%s"', gyp.devDir)
417 if (process.cwd() == tmpdir) {
418 log.verbose('tmpdir == cwd', 'automatically will remove dev files after to save disk space')
419 gyp.todo.push({ name: 'remove', args: argv })
421 gyp.commands.install(argv, cb)
426 function download (gyp, env, url) {
432 'User-Agent': 'node-gyp v' + gyp.version + ' (node ' + process.version + ')'
436 var cafile = gyp.opts.cafile
438 requestOpts.ca = readCAFile(cafile)
441 // basic support for a proxy server
442 var proxyUrl = gyp.opts.proxy
445 || env.npm_config_proxy
447 if (/^https?:\/\//i.test(proxyUrl)) {
448 log.verbose('download', 'using proxy url: "%s"', proxyUrl)
449 requestOpts.proxy = proxyUrl
451 log.warn('download', 'ignoring invalid "proxy" config setting: "%s"', proxyUrl)
455 var req = request(requestOpts)
456 req.on('response', function (res) {
457 log.http(res.statusCode, url)
463 function readCAFile (filename) {
464 // The CA file can contain multiple certificates so split on certificate
465 // boundaries. [\S\s]*? is used to match everything including newlines.
466 var ca = fs.readFileSync(filename, 'utf8')
467 var re = /(-----BEGIN CERTIFICATE-----[\S\s]*?-----END CERTIFICATE-----)/g