assetguard.js 67 KB

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