assetguard.js 68 KB

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