assetguard.js 67 KB

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