Front end of the Slack clone application.

install.js 15KB

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