assetguard.js 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648
  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 isDev = require('electron-is-dev')
  32. const mkpath = require('mkdirp');
  33. const path = require('path')
  34. const Registry = require('winreg')
  35. const request = require('request')
  36. const tar = require('tar-fs')
  37. const zlib = require('zlib')
  38. // Constants
  39. const PLATFORM_MAP = {
  40. win32: '-windows-x64.tar.gz',
  41. darwin: '-macosx-x64.tar.gz',
  42. linux: '-linux-x64.tar.gz'
  43. }
  44. // Classes
  45. /** Class representing a base asset. */
  46. class Asset {
  47. /**
  48. * Create an asset.
  49. *
  50. * @param {any} id The id of the asset.
  51. * @param {string} hash The hash value of the asset.
  52. * @param {number} size The size in bytes of the asset.
  53. * @param {string} from The url where the asset can be found.
  54. * @param {string} to The absolute local file path of the asset.
  55. */
  56. constructor(id, hash, size, from, to){
  57. this.id = id
  58. this.hash = hash
  59. this.size = size
  60. this.from = from
  61. this.to = to
  62. }
  63. }
  64. /** Class representing a mojang library. */
  65. class Library extends Asset {
  66. /**
  67. * Converts the process.platform OS names to match mojang's OS names.
  68. */
  69. static mojangFriendlyOS(){
  70. const opSys = process.platform
  71. if (opSys === 'darwin') {
  72. return 'osx';
  73. } else if (opSys === 'win32'){
  74. return 'windows';
  75. } else if (opSys === 'linux'){
  76. return 'linux';
  77. } else {
  78. return 'unknown_os';
  79. }
  80. }
  81. /**
  82. * Checks whether or not a library is valid for download on a particular OS, following
  83. * the rule format specified in the mojang version data index. If the allow property has
  84. * an OS specified, then the library can ONLY be downloaded on that OS. If the disallow
  85. * property has instead specified an OS, the library can be downloaded on any OS EXCLUDING
  86. * the one specified.
  87. *
  88. * @param {Object} rules The Library's download rules.
  89. * @returns {boolean} True if the Library follows the specified rules, otherwise false.
  90. */
  91. static validateRules(rules){
  92. if(rules == null) return true
  93. let result = true
  94. rules.forEach(function(rule){
  95. const action = rule['action']
  96. const osProp = rule['os']
  97. if(action != null){
  98. if(osProp != null){
  99. const osName = osProp['name']
  100. const osMoj = Library.mojangFriendlyOS()
  101. if(action === 'allow'){
  102. result = osName === osMoj
  103. return
  104. } else if(action === 'disallow'){
  105. result = osName !== osMoj
  106. return
  107. }
  108. }
  109. }
  110. })
  111. return result
  112. }
  113. }
  114. class DistroModule extends Asset {
  115. /**
  116. * Create a DistroModule. This is for processing,
  117. * not equivalent to the module objects in the
  118. * distro index.
  119. *
  120. * @param {any} id The id of the asset.
  121. * @param {string} hash The hash value of the asset.
  122. * @param {number} size The size in bytes of the asset.
  123. * @param {string} from The url where the asset can be found.
  124. * @param {string} to The absolute local file path of the asset.
  125. * @param {string} type The the module type.
  126. */
  127. constructor(id, hash, size, from, to, type){
  128. super(id, hash, size, from, to)
  129. this.type = type
  130. }
  131. }
  132. /**
  133. * Class representing a download tracker. This is used to store meta data
  134. * about a download queue, including the queue itself.
  135. */
  136. class DLTracker {
  137. /**
  138. * Create a DLTracker
  139. *
  140. * @param {Array.<Asset>} dlqueue An array containing assets queued for download.
  141. * @param {number} dlsize The combined size of each asset in the download queue array.
  142. * @param {function(Asset)} callback Optional callback which is called when an asset finishes downloading.
  143. */
  144. constructor(dlqueue, dlsize, callback = null){
  145. this.dlqueue = dlqueue
  146. this.dlsize = dlsize
  147. this.callback = callback
  148. }
  149. }
  150. let distributionData = null
  151. /**
  152. * Central object class used for control flow. This object stores data about
  153. * categories of downloads. Each category is assigned an identifier with a
  154. * DLTracker object as its value. Combined information is also stored, such as
  155. * the total size of all the queued files in each category. This event is used
  156. * to emit events so that external modules can listen into processing done in
  157. * this module.
  158. */
  159. class AssetGuard extends EventEmitter {
  160. /**
  161. * Create an instance of AssetGuard.
  162. * On creation the object's properties are never-null default
  163. * values. Each identifier is resolved to an empty DLTracker.
  164. *
  165. * @param {string} basePath The base path for asset validation (game root).
  166. * @param {string} launcherPath The root launcher directory.
  167. * @param {string} javaexec The path to a java executable which will be used
  168. * to finalize installation.
  169. */
  170. constructor(basePath, launcherPath, javaexec){
  171. super()
  172. this.totaldlsize = 0
  173. this.progress = 0
  174. this.assets = new DLTracker([], 0)
  175. this.libraries = new DLTracker([], 0)
  176. this.files = new DLTracker([], 0)
  177. this.forge = new DLTracker([], 0)
  178. this.java = new DLTracker([], 0)
  179. this.extractQueue = []
  180. this.basePath = basePath
  181. this.launcherPath = launcherPath
  182. this.javaexec = javaexec
  183. }
  184. // Static Utility Functions
  185. // #region
  186. // Static General Resolve Functions
  187. // #region
  188. /**
  189. * Resolve an artifact id into a path. For example, on windows
  190. * 'net.minecraftforge:forge:1.11.2-13.20.0.2282', '.jar' becomes
  191. * net\minecraftforge\forge\1.11.2-13.20.0.2282\forge-1.11.2-13.20.0.2282.jar
  192. *
  193. * @param {string} artifactid The artifact id string.
  194. * @param {string} extension The extension of the file at the resolved path.
  195. * @returns {string} The resolved relative path from the artifact id.
  196. */
  197. static _resolvePath(artifactid, extension){
  198. let ps = artifactid.split(':')
  199. let cs = ps[0].split('.')
  200. cs.push(ps[1])
  201. cs.push(ps[2])
  202. cs.push(ps[1].concat('-').concat(ps[2]).concat(extension))
  203. return path.join.apply(path, cs)
  204. }
  205. /**
  206. * Resolve an artifact id into a URL. For example,
  207. * 'net.minecraftforge:forge:1.11.2-13.20.0.2282', '.jar' becomes
  208. * net/minecraftforge/forge/1.11.2-13.20.0.2282/forge-1.11.2-13.20.0.2282.jar
  209. *
  210. * @param {string} artifactid The artifact id string.
  211. * @param {string} extension The extension of the file at the resolved url.
  212. * @returns {string} The resolved relative URL from the artifact id.
  213. */
  214. static _resolveURL(artifactid, extension){
  215. let ps = artifactid.split(':')
  216. let cs = ps[0].split('.')
  217. cs.push(ps[1])
  218. cs.push(ps[2])
  219. cs.push(ps[1].concat('-').concat(ps[2]).concat(extension))
  220. return cs.join('/')
  221. }
  222. // #endregion
  223. // Static Hash Validation Functions
  224. // #region
  225. /**
  226. * Calculates the hash for a file using the specified algorithm.
  227. *
  228. * @param {Buffer} buf The buffer containing file data.
  229. * @param {string} algo The hash algorithm.
  230. * @returns {string} The calculated hash in hex.
  231. */
  232. static _calculateHash(buf, algo){
  233. return crypto.createHash(algo).update(buf).digest('hex')
  234. }
  235. /**
  236. * Used to parse a checksums file. This is specifically designed for
  237. * the checksums.sha1 files found inside the forge scala dependencies.
  238. *
  239. * @param {string} content The string content of the checksums file.
  240. * @returns {Object} An object with keys being the file names, and values being the hashes.
  241. */
  242. static _parseChecksumsFile(content){
  243. let finalContent = {}
  244. let lines = content.split('\n')
  245. for(let i=0; i<lines.length; i++){
  246. let bits = lines[i].split(' ')
  247. if(bits[1] == null) {
  248. continue
  249. }
  250. finalContent[bits[1]] = bits[0]
  251. }
  252. return finalContent
  253. }
  254. /**
  255. * Validate that a file exists and matches a given hash value.
  256. *
  257. * @param {string} filePath The path of the file to validate.
  258. * @param {string} algo The hash algorithm to check against.
  259. * @param {string} hash The existing hash to check against.
  260. * @returns {boolean} True if the file exists and calculated hash matches the given hash, otherwise false.
  261. */
  262. static _validateLocal(filePath, algo, hash){
  263. if(fs.existsSync(filePath)){
  264. //No hash provided, have to assume it's good.
  265. if(hash == null){
  266. return true
  267. }
  268. let fileName = path.basename(filePath)
  269. let buf = fs.readFileSync(filePath)
  270. let calcdhash = AssetGuard._calculateHash(buf, algo)
  271. return calcdhash === hash
  272. }
  273. return false;
  274. }
  275. /**
  276. * Validates a file in the style used by forge's version index.
  277. *
  278. * @param {string} filePath The path of the file to validate.
  279. * @param {Array.<string>} checksums The checksums listed in the forge version index.
  280. * @returns {boolean} True if the file exists and the hashes match, otherwise false.
  281. */
  282. static _validateForgeChecksum(filePath, checksums){
  283. if(fs.existsSync(filePath)){
  284. if(checksums == null || checksums.length === 0){
  285. return true
  286. }
  287. let buf = fs.readFileSync(filePath)
  288. let calcdhash = AssetGuard._calculateHash(buf, 'sha1')
  289. let valid = checksums.includes(calcdhash)
  290. if(!valid && filePath.endsWith('.jar')){
  291. valid = AssetGuard._validateForgeJar(filePath, checksums)
  292. }
  293. return valid
  294. }
  295. return false
  296. }
  297. /**
  298. * Validates a forge jar file dependency who declares a checksums.sha1 file.
  299. * This can be an expensive task as it usually requires that we calculate thousands
  300. * of hashes.
  301. *
  302. * @param {Buffer} buf The buffer of the jar file.
  303. * @param {Array.<string>} checksums The checksums listed in the forge version index.
  304. * @returns {boolean} True if all hashes declared in the checksums.sha1 file match the actual hashes.
  305. */
  306. static _validateForgeJar(buf, checksums){
  307. // Double pass method was the quickest I found. I tried a version where we store data
  308. // to only require a single pass, plus some quick cleanup but that seemed to take slightly more time.
  309. const hashes = {}
  310. let expected = {}
  311. const zip = new AdmZip(buf)
  312. const zipEntries = zip.getEntries()
  313. //First pass
  314. for(let i=0; i<zipEntries.length; i++){
  315. let entry = zipEntries[i]
  316. if(entry.entryName === 'checksums.sha1'){
  317. expected = AssetGuard._parseChecksumsFile(zip.readAsText(entry))
  318. }
  319. hashes[entry.entryName] = AssetGuard._calculateHash(entry.getData(), 'sha1')
  320. }
  321. if(!checksums.includes(hashes['checksums.sha1'])){
  322. return false
  323. }
  324. //Check against expected
  325. const expectedEntries = Object.keys(expected)
  326. for(let i=0; i<expectedEntries.length; i++){
  327. if(expected[expectedEntries[i]] !== hashes[expectedEntries[i]]){
  328. return false
  329. }
  330. }
  331. return true
  332. }
  333. // #endregion
  334. // Static Distribution Index Functions
  335. // #region
  336. /**
  337. * Statically retrieve the distribution data.
  338. *
  339. * @param {string} launcherPath The root launcher directory.
  340. * @param {boolean} cached Optional. False if the distro should be freshly downloaded, else
  341. * a cached copy will be returned.
  342. * @returns {Promise.<Object>} A promise which resolves to the distribution data object.
  343. */
  344. static retrieveDistributionData(launcherPath, cached = true){
  345. return new Promise(function(resolve, reject){
  346. if(!cached || distributionData == null){
  347. // TODO Download file from upstream.
  348. const distroURL = 'http://mc.westeroscraft.com/WesterosCraftLauncher/westeroscraft.json'
  349. const distroDest = path.join(launcherPath, 'westeroscraft.json')
  350. // TODO Fulfill with JSON.parse()
  351. request(distroURL, (error, resp, body) => {
  352. distributionData = JSON.parse(body)
  353. fs.writeFile(distroDest, body, 'utf-8', (err) => {
  354. if(!err){
  355. resolve(distributionData)
  356. } else {
  357. reject(err)
  358. }
  359. })
  360. })
  361. // Workaround while file is not hosted.
  362. /*fs.readFile(path.join(__dirname, '..', 'westeroscraft.json'), 'utf-8', (err, data) => {
  363. distributionData = JSON.parse(data)
  364. fulfill(distributionData)
  365. })*/
  366. } else {
  367. resolve(distributionData)
  368. }
  369. })
  370. }
  371. /**
  372. * Recieved a cached version of the distribution index.
  373. *
  374. * @param {string} launcherPath The root launcher directory.
  375. * @param {boolean} cached Optional. False if the distro should be freshly downloaded, else
  376. * a cached copy will be returned.
  377. * @returns {Object} The distribution data object.
  378. */
  379. static retrieveDistributionDataSync(launcherPath, cached = true){
  380. if(!cached || distributionData == null){
  381. distributionData = JSON.parse(fs.readFileSync(path.join(launcherPath, 'westeroscraft.json'), 'utf-8'))
  382. }
  383. return distributionData
  384. }
  385. /**
  386. * Resolve the default selected server from the distribution index.
  387. *
  388. * @param {string} launcherPath The root launcher directory.
  389. * @returns {Object} An object resolving to the default selected server.
  390. */
  391. static resolveSelectedServer(launcherPath){
  392. const distro = AssetGuard.retrieveDistributionDataSync(launcherPath)
  393. const servers = distro.servers
  394. for(let i=0; i<servers.length; i++){
  395. if(servers[i].default_selected){
  396. return servers[i]
  397. }
  398. }
  399. // If no server declares default_selected, default to the first one declared.
  400. return (servers.length > 0) ? servers[0] : null
  401. }
  402. /**
  403. * Gets a server from the distro index which maches the provided ID.
  404. * Returns null if the ID could not be found or the distro index has
  405. * not yet been loaded.
  406. *
  407. * @param {string} launcherPath The root launcher directory.
  408. * @param {string} serverID The id of the server to retrieve.
  409. * @returns {Object} The server object whose id matches the parameter.
  410. */
  411. static getServerById(launcherPath, serverID){
  412. if(distributionData == null){
  413. AssetGuard.retrieveDistributionDataSync(launcherPath, false)
  414. }
  415. const servers = distributionData.servers
  416. let serv = null
  417. for(let i=0; i<servers.length; i++){
  418. if(servers[i].id === serverID){
  419. serv = servers[i]
  420. }
  421. }
  422. return serv
  423. }
  424. // #endregion
  425. // Miscellaneous Static Functions
  426. // #region
  427. /**
  428. * Extracts and unpacks a file from .pack.xz format.
  429. *
  430. * @param {Array.<string>} filePaths The paths of the files to be extracted and unpacked.
  431. * @returns {Promise.<void>} An empty promise to indicate the extraction has completed.
  432. */
  433. static _extractPackXZ(filePaths, javaExecutable){
  434. return new Promise(function(resolve, reject){
  435. let libPath
  436. if(isDev){
  437. libPath = path.join(process.cwd(), 'libraries', 'java', 'PackXZExtract.jar')
  438. } else {
  439. if(process.platform === 'darwin'){
  440. libPath = path.join(process.cwd(),'Contents', 'Resources', 'libraries', 'java', 'PackXZExtract.jar')
  441. } else {
  442. libPath = path.join(process.cwd(), 'resources', 'libraries', 'java', 'PackXZExtract.jar')
  443. }
  444. }
  445. const filePath = filePaths.join(',')
  446. const child = child_process.spawn(javaExecutable, ['-jar', libPath, '-packxz', filePath])
  447. child.stdout.on('data', (data) => {
  448. console.log('PackXZExtract:', data.toString('utf8'))
  449. })
  450. child.stderr.on('data', (data) => {
  451. console.log('PackXZExtract:', data.toString('utf8'))
  452. })
  453. child.on('close', (code, signal) => {
  454. console.log('PackXZExtract: Exited with code', code)
  455. resolve()
  456. })
  457. })
  458. }
  459. /**
  460. * Function which finalizes the forge installation process. This creates a 'version'
  461. * instance for forge and saves its version.json file into that instance. If that
  462. * instance already exists, the contents of the version.json file are read and returned
  463. * in a promise.
  464. *
  465. * @param {Asset} asset The Asset object representing Forge.
  466. * @param {string} basePath Base path for asset validation (game root).
  467. * @returns {Promise.<Object>} A promise which resolves to the contents of forge's version.json.
  468. */
  469. static _finalizeForgeAsset(asset, basePath){
  470. return new Promise(function(resolve, reject){
  471. fs.readFile(asset.to, (err, data) => {
  472. const zip = new AdmZip(data)
  473. const zipEntries = zip.getEntries()
  474. for(let i=0; i<zipEntries.length; i++){
  475. if(zipEntries[i].entryName === 'version.json'){
  476. const forgeVersion = JSON.parse(zip.readAsText(zipEntries[i]))
  477. const versionPath = path.join(basePath, 'versions', forgeVersion.id)
  478. const versionFile = path.join(versionPath, forgeVersion.id + '.json')
  479. if(!fs.existsSync(versionFile)){
  480. mkpath.sync(versionPath)
  481. fs.writeFileSync(path.join(versionPath, forgeVersion.id + '.json'), zipEntries[i].getData())
  482. resolve(forgeVersion)
  483. } else {
  484. //Read the saved file to allow for user modifications.
  485. resolve(JSON.parse(fs.readFileSync(versionFile, 'utf-8')))
  486. }
  487. return
  488. }
  489. }
  490. //We didn't find forge's version.json.
  491. reject('Unable to finalize Forge processing, version.json not found! Has forge changed their format?')
  492. })
  493. })
  494. }
  495. // #endregion
  496. // Static Java Utility
  497. // #region
  498. /**
  499. * @typedef OracleJREData
  500. * @property {string} uri The base uri of the JRE.
  501. * @property {{major: string, update: string, build: string}} version Object containing version information.
  502. */
  503. /**
  504. * Resolves the latest version of Oracle's JRE and parses its download link.
  505. *
  506. * @returns {Promise.<OracleJREData>} Promise which resolved to an object containing the JRE download data.
  507. */
  508. static _latestJREOracle(){
  509. const url = 'http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html'
  510. const regex = /http:\/\/.+?(?=\/java)\/java\/jdk\/([0-9]+u[0-9]+)-(b[0-9]+)\/([a-f0-9]{32})?\/jre-\1/
  511. return new Promise((resolve, reject) => {
  512. request(url, (err, resp, body) => {
  513. if(!err){
  514. const arr = body.match(regex)
  515. const verSplit = arr[1].split('u')
  516. resolve({
  517. uri: arr[0],
  518. version: {
  519. major: verSplit[0],
  520. update: verSplit[1],
  521. build: arr[2]
  522. }
  523. })
  524. } else {
  525. resolve(null)
  526. }
  527. })
  528. })
  529. }
  530. /**
  531. * Returns the path of the OS-specific executable for the given Java
  532. * installation. Supported OS's are win32, darwin, linux.
  533. *
  534. * @param {string} rootDir The root directory of the Java installation.
  535. * @returns {string} The path to the Java executable.
  536. */
  537. static javaExecFromRoot(rootDir){
  538. if(process.platform === 'win32'){
  539. return path.join(rootDir, 'bin', 'javaw.exe')
  540. } else if(process.platform === 'darwin'){
  541. return path.join(rootDir, 'Contents', 'Home', 'bin', 'java')
  542. } else if(process.platform === 'linux'){
  543. return path.join(rootDir, 'bin', 'java')
  544. }
  545. return rootDir
  546. }
  547. /**
  548. * Check to see if the given path points to a Java executable.
  549. *
  550. * @param {string} pth The path to check against.
  551. * @returns {boolean} True if the path points to a Java executable, otherwise false.
  552. */
  553. static isJavaExecPath(pth){
  554. if(process.platform === 'win32'){
  555. return pth.endsWith(path.join('bin', 'javaw.exe'))
  556. } else if(process.platform === 'darwin'){
  557. return pth.endsWith(path.join('bin', 'java'))
  558. } else if(process.platform === 'linux'){
  559. return pth.endsWith(path.join('bin', 'java'))
  560. }
  561. return false
  562. }
  563. /**
  564. * Load Mojang's launcher.json file.
  565. *
  566. * @returns {Promise.<Object>} Promise which resolves to Mojang's launcher.json object.
  567. */
  568. static loadMojangLauncherData(){
  569. return new Promise((resolve, reject) => {
  570. request.get('https://launchermeta.mojang.com/mc/launcher.json', (err, resp, body) => {
  571. if(err){
  572. resolve(null)
  573. } else {
  574. resolve(JSON.parse(body))
  575. }
  576. })
  577. })
  578. }
  579. /**
  580. * Parses a **full** Java Runtime version string and resolves
  581. * the version information. Uses Java 8 formatting.
  582. *
  583. * @param {string} verString Full version string to parse.
  584. * @returns Object containing the version information.
  585. */
  586. static parseJavaRuntimeVersion(verString){
  587. // 1.{major}.0_{update}-b{build}
  588. // ex. 1.8.0_152-b16
  589. const ret = {}
  590. let pts = verString.split('-')
  591. ret.build = parseInt(pts[1].substring(1))
  592. pts = pts[0].split('_')
  593. ret.update = parseInt(pts[1])
  594. ret.major = parseInt(pts[0].split('.')[1])
  595. return ret
  596. }
  597. /**
  598. * Validates the output of a JVM's properties. Currently validates that a JRE is x64
  599. * and that the major = 8, update > 52.
  600. *
  601. * @param {string} stderr The output to validate.
  602. *
  603. * @returns {Promise.<boolean>} A promise which resolves to true if the properties are valid.
  604. * Otherwise false.
  605. */
  606. static _validateJVMProperties(stderr){
  607. const res = stderr
  608. const props = res.split('\n')
  609. const goal = 2
  610. let checksum = 0
  611. for(let i=0; i<props.length; i++){
  612. if(props[i].indexOf('sun.arch.data.model') > -1){
  613. let arch = props[i].split('=')[1].trim()
  614. console.log(props[i].trim())
  615. if(parseInt(arch) === 64){
  616. ++checksum
  617. if(checksum === goal){
  618. return true
  619. }
  620. }
  621. } else if(props[i].indexOf('java.runtime.version') > -1){
  622. let verString = props[i].split('=')[1].trim()
  623. console.log(props[i].trim())
  624. const verOb = AssetGuard.parseJavaRuntimeVersion(verString)
  625. if(verOb.major === 8 && verOb.update > 52){
  626. ++checksum
  627. if(checksum === goal){
  628. return true
  629. }
  630. }
  631. }
  632. }
  633. return checksum === goal
  634. }
  635. /**
  636. * Validates that a Java binary is at least 64 bit. This makes use of the non-standard
  637. * command line option -XshowSettings:properties. The output of this contains a property,
  638. * sun.arch.data.model = ARCH, in which ARCH is either 32 or 64. This option is supported
  639. * in Java 8 and 9. Since this is a non-standard option. This will resolve to true if
  640. * the function's code throws errors. That would indicate that the option is changed or
  641. * removed.
  642. *
  643. * @param {string} binaryExecPath Path to the java executable we wish to validate.
  644. *
  645. * @returns {Promise.<boolean>} Resolves to false only if the test is successful and the result
  646. * is less than 64.
  647. */
  648. static _validateJavaBinary(binaryExecPath){
  649. return new Promise((resolve, reject) => {
  650. if(fs.existsSync(binaryExecPath)){
  651. child_process.exec('"' + binaryExecPath + '" -XshowSettings:properties', (err, stdout, stderr) => {
  652. try {
  653. // Output is stored in stderr?
  654. resolve(this._validateJVMProperties(stderr))
  655. } catch (err){
  656. // Output format might have changed, validation cannot be completed.
  657. resolve(false)
  658. }
  659. })
  660. } else {
  661. resolve(false)
  662. }
  663. })
  664. }
  665. /*static _validateJavaBinaryDarwin(binaryPath){
  666. return new Promise((resolve, reject) => {
  667. if(fs.existsSync(binaryExecPath)){
  668. child_process.exec('export JAVA_HOME="' + binaryPath + '"; java -XshowSettings:properties', (err, stdout, stderr) => {
  669. try {
  670. // Output is stored in stderr?
  671. resolve(this._validateJVMProperties(stderr))
  672. } catch (err){
  673. // Output format might have changed, validation cannot be completed.
  674. resolve(false)
  675. }
  676. })
  677. } else {
  678. resolve(false)
  679. }
  680. })
  681. }*/
  682. /**
  683. * Checks for the presence of the environment variable JAVA_HOME. If it exits, we will check
  684. * to see if the value points to a path which exists. If the path exits, the path is returned.
  685. *
  686. * @returns {string} The path defined by JAVA_HOME, if it exists. Otherwise null.
  687. */
  688. static _scanJavaHome(){
  689. const jHome = process.env.JAVA_HOME
  690. try {
  691. let res = fs.existsSync(jHome)
  692. return res ? jHome : null
  693. } catch (err) {
  694. // Malformed JAVA_HOME property.
  695. return null
  696. }
  697. }
  698. /**
  699. * Scans the data folder's runtime directory for suitable JRE candidates.
  700. *
  701. * @param {string} dataDir The base launcher directory.
  702. * @returns {Promise.<Set.<string>>} A set containing suitable JRE candidates found
  703. * in the runtime directory.
  704. */
  705. static _scanDataFolder(dataDir){
  706. return new Promise((resolve, reject) => {
  707. const x64RuntimeDir = path.join(dataDir, 'runtime', 'x64')
  708. fs.exists(x64RuntimeDir, (e) => {
  709. let res = new Set()
  710. if(e){
  711. fs.readdir(x64RuntimeDir, (err, files) => {
  712. if(err){
  713. resolve(res)
  714. console.log(err)
  715. } else {
  716. for(let i=0; i<files.length; i++){
  717. res.add(path.join(x64RuntimeDir, files[i]))
  718. }
  719. resolve(res)
  720. }
  721. })
  722. } else {
  723. resolve(res)
  724. }
  725. })
  726. })
  727. }
  728. /**
  729. * Scans the registry for 64-bit Java entries. The paths of each entry are added to
  730. * a set and returned. Currently, only Java 8 (1.8) is supported.
  731. *
  732. * @returns {Promise.<Set.<string>>} A promise which resolves to a set of 64-bit Java root
  733. * paths found in the registry.
  734. */
  735. static _scanRegistry(){
  736. return new Promise((resolve, reject) => {
  737. // Keys for Java v9.0.0 and later:
  738. // 'SOFTWARE\\JavaSoft\\JRE'
  739. // 'SOFTWARE\\JavaSoft\\JDK'
  740. // Forge does not yet support Java 9, therefore we do not.
  741. let cbTracker = 0
  742. let cbAcc = 0
  743. // Keys for Java 1.8 and prior:
  744. const regKeys = [
  745. '\\SOFTWARE\\JavaSoft\\Java Runtime Environment',
  746. '\\SOFTWARE\\JavaSoft\\Java Development Kit'
  747. ]
  748. const candidates = new Set()
  749. for(let i=0; i<regKeys.length; i++){
  750. const key = new Registry({
  751. hive: Registry.HKLM,
  752. key: regKeys[i],
  753. arch: 'x64'
  754. })
  755. key.keyExists((err, exists) => {
  756. if(exists) {
  757. key.keys((err, javaVers) => {
  758. if(err){
  759. console.error(err)
  760. if(i === regKeys.length-1 && cbAcc === cbTracker){
  761. resolve(candidates)
  762. }
  763. } else {
  764. cbTracker += javaVers.length
  765. if(i === regKeys.length-1 && cbTracker === cbAcc){
  766. resolve(candidates)
  767. } else {
  768. for(let j=0; j<javaVers.length; j++){
  769. const javaVer = javaVers[j]
  770. const vKey = javaVer.key.substring(javaVer.key.lastIndexOf('\\')+1)
  771. // Only Java 8 is supported currently.
  772. if(parseFloat(vKey) === 1.8){
  773. javaVer.get('JavaHome', (err, res) => {
  774. const jHome = res.value
  775. if(jHome.indexOf('(x86)') === -1){
  776. candidates.add(jHome)
  777. }
  778. cbAcc++
  779. if(i === regKeys.length-1 && cbAcc === cbTracker){
  780. resolve(candidates)
  781. }
  782. })
  783. } else {
  784. cbAcc++
  785. if(i === regKeys.length-1 && cbAcc === cbTracker){
  786. resolve(candidates)
  787. }
  788. }
  789. }
  790. }
  791. }
  792. })
  793. } else {
  794. if(i === regKeys.length-1 && cbAcc === cbTracker){
  795. resolve(candidates)
  796. }
  797. }
  798. })
  799. }
  800. })
  801. }
  802. /**
  803. * Attempts to find a valid x64 installation of Java on Windows machines.
  804. * Possible paths will be pulled from the registry and the JAVA_HOME environment
  805. * variable. The paths will be sorted with higher versions preceeding lower, and
  806. * JREs preceeding JDKs. The binaries at the sorted paths will then be validated.
  807. * The first validated is returned.
  808. *
  809. * Higher versions > Lower versions
  810. * If versions are equal, JRE > JDK.
  811. *
  812. * @param {string} dataDir The base launcher directory.
  813. * @returns {Promise.<string>} A Promise which resolves to the executable path of a valid
  814. * x64 Java installation. If none are found, null is returned.
  815. */
  816. static async _win32JavaValidate(dataDir){
  817. // Get possible paths from the registry.
  818. const pathSet = await AssetGuard._scanRegistry()
  819. //console.log(Array.from(pathSet)) // DEBUGGING
  820. // Get possible paths from the data directory.
  821. const pathSet2 = await AssetGuard._scanDataFolder(dataDir)
  822. // Validate JAVA_HOME
  823. const jHome = AssetGuard._scanJavaHome()
  824. if(jHome != null && jHome.indexOf('(x86)') === -1){
  825. pathSet.add(jHome)
  826. }
  827. const mergedSet = new Set([...pathSet, ...pathSet2])
  828. // Convert path set to an array for processing.
  829. let pathArr = Array.from(mergedSet)
  830. //console.log(pathArr) // DEBUGGING
  831. // Sorts array. Higher version numbers preceed lower. JRE preceeds JDK.
  832. pathArr = pathArr.sort((a, b) => {
  833. // Note that Java 9+ uses semver and that will need to be accounted for in
  834. // the future.
  835. const aVer = parseInt(a.split('_')[1])
  836. const bVer = parseInt(b.split('_')[1])
  837. if(bVer === aVer){
  838. return a.indexOf('jdk') > -1 ? 1 : 0
  839. } else {
  840. return bVer - aVer
  841. }
  842. })
  843. //console.log(pathArr) // DEBUGGING
  844. // Validate that the binary is actually x64.
  845. for(let i=0; i<pathArr.length; i++) {
  846. const execPath = AssetGuard.javaExecFromRoot(pathArr[i])
  847. let res = await AssetGuard._validateJavaBinary(execPath)
  848. if(res){
  849. return execPath
  850. }
  851. }
  852. // No suitable candidates found.
  853. return null;
  854. }
  855. /**
  856. * See if JRE exists in the Internet Plug-Ins folder.
  857. *
  858. * @returns {string} The path of the JRE if found, otherwise null.
  859. */
  860. static _scanInternetPlugins(){
  861. // /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java
  862. const pth = '/Library/Internet Plug-Ins/JavaAppletPlugin.plugin'
  863. const res = fs.existsSync(AssetGuard.javaExecFromRoot(pth))
  864. return res ? pth : null
  865. }
  866. /**
  867. * WIP -> get a valid x64 Java path on macOS.
  868. */
  869. static async _darwinJavaValidate(dataDir){
  870. const pathSet = new Set()
  871. // Check Internet Plugins folder.
  872. const iPPath = AssetGuard._scanInternetPlugins()
  873. if(iPPath != null){
  874. pathSet.add(iPPath)
  875. }
  876. // Check the JAVA_HOME environment variable.
  877. const jHome = AssetGuard._scanJavaHome()
  878. if(jHome != null){
  879. // Ensure we are at the absolute root.
  880. if(jHome.contains('/Contents/Home')){
  881. jHome = jHome.substring(0, jHome.indexOf('/Contents/Home'))
  882. }
  883. pathSet.add(jHome)
  884. }
  885. // Get possible paths from the data directory.
  886. const pathSet2 = await AssetGuard._scanDataFolder(dataDir)
  887. // TODO Sort by highest version.
  888. let pathArr = Array.from(pathSet2).concat(Array.from(pathSet))
  889. for(let i=0; i<pathArr.length; i++) {
  890. const execPath = AssetGuard.javaExecFromRoot(pathArr[i])
  891. let res = await AssetGuard._validateJavaBinary(execPath)
  892. if(res){
  893. return execPath
  894. }
  895. }
  896. return null
  897. }
  898. /**
  899. * WIP -> get a valid x64 Java path on linux.
  900. */
  901. static async _linuxJavaValidate(dataDir){
  902. return null
  903. }
  904. /**
  905. * Retrieve the path of a valid x64 Java installation.
  906. *
  907. * @param {string} dataDir The base launcher directory.
  908. * @returns {string} A path to a valid x64 Java installation, null if none found.
  909. */
  910. static async validateJava(dataDir){
  911. return await AssetGuard['_' + process.platform + 'JavaValidate'](dataDir)
  912. }
  913. // #endregion
  914. // #endregion
  915. // Validation Functions
  916. // #region
  917. /**
  918. * Loads the version data for a given minecraft version.
  919. *
  920. * @param {string} version The game version for which to load the index data.
  921. * @param {boolean} force Optional. If true, the version index will be downloaded even if it exists locally. Defaults to false.
  922. * @returns {Promise.<Object>} Promise which resolves to the version data object.
  923. */
  924. loadVersionData(version, force = false){
  925. const self = this
  926. return new Promise((resolve, reject) => {
  927. const name = version + '.json'
  928. const url = 'https://s3.amazonaws.com/Minecraft.Download/versions/' + version + '/' + name
  929. const versionPath = path.join(self.basePath, 'versions', version)
  930. const versionFile = path.join(versionPath, name)
  931. if(!fs.existsSync(versionFile) || force){
  932. //This download will never be tracked as it's essential and trivial.
  933. console.log('Preparing download of ' + version + ' assets.')
  934. mkpath.sync(versionPath)
  935. const stream = request(url).pipe(fs.createWriteStream(versionFile))
  936. stream.on('finish', () => {
  937. resolve(JSON.parse(fs.readFileSync(versionFile)))
  938. })
  939. } else {
  940. resolve(JSON.parse(fs.readFileSync(versionFile)))
  941. }
  942. })
  943. }
  944. // Asset (Category=''') Validation Functions
  945. // #region
  946. /**
  947. * Public asset validation function. This function will handle the validation of assets.
  948. * It will parse the asset index specified in the version data, analyzing each
  949. * asset entry. In this analysis it will check to see if the local file exists and is valid.
  950. * If not, it will be added to the download queue for the 'assets' identifier.
  951. *
  952. * @param {Object} versionData The version data for the assets.
  953. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  954. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  955. */
  956. validateAssets(versionData, force = false){
  957. const self = this
  958. return new Promise(function(fulfill, reject){
  959. self._assetChainIndexData(versionData, force).then(() => {
  960. fulfill()
  961. })
  962. })
  963. }
  964. //Chain the asset tasks to provide full async. The below functions are private.
  965. /**
  966. * Private function used to chain the asset validation process. This function retrieves
  967. * the index data.
  968. * @param {Object} versionData
  969. * @param {boolean} force
  970. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  971. */
  972. _assetChainIndexData(versionData, force = false){
  973. const self = this
  974. return new Promise(function(fulfill, reject){
  975. //Asset index constants.
  976. const assetIndex = versionData.assetIndex
  977. const name = assetIndex.id + '.json'
  978. const indexPath = path.join(self.basePath, 'assets', 'indexes')
  979. const assetIndexLoc = path.join(indexPath, name)
  980. let data = null
  981. if(!fs.existsSync(assetIndexLoc) || force){
  982. console.log('Downloading ' + versionData.id + ' asset index.')
  983. mkpath.sync(indexPath)
  984. const stream = request(assetIndex.url).pipe(fs.createWriteStream(assetIndexLoc))
  985. stream.on('finish', function() {
  986. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  987. self._assetChainValidateAssets(versionData, data).then(() => {
  988. fulfill()
  989. })
  990. })
  991. } else {
  992. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  993. self._assetChainValidateAssets(versionData, data).then(() => {
  994. fulfill()
  995. })
  996. }
  997. })
  998. }
  999. /**
  1000. * Private function used to chain the asset validation process. This function processes
  1001. * the assets and enqueues missing or invalid files.
  1002. * @param {Object} versionData
  1003. * @param {boolean} force
  1004. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1005. */
  1006. _assetChainValidateAssets(versionData, indexData){
  1007. const self = this
  1008. return new Promise(function(fulfill, reject){
  1009. //Asset constants
  1010. const resourceURL = 'http://resources.download.minecraft.net/'
  1011. const localPath = path.join(self.basePath, 'assets')
  1012. const indexPath = path.join(localPath, 'indexes')
  1013. const objectPath = path.join(localPath, 'objects')
  1014. const assetDlQueue = []
  1015. let dlSize = 0
  1016. let acc = 0
  1017. const total = Object.keys(indexData.objects).length
  1018. //const objKeys = Object.keys(data.objects)
  1019. async.forEachOfLimit(indexData.objects, 10, function(value, key, cb){
  1020. acc++
  1021. self.emit('assetVal', {acc, total})
  1022. const hash = value.hash
  1023. const assetName = path.join(hash.substring(0, 2), hash)
  1024. const urlName = hash.substring(0, 2) + "/" + hash
  1025. const ast = new Asset(key, hash, String(value.size), resourceURL + urlName, path.join(objectPath, assetName))
  1026. if(!AssetGuard._validateLocal(ast.to, 'sha1', ast.hash)){
  1027. dlSize += (ast.size*1)
  1028. assetDlQueue.push(ast)
  1029. }
  1030. cb()
  1031. }, function(err){
  1032. self.assets = new DLTracker(assetDlQueue, dlSize)
  1033. fulfill()
  1034. })
  1035. })
  1036. }
  1037. // #endregion
  1038. // Library (Category=''') Validation Functions
  1039. // #region
  1040. /**
  1041. * Public library validation function. This function will handle the validation of libraries.
  1042. * It will parse the version data, analyzing each library entry. In this analysis, it will
  1043. * check to see if the local file exists and is valid. If not, it will be added to the download
  1044. * queue for the 'libraries' identifier.
  1045. *
  1046. * @param {Object} versionData The version data for the assets.
  1047. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1048. */
  1049. validateLibraries(versionData){
  1050. const self = this
  1051. return new Promise(function(fulfill, reject){
  1052. const libArr = versionData.libraries
  1053. const libPath = path.join(self.basePath, 'libraries')
  1054. const libDlQueue = []
  1055. let dlSize = 0
  1056. //Check validity of each library. If the hashs don't match, download the library.
  1057. async.eachLimit(libArr, 5, function(lib, cb){
  1058. if(Library.validateRules(lib.rules)){
  1059. let artifact = (lib.natives == null) ? lib.downloads.artifact : lib.downloads.classifiers[lib.natives[Library.mojangFriendlyOS()]]
  1060. const libItm = new Library(lib.name, artifact.sha1, artifact.size, artifact.url, path.join(libPath, artifact.path))
  1061. if(!AssetGuard._validateLocal(libItm.to, 'sha1', libItm.hash)){
  1062. dlSize += (libItm.size*1)
  1063. libDlQueue.push(libItm)
  1064. }
  1065. }
  1066. cb()
  1067. }, function(err){
  1068. self.libraries = new DLTracker(libDlQueue, dlSize)
  1069. fulfill()
  1070. })
  1071. })
  1072. }
  1073. // #endregion
  1074. // Miscellaneous (Category=files) Validation Functions
  1075. // #region
  1076. /**
  1077. * Public miscellaneous mojang file validation function. These files will be enqueued under
  1078. * the 'files' identifier.
  1079. *
  1080. * @param {Object} versionData The version data for the assets.
  1081. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1082. */
  1083. validateMiscellaneous(versionData){
  1084. const self = this
  1085. return new Promise(async function(fulfill, reject){
  1086. await self.validateClient(versionData)
  1087. await self.validateLogConfig(versionData)
  1088. fulfill()
  1089. })
  1090. }
  1091. /**
  1092. * Validate client file - artifact renamed from client.jar to '{version}'.jar.
  1093. *
  1094. * @param {Object} versionData The version data for the assets.
  1095. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  1096. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1097. */
  1098. validateClient(versionData, force = false){
  1099. const self = this
  1100. return new Promise(function(fulfill, reject){
  1101. const clientData = versionData.downloads.client
  1102. const version = versionData.id
  1103. const targetPath = path.join(self.basePath, 'versions', version)
  1104. const targetFile = version + '.jar'
  1105. let client = new Asset(version + ' client', clientData.sha1, clientData.size, clientData.url, path.join(targetPath, targetFile))
  1106. if(!AssetGuard._validateLocal(client.to, 'sha1', client.hash) || force){
  1107. self.files.dlqueue.push(client)
  1108. self.files.dlsize += client.size*1
  1109. fulfill()
  1110. } else {
  1111. fulfill()
  1112. }
  1113. })
  1114. }
  1115. /**
  1116. * Validate log config.
  1117. *
  1118. * @param {Object} versionData The version data for the assets.
  1119. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  1120. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1121. */
  1122. validateLogConfig(versionData){
  1123. const self = this
  1124. return new Promise(function(fulfill, reject){
  1125. const client = versionData.logging.client
  1126. const file = client.file
  1127. const targetPath = path.join(self.basePath, 'assets', 'log_configs')
  1128. let logConfig = new Asset(file.id, file.sha1, file.size, file.url, path.join(targetPath, file.id))
  1129. if(!AssetGuard._validateLocal(logConfig.to, 'sha1', logConfig.hash)){
  1130. self.files.dlqueue.push(logConfig)
  1131. self.files.dlsize += logConfig.size*1
  1132. fulfill()
  1133. } else {
  1134. fulfill()
  1135. }
  1136. })
  1137. }
  1138. // #endregion
  1139. // Distribution (Category=forge) Validation Functions
  1140. // #region
  1141. /**
  1142. * Validate the distribution.
  1143. *
  1144. * @param {string} serverpackid The id of the server to validate.
  1145. * @returns {Promise.<Object>} A promise which resolves to the server distribution object.
  1146. */
  1147. validateDistribution(serverpackid){
  1148. const self = this
  1149. return new Promise(function(fulfill, reject){
  1150. AssetGuard.retrieveDistributionData(self.launcherPath, false).then((value) => {
  1151. /*const servers = value.servers
  1152. let serv = null
  1153. for(let i=0; i<servers.length; i++){
  1154. if(servers[i].id === serverpackid){
  1155. serv = servers[i]
  1156. break
  1157. }
  1158. }*/
  1159. const serv = AssetGuard.getServerById(self.launcherPath, serverpackid)
  1160. if(serv == null) {
  1161. console.error('Invalid server pack id:', serverpackid)
  1162. }
  1163. self.forge = self._parseDistroModules(serv.modules, serv.mc_version)
  1164. // Correct our workaround here.
  1165. let decompressqueue = self.forge.callback
  1166. self.extractQueue = decompressqueue
  1167. self.forge.callback = function(asset, self){
  1168. if(asset.type === 'forge-hosted' || asset.type === 'forge'){
  1169. AssetGuard._finalizeForgeAsset(asset, self.basePath)
  1170. }
  1171. }
  1172. fulfill(serv)
  1173. })
  1174. })
  1175. }
  1176. /*//TODO The file should be hosted, the following code is for local testing.
  1177. _chainValidateDistributionIndex(basePath){
  1178. return new Promise(function(fulfill, reject){
  1179. //const distroURL = 'http://mc.westeroscraft.com/WesterosCraftLauncher/westeroscraft.json'
  1180. //const targetFile = path.join(basePath, 'westeroscraft.json')
  1181. //TEMP WORKAROUND TO TEST WHILE THIS IS NOT HOSTED
  1182. fs.readFile(path.join(__dirname, '..', 'westeroscraft.json'), 'utf-8', (err, data) => {
  1183. fulfill(JSON.parse(data))
  1184. })
  1185. })
  1186. }*/
  1187. _parseDistroModules(modules, version){
  1188. let alist = []
  1189. let asize = 0;
  1190. let decompressqueue = []
  1191. for(let i=0; i<modules.length; i++){
  1192. let ob = modules[i]
  1193. let obType = ob.type
  1194. let obArtifact = ob.artifact
  1195. let obPath = obArtifact.path == null ? AssetGuard._resolvePath(ob.id, obArtifact.extension) : obArtifact.path
  1196. switch(obType){
  1197. case 'forge-hosted':
  1198. case 'forge':
  1199. case 'library':
  1200. obPath = path.join(this.basePath, 'libraries', obPath)
  1201. break
  1202. case 'forgemod':
  1203. //obPath = path.join(this.basePath, 'mods', obPath)
  1204. obPath = path.join(this.basePath, 'modstore', obPath)
  1205. break
  1206. case 'litemod':
  1207. //obPath = path.join(this.basePath, 'mods', version, obPath)
  1208. obPath = path.join(this.basePath, 'modstore', obPath)
  1209. break
  1210. case 'file':
  1211. default:
  1212. obPath = path.join(this.basePath, obPath)
  1213. }
  1214. let artifact = new DistroModule(ob.id, obArtifact.MD5, obArtifact.size, obArtifact.url, obPath, obType)
  1215. const validationPath = obPath.toLowerCase().endsWith('.pack.xz') ? obPath.substring(0, obPath.toLowerCase().lastIndexOf('.pack.xz')) : obPath
  1216. if(!AssetGuard._validateLocal(validationPath, 'MD5', artifact.hash)){
  1217. asize += artifact.size*1
  1218. alist.push(artifact)
  1219. if(validationPath !== obPath) decompressqueue.push(obPath)
  1220. }
  1221. //Recursively process the submodules then combine the results.
  1222. if(ob.sub_modules != null){
  1223. let dltrack = this._parseDistroModules(ob.sub_modules, version)
  1224. asize += dltrack.dlsize*1
  1225. alist = alist.concat(dltrack.dlqueue)
  1226. decompressqueue = decompressqueue.concat(dltrack.callback)
  1227. }
  1228. }
  1229. //Since we have no callback at this point, we use this value to store the decompressqueue.
  1230. return new DLTracker(alist, asize, decompressqueue)
  1231. }
  1232. /**
  1233. * Loads Forge's version.json data into memory for the specified server id.
  1234. *
  1235. * @param {string} serverpack The id of the server to load Forge data for.
  1236. * @returns {Promise.<Object>} A promise which resolves to Forge's version.json data.
  1237. */
  1238. loadForgeData(serverpack){
  1239. const self = this
  1240. return new Promise(async function(fulfill, reject){
  1241. let distro = AssetGuard.retrieveDistributionDataSync(self.launcherPath)
  1242. const servers = distro.servers
  1243. let serv = null
  1244. for(let i=0; i<servers.length; i++){
  1245. if(servers[i].id === serverpack){
  1246. serv = servers[i]
  1247. break
  1248. }
  1249. }
  1250. const modules = serv.modules
  1251. for(let i=0; i<modules.length; i++){
  1252. const ob = modules[i]
  1253. if(ob.type === 'forge-hosted' || ob.type === 'forge'){
  1254. let obArtifact = ob.artifact
  1255. let obPath = obArtifact.path == null ? path.join(self.basePath, 'libraries', AssetGuard._resolvePath(ob.id, obArtifact.extension)) : obArtifact.path
  1256. let asset = new DistroModule(ob.id, obArtifact.MD5, obArtifact.size, obArtifact.url, obPath, ob.type)
  1257. let forgeData = await AssetGuard._finalizeForgeAsset(asset, self.basePath)
  1258. fulfill(forgeData)
  1259. return
  1260. }
  1261. }
  1262. reject('No forge module found!')
  1263. })
  1264. }
  1265. _parseForgeLibraries(){
  1266. /* TODO
  1267. * Forge asset validations are already implemented. When there's nothing much
  1268. * to work on, implement forge downloads using forge's version.json. This is to
  1269. * have the code on standby if we ever need it (since it's half implemented already).
  1270. */
  1271. }
  1272. // #endregion
  1273. // Java (Category=''') Validation (download) Functions
  1274. // #region
  1275. _enqueueOracleJRE(dataDir){
  1276. return new Promise((resolve, reject) => {
  1277. AssetGuard._latestJREOracle().then(verData => {
  1278. if(verData != null){
  1279. const combined = verData.uri + PLATFORM_MAP[process.platform]
  1280. const opts = {
  1281. url: combined,
  1282. headers: {
  1283. 'Cookie': 'oraclelicense=accept-securebackup-cookie'
  1284. }
  1285. }
  1286. request.head(opts, (err, resp, body) => {
  1287. if(err){
  1288. resolve(false)
  1289. } else {
  1290. dataDir = path.join(dataDir, 'runtime', 'x64')
  1291. const name = combined.substring(combined.lastIndexOf('/')+1)
  1292. const fDir = path.join(dataDir, name)
  1293. const jre = new Asset(name, null, resp.headers['content-length'], opts, fDir)
  1294. this.java = new DLTracker([jre], jre.size, (a, self) => {
  1295. let h = null
  1296. fs.createReadStream(a.to)
  1297. .on('error', err => console.log(err))
  1298. .pipe(zlib.createGunzip())
  1299. .on('error', err => console.log(err))
  1300. .pipe(tar.extract(dataDir, {
  1301. map: (header) => {
  1302. if(h == null){
  1303. h = header.name
  1304. }
  1305. }
  1306. }))
  1307. .on('error', err => console.log(err))
  1308. .on('finish', () => {
  1309. fs.unlink(a.to, err => {
  1310. if(err){
  1311. console.log(err)
  1312. }
  1313. if(h.indexOf('/') > -1){
  1314. h = h.substring(0, h.indexOf('/'))
  1315. }
  1316. const pos = path.join(dataDir, h)
  1317. self.emit('jExtracted', AssetGuard.javaExecFromRoot(pos))
  1318. })
  1319. })
  1320. })
  1321. resolve(true)
  1322. }
  1323. })
  1324. } else {
  1325. resolve(false)
  1326. }
  1327. })
  1328. })
  1329. }
  1330. /*_enqueueMojangJRE(dir){
  1331. return new Promise((resolve, reject) => {
  1332. // Mojang does not host the JRE for linux.
  1333. if(process.platform === 'linux'){
  1334. resolve(false)
  1335. }
  1336. AssetGuard.loadMojangLauncherData().then(data => {
  1337. if(data != null) {
  1338. try {
  1339. const mJRE = data[Library.mojangFriendlyOS()]['64'].jre
  1340. const url = mJRE.url
  1341. request.head(url, (err, resp, body) => {
  1342. if(err){
  1343. resolve(false)
  1344. } else {
  1345. const name = url.substring(url.lastIndexOf('/')+1)
  1346. const fDir = path.join(dir, name)
  1347. const jre = new Asset('jre' + mJRE.version, mJRE.sha1, resp.headers['content-length'], url, fDir)
  1348. this.java = new DLTracker([jre], jre.size, a => {
  1349. fs.readFile(a.to, (err, data) => {
  1350. // Data buffer needs to be decompressed from lzma,
  1351. // not really possible using node.js
  1352. })
  1353. })
  1354. }
  1355. })
  1356. } catch (err){
  1357. resolve(false)
  1358. }
  1359. }
  1360. })
  1361. })
  1362. }*/
  1363. // #endregion
  1364. // #endregion
  1365. // Control Flow Functions
  1366. // #region
  1367. /**
  1368. * Initiate an async download process for an AssetGuard DLTracker.
  1369. *
  1370. * @param {string} identifier The identifier of the AssetGuard DLTracker.
  1371. * @param {number} limit Optional. The number of async processes to run in parallel.
  1372. * @returns {boolean} True if the process began, otherwise false.
  1373. */
  1374. startAsyncProcess(identifier, limit = 5){
  1375. const self = this
  1376. let acc = 0
  1377. const concurrentDlTracker = this[identifier]
  1378. const concurrentDlQueue = concurrentDlTracker.dlqueue.slice(0)
  1379. if(concurrentDlQueue.length === 0){
  1380. return false
  1381. } else {
  1382. async.eachLimit(concurrentDlQueue, limit, function(asset, cb){
  1383. let count = 0;
  1384. mkpath.sync(path.join(asset.to, ".."))
  1385. let req = request(asset.from)
  1386. req.pause()
  1387. req.on('response', (resp) => {
  1388. if(resp.statusCode === 200){
  1389. let writeStream = fs.createWriteStream(asset.to)
  1390. writeStream.on('close', () => {
  1391. //console.log('DLResults ' + asset.size + ' ' + count + ' ', asset.size === count)
  1392. if(concurrentDlTracker.callback != null){
  1393. concurrentDlTracker.callback.apply(concurrentDlTracker, [asset, self])
  1394. }
  1395. cb()
  1396. })
  1397. req.pipe(writeStream)
  1398. req.resume()
  1399. } else {
  1400. req.abort()
  1401. const realFrom = typeof asset.from === 'object' ? asset.from.url : asset.from
  1402. console.log('Failed to download ' + realFrom + '. Response code', resp.statusCode)
  1403. self.progress += asset.size*1
  1404. self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize})
  1405. cb()
  1406. }
  1407. })
  1408. req.on('error', (err) => {
  1409. self.emit('dlerror', err)
  1410. })
  1411. req.on('data', function(chunk){
  1412. count += chunk.length
  1413. self.progress += chunk.length
  1414. acc += chunk.length
  1415. self.emit(identifier + 'dlprogress', acc)
  1416. self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize})
  1417. })
  1418. }, function(err){
  1419. if(err){
  1420. self.emit(identifier + 'dlerror')
  1421. console.log('An item in ' + identifier + ' failed to process');
  1422. } else {
  1423. self.emit(identifier + 'dlcomplete')
  1424. console.log('All ' + identifier + ' have been processed successfully')
  1425. }
  1426. self.totaldlsize -= self[identifier].dlsize
  1427. self.progress -= self[identifier].dlsize
  1428. self[identifier] = new DLTracker([], 0)
  1429. if(self.totaldlsize === 0) {
  1430. if(self.extractQueue.length > 0){
  1431. self.emit('extracting')
  1432. AssetGuard._extractPackXZ(self.extractQueue, self.javaexec).then(() => {
  1433. self.extractQueue = []
  1434. self.emit('dlcomplete')
  1435. })
  1436. } else {
  1437. self.emit('dlcomplete')
  1438. }
  1439. }
  1440. })
  1441. return true
  1442. }
  1443. }
  1444. /**
  1445. * This function will initiate the download processed for the specified identifiers. If no argument is
  1446. * given, all identifiers will be initiated. Note that in order for files to be processed you need to run
  1447. * the processing function corresponding to that identifier. If you run this function without processing
  1448. * the files, it is likely nothing will be enqueued in the object and processing will complete
  1449. * immediately. Once all downloads are complete, this function will fire the 'dlcomplete' event on the
  1450. * global object instance.
  1451. *
  1452. * @param {Array.<{id: string, limit: number}>} identifiers Optional. The identifiers to process and corresponding parallel async task limit.
  1453. */
  1454. processDlQueues(identifiers = [{id:'assets', limit:20}, {id:'libraries', limit:5}, {id:'files', limit:5}, {id:'forge', limit:5}]){
  1455. this.progress = 0;
  1456. let shouldFire = true
  1457. // Assign dltracking variables.
  1458. this.totaldlsize = 0
  1459. this.progress = 0
  1460. for(let i=0; i<identifiers.length; i++){
  1461. this.totaldlsize += this[identifiers[i].id].dlsize
  1462. }
  1463. for(let i=0; i<identifiers.length; i++){
  1464. let iden = identifiers[i]
  1465. let r = this.startAsyncProcess(iden.id, iden.limit)
  1466. if(r) shouldFire = false
  1467. }
  1468. if(shouldFire){
  1469. this.emit('dlcomplete')
  1470. }
  1471. }
  1472. // #endregion
  1473. }
  1474. module.exports = {
  1475. AssetGuard,
  1476. Asset,
  1477. Library
  1478. }