assetguard.js 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796
  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(fs.existsSync(binaryExecPath)){
  697. child_process.exec('"' + binaryExecPath + '" -XshowSettings:properties', (err, stdout, stderr) => {
  698. try {
  699. // Output is stored in stderr?
  700. resolve(this._validateJVMProperties(stderr))
  701. } catch (err){
  702. // Output format might have changed, validation cannot be completed.
  703. resolve({valid: false})
  704. }
  705. })
  706. } else {
  707. resolve({valid: false})
  708. }
  709. })
  710. }
  711. /**
  712. * Checks for the presence of the environment variable JAVA_HOME. If it exits, we will check
  713. * to see if the value points to a path which exists. If the path exits, the path is returned.
  714. *
  715. * @returns {string} The path defined by JAVA_HOME, if it exists. Otherwise null.
  716. */
  717. static _scanJavaHome(){
  718. const jHome = process.env.JAVA_HOME
  719. try {
  720. let res = fs.existsSync(jHome)
  721. return res ? jHome : null
  722. } catch (err) {
  723. // Malformed JAVA_HOME property.
  724. return null
  725. }
  726. }
  727. /**
  728. * Scans the registry for 64-bit Java entries. The paths of each entry are added to
  729. * a set and returned. Currently, only Java 8 (1.8) is supported.
  730. *
  731. * @returns {Promise.<Set.<string>>} A promise which resolves to a set of 64-bit Java root
  732. * paths found in the registry.
  733. */
  734. static _scanRegistry(){
  735. return new Promise((resolve, reject) => {
  736. // Keys for Java v9.0.0 and later:
  737. // 'SOFTWARE\\JavaSoft\\JRE'
  738. // 'SOFTWARE\\JavaSoft\\JDK'
  739. // Forge does not yet support Java 9, therefore we do not.
  740. // Keys for Java 1.8 and prior:
  741. const regKeys = [
  742. '\\SOFTWARE\\JavaSoft\\Java Runtime Environment',
  743. '\\SOFTWARE\\JavaSoft\\Java Development Kit'
  744. ]
  745. let keysDone = 0
  746. const candidates = new Set()
  747. for(let i=0; i<regKeys.length; i++){
  748. const key = new Registry({
  749. hive: Registry.HKLM,
  750. key: regKeys[i],
  751. arch: 'x64'
  752. })
  753. key.keyExists((err, exists) => {
  754. if(exists) {
  755. key.keys((err, javaVers) => {
  756. if(err){
  757. keysDone++
  758. console.error(err)
  759. // REG KEY DONE
  760. // DUE TO ERROR
  761. if(keysDone === regKeys.length){
  762. resolve(candidates)
  763. }
  764. } else {
  765. if(javaVers.length === 0){
  766. // REG KEY DONE
  767. // NO SUBKEYS
  768. keysDone++
  769. if(keysDone === regKeys.length){
  770. resolve(candidates)
  771. }
  772. } else {
  773. let numDone = 0
  774. for(let j=0; j<javaVers.length; j++){
  775. const javaVer = javaVers[j]
  776. const vKey = javaVer.key.substring(javaVer.key.lastIndexOf('\\')+1)
  777. // Only Java 8 is supported currently.
  778. if(parseFloat(vKey) === 1.8){
  779. javaVer.get('JavaHome', (err, res) => {
  780. const jHome = res.value
  781. if(jHome.indexOf('(x86)') === -1){
  782. candidates.add(jHome)
  783. }
  784. // SUBKEY DONE
  785. numDone++
  786. if(numDone === javaVers.length){
  787. keysDone++
  788. if(keysDone === regKeys.length){
  789. resolve(candidates)
  790. }
  791. }
  792. })
  793. } else {
  794. // SUBKEY DONE
  795. // NOT JAVA 8
  796. numDone++
  797. if(numDone === javaVers.length){
  798. keysDone++
  799. if(keysDone === regKeys.length){
  800. resolve(candidates)
  801. }
  802. }
  803. }
  804. }
  805. }
  806. }
  807. })
  808. } else {
  809. // REG KEY DONE
  810. // DUE TO NON-EXISTANCE
  811. keysDone++
  812. if(keysDone === regKeys.length){
  813. resolve(candidates)
  814. }
  815. }
  816. })
  817. }
  818. })
  819. }
  820. /**
  821. * See if JRE exists in the Internet Plug-Ins folder.
  822. *
  823. * @returns {string} The path of the JRE if found, otherwise null.
  824. */
  825. static _scanInternetPlugins(){
  826. // /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java
  827. const pth = '/Library/Internet Plug-Ins/JavaAppletPlugin.plugin'
  828. const res = fs.existsSync(AssetGuard.javaExecFromRoot(pth))
  829. return res ? pth : null
  830. }
  831. /**
  832. * Scan a directory for root JVM folders.
  833. *
  834. * @param {string} scanDir The directory to scan.
  835. * @returns {Promise.<Set.<string>>} A promise which resolves to a set of the discovered
  836. * root JVM folders.
  837. */
  838. static _scanFileSystem(scanDir){
  839. return new Promise((resolve, reject) => {
  840. fs.exists(scanDir, (e) => {
  841. let res = new Set()
  842. if(e){
  843. fs.readdir(scanDir, (err, files) => {
  844. if(err){
  845. resolve(res)
  846. console.log(err)
  847. } else {
  848. let pathsDone = 0
  849. for(let i=0; i<files.length; i++){
  850. const combinedPath = path.join(scanDir, files[i])
  851. const execPath = AssetGuard.javaExecFromRoot(combinedPath)
  852. fs.exists(execPath, (v) => {
  853. if(v){
  854. res.add(combinedPath)
  855. }
  856. ++pathsDone
  857. if(pathsDone === files.length){
  858. resolve(res)
  859. }
  860. })
  861. }
  862. if(pathsDone === files.length){
  863. resolve(res)
  864. }
  865. }
  866. })
  867. } else {
  868. resolve(res)
  869. }
  870. })
  871. })
  872. }
  873. /**
  874. *
  875. * @param {Set.<string>} rootSet A set of JVM root strings to validate.
  876. * @returns {Promise.<Object[]>} A promise which resolves to an array of meta objects
  877. * for each valid JVM root directory.
  878. */
  879. static async _validateJavaRootSet(rootSet){
  880. const rootArr = Array.from(rootSet)
  881. const validArr = []
  882. for(let i=0; i<rootArr.length; i++){
  883. const execPath = AssetGuard.javaExecFromRoot(rootArr[i])
  884. const metaOb = await AssetGuard._validateJavaBinary(execPath)
  885. if(metaOb.valid){
  886. metaOb.execPath = execPath
  887. validArr.push(metaOb)
  888. }
  889. }
  890. return validArr
  891. }
  892. /**
  893. * Sort an array of JVM meta objects. Best candidates are placed before all others.
  894. * Sorts based on version and gives priority to JREs over JDKs if versions match.
  895. *
  896. * @param {Object[]} validArr An array of JVM meta objects.
  897. * @returns {Object[]} A sorted array of JVM meta objects.
  898. */
  899. static _sortValidJavaArray(validArr){
  900. const retArr = validArr.sort((a, b) => {
  901. // Note that Java 9+ uses semver and that will need to be accounted for in
  902. // the future.
  903. if(a.version.major === b.version.major){
  904. if(a.version.update === b.version.update){
  905. if(a.version.build === b.version.build){
  906. // Same version, give priority to JRE.
  907. if(a.execPath.toLowerCase().indexOf('jdk') > -1){
  908. return b.execPath.toLowerCase().indexOf('jdk') > -1 ? 0 : 1
  909. } else {
  910. return -1
  911. }
  912. } else {
  913. return a.version.build > b.version.build ? -1 : 1
  914. }
  915. } else {
  916. return a.version.update > b.version.update ? -1 : 1
  917. }
  918. } else {
  919. return a.version.major > b.version.major ? -1 : 1
  920. }
  921. })
  922. return retArr
  923. }
  924. /**
  925. * Attempts to find a valid x64 installation of Java on Windows machines.
  926. * Possible paths will be pulled from the registry and the JAVA_HOME environment
  927. * variable. The paths will be sorted with higher versions preceeding lower, and
  928. * JREs preceeding JDKs. The binaries at the sorted paths will then be validated.
  929. * The first validated is returned.
  930. *
  931. * Higher versions > Lower versions
  932. * If versions are equal, JRE > JDK.
  933. *
  934. * @param {string} dataDir The base launcher directory.
  935. * @returns {Promise.<string>} A Promise which resolves to the executable path of a valid
  936. * x64 Java installation. If none are found, null is returned.
  937. */
  938. static async _win32JavaValidate(dataDir){
  939. // Get possible paths from the registry.
  940. let pathSet1 = await AssetGuard._scanRegistry()
  941. if(pathSet1.length === 0){
  942. // Do a manual file system scan of program files.
  943. pathSet1 = AssetGuard._scanFileSystem('C:\\Program Files\\Java')
  944. }
  945. // Get possible paths from the data directory.
  946. const pathSet2 = await AssetGuard._scanFileSystem(path.join(dataDir, 'runtime', 'x64'))
  947. // Merge the results.
  948. const uberSet = new Set([...pathSet1, ...pathSet2])
  949. // Validate JAVA_HOME.
  950. const jHome = AssetGuard._scanJavaHome()
  951. if(jHome != null && jHome.indexOf('(x86)') === -1){
  952. uberSet.add(jHome)
  953. }
  954. let pathArr = await AssetGuard._validateJavaRootSet(uberSet)
  955. pathArr = AssetGuard._sortValidJavaArray(pathArr)
  956. if(pathArr.length > 0){
  957. return pathArr[0].execPath
  958. } else {
  959. return null
  960. }
  961. }
  962. /**
  963. * Attempts to find a valid x64 installation of Java on MacOS.
  964. * The system JVM directory is scanned for possible installations.
  965. * The JAVA_HOME enviroment variable and internet plugins directory
  966. * are also scanned and validated.
  967. *
  968. * Higher versions > Lower versions
  969. * If versions are equal, JRE > JDK.
  970. *
  971. * @param {string} dataDir The base launcher directory.
  972. * @returns {Promise.<string>} A Promise which resolves to the executable path of a valid
  973. * x64 Java installation. If none are found, null is returned.
  974. */
  975. static async _darwinJavaValidate(dataDir){
  976. const pathSet1 = await AssetGuard._scanFileSystem('/Library/Java/JavaVirtualMachines')
  977. const pathSet2 = await AssetGuard._scanFileSystem(path.join(dataDir, 'runtime', 'x64'))
  978. const uberSet = new Set([...pathSet1, ...pathSet2])
  979. // Check Internet Plugins folder.
  980. const iPPath = AssetGuard._scanInternetPlugins()
  981. if(iPPath != null){
  982. uberSet.add(iPPath)
  983. }
  984. // Check the JAVA_HOME environment variable.
  985. const jHome = AssetGuard._scanJavaHome()
  986. if(jHome != null){
  987. // Ensure we are at the absolute root.
  988. if(jHome.contains('/Contents/Home')){
  989. jHome = jHome.substring(0, jHome.indexOf('/Contents/Home'))
  990. }
  991. uberSet.add(jHome)
  992. }
  993. let pathArr = await AssetGuard._validateJavaRootSet(uberSet)
  994. pathArr = AssetGuard._sortValidJavaArray(pathArr)
  995. if(pathArr.length > 0){
  996. return pathArr[0].execPath
  997. } else {
  998. return null
  999. }
  1000. }
  1001. /**
  1002. * Attempts to find a valid x64 installation of Java on Linux.
  1003. * The system JVM directory is scanned for possible installations.
  1004. * The JAVA_HOME enviroment variable is also scanned and validated.
  1005. *
  1006. * Higher versions > Lower versions
  1007. * If versions are equal, JRE > JDK.
  1008. *
  1009. * @param {string} dataDir The base launcher directory.
  1010. * @returns {Promise.<string>} A Promise which resolves to the executable path of a valid
  1011. * x64 Java installation. If none are found, null is returned.
  1012. */
  1013. static async _linuxJavaValidate(dataDir){
  1014. const pathSet1 = await AssetGuard._scanFileSystem('/usr/lib/jvm')
  1015. const pathSet2 = await AssetGuard._scanFileSystem(path.join(dataDir, 'runtime', 'x64'))
  1016. const uberSet = new Set([...pathSet1, ...pathSet2])
  1017. // Validate JAVA_HOME
  1018. const jHome = AssetGuard._scanJavaHome()
  1019. if(jHome != null){
  1020. uberSet.add(jHome)
  1021. }
  1022. let pathArr = await AssetGuard._validateJavaRootSet(uberSet)
  1023. pathArr = AssetGuard._sortValidJavaArray(pathArr)
  1024. if(pathArr.length > 0){
  1025. return pathArr[0].execPath
  1026. } else {
  1027. return null
  1028. }
  1029. }
  1030. /**
  1031. * Retrieve the path of a valid x64 Java installation.
  1032. *
  1033. * @param {string} dataDir The base launcher directory.
  1034. * @returns {string} A path to a valid x64 Java installation, null if none found.
  1035. */
  1036. static async validateJava(dataDir){
  1037. return await AssetGuard['_' + process.platform + 'JavaValidate'](dataDir)
  1038. }
  1039. // #endregion
  1040. // #endregion
  1041. // Validation Functions
  1042. // #region
  1043. /**
  1044. * Loads the version data for a given minecraft version.
  1045. *
  1046. * @param {string} version The game version for which to load the index data.
  1047. * @param {boolean} force Optional. If true, the version index will be downloaded even if it exists locally. Defaults to false.
  1048. * @returns {Promise.<Object>} Promise which resolves to the version data object.
  1049. */
  1050. loadVersionData(version, force = false){
  1051. const self = this
  1052. return new Promise((resolve, reject) => {
  1053. const name = version + '.json'
  1054. const url = 'https://s3.amazonaws.com/Minecraft.Download/versions/' + version + '/' + name
  1055. const versionPath = path.join(self.commonPath, 'versions', version)
  1056. const versionFile = path.join(versionPath, name)
  1057. if(!fs.existsSync(versionFile) || force){
  1058. //This download will never be tracked as it's essential and trivial.
  1059. console.log('Preparing download of ' + version + ' assets.')
  1060. mkpath.sync(versionPath)
  1061. const stream = request(url).pipe(fs.createWriteStream(versionFile))
  1062. stream.on('finish', () => {
  1063. resolve(JSON.parse(fs.readFileSync(versionFile)))
  1064. })
  1065. } else {
  1066. resolve(JSON.parse(fs.readFileSync(versionFile)))
  1067. }
  1068. })
  1069. }
  1070. // Asset (Category=''') Validation Functions
  1071. // #region
  1072. /**
  1073. * Public asset validation function. This function will handle the validation of assets.
  1074. * It will parse the asset index specified in the version data, analyzing each
  1075. * asset entry. In this analysis it will check to see if the local file exists and is valid.
  1076. * If not, it will be added to the download queue for the 'assets' identifier.
  1077. *
  1078. * @param {Object} versionData The version data for the assets.
  1079. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  1080. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1081. */
  1082. validateAssets(versionData, force = false){
  1083. const self = this
  1084. return new Promise((resolve, reject) => {
  1085. self._assetChainIndexData(versionData, force).then(() => {
  1086. resolve()
  1087. })
  1088. })
  1089. }
  1090. //Chain the asset tasks to provide full async. The below functions are private.
  1091. /**
  1092. * Private function used to chain the asset validation process. This function retrieves
  1093. * the index data.
  1094. * @param {Object} versionData
  1095. * @param {boolean} force
  1096. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1097. */
  1098. _assetChainIndexData(versionData, force = false){
  1099. const self = this
  1100. return new Promise((resolve, reject) => {
  1101. //Asset index constants.
  1102. const assetIndex = versionData.assetIndex
  1103. const name = assetIndex.id + '.json'
  1104. const indexPath = path.join(self.commonPath, 'assets', 'indexes')
  1105. const assetIndexLoc = path.join(indexPath, name)
  1106. let data = null
  1107. if(!fs.existsSync(assetIndexLoc) || force){
  1108. console.log('Downloading ' + versionData.id + ' asset index.')
  1109. mkpath.sync(indexPath)
  1110. const stream = request(assetIndex.url).pipe(fs.createWriteStream(assetIndexLoc))
  1111. stream.on('finish', () => {
  1112. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  1113. self._assetChainValidateAssets(versionData, data).then(() => {
  1114. resolve()
  1115. })
  1116. })
  1117. } else {
  1118. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  1119. self._assetChainValidateAssets(versionData, data).then(() => {
  1120. resolve()
  1121. })
  1122. }
  1123. })
  1124. }
  1125. /**
  1126. * Private function used to chain the asset validation process. This function processes
  1127. * the assets and enqueues missing or invalid files.
  1128. * @param {Object} versionData
  1129. * @param {boolean} force
  1130. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1131. */
  1132. _assetChainValidateAssets(versionData, indexData){
  1133. const self = this
  1134. return new Promise((resolve, reject) => {
  1135. //Asset constants
  1136. const resourceURL = 'http://resources.download.minecraft.net/'
  1137. const localPath = path.join(self.commonPath, 'assets')
  1138. const indexPath = path.join(localPath, 'indexes')
  1139. const objectPath = path.join(localPath, 'objects')
  1140. const assetDlQueue = []
  1141. let dlSize = 0
  1142. let acc = 0
  1143. const total = Object.keys(indexData.objects).length
  1144. //const objKeys = Object.keys(data.objects)
  1145. async.forEachOfLimit(indexData.objects, 10, (value, key, cb) => {
  1146. acc++
  1147. self.emit('assetVal', {acc, total})
  1148. const hash = value.hash
  1149. const assetName = path.join(hash.substring(0, 2), hash)
  1150. const urlName = hash.substring(0, 2) + "/" + hash
  1151. const ast = new Asset(key, hash, String(value.size), resourceURL + urlName, path.join(objectPath, assetName))
  1152. if(!AssetGuard._validateLocal(ast.to, 'sha1', ast.hash)){
  1153. dlSize += (ast.size*1)
  1154. assetDlQueue.push(ast)
  1155. }
  1156. cb()
  1157. }, (err) => {
  1158. self.assets = new DLTracker(assetDlQueue, dlSize)
  1159. resolve()
  1160. })
  1161. })
  1162. }
  1163. // #endregion
  1164. // Library (Category=''') Validation Functions
  1165. // #region
  1166. /**
  1167. * Public library validation function. This function will handle the validation of libraries.
  1168. * It will parse the version data, analyzing each library entry. In this analysis, it will
  1169. * check to see if the local file exists and is valid. If not, it will be added to the download
  1170. * queue for the 'libraries' identifier.
  1171. *
  1172. * @param {Object} versionData The version data for the assets.
  1173. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1174. */
  1175. validateLibraries(versionData){
  1176. const self = this
  1177. return new Promise((resolve, reject) => {
  1178. const libArr = versionData.libraries
  1179. const libPath = path.join(self.commonPath, 'libraries')
  1180. const libDlQueue = []
  1181. let dlSize = 0
  1182. //Check validity of each library. If the hashs don't match, download the library.
  1183. async.eachLimit(libArr, 5, (lib, cb) => {
  1184. if(Library.validateRules(lib.rules)){
  1185. let artifact = (lib.natives == null) ? lib.downloads.artifact : lib.downloads.classifiers[lib.natives[Library.mojangFriendlyOS()]]
  1186. const libItm = new Library(lib.name, artifact.sha1, artifact.size, artifact.url, path.join(libPath, artifact.path))
  1187. if(!AssetGuard._validateLocal(libItm.to, 'sha1', libItm.hash)){
  1188. dlSize += (libItm.size*1)
  1189. libDlQueue.push(libItm)
  1190. }
  1191. }
  1192. cb()
  1193. }, (err) => {
  1194. self.libraries = new DLTracker(libDlQueue, dlSize)
  1195. resolve()
  1196. })
  1197. })
  1198. }
  1199. // #endregion
  1200. // Miscellaneous (Category=files) Validation Functions
  1201. // #region
  1202. /**
  1203. * Public miscellaneous mojang file validation function. These files will be enqueued under
  1204. * the 'files' identifier.
  1205. *
  1206. * @param {Object} versionData The version data for the assets.
  1207. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1208. */
  1209. validateMiscellaneous(versionData){
  1210. const self = this
  1211. return new Promise(async (resolve, reject) => {
  1212. await self.validateClient(versionData)
  1213. await self.validateLogConfig(versionData)
  1214. resolve()
  1215. })
  1216. }
  1217. /**
  1218. * Validate client file - artifact renamed from client.jar to '{version}'.jar.
  1219. *
  1220. * @param {Object} versionData The version data for the assets.
  1221. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  1222. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1223. */
  1224. validateClient(versionData, force = false){
  1225. const self = this
  1226. return new Promise((resolve, reject) => {
  1227. const clientData = versionData.downloads.client
  1228. const version = versionData.id
  1229. const targetPath = path.join(self.commonPath, 'versions', version)
  1230. const targetFile = version + '.jar'
  1231. let client = new Asset(version + ' client', clientData.sha1, clientData.size, clientData.url, path.join(targetPath, targetFile))
  1232. if(!AssetGuard._validateLocal(client.to, 'sha1', client.hash) || force){
  1233. self.files.dlqueue.push(client)
  1234. self.files.dlsize += client.size*1
  1235. resolve()
  1236. } else {
  1237. resolve()
  1238. }
  1239. })
  1240. }
  1241. /**
  1242. * Validate log config.
  1243. *
  1244. * @param {Object} versionData The version data for the assets.
  1245. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  1246. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1247. */
  1248. validateLogConfig(versionData){
  1249. const self = this
  1250. return new Promise((resolve, reject) => {
  1251. const client = versionData.logging.client
  1252. const file = client.file
  1253. const targetPath = path.join(self.commonPath, 'assets', 'log_configs')
  1254. let logConfig = new Asset(file.id, file.sha1, file.size, file.url, path.join(targetPath, file.id))
  1255. if(!AssetGuard._validateLocal(logConfig.to, 'sha1', logConfig.hash)){
  1256. self.files.dlqueue.push(logConfig)
  1257. self.files.dlsize += logConfig.size*1
  1258. resolve()
  1259. } else {
  1260. resolve()
  1261. }
  1262. })
  1263. }
  1264. // #endregion
  1265. // Distribution (Category=forge) Validation Functions
  1266. // #region
  1267. /**
  1268. * Validate the distribution.
  1269. *
  1270. * @param {string} serverpackid The id of the server to validate.
  1271. * @returns {Promise.<Object>} A promise which resolves to the server distribution object.
  1272. */
  1273. validateDistribution(serverpackid){
  1274. const self = this
  1275. return new Promise((resolve, reject) => {
  1276. AssetGuard.refreshDistributionDataLocal(self.launcherPath).then((v) => {
  1277. const serv = AssetGuard.getServerById(serverpackid)
  1278. if(serv == null) {
  1279. console.error('Invalid server pack id:', serverpackid)
  1280. }
  1281. self.forge = self._parseDistroModules(serv.modules, serv.mc_version, serv.id)
  1282. // Correct our workaround here.
  1283. let decompressqueue = self.forge.callback
  1284. self.extractQueue = decompressqueue
  1285. self.forge.callback = (asset, self) => {
  1286. if(asset.type === 'forge-hosted' || asset.type === 'forge'){
  1287. AssetGuard._finalizeForgeAsset(asset, self.commonPath)
  1288. }
  1289. }
  1290. resolve(serv)
  1291. })
  1292. })
  1293. }
  1294. _parseDistroModules(modules, version, servid){
  1295. let alist = []
  1296. let asize = 0;
  1297. let decompressqueue = []
  1298. for(let i=0; i<modules.length; i++){
  1299. let ob = modules[i]
  1300. let obType = ob.type
  1301. let obArtifact = ob.artifact
  1302. let obPath = obArtifact.path == null ? AssetGuard._resolvePath(ob.id, obArtifact.extension) : obArtifact.path
  1303. switch(obType){
  1304. case 'forge-hosted':
  1305. case 'forge':
  1306. case 'library':
  1307. obPath = path.join(this.commonPath, 'libraries', obPath)
  1308. break
  1309. case 'forgemod':
  1310. obPath = path.join(this.commonPath, 'modstore', obPath)
  1311. break
  1312. case 'litemod':
  1313. obPath = path.join(this.commonPath, 'modstore', obPath)
  1314. break
  1315. case 'file':
  1316. default:
  1317. obPath = path.join(this.instancePath, servid, obPath)
  1318. }
  1319. let artifact = new DistroModule(ob.id, obArtifact.MD5, obArtifact.size, obArtifact.url, obPath, obType)
  1320. const validationPath = obPath.toLowerCase().endsWith('.pack.xz') ? obPath.substring(0, obPath.toLowerCase().lastIndexOf('.pack.xz')) : obPath
  1321. if(!AssetGuard._validateLocal(validationPath, 'MD5', artifact.hash)){
  1322. asize += artifact.size*1
  1323. alist.push(artifact)
  1324. if(validationPath !== obPath) decompressqueue.push(obPath)
  1325. }
  1326. //Recursively process the submodules then combine the results.
  1327. if(ob.sub_modules != null){
  1328. let dltrack = this._parseDistroModules(ob.sub_modules, version, servid)
  1329. asize += dltrack.dlsize*1
  1330. alist = alist.concat(dltrack.dlqueue)
  1331. decompressqueue = decompressqueue.concat(dltrack.callback)
  1332. }
  1333. }
  1334. //Since we have no callback at this point, we use this value to store the decompressqueue.
  1335. return new DLTracker(alist, asize, decompressqueue)
  1336. }
  1337. /**
  1338. * Loads Forge's version.json data into memory for the specified server id.
  1339. *
  1340. * @param {string} serverpack The id of the server to load Forge data for.
  1341. * @returns {Promise.<Object>} A promise which resolves to Forge's version.json data.
  1342. */
  1343. loadForgeData(serverpack){
  1344. const self = this
  1345. return new Promise(async (resolve, reject) => {
  1346. let distro = AssetGuard.getDistributionData()
  1347. const servers = distro.servers
  1348. let serv = null
  1349. for(let i=0; i<servers.length; i++){
  1350. if(servers[i].id === serverpack){
  1351. serv = servers[i]
  1352. break
  1353. }
  1354. }
  1355. const modules = serv.modules
  1356. for(let i=0; i<modules.length; i++){
  1357. const ob = modules[i]
  1358. if(ob.type === 'forge-hosted' || ob.type === 'forge'){
  1359. let obArtifact = ob.artifact
  1360. let obPath = obArtifact.path == null ? path.join(self.commonPath, 'libraries', AssetGuard._resolvePath(ob.id, obArtifact.extension)) : obArtifact.path
  1361. let asset = new DistroModule(ob.id, obArtifact.MD5, obArtifact.size, obArtifact.url, obPath, ob.type)
  1362. let forgeData = await AssetGuard._finalizeForgeAsset(asset, self.commonPath)
  1363. resolve(forgeData)
  1364. return
  1365. }
  1366. }
  1367. reject('No forge module found!')
  1368. })
  1369. }
  1370. _parseForgeLibraries(){
  1371. /* TODO
  1372. * Forge asset validations are already implemented. When there's nothing much
  1373. * to work on, implement forge downloads using forge's version.json. This is to
  1374. * have the code on standby if we ever need it (since it's half implemented already).
  1375. */
  1376. }
  1377. // #endregion
  1378. // Java (Category=''') Validation (download) Functions
  1379. // #region
  1380. _enqueueOracleJRE(dataDir){
  1381. return new Promise((resolve, reject) => {
  1382. AssetGuard._latestJREOracle().then(verData => {
  1383. if(verData != null){
  1384. const combined = verData.uri + PLATFORM_MAP[process.platform]
  1385. const opts = {
  1386. url: combined,
  1387. headers: {
  1388. 'Cookie': 'oraclelicense=accept-securebackup-cookie'
  1389. }
  1390. }
  1391. request.head(opts, (err, resp, body) => {
  1392. if(err){
  1393. resolve(false)
  1394. } else {
  1395. dataDir = path.join(dataDir, 'runtime', 'x64')
  1396. const name = combined.substring(combined.lastIndexOf('/')+1)
  1397. const fDir = path.join(dataDir, name)
  1398. const jre = new Asset(name, null, resp.headers['content-length'], opts, fDir)
  1399. this.java = new DLTracker([jre], jre.size, (a, self) => {
  1400. let h = null
  1401. fs.createReadStream(a.to)
  1402. .on('error', err => console.log(err))
  1403. .pipe(zlib.createGunzip())
  1404. .on('error', err => console.log(err))
  1405. .pipe(tar.extract(dataDir, {
  1406. map: (header) => {
  1407. if(h == null){
  1408. h = header.name
  1409. }
  1410. }
  1411. }))
  1412. .on('error', err => console.log(err))
  1413. .on('finish', () => {
  1414. fs.unlink(a.to, err => {
  1415. if(err){
  1416. console.log(err)
  1417. }
  1418. if(h.indexOf('/') > -1){
  1419. h = h.substring(0, h.indexOf('/'))
  1420. }
  1421. const pos = path.join(dataDir, h)
  1422. self.emit('jExtracted', AssetGuard.javaExecFromRoot(pos))
  1423. })
  1424. })
  1425. })
  1426. resolve(true)
  1427. }
  1428. })
  1429. } else {
  1430. resolve(false)
  1431. }
  1432. })
  1433. })
  1434. }
  1435. /*_enqueueMojangJRE(dir){
  1436. return new Promise((resolve, reject) => {
  1437. // Mojang does not host the JRE for linux.
  1438. if(process.platform === 'linux'){
  1439. resolve(false)
  1440. }
  1441. AssetGuard.loadMojangLauncherData().then(data => {
  1442. if(data != null) {
  1443. try {
  1444. const mJRE = data[Library.mojangFriendlyOS()]['64'].jre
  1445. const url = mJRE.url
  1446. request.head(url, (err, resp, body) => {
  1447. if(err){
  1448. resolve(false)
  1449. } else {
  1450. const name = url.substring(url.lastIndexOf('/')+1)
  1451. const fDir = path.join(dir, name)
  1452. const jre = new Asset('jre' + mJRE.version, mJRE.sha1, resp.headers['content-length'], url, fDir)
  1453. this.java = new DLTracker([jre], jre.size, a => {
  1454. fs.readFile(a.to, (err, data) => {
  1455. // Data buffer needs to be decompressed from lzma,
  1456. // not really possible using node.js
  1457. })
  1458. })
  1459. }
  1460. })
  1461. } catch (err){
  1462. resolve(false)
  1463. }
  1464. }
  1465. })
  1466. })
  1467. }*/
  1468. // #endregion
  1469. // #endregion
  1470. // Control Flow Functions
  1471. // #region
  1472. /**
  1473. * Initiate an async download process for an AssetGuard DLTracker.
  1474. *
  1475. * @param {string} identifier The identifier of the AssetGuard DLTracker.
  1476. * @param {number} limit Optional. The number of async processes to run in parallel.
  1477. * @returns {boolean} True if the process began, otherwise false.
  1478. */
  1479. startAsyncProcess(identifier, limit = 5){
  1480. const self = this
  1481. let acc = 0
  1482. const concurrentDlTracker = this[identifier]
  1483. const concurrentDlQueue = concurrentDlTracker.dlqueue.slice(0)
  1484. if(concurrentDlQueue.length === 0){
  1485. return false
  1486. } else {
  1487. console.log('DLQueue', concurrentDlQueue)
  1488. async.eachLimit(concurrentDlQueue, limit, (asset, cb) => {
  1489. let count = 0;
  1490. mkpath.sync(path.join(asset.to, ".."))
  1491. let req = request(asset.from)
  1492. req.pause()
  1493. req.on('response', (resp) => {
  1494. if(resp.statusCode === 200){
  1495. let writeStream = fs.createWriteStream(asset.to)
  1496. writeStream.on('close', () => {
  1497. //console.log('DLResults ' + asset.size + ' ' + count + ' ', asset.size === count)
  1498. if(concurrentDlTracker.callback != null){
  1499. concurrentDlTracker.callback.apply(concurrentDlTracker, [asset, self])
  1500. }
  1501. cb()
  1502. })
  1503. req.pipe(writeStream)
  1504. req.resume()
  1505. } else {
  1506. req.abort()
  1507. const realFrom = typeof asset.from === 'object' ? asset.from.url : asset.from
  1508. console.log('Failed to download ' + realFrom + '. Response code', resp.statusCode)
  1509. self.progress += asset.size*1
  1510. self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize})
  1511. cb()
  1512. }
  1513. })
  1514. req.on('error', (err) => {
  1515. self.emit('dlerror', err)
  1516. })
  1517. req.on('data', (chunk) => {
  1518. count += chunk.length
  1519. self.progress += chunk.length
  1520. acc += chunk.length
  1521. self.emit(identifier + 'dlprogress', acc)
  1522. self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize})
  1523. })
  1524. }, (err) => {
  1525. if(err){
  1526. self.emit(identifier + 'dlerror')
  1527. console.log('An item in ' + identifier + ' failed to process');
  1528. } else {
  1529. self.emit(identifier + 'dlcomplete')
  1530. console.log('All ' + identifier + ' have been processed successfully')
  1531. }
  1532. self.totaldlsize -= self[identifier].dlsize
  1533. self.progress -= self[identifier].dlsize
  1534. self[identifier] = new DLTracker([], 0)
  1535. if(self.totaldlsize === 0) {
  1536. if(self.extractQueue.length > 0){
  1537. self.emit('extracting')
  1538. AssetGuard._extractPackXZ(self.extractQueue, self.javaexec).then(() => {
  1539. self.extractQueue = []
  1540. self.emit('dlcomplete')
  1541. })
  1542. } else {
  1543. self.emit('dlcomplete')
  1544. }
  1545. }
  1546. })
  1547. return true
  1548. }
  1549. }
  1550. /**
  1551. * This function will initiate the download processed for the specified identifiers. If no argument is
  1552. * given, all identifiers will be initiated. Note that in order for files to be processed you need to run
  1553. * the processing function corresponding to that identifier. If you run this function without processing
  1554. * the files, it is likely nothing will be enqueued in the object and processing will complete
  1555. * immediately. Once all downloads are complete, this function will fire the 'dlcomplete' event on the
  1556. * global object instance.
  1557. *
  1558. * @param {Array.<{id: string, limit: number}>} identifiers Optional. The identifiers to process and corresponding parallel async task limit.
  1559. */
  1560. processDlQueues(identifiers = [{id:'assets', limit:20}, {id:'libraries', limit:5}, {id:'files', limit:5}, {id:'forge', limit:5}]){
  1561. this.progress = 0;
  1562. let shouldFire = true
  1563. // Assign dltracking variables.
  1564. this.totaldlsize = 0
  1565. this.progress = 0
  1566. for(let i=0; i<identifiers.length; i++){
  1567. this.totaldlsize += this[identifiers[i].id].dlsize
  1568. }
  1569. for(let i=0; i<identifiers.length; i++){
  1570. let iden = identifiers[i]
  1571. let r = this.startAsyncProcess(iden.id, iden.limit)
  1572. if(r) shouldFire = false
  1573. }
  1574. if(shouldFire){
  1575. this.emit('dlcomplete')
  1576. }
  1577. }
  1578. // #endregion
  1579. }
  1580. module.exports = {
  1581. AssetGuard,
  1582. Asset,
  1583. Library
  1584. }