assetguard.js 60 KB

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