assetguard.js 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  1. /**
  2. * AssetGuard
  3. *
  4. * This module aims to provide a comprehensive and stable method for processing
  5. * and downloading game assets for the WesterosCraft server. Download meta is
  6. * for several identifiers (categories) is stored inside of an AssetGuard object.
  7. * This meta data is initially empty until one of the module's processing functions
  8. * are called. That function will process the corresponding asset index and validate
  9. * any exisitng local files. If a file is missing or fails validation, it will be
  10. * placed into a download queue (array). This queue is wrapped in a download tracker object
  11. * so that essential information can be cached. The download tracker object is then
  12. * assigned as the value of the identifier in the AssetGuard object. These download
  13. * trackers will remain idle until an async process is started to process them.
  14. *
  15. * Once the async process is started, any enqueued assets will be downloaded. The AssetGuard
  16. * object will emit events throughout the download whose name correspond to the identifier
  17. * being processed. For example, if the 'assets' identifier was being processed, whenever
  18. * the download stream recieves data, the event 'assetsdlprogress' will be emitted off of
  19. * the AssetGuard instance. This can be listened to by external modules allowing for
  20. * categorical tracking of the downloading process.
  21. *
  22. * @module assetguard
  23. */
  24. // Requirements
  25. const AdmZip = require('adm-zip')
  26. const async = require('async')
  27. const child_process = require('child_process')
  28. const crypto = require('crypto')
  29. const EventEmitter = require('events')
  30. const fs = require('fs')
  31. const mkpath = require('mkdirp');
  32. const path = require('path')
  33. const Registry = require('winreg')
  34. const request = require('request')
  35. // Classes
  36. /** Class representing a base asset. */
  37. class Asset {
  38. /**
  39. * Create an asset.
  40. *
  41. * @param {any} id The id of the asset.
  42. * @param {string} hash The hash value of the asset.
  43. * @param {number} size The size in bytes of the asset.
  44. * @param {string} from The url where the asset can be found.
  45. * @param {string} to The absolute local file path of the asset.
  46. */
  47. constructor(id, hash, size, from, to){
  48. this.id = id
  49. this.hash = hash
  50. this.size = size
  51. this.from = from
  52. this.to = to
  53. }
  54. }
  55. /** Class representing a mojang library. */
  56. class Library extends Asset {
  57. /**
  58. * Converts the process.platform OS names to match mojang's OS names.
  59. */
  60. static mojangFriendlyOS(){
  61. const opSys = process.platform
  62. if (opSys === 'darwin') {
  63. return 'osx';
  64. } else if (opSys === 'win32'){
  65. return 'windows';
  66. } else if (opSys === 'linux'){
  67. return 'linux';
  68. } else {
  69. return 'unknown_os';
  70. }
  71. }
  72. /**
  73. * Checks whether or not a library is valid for download on a particular OS, following
  74. * the rule format specified in the mojang version data index. If the allow property has
  75. * an OS specified, then the library can ONLY be downloaded on that OS. If the disallow
  76. * property has instead specified an OS, the library can be downloaded on any OS EXCLUDING
  77. * the one specified.
  78. *
  79. * @param {Object} rules The Library's download rules.
  80. * @returns {boolean} True if the Library follows the specified rules, otherwise false.
  81. */
  82. static validateRules(rules){
  83. if(rules == null) return true
  84. let result = true
  85. rules.forEach(function(rule){
  86. const action = rule['action']
  87. const osProp = rule['os']
  88. if(action != null){
  89. if(osProp != null){
  90. const osName = osProp['name']
  91. const osMoj = Library.mojangFriendlyOS()
  92. if(action === 'allow'){
  93. result = osName === osMoj
  94. return
  95. } else if(action === 'disallow'){
  96. result = osName !== osMoj
  97. return
  98. }
  99. }
  100. }
  101. })
  102. return result
  103. }
  104. }
  105. class DistroModule extends Asset {
  106. /**
  107. * Create a DistroModule. This is for processing,
  108. * not equivalent to the module objects in the
  109. * distro index.
  110. *
  111. * @param {any} id The id of the asset.
  112. * @param {string} hash The hash value of the asset.
  113. * @param {number} size The size in bytes of the asset.
  114. * @param {string} from The url where the asset can be found.
  115. * @param {string} to The absolute local file path of the asset.
  116. * @param {string} type The the module type.
  117. */
  118. constructor(id, hash, size, from, to, type){
  119. super(id, hash, size, from, to)
  120. this.type = type
  121. }
  122. }
  123. /**
  124. * Class representing a download tracker. This is used to store meta data
  125. * about a download queue, including the queue itself.
  126. */
  127. class DLTracker {
  128. /**
  129. * Create a DLTracker
  130. *
  131. * @param {Array.<Asset>} dlqueue An array containing assets queued for download.
  132. * @param {number} dlsize The combined size of each asset in the download queue array.
  133. * @param {function(Asset)} callback Optional callback which is called when an asset finishes downloading.
  134. */
  135. constructor(dlqueue, dlsize, callback = null){
  136. this.dlqueue = dlqueue
  137. this.dlsize = dlsize
  138. this.callback = callback
  139. }
  140. }
  141. let distributionData = null
  142. /**
  143. * Central object class used for control flow. This object stores data about
  144. * categories of downloads. Each category is assigned an identifier with a
  145. * DLTracker object as its value. Combined information is also stored, such as
  146. * the total size of all the queued files in each category. This event is used
  147. * to emit events so that external modules can listen into processing done in
  148. * this module.
  149. */
  150. class AssetGuard extends EventEmitter {
  151. /**
  152. * Create an instance of AssetGuard.
  153. * On creation the object's properties are never-null default
  154. * values. Each identifier is resolved to an empty DLTracker.
  155. *
  156. * @param {string} basePath The base path for asset validation (game root).
  157. * @param {string} javaexec The path to a java executable which will be used
  158. * to finalize installation.
  159. */
  160. constructor(basePath, javaexec){
  161. super()
  162. this.totaldlsize = 0
  163. this.progress = 0
  164. this.assets = new DLTracker([], 0)
  165. this.libraries = new DLTracker([], 0)
  166. this.files = new DLTracker([], 0)
  167. this.forge = new DLTracker([], 0)
  168. this.java = new DLTracker([], 0)
  169. this.basePath = basePath
  170. this.javaexec = javaexec
  171. }
  172. // Static Utility Functions
  173. // #region
  174. // Static General Resolve Functions
  175. // #region
  176. /**
  177. * Resolve an artifact id into a path. For example, on windows
  178. * 'net.minecraftforge:forge:1.11.2-13.20.0.2282', '.jar' becomes
  179. * net\minecraftforge\forge\1.11.2-13.20.0.2282\forge-1.11.2-13.20.0.2282.jar
  180. *
  181. * @param {string} artifactid The artifact id string.
  182. * @param {string} extension The extension of the file at the resolved path.
  183. * @returns {string} The resolved relative path from the artifact id.
  184. */
  185. static _resolvePath(artifactid, extension){
  186. let ps = artifactid.split(':')
  187. let cs = ps[0].split('.')
  188. cs.push(ps[1])
  189. cs.push(ps[2])
  190. cs.push(ps[1].concat('-').concat(ps[2]).concat(extension))
  191. return path.join.apply(path, cs)
  192. }
  193. /**
  194. * Resolve an artifact id into a URL. For example,
  195. * 'net.minecraftforge:forge:1.11.2-13.20.0.2282', '.jar' becomes
  196. * net/minecraftforge/forge/1.11.2-13.20.0.2282/forge-1.11.2-13.20.0.2282.jar
  197. *
  198. * @param {string} artifactid The artifact id string.
  199. * @param {string} extension The extension of the file at the resolved url.
  200. * @returns {string} The resolved relative URL from the artifact id.
  201. */
  202. static _resolveURL(artifactid, extension){
  203. let ps = artifactid.split(':')
  204. let cs = ps[0].split('.')
  205. cs.push(ps[1])
  206. cs.push(ps[2])
  207. cs.push(ps[1].concat('-').concat(ps[2]).concat(extension))
  208. return cs.join('/')
  209. }
  210. // #endregion
  211. // Static Hash Validation Functions
  212. // #region
  213. /**
  214. * Calculates the hash for a file using the specified algorithm.
  215. *
  216. * @param {Buffer} buf The buffer containing file data.
  217. * @param {string} algo The hash algorithm.
  218. * @returns {string} The calculated hash in hex.
  219. */
  220. static _calculateHash(buf, algo){
  221. return crypto.createHash(algo).update(buf).digest('hex')
  222. }
  223. /**
  224. * Used to parse a checksums file. This is specifically designed for
  225. * the checksums.sha1 files found inside the forge scala dependencies.
  226. *
  227. * @param {string} content The string content of the checksums file.
  228. * @returns {Object} An object with keys being the file names, and values being the hashes.
  229. */
  230. static _parseChecksumsFile(content){
  231. let finalContent = {}
  232. let lines = content.split('\n')
  233. for(let i=0; i<lines.length; i++){
  234. let bits = lines[i].split(' ')
  235. if(bits[1] == null) {
  236. continue
  237. }
  238. finalContent[bits[1]] = bits[0]
  239. }
  240. return finalContent
  241. }
  242. /**
  243. * Validate that a file exists and matches a given hash value.
  244. *
  245. * @param {string} filePath The path of the file to validate.
  246. * @param {string} algo The hash algorithm to check against.
  247. * @param {string} hash The existing hash to check against.
  248. * @returns {boolean} True if the file exists and calculated hash matches the given hash, otherwise false.
  249. */
  250. static _validateLocal(filePath, algo, hash){
  251. if(fs.existsSync(filePath)){
  252. //No hash provided, have to assume it's good.
  253. if(hash == null){
  254. return true
  255. }
  256. let fileName = path.basename(filePath)
  257. let buf = fs.readFileSync(filePath)
  258. let calcdhash = AssetGuard._calculateHash(buf, algo)
  259. return calcdhash === hash
  260. }
  261. return false;
  262. }
  263. /**
  264. * Validates a file in the style used by forge's version index.
  265. *
  266. * @param {string} filePath The path of the file to validate.
  267. * @param {Array.<string>} checksums The checksums listed in the forge version index.
  268. * @returns {boolean} True if the file exists and the hashes match, otherwise false.
  269. */
  270. static _validateForgeChecksum(filePath, checksums){
  271. if(fs.existsSync(filePath)){
  272. if(checksums == null || checksums.length === 0){
  273. return true
  274. }
  275. let buf = fs.readFileSync(filePath)
  276. let calcdhash = AssetGuard._calculateHash(buf, 'sha1')
  277. let valid = checksums.includes(calcdhash)
  278. if(!valid && filePath.endsWith('.jar')){
  279. valid = AssetGuard._validateForgeJar(filePath, checksums)
  280. }
  281. return valid
  282. }
  283. return false
  284. }
  285. /**
  286. * Validates a forge jar file dependency who declares a checksums.sha1 file.
  287. * This can be an expensive task as it usually requires that we calculate thousands
  288. * of hashes.
  289. *
  290. * @param {Buffer} buf The buffer of the jar file.
  291. * @param {Array.<string>} checksums The checksums listed in the forge version index.
  292. * @returns {boolean} True if all hashes declared in the checksums.sha1 file match the actual hashes.
  293. */
  294. static _validateForgeJar(buf, checksums){
  295. // Double pass method was the quickest I found. I tried a version where we store data
  296. // to only require a single pass, plus some quick cleanup but that seemed to take slightly more time.
  297. const hashes = {}
  298. let expected = {}
  299. const zip = new AdmZip(buf)
  300. const zipEntries = zip.getEntries()
  301. //First pass
  302. for(let i=0; i<zipEntries.length; i++){
  303. let entry = zipEntries[i]
  304. if(entry.entryName === 'checksums.sha1'){
  305. expected = AssetGuard._parseChecksumsFile(zip.readAsText(entry))
  306. }
  307. hashes[entry.entryName] = AssetGuard._calculateHash(entry.getData(), 'sha1')
  308. }
  309. if(!checksums.includes(hashes['checksums.sha1'])){
  310. return false
  311. }
  312. //Check against expected
  313. const expectedEntries = Object.keys(expected)
  314. for(let i=0; i<expectedEntries.length; i++){
  315. if(expected[expectedEntries[i]] !== hashes[expectedEntries[i]]){
  316. return false
  317. }
  318. }
  319. return true
  320. }
  321. // #endregion
  322. // Static Distribution Index Functions
  323. // #region
  324. /**
  325. * Statically retrieve the distribution data.
  326. *
  327. * @param {string} basePath The base path for asset validation (game root).
  328. * @param {boolean} cached Optional. False if the distro should be freshly downloaded, else
  329. * a cached copy will be returned.
  330. * @returns {Promise.<Object>} A promise which resolves to the distribution data object.
  331. */
  332. static retrieveDistributionData(basePath, cached = true){
  333. return new Promise(function(fulfill, reject){
  334. if(!cached || distributionData == null){
  335. // TODO Download file from upstream.
  336. //const distroURL = 'http://mc.westeroscraft.com/WesterosCraftLauncher/westeroscraft.json'
  337. // TODO Save file to path.join(basePath, 'westeroscraft.json')
  338. // TODO Fulfill with JSON.parse()
  339. // Workaround while file is not hosted.
  340. fs.readFile(path.join(__dirname, '..', 'westeroscraft.json'), 'utf-8', (err, data) => {
  341. distributionData = JSON.parse(data)
  342. fulfill(distributionData)
  343. })
  344. } else {
  345. fulfill(distributionData)
  346. }
  347. })
  348. }
  349. /**
  350. * Statically retrieve the distribution data.
  351. *
  352. * @param {string} basePath The base path for asset validation (game root).
  353. * @param {boolean} cached Optional. False if the distro should be freshly downloaded, else
  354. * a cached copy will be returned.
  355. * @returns {Object} The distribution data object.
  356. */
  357. static retrieveDistributionDataSync(basePath, cached = true){
  358. if(!cached || distributionData == null){
  359. distributionData = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'westeroscraft.json'), 'utf-8'))
  360. }
  361. return distributionData
  362. }
  363. /**
  364. * Resolve the default selected server from the distribution index.
  365. *
  366. * @param {string} basePath The base path for asset validation (game root).
  367. * @returns {Object} An object resolving to the default selected server.
  368. */
  369. static resolveSelectedServer(basePath){
  370. const distro = AssetGuard.retrieveDistributionDataSync(basePath)
  371. const servers = distro.servers
  372. for(let i=0; i<servers.length; i++){
  373. if(servers[i].default_selected){
  374. return servers[i].id
  375. }
  376. }
  377. // If no server declares default_selected, default to the first one declared.
  378. return (servers.length > 0) ? servers[0].id : null
  379. }
  380. /**
  381. * Gets a server from the distro index which maches the provided ID.
  382. * Returns null if the ID could not be found or the distro index has
  383. * not yet been loaded.
  384. *
  385. * @param {string} basePath The base path for asset validation (game root).
  386. * @param {string} serverID The id of the server to retrieve.
  387. * @returns {Object} The server object whose id matches the parameter.
  388. */
  389. static getServerById(basePath, serverID){
  390. if(distributionData == null){
  391. AssetGuard.retrieveDistributionDataSync(basePath, false)
  392. }
  393. const servers = distributionData.servers
  394. let serv = null
  395. for(let i=0; i<servers.length; i++){
  396. if(servers[i].id === serverID){
  397. serv = servers[i]
  398. }
  399. }
  400. return serv
  401. }
  402. // #endregion
  403. // Miscellaneous Static Functions
  404. // #region
  405. /**
  406. * Extracts and unpacks a file from .pack.xz format.
  407. *
  408. * @param {Array.<string>} filePaths The paths of the files to be extracted and unpacked.
  409. * @returns {Promise.<void>} An empty promise to indicate the extraction has completed.
  410. */
  411. static _extractPackXZ(filePaths, javaExecutable){
  412. return new Promise(function(fulfill, reject){
  413. const libPath = path.join(__dirname, '..', 'libraries', 'java', 'PackXZExtract.jar')
  414. const filePath = filePaths.join(',')
  415. const child = child_process.spawn(javaExecutable, ['-jar', libPath, '-packxz', filePath])
  416. child.stdout.on('data', (data) => {
  417. //console.log('PackXZExtract:', data.toString('utf8'))
  418. })
  419. child.stderr.on('data', (data) => {
  420. //console.log('PackXZExtract:', data.toString('utf8'))
  421. })
  422. child.on('close', (code, signal) => {
  423. //console.log('PackXZExtract: Exited with code', code)
  424. fulfill()
  425. })
  426. })
  427. }
  428. /**
  429. * Function which finalizes the forge installation process. This creates a 'version'
  430. * instance for forge and saves its version.json file into that instance. If that
  431. * instance already exists, the contents of the version.json file are read and returned
  432. * in a promise.
  433. *
  434. * @param {Asset} asset The Asset object representing Forge.
  435. * @param {string} basePath Base path for asset validation (game root).
  436. * @returns {Promise.<Object>} A promise which resolves to the contents of forge's version.json.
  437. */
  438. static _finalizeForgeAsset(asset, basePath){
  439. return new Promise(function(fulfill, reject){
  440. fs.readFile(asset.to, (err, data) => {
  441. const zip = new AdmZip(data)
  442. const zipEntries = zip.getEntries()
  443. for(let i=0; i<zipEntries.length; i++){
  444. if(zipEntries[i].entryName === 'version.json'){
  445. const forgeVersion = JSON.parse(zip.readAsText(zipEntries[i]))
  446. const versionPath = path.join(basePath, 'versions', forgeVersion.id)
  447. const versionFile = path.join(versionPath, forgeVersion.id + '.json')
  448. if(!fs.existsSync(versionFile)){
  449. mkpath.sync(versionPath)
  450. fs.writeFileSync(path.join(versionPath, forgeVersion.id + '.json'), zipEntries[i].getData())
  451. fulfill(forgeVersion)
  452. } else {
  453. //Read the saved file to allow for user modifications.
  454. fulfill(JSON.parse(fs.readFileSync(versionFile, 'utf-8')))
  455. }
  456. return
  457. }
  458. }
  459. //We didn't find forge's version.json.
  460. reject('Unable to finalize Forge processing, version.json not found! Has forge changed their format?')
  461. })
  462. })
  463. }
  464. // #endregion
  465. // Static Java Utility
  466. // #region
  467. /**
  468. * Validates that a Java binary is at least 64 bit. This makes use of the non-standard
  469. * command line option -XshowSettings:properties. The output of this contains a property,
  470. * sun.arch.data.model = ARCH, in which ARCH is either 32 or 64. This option is supported
  471. * in Java 8 and 9. Since this is a non-standard option. This will resolve to true if
  472. * the function's code throws errors. That would indicate that the option is changed or
  473. * removed.
  474. *
  475. * @param {string} binaryPath Path to the root of the java binary we wish to validate.
  476. *
  477. * @returns {Promise.<boolean>} Resolves to false only if the test is successful and the result
  478. * is less than 64.
  479. */
  480. static _validateJavaBinary(binaryPath){
  481. return new Promise((resolve, reject) => {
  482. const fBp = path.join(binaryPath, 'bin', 'java.exe')
  483. if(fs.existsSync(fBp)){
  484. child_process.exec('"' + fBp + '" -XshowSettings:properties', (err, stdout, stderr) => {
  485. try {
  486. // Output is stored in stderr?
  487. const res = stderr
  488. const props = res.split('\n')
  489. for(let i=0; i<props.length; i++){
  490. if(props[i].indexOf('sun.arch.data.model') > -1){
  491. let arch = props[i].split('=')[1].trim()
  492. console.log(props[i].trim() + ' for ' + binaryPath)
  493. resolve(parseInt(arch) >= 64)
  494. }
  495. }
  496. // sun.arch.data.model not found?
  497. // Disregard this test.
  498. resolve(true)
  499. } catch (err){
  500. // Output format might have changed, validation cannot be completed.
  501. // Disregard this test in that case.
  502. resolve(true)
  503. }
  504. })
  505. } else {
  506. resolve(false)
  507. }
  508. })
  509. }
  510. /**
  511. * Checks for the presence of the environment variable JAVA_HOME. If it exits, we will check
  512. * to see if the value points to a path which exists. If the path exits, the path is returned.
  513. *
  514. * @returns {string} The path defined by JAVA_HOME, if it exists. Otherwise null.
  515. */
  516. static _scanJavaHome(){
  517. const jHome = process.env.JAVA_HOME
  518. try {
  519. let res = fs.existsSync(jHome)
  520. return res ? jHome : null
  521. } catch (err) {
  522. // Malformed JAVA_HOME property.
  523. return null
  524. }
  525. }
  526. /**
  527. * Scans the registry for 64-bit Java entries. The paths of each entry are added to
  528. * a set and returned. Currently, only Java 8 (1.8) is supported.
  529. *
  530. * @returns {Promise.<Set.<string>>} A promise which resolves to a set of 64-bit Java root
  531. * paths found in the registry.
  532. */
  533. static _scanRegistry(){
  534. return new Promise((resolve, reject) => {
  535. // Keys for Java v9.0.0 and later:
  536. // 'SOFTWARE\\JavaSoft\\JRE'
  537. // 'SOFTWARE\\JavaSoft\\JDK'
  538. // Forge does not yet support Java 9, therefore we do not.
  539. let cbTracker = 0
  540. let cbAcc = 0
  541. // Keys for Java 1.8 and prior:
  542. const regKeys = [
  543. '\\SOFTWARE\\JavaSoft\\Java Runtime Environment',
  544. '\\SOFTWARE\\JavaSoft\\Java Development Kit'
  545. ]
  546. const candidates = new Set()
  547. for(let i=0; i<regKeys.length; i++){
  548. const key = new Registry({
  549. hive: Registry.HKLM,
  550. key: regKeys[i],
  551. arch: 'x64'
  552. })
  553. key.keyExists((err, exists) => {
  554. if(exists) {
  555. key.keys((err, javaVers) => {
  556. if(err){
  557. console.error(err)
  558. if(i === regKeys.length-1 && cbAcc === cbTracker){
  559. resolve(candidates)
  560. }
  561. } else {
  562. cbTracker += javaVers.length
  563. if(i === regKeys.length-1 && cbTracker === cbAcc){
  564. resolve(candidates)
  565. } else {
  566. for(let j=0; j<javaVers.length; j++){
  567. const javaVer = javaVers[j]
  568. const vKey = javaVer.key.substring(javaVer.key.lastIndexOf('\\')+1)
  569. // Only Java 8 is supported currently.
  570. if(parseFloat(vKey) === 1.8){
  571. javaVer.get('JavaHome', (err, res) => {
  572. const jHome = res.value
  573. if(jHome.indexOf('(x86)') === -1){
  574. candidates.add(jHome)
  575. }
  576. cbAcc++
  577. if(i === regKeys.length-1 && cbAcc === cbTracker){
  578. resolve(candidates)
  579. }
  580. })
  581. } else {
  582. cbAcc++
  583. if(i === regKeys.length-1 && cbAcc === cbTracker){
  584. resolve(candidates)
  585. }
  586. }
  587. }
  588. }
  589. }
  590. })
  591. } else {
  592. if(i === regKeys.length-1 && cbAcc === cbTracker){
  593. resolve(candidates)
  594. }
  595. }
  596. })
  597. }
  598. })
  599. }
  600. /**
  601. * Attempts to find a valid x64 installation of Java on Windows machines.
  602. * Possible paths will be pulled from the registry and the JAVA_HOME environment
  603. * variable. The paths will be sorted with higher versions preceeding lower, and
  604. * JREs preceeding JDKs. The binaries at the sorted paths will then be validated.
  605. * The first validated is returned.
  606. *
  607. * Higher versions > Lower versions
  608. * If versions are equal, JRE > JDK.
  609. *
  610. * @returns {string} The root path of a valid x64 Java installation. If none are
  611. * found, null is returned.
  612. */
  613. static async _win32JavaValidate(){
  614. // Get possible paths from the registry.
  615. const pathSet = await AssetGuard._scanRegistry()
  616. console.log(Array.from(pathSet)) // DEBUGGING
  617. // Validate JAVA_HOME
  618. const jHome = AssetGuard._scanJavaHome()
  619. if(jHome != null && jHome.indexOf('(x86)') === -1){
  620. pathSet.add(jHome)
  621. }
  622. // Convert path set to an array for processing.
  623. let pathArr = Array.from(pathSet)
  624. console.log(pathArr) // DEBUGGING
  625. // Sorts array. Higher version numbers preceed lower. JRE preceeds JDK.
  626. pathArr = pathArr.sort((a, b) => {
  627. // Note that Java 9+ uses semver and that will need to be accounted for in
  628. // the future.
  629. const aVer = parseInt(a.split('_')[1])
  630. const bVer = parseInt(b.split('_')[1])
  631. if(bVer === aVer){
  632. return a.indexOf('jdk') > -1 ? 1 : 0
  633. } else {
  634. return bVer - aVer
  635. }
  636. })
  637. console.log(pathArr) // DEBUGGING
  638. // Validate that the binary is actually x64.
  639. for(let i=0; i<pathArr.length; i++) {
  640. let res = await AssetGuard._validateJavaBinary(pathArr[i])
  641. if(res){
  642. return pathArr[i]
  643. }
  644. }
  645. // No suitable candidates found.
  646. return null;
  647. }
  648. /**
  649. * WIP -> get a valid x64 Java path on macOS.
  650. */
  651. static async _darwinJavaValidate(){
  652. return null
  653. }
  654. /**
  655. * WIP -> get a valid x64 Java path on linux.
  656. */
  657. static async _linuxJavaValidate(){
  658. return null
  659. }
  660. static async validate(){
  661. return await AssetGuard['_' + process.platform + 'JavaValidate']()
  662. }
  663. // #endregion
  664. // #endregion
  665. // Validation Functions
  666. // #region
  667. /**
  668. * Loads the version data for a given minecraft version.
  669. *
  670. * @param {string} version The game version for which to load the index data.
  671. * @param {boolean} force Optional. If true, the version index will be downloaded even if it exists locally. Defaults to false.
  672. * @returns {Promise.<Object>} Promise which resolves to the version data object.
  673. */
  674. loadVersionData(version, force = false){
  675. const self = this
  676. return new Promise(function(fulfill, reject){
  677. const name = version + '.json'
  678. const url = 'https://s3.amazonaws.com/Minecraft.Download/versions/' + version + '/' + name
  679. const versionPath = path.join(self.basePath, 'versions', version)
  680. const versionFile = path.join(versionPath, name)
  681. if(!fs.existsSync(versionFile) || force){
  682. //This download will never be tracked as it's essential and trivial.
  683. request.head(url, function(err, res, body){
  684. console.log('Preparing download of ' + version + ' assets.')
  685. mkpath.sync(versionPath)
  686. const stream = request(url).pipe(fs.createWriteStream(versionFile))
  687. stream.on('finish', function(){
  688. fulfill(JSON.parse(fs.readFileSync(versionFile)))
  689. })
  690. })
  691. } else {
  692. fulfill(JSON.parse(fs.readFileSync(versionFile)))
  693. }
  694. })
  695. }
  696. // Asset (Category=''') Validation Functions
  697. // #region
  698. /**
  699. * Public asset validation function. This function will handle the validation of assets.
  700. * It will parse the asset index specified in the version data, analyzing each
  701. * asset entry. In this analysis it will check to see if the local file exists and is valid.
  702. * If not, it will be added to the download queue for the 'assets' identifier.
  703. *
  704. * @param {Object} versionData The version data for the assets.
  705. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  706. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  707. */
  708. validateAssets(versionData, force = false){
  709. const self = this
  710. return new Promise(function(fulfill, reject){
  711. self._assetChainIndexData(versionData, force).then(() => {
  712. fulfill()
  713. })
  714. })
  715. }
  716. //Chain the asset tasks to provide full async. The below functions are private.
  717. /**
  718. * Private function used to chain the asset validation process. This function retrieves
  719. * the index data.
  720. * @param {Object} versionData
  721. * @param {boolean} force
  722. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  723. */
  724. _assetChainIndexData(versionData, force = false){
  725. const self = this
  726. return new Promise(function(fulfill, reject){
  727. //Asset index constants.
  728. const assetIndex = versionData.assetIndex
  729. const name = assetIndex.id + '.json'
  730. const indexPath = path.join(self.basePath, 'assets', 'indexes')
  731. const assetIndexLoc = path.join(indexPath, name)
  732. let data = null
  733. if(!fs.existsSync(assetIndexLoc) || force){
  734. console.log('Downloading ' + versionData.id + ' asset index.')
  735. mkpath.sync(indexPath)
  736. const stream = request(assetIndex.url).pipe(fs.createWriteStream(assetIndexLoc))
  737. stream.on('finish', function() {
  738. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  739. self._assetChainValidateAssets(versionData, data).then(() => {
  740. fulfill()
  741. })
  742. })
  743. } else {
  744. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  745. self._assetChainValidateAssets(versionData, data).then(() => {
  746. fulfill()
  747. })
  748. }
  749. })
  750. }
  751. /**
  752. * Private function used to chain the asset validation process. This function processes
  753. * the assets and enqueues missing or invalid files.
  754. * @param {Object} versionData
  755. * @param {boolean} force
  756. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  757. */
  758. _assetChainValidateAssets(versionData, indexData){
  759. const self = this
  760. return new Promise(function(fulfill, reject){
  761. //Asset constants
  762. const resourceURL = 'http://resources.download.minecraft.net/'
  763. const localPath = path.join(self.basePath, 'assets')
  764. const indexPath = path.join(localPath, 'indexes')
  765. const objectPath = path.join(localPath, 'objects')
  766. const assetDlQueue = []
  767. let dlSize = 0;
  768. //const objKeys = Object.keys(data.objects)
  769. async.forEachOfLimit(indexData.objects, 10, function(value, key, cb){
  770. const hash = value.hash
  771. const assetName = path.join(hash.substring(0, 2), hash)
  772. const urlName = hash.substring(0, 2) + "/" + hash
  773. const ast = new Asset(key, hash, String(value.size), resourceURL + urlName, path.join(objectPath, assetName))
  774. if(!AssetGuard._validateLocal(ast.to, 'sha1', ast.hash)){
  775. dlSize += (ast.size*1)
  776. assetDlQueue.push(ast)
  777. }
  778. cb()
  779. }, function(err){
  780. self.assets = new DLTracker(assetDlQueue, dlSize)
  781. fulfill()
  782. })
  783. })
  784. }
  785. // #endregion
  786. // Library (Category=''') Validation Functions
  787. // #region
  788. /**
  789. * Public library validation function. This function will handle the validation of libraries.
  790. * It will parse the version data, analyzing each library entry. In this analysis, it will
  791. * check to see if the local file exists and is valid. If not, it will be added to the download
  792. * queue for the 'libraries' identifier.
  793. *
  794. * @param {Object} versionData The version data for the assets.
  795. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  796. */
  797. validateLibraries(versionData){
  798. const self = this
  799. return new Promise(function(fulfill, reject){
  800. const libArr = versionData.libraries
  801. const libPath = path.join(self.basePath, 'libraries')
  802. const libDlQueue = []
  803. let dlSize = 0
  804. //Check validity of each library. If the hashs don't match, download the library.
  805. async.eachLimit(libArr, 5, function(lib, cb){
  806. if(Library.validateRules(lib.rules)){
  807. let artifact = (lib.natives == null) ? lib.downloads.artifact : lib.downloads.classifiers[lib.natives[Library.mojangFriendlyOS()]]
  808. const libItm = new Library(lib.name, artifact.sha1, artifact.size, artifact.url, path.join(libPath, artifact.path))
  809. if(!AssetGuard._validateLocal(libItm.to, 'sha1', libItm.hash)){
  810. dlSize += (libItm.size*1)
  811. libDlQueue.push(libItm)
  812. }
  813. }
  814. cb()
  815. }, function(err){
  816. self.libraries = new DLTracker(libDlQueue, dlSize)
  817. fulfill()
  818. })
  819. })
  820. }
  821. // #endregion
  822. // Miscellaneous (Category=files) Validation Functions
  823. // #region
  824. /**
  825. * Public miscellaneous mojang file validation function. These files will be enqueued under
  826. * the 'files' identifier.
  827. *
  828. * @param {Object} versionData The version data for the assets.
  829. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  830. */
  831. validateMiscellaneous(versionData){
  832. const self = this
  833. return new Promise(async function(fulfill, reject){
  834. await self.validateClient(versionData)
  835. await self.validateLogConfig(versionData)
  836. fulfill()
  837. })
  838. }
  839. /**
  840. * Validate client file - artifact renamed from client.jar to '{version}'.jar.
  841. *
  842. * @param {Object} versionData The version data for the assets.
  843. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  844. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  845. */
  846. validateClient(versionData, force = false){
  847. const self = this
  848. return new Promise(function(fulfill, reject){
  849. const clientData = versionData.downloads.client
  850. const version = versionData.id
  851. const targetPath = path.join(self.basePath, 'versions', version)
  852. const targetFile = version + '.jar'
  853. let client = new Asset(version + ' client', clientData.sha1, clientData.size, clientData.url, path.join(targetPath, targetFile))
  854. if(!AssetGuard._validateLocal(client.to, 'sha1', client.hash) || force){
  855. self.files.dlqueue.push(client)
  856. self.files.dlsize += client.size*1
  857. fulfill()
  858. } else {
  859. fulfill()
  860. }
  861. })
  862. }
  863. /**
  864. * Validate log config.
  865. *
  866. * @param {Object} versionData The version data for the assets.
  867. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  868. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  869. */
  870. validateLogConfig(versionData){
  871. const self = this
  872. return new Promise(function(fulfill, reject){
  873. const client = versionData.logging.client
  874. const file = client.file
  875. const targetPath = path.join(self.basePath, 'assets', 'log_configs')
  876. let logConfig = new Asset(file.id, file.sha1, file.size, file.url, path.join(targetPath, file.id))
  877. if(!AssetGuard._validateLocal(logConfig.to, 'sha1', logConfig.hash)){
  878. self.files.dlqueue.push(logConfig)
  879. self.files.dlsize += logConfig.size*1
  880. fulfill()
  881. } else {
  882. fulfill()
  883. }
  884. })
  885. }
  886. // #endregion
  887. // Distribution (Category=forge) Validation Functions
  888. // #region
  889. /**
  890. * Validate the distribution.
  891. *
  892. * @param {string} serverpackid The id of the server to validate.
  893. * @returns {Promise.<Object>} A promise which resolves to the server distribution object.
  894. */
  895. validateDistribution(serverpackid){
  896. const self = this
  897. return new Promise(function(fulfill, reject){
  898. AssetGuard.retrieveDistributionData(self.basePath, false).then((value) => {
  899. /*const servers = value.servers
  900. let serv = null
  901. for(let i=0; i<servers.length; i++){
  902. if(servers[i].id === serverpackid){
  903. serv = servers[i]
  904. break
  905. }
  906. }*/
  907. const serv = AssetGuard.getServerById(self.basePath, serverpackid)
  908. if(serv == null) {
  909. console.error('Invalid server pack id:', serverpackid)
  910. }
  911. self.forge = self._parseDistroModules(serv.modules, serv.mc_version)
  912. //Correct our workaround here.
  913. let decompressqueue = self.forge.callback
  914. self.forge.callback = function(asset){
  915. if(asset.to.toLowerCase().endsWith('.pack.xz')){
  916. AssetGuard._extractPackXZ([asset.to], self.javaexec)
  917. }
  918. if(asset.type === 'forge-hosted' || asset.type === 'forge'){
  919. AssetGuard._finalizeForgeAsset(asset, self.basePath)
  920. }
  921. }
  922. fulfill(serv)
  923. })
  924. })
  925. }
  926. /*//TODO The file should be hosted, the following code is for local testing.
  927. _chainValidateDistributionIndex(basePath){
  928. return new Promise(function(fulfill, reject){
  929. //const distroURL = 'http://mc.westeroscraft.com/WesterosCraftLauncher/westeroscraft.json'
  930. //const targetFile = path.join(basePath, 'westeroscraft.json')
  931. //TEMP WORKAROUND TO TEST WHILE THIS IS NOT HOSTED
  932. fs.readFile(path.join(__dirname, '..', 'westeroscraft.json'), 'utf-8', (err, data) => {
  933. fulfill(JSON.parse(data))
  934. })
  935. })
  936. }*/
  937. _parseDistroModules(modules, version){
  938. let alist = []
  939. let asize = 0;
  940. //This may be removed soon, considering the most efficient way to extract.
  941. let decompressqueue = []
  942. for(let i=0; i<modules.length; i++){
  943. let ob = modules[i]
  944. let obType = ob.type
  945. let obArtifact = ob.artifact
  946. let obPath = obArtifact.path == null ? AssetGuard._resolvePath(ob.id, obArtifact.extension) : obArtifact.path
  947. switch(obType){
  948. case 'forge-hosted':
  949. case 'forge':
  950. case 'library':
  951. obPath = path.join(this.basePath, 'libraries', obPath)
  952. break
  953. case 'forgemod':
  954. //obPath = path.join(this.basePath, 'mods', obPath)
  955. obPath = path.join(this.basePath, 'modstore', obPath)
  956. break
  957. case 'litemod':
  958. //obPath = path.join(this.basePath, 'mods', version, obPath)
  959. obPath = path.join(this.basePath, 'modstore', obPath)
  960. break
  961. case 'file':
  962. default:
  963. obPath = path.join(this.basePath, obPath)
  964. }
  965. let artifact = new DistroModule(ob.id, obArtifact.MD5, obArtifact.size, obArtifact.url, obPath, obType)
  966. const validationPath = obPath.toLowerCase().endsWith('.pack.xz') ? obPath.substring(0, obPath.toLowerCase().lastIndexOf('.pack.xz')) : obPath
  967. if(!AssetGuard._validateLocal(validationPath, 'MD5', artifact.hash)){
  968. asize += artifact.size*1
  969. alist.push(artifact)
  970. if(validationPath !== obPath) decompressqueue.push(obPath)
  971. }
  972. //Recursively process the submodules then combine the results.
  973. if(ob.sub_modules != null){
  974. let dltrack = this._parseDistroModules(ob.sub_modules, version)
  975. asize += dltrack.dlsize*1
  976. alist = alist.concat(dltrack.dlqueue)
  977. decompressqueue = decompressqueue.concat(dltrack.callback)
  978. }
  979. }
  980. //Since we have no callback at this point, we use this value to store the decompressqueue.
  981. return new DLTracker(alist, asize, decompressqueue)
  982. }
  983. /**
  984. * Loads Forge's version.json data into memory for the specified server id.
  985. *
  986. * @param {string} serverpack The id of the server to load Forge data for.
  987. * @returns {Promise.<Object>} A promise which resolves to Forge's version.json data.
  988. */
  989. loadForgeData(serverpack){
  990. const self = this
  991. return new Promise(async function(fulfill, reject){
  992. let distro = AssetGuard.retrieveDistributionDataSync(self.basePath)
  993. const servers = distro.servers
  994. let serv = null
  995. for(let i=0; i<servers.length; i++){
  996. if(servers[i].id === serverpack){
  997. serv = servers[i]
  998. break
  999. }
  1000. }
  1001. const modules = serv.modules
  1002. for(let i=0; i<modules.length; i++){
  1003. const ob = modules[i]
  1004. if(ob.type === 'forge-hosted' || ob.type === 'forge'){
  1005. let obArtifact = ob.artifact
  1006. let obPath = obArtifact.path == null ? path.join(self.basePath, 'libraries', AssetGuard._resolvePath(ob.id, obArtifact.extension)) : obArtifact.path
  1007. let asset = new DistroModule(ob.id, obArtifact.MD5, obArtifact.size, obArtifact.url, obPath, ob.type)
  1008. let forgeData = await AssetGuard._finalizeForgeAsset(asset, self.basePath)
  1009. fulfill(forgeData)
  1010. return
  1011. }
  1012. }
  1013. reject('No forge module found!')
  1014. })
  1015. }
  1016. _parseForgeLibraries(){
  1017. /* TODO
  1018. * Forge asset validations are already implemented. When there's nothing much
  1019. * to work on, implement forge downloads using forge's version.json. This is to
  1020. * have the code on standby if we ever need it (since it's half implemented already).
  1021. */
  1022. }
  1023. // #endregion
  1024. // #endregion
  1025. // Control Flow Functions
  1026. // #region
  1027. /**
  1028. * Initiate an async download process for an AssetGuard DLTracker.
  1029. *
  1030. * @param {string} identifier The identifier of the AssetGuard DLTracker.
  1031. * @param {number} limit Optional. The number of async processes to run in parallel.
  1032. * @returns {boolean} True if the process began, otherwise false.
  1033. */
  1034. startAsyncProcess(identifier, limit = 5){
  1035. const self = this
  1036. let acc = 0
  1037. const concurrentDlTracker = this[identifier]
  1038. const concurrentDlQueue = concurrentDlTracker.dlqueue.slice(0)
  1039. if(concurrentDlQueue.length === 0){
  1040. return false
  1041. } else {
  1042. async.eachLimit(concurrentDlQueue, limit, function(asset, cb){
  1043. let count = 0;
  1044. mkpath.sync(path.join(asset.to, ".."))
  1045. let req = request(asset.from)
  1046. req.pause()
  1047. req.on('response', (resp) => {
  1048. if(resp.statusCode === 200){
  1049. let writeStream = fs.createWriteStream(asset.to)
  1050. writeStream.on('close', () => {
  1051. //console.log('DLResults ' + asset.size + ' ' + count + ' ', asset.size === count)
  1052. if(concurrentDlTracker.callback != null){
  1053. concurrentDlTracker.callback.apply(concurrentDlTracker, [asset])
  1054. }
  1055. cb()
  1056. })
  1057. req.pipe(writeStream)
  1058. req.resume()
  1059. } else {
  1060. req.abort()
  1061. console.log('Failed to download ' + asset.from + '. Response code', resp.statusCode)
  1062. self.progress += asset.size*1
  1063. self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize})
  1064. cb()
  1065. }
  1066. })
  1067. req.on('data', function(chunk){
  1068. count += chunk.length
  1069. self.progress += chunk.length
  1070. acc += chunk.length
  1071. self.emit(identifier + 'dlprogress', acc)
  1072. self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize})
  1073. })
  1074. }, function(err){
  1075. if(err){
  1076. self.emit(identifier + 'dlerror')
  1077. console.log('An item in ' + identifier + ' failed to process');
  1078. } else {
  1079. self.emit(identifier + 'dlcomplete')
  1080. console.log('All ' + identifier + ' have been processed successfully')
  1081. }
  1082. self.totaldlsize -= self[identifier].dlsize
  1083. self.progress -= self[identifier].dlsize
  1084. self[identifier] = new DLTracker([], 0)
  1085. if(self.totaldlsize === 0) {
  1086. self.emit('dlcomplete')
  1087. }
  1088. })
  1089. return true
  1090. }
  1091. }
  1092. /**
  1093. * This function will initiate the download processed for the specified identifiers. If no argument is
  1094. * given, all identifiers will be initiated. Note that in order for files to be processed you need to run
  1095. * the processing function corresponding to that identifier. If you run this function without processing
  1096. * the files, it is likely nothing will be enqueued in the object and processing will complete
  1097. * immediately. Once all downloads are complete, this function will fire the 'dlcomplete' event on the
  1098. * global object instance.
  1099. *
  1100. * @param {Array.<{id: string, limit: number}>} identifiers Optional. The identifiers to process and corresponding parallel async task limit.
  1101. */
  1102. processDlQueues(identifiers = [{id:'assets', limit:20}, {id:'libraries', limit:5}, {id:'files', limit:5}, {id:'forge', limit:5}]){
  1103. this.progress = 0;
  1104. let shouldFire = true
  1105. // Assign dltracking variables.
  1106. this.totaldlsize = 0
  1107. this.progress = 0
  1108. for(let i=0; i<identifiers.length; i++){
  1109. this.totaldlsize += this[identifiers[i].id].dlsize
  1110. }
  1111. for(let i=0; i<identifiers.length; i++){
  1112. let iden = identifiers[i]
  1113. let r = this.startAsyncProcess(iden.id, iden.limit)
  1114. if(r) shouldFire = false
  1115. }
  1116. if(shouldFire){
  1117. this.emit('dlcomplete')
  1118. }
  1119. }
  1120. // #endregion
  1121. }
  1122. module.exports = {
  1123. AssetGuard,
  1124. Asset,
  1125. Library
  1126. }