assetguard.js 62 KB

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