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