assetguard.js 62 KB

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