assetguard.js 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617
  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. * Parses a **full** Java Runtime version string and resolves
  558. * the version information. Uses Java 8 formatting.
  559. *
  560. * @param {string} verString Full version string to parse.
  561. * @returns Object containing the version information.
  562. */
  563. static parseJavaRuntimeVersion(verString){
  564. // 1.{major}.0_{update}-b{build}
  565. // ex. 1.8.0_152-b16
  566. const ret = {}
  567. let pts = verString.split('-')
  568. ret.build = parseInt(pts[1].substring(1))
  569. pts = verString[0].split('_')
  570. ret.update = parseInt(pts[1])
  571. ret.major = parseInt(pts[0].split['.'][1])
  572. return ret
  573. }
  574. /**
  575. * Validates the output of a JVM's properties. Currently validates that a JRE is x64
  576. * and that the major = 8, update > 52.
  577. *
  578. * @param {string} stderr The output to validate.
  579. *
  580. * @returns {Promise.<boolean>} A promise which resolves to true if the properties are valid.
  581. * Otherwise false.
  582. */
  583. static _validateJVMProperties(stderr){
  584. const res = stderr
  585. const props = res.split('\n')
  586. const goal = 2
  587. let checksum = 0
  588. for(let i=0; i<props.length; i++){
  589. if(props[i].indexOf('sun.arch.data.model') > -1){
  590. let arch = props[i].split('=')[1].trim()
  591. console.log(props[i].trim())
  592. if(parseInt(arch) === 64){
  593. ++checksum
  594. if(checksum === goal){
  595. return true
  596. }
  597. }
  598. } else if(props[i].indexOf('java.runtime.version') > -1){
  599. let verString = props[i].split('=')[1].trim()
  600. console.log(props[i].trim())
  601. const verOb = AssetGuard.parseJavaRuntimeVersion(verString)
  602. if(verOb.major === 8 && verOb.update > 52){
  603. ++checksum
  604. if(checksum === goal){
  605. return true
  606. }
  607. }
  608. }
  609. }
  610. return checksum === goal
  611. }
  612. /**
  613. * Validates that a Java binary is at least 64 bit. This makes use of the non-standard
  614. * command line option -XshowSettings:properties. The output of this contains a property,
  615. * sun.arch.data.model = ARCH, in which ARCH is either 32 or 64. This option is supported
  616. * in Java 8 and 9. Since this is a non-standard option. This will resolve to true if
  617. * the function's code throws errors. That would indicate that the option is changed or
  618. * removed.
  619. *
  620. * @param {string} binaryExecPath Path to the java executable we wish to validate.
  621. *
  622. * @returns {Promise.<boolean>} Resolves to false only if the test is successful and the result
  623. * is less than 64.
  624. */
  625. static _validateJavaBinary(binaryExecPath){
  626. return new Promise((resolve, reject) => {
  627. if(fs.existsSync(binaryExecPath)){
  628. child_process.exec('"' + binaryExecPath + '" -XshowSettings:properties', (err, stdout, stderr) => {
  629. try {
  630. // Output is stored in stderr?
  631. resolve(this._validateJVMProperties(stderr))
  632. } catch (err){
  633. // Output format might have changed, validation cannot be completed.
  634. resolve(false)
  635. }
  636. })
  637. } else {
  638. resolve(false)
  639. }
  640. })
  641. }
  642. /*static _validateJavaBinaryDarwin(binaryPath){
  643. return new Promise((resolve, reject) => {
  644. if(fs.existsSync(binaryExecPath)){
  645. child_process.exec('export JAVA_HOME="' + binaryPath + '"; java -XshowSettings:properties', (err, stdout, stderr) => {
  646. try {
  647. // Output is stored in stderr?
  648. resolve(this._validateJVMProperties(stderr))
  649. } catch (err){
  650. // Output format might have changed, validation cannot be completed.
  651. resolve(false)
  652. }
  653. })
  654. } else {
  655. resolve(false)
  656. }
  657. })
  658. }*/
  659. /**
  660. * Checks for the presence of the environment variable JAVA_HOME. If it exits, we will check
  661. * to see if the value points to a path which exists. If the path exits, the path is returned.
  662. *
  663. * @returns {string} The path defined by JAVA_HOME, if it exists. Otherwise null.
  664. */
  665. static _scanJavaHome(){
  666. const jHome = process.env.JAVA_HOME
  667. try {
  668. let res = fs.existsSync(jHome)
  669. return res ? jHome : null
  670. } catch (err) {
  671. // Malformed JAVA_HOME property.
  672. return null
  673. }
  674. }
  675. /**
  676. * Scans the data folder's runtime directory for suitable JRE candidates.
  677. *
  678. * @param {string} dataDir The base launcher directory.
  679. * @returns {Promise.<Set.<string>>} A set containing suitable JRE candidates found
  680. * in the runtime directory.
  681. */
  682. static _scanDataFolder(dataDir){
  683. return new Promise((resolve, reject) => {
  684. const x64RuntimeDir = path.join(dataDir, 'runtime', 'x64')
  685. fs.exists(x64RuntimeDir, (e) => {
  686. let res = new Set()
  687. if(e){
  688. fs.readdir(x64RuntimeDir, (err, files) => {
  689. if(err){
  690. resolve(res)
  691. console.log(err)
  692. } else {
  693. for(let i=0; i<files.length; i++){
  694. if(process.platform === 'darwin'){
  695. // On darwin, Java home is root/Contents/Home
  696. res.add(path.join(x64RuntimeDir, files[i], 'Contents', 'Home'))
  697. } else {
  698. res.add(path.join(x64RuntimeDir, files[i]))
  699. }
  700. }
  701. resolve(res)
  702. }
  703. })
  704. } else {
  705. resolve(res)
  706. }
  707. })
  708. })
  709. }
  710. /**
  711. * Scans the registry for 64-bit Java entries. The paths of each entry are added to
  712. * a set and returned. Currently, only Java 8 (1.8) is supported.
  713. *
  714. * @returns {Promise.<Set.<string>>} A promise which resolves to a set of 64-bit Java root
  715. * paths found in the registry.
  716. */
  717. static _scanRegistry(){
  718. return new Promise((resolve, reject) => {
  719. // Keys for Java v9.0.0 and later:
  720. // 'SOFTWARE\\JavaSoft\\JRE'
  721. // 'SOFTWARE\\JavaSoft\\JDK'
  722. // Forge does not yet support Java 9, therefore we do not.
  723. let cbTracker = 0
  724. let cbAcc = 0
  725. // Keys for Java 1.8 and prior:
  726. const regKeys = [
  727. '\\SOFTWARE\\JavaSoft\\Java Runtime Environment',
  728. '\\SOFTWARE\\JavaSoft\\Java Development Kit'
  729. ]
  730. const candidates = new Set()
  731. for(let i=0; i<regKeys.length; i++){
  732. const key = new Registry({
  733. hive: Registry.HKLM,
  734. key: regKeys[i],
  735. arch: 'x64'
  736. })
  737. key.keyExists((err, exists) => {
  738. if(exists) {
  739. key.keys((err, javaVers) => {
  740. if(err){
  741. console.error(err)
  742. if(i === regKeys.length-1 && cbAcc === cbTracker){
  743. resolve(candidates)
  744. }
  745. } else {
  746. cbTracker += javaVers.length
  747. if(i === regKeys.length-1 && cbTracker === cbAcc){
  748. resolve(candidates)
  749. } else {
  750. for(let j=0; j<javaVers.length; j++){
  751. const javaVer = javaVers[j]
  752. const vKey = javaVer.key.substring(javaVer.key.lastIndexOf('\\')+1)
  753. // Only Java 8 is supported currently.
  754. if(parseFloat(vKey) === 1.8){
  755. javaVer.get('JavaHome', (err, res) => {
  756. const jHome = res.value
  757. if(jHome.indexOf('(x86)') === -1){
  758. candidates.add(jHome)
  759. }
  760. cbAcc++
  761. if(i === regKeys.length-1 && cbAcc === cbTracker){
  762. resolve(candidates)
  763. }
  764. })
  765. } else {
  766. cbAcc++
  767. if(i === regKeys.length-1 && cbAcc === cbTracker){
  768. resolve(candidates)
  769. }
  770. }
  771. }
  772. }
  773. }
  774. })
  775. } else {
  776. if(i === regKeys.length-1 && cbAcc === cbTracker){
  777. resolve(candidates)
  778. }
  779. }
  780. })
  781. }
  782. })
  783. }
  784. /**
  785. * Attempts to find a valid x64 installation of Java on Windows machines.
  786. * Possible paths will be pulled from the registry and the JAVA_HOME environment
  787. * variable. The paths will be sorted with higher versions preceeding lower, and
  788. * JREs preceeding JDKs. The binaries at the sorted paths will then be validated.
  789. * The first validated is returned.
  790. *
  791. * Higher versions > Lower versions
  792. * If versions are equal, JRE > JDK.
  793. *
  794. * @param {string} dataDir The base launcher directory.
  795. * @returns {Promise.<string>} A Promise which resolves to the executable path of a valid
  796. * x64 Java installation. If none are found, null is returned.
  797. */
  798. static async _win32JavaValidate(dataDir){
  799. // Get possible paths from the registry.
  800. const pathSet = await AssetGuard._scanRegistry()
  801. //console.log(Array.from(pathSet)) // DEBUGGING
  802. // Get possible paths from the data directory.
  803. const pathSet2 = await AssetGuard._scanDataFolder(dataDir)
  804. // Validate JAVA_HOME
  805. const jHome = AssetGuard._scanJavaHome()
  806. if(jHome != null && jHome.indexOf('(x86)') === -1){
  807. pathSet.add(jHome)
  808. }
  809. const mergedSet = new Set([...pathSet, ...pathSet2])
  810. // Convert path set to an array for processing.
  811. let pathArr = Array.from(mergedSet)
  812. //console.log(pathArr) // DEBUGGING
  813. // Sorts array. Higher version numbers preceed lower. JRE preceeds JDK.
  814. pathArr = pathArr.sort((a, b) => {
  815. // Note that Java 9+ uses semver and that will need to be accounted for in
  816. // the future.
  817. const aVer = parseInt(a.split('_')[1])
  818. const bVer = parseInt(b.split('_')[1])
  819. if(bVer === aVer){
  820. return a.indexOf('jdk') > -1 ? 1 : 0
  821. } else {
  822. return bVer - aVer
  823. }
  824. })
  825. //console.log(pathArr) // DEBUGGING
  826. // Validate that the binary is actually x64.
  827. for(let i=0; i<pathArr.length; i++) {
  828. const execPath = AssetGuard.javaExecFromRoot(pathArr[i])
  829. let res = await AssetGuard._validateJavaBinary(execPath)
  830. if(res){
  831. return execPath
  832. }
  833. }
  834. // No suitable candidates found.
  835. return null;
  836. }
  837. /**
  838. * See if JRE exists in the Internet Plug-Ins folder.
  839. *
  840. * @returns {string} The path of the JRE if found, otherwise null.
  841. */
  842. static _scanInternetPlugins(){
  843. // /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java
  844. const pth = '/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home'
  845. const res = fs.existsSync(pth)
  846. return res ? pth : null
  847. }
  848. /**
  849. * WIP -> get a valid x64 Java path on macOS.
  850. */
  851. static async _darwinJavaValidate(dataDir){
  852. const pathSet = new Set()
  853. // Check Internet Plugins folder.
  854. const iPPath = AssetGuard._scanInternetPlugins()
  855. if(iPPath != null){
  856. pathSet.add(iPPath)
  857. }
  858. // Check the JAVA_HOME environment variable.
  859. const jHome = AssetGuard._scanJavaHome()
  860. if(jHome != null){
  861. pathSet.add(jHome)
  862. }
  863. // Get possible paths from the data directory.
  864. const pathSet2 = await AssetGuard._scanDataFolder(dataDir)
  865. // TODO Sort by highest version.
  866. let pathArr = Array.from(pathSet2).concat(Array.from(pathSet))
  867. for(let i=0; i<pathArr.length; i++) {
  868. const execPath = AssetGuard.javaExecFromRoot(pathArr[i])
  869. let res = await AssetGuard._validateJavaBinary(execPath)
  870. if(res){
  871. return execPath
  872. }
  873. }
  874. return null
  875. }
  876. /**
  877. * WIP -> get a valid x64 Java path on linux.
  878. */
  879. static async _linuxJavaValidate(dataDir){
  880. return null
  881. }
  882. /**
  883. * Retrieve the path of a valid x64 Java installation.
  884. *
  885. * @param {string} dataDir The base launcher directory.
  886. * @returns {string} A path to a valid x64 Java installation, null if none found.
  887. */
  888. static async validateJava(dataDir){
  889. return await AssetGuard['_' + process.platform + 'JavaValidate'](dataDir)
  890. }
  891. // #endregion
  892. // #endregion
  893. // Validation Functions
  894. // #region
  895. /**
  896. * Loads the version data for a given minecraft version.
  897. *
  898. * @param {string} version The game version for which to load the index data.
  899. * @param {boolean} force Optional. If true, the version index will be downloaded even if it exists locally. Defaults to false.
  900. * @returns {Promise.<Object>} Promise which resolves to the version data object.
  901. */
  902. loadVersionData(version, force = false){
  903. const self = this
  904. return new Promise((resolve, reject) => {
  905. const name = version + '.json'
  906. const url = 'https://s3.amazonaws.com/Minecraft.Download/versions/' + version + '/' + name
  907. const versionPath = path.join(self.basePath, 'versions', version)
  908. const versionFile = path.join(versionPath, name)
  909. if(!fs.existsSync(versionFile) || force){
  910. //This download will never be tracked as it's essential and trivial.
  911. console.log('Preparing download of ' + version + ' assets.')
  912. mkpath.sync(versionPath)
  913. const stream = request(url).pipe(fs.createWriteStream(versionFile))
  914. stream.on('finish', () => {
  915. resolve(JSON.parse(fs.readFileSync(versionFile)))
  916. })
  917. } else {
  918. resolve(JSON.parse(fs.readFileSync(versionFile)))
  919. }
  920. })
  921. }
  922. // Asset (Category=''') Validation Functions
  923. // #region
  924. /**
  925. * Public asset validation function. This function will handle the validation of assets.
  926. * It will parse the asset index specified in the version data, analyzing each
  927. * asset entry. In this analysis it will check to see if the local file exists and is valid.
  928. * If not, it will be added to the download queue for the 'assets' identifier.
  929. *
  930. * @param {Object} versionData The version data for the assets.
  931. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  932. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  933. */
  934. validateAssets(versionData, force = false){
  935. const self = this
  936. return new Promise(function(fulfill, reject){
  937. self._assetChainIndexData(versionData, force).then(() => {
  938. fulfill()
  939. })
  940. })
  941. }
  942. //Chain the asset tasks to provide full async. The below functions are private.
  943. /**
  944. * Private function used to chain the asset validation process. This function retrieves
  945. * the index data.
  946. * @param {Object} versionData
  947. * @param {boolean} force
  948. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  949. */
  950. _assetChainIndexData(versionData, force = false){
  951. const self = this
  952. return new Promise(function(fulfill, reject){
  953. //Asset index constants.
  954. const assetIndex = versionData.assetIndex
  955. const name = assetIndex.id + '.json'
  956. const indexPath = path.join(self.basePath, 'assets', 'indexes')
  957. const assetIndexLoc = path.join(indexPath, name)
  958. let data = null
  959. if(!fs.existsSync(assetIndexLoc) || force){
  960. console.log('Downloading ' + versionData.id + ' asset index.')
  961. mkpath.sync(indexPath)
  962. const stream = request(assetIndex.url).pipe(fs.createWriteStream(assetIndexLoc))
  963. stream.on('finish', function() {
  964. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  965. self._assetChainValidateAssets(versionData, data).then(() => {
  966. fulfill()
  967. })
  968. })
  969. } else {
  970. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  971. self._assetChainValidateAssets(versionData, data).then(() => {
  972. fulfill()
  973. })
  974. }
  975. })
  976. }
  977. /**
  978. * Private function used to chain the asset validation process. This function processes
  979. * the assets and enqueues missing or invalid files.
  980. * @param {Object} versionData
  981. * @param {boolean} force
  982. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  983. */
  984. _assetChainValidateAssets(versionData, indexData){
  985. const self = this
  986. return new Promise(function(fulfill, reject){
  987. //Asset constants
  988. const resourceURL = 'http://resources.download.minecraft.net/'
  989. const localPath = path.join(self.basePath, 'assets')
  990. const indexPath = path.join(localPath, 'indexes')
  991. const objectPath = path.join(localPath, 'objects')
  992. const assetDlQueue = []
  993. let dlSize = 0
  994. let acc = 0
  995. const total = Object.keys(indexData.objects).length
  996. //const objKeys = Object.keys(data.objects)
  997. async.forEachOfLimit(indexData.objects, 10, function(value, key, cb){
  998. acc++
  999. self.emit('assetVal', {acc, total})
  1000. const hash = value.hash
  1001. const assetName = path.join(hash.substring(0, 2), hash)
  1002. const urlName = hash.substring(0, 2) + "/" + hash
  1003. const ast = new Asset(key, hash, String(value.size), resourceURL + urlName, path.join(objectPath, assetName))
  1004. if(!AssetGuard._validateLocal(ast.to, 'sha1', ast.hash)){
  1005. dlSize += (ast.size*1)
  1006. assetDlQueue.push(ast)
  1007. }
  1008. cb()
  1009. }, function(err){
  1010. self.assets = new DLTracker(assetDlQueue, dlSize)
  1011. fulfill()
  1012. })
  1013. })
  1014. }
  1015. // #endregion
  1016. // Library (Category=''') Validation Functions
  1017. // #region
  1018. /**
  1019. * Public library validation function. This function will handle the validation of libraries.
  1020. * It will parse the version data, analyzing each library entry. In this analysis, it will
  1021. * check to see if the local file exists and is valid. If not, it will be added to the download
  1022. * queue for the 'libraries' identifier.
  1023. *
  1024. * @param {Object} versionData The version data for the assets.
  1025. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1026. */
  1027. validateLibraries(versionData){
  1028. const self = this
  1029. return new Promise(function(fulfill, reject){
  1030. const libArr = versionData.libraries
  1031. const libPath = path.join(self.basePath, 'libraries')
  1032. const libDlQueue = []
  1033. let dlSize = 0
  1034. //Check validity of each library. If the hashs don't match, download the library.
  1035. async.eachLimit(libArr, 5, function(lib, cb){
  1036. if(Library.validateRules(lib.rules)){
  1037. let artifact = (lib.natives == null) ? lib.downloads.artifact : lib.downloads.classifiers[lib.natives[Library.mojangFriendlyOS()]]
  1038. const libItm = new Library(lib.name, artifact.sha1, artifact.size, artifact.url, path.join(libPath, artifact.path))
  1039. if(!AssetGuard._validateLocal(libItm.to, 'sha1', libItm.hash)){
  1040. dlSize += (libItm.size*1)
  1041. libDlQueue.push(libItm)
  1042. }
  1043. }
  1044. cb()
  1045. }, function(err){
  1046. self.libraries = new DLTracker(libDlQueue, dlSize)
  1047. fulfill()
  1048. })
  1049. })
  1050. }
  1051. // #endregion
  1052. // Miscellaneous (Category=files) Validation Functions
  1053. // #region
  1054. /**
  1055. * Public miscellaneous mojang file validation function. These files will be enqueued under
  1056. * the 'files' identifier.
  1057. *
  1058. * @param {Object} versionData The version data for the assets.
  1059. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1060. */
  1061. validateMiscellaneous(versionData){
  1062. const self = this
  1063. return new Promise(async function(fulfill, reject){
  1064. await self.validateClient(versionData)
  1065. await self.validateLogConfig(versionData)
  1066. fulfill()
  1067. })
  1068. }
  1069. /**
  1070. * Validate client file - artifact renamed from client.jar to '{version}'.jar.
  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. validateClient(versionData, force = false){
  1077. const self = this
  1078. return new Promise(function(fulfill, reject){
  1079. const clientData = versionData.downloads.client
  1080. const version = versionData.id
  1081. const targetPath = path.join(self.basePath, 'versions', version)
  1082. const targetFile = version + '.jar'
  1083. let client = new Asset(version + ' client', clientData.sha1, clientData.size, clientData.url, path.join(targetPath, targetFile))
  1084. if(!AssetGuard._validateLocal(client.to, 'sha1', client.hash) || force){
  1085. self.files.dlqueue.push(client)
  1086. self.files.dlsize += client.size*1
  1087. fulfill()
  1088. } else {
  1089. fulfill()
  1090. }
  1091. })
  1092. }
  1093. /**
  1094. * Validate log config.
  1095. *
  1096. * @param {Object} versionData The version data for the assets.
  1097. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  1098. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1099. */
  1100. validateLogConfig(versionData){
  1101. const self = this
  1102. return new Promise(function(fulfill, reject){
  1103. const client = versionData.logging.client
  1104. const file = client.file
  1105. const targetPath = path.join(self.basePath, 'assets', 'log_configs')
  1106. let logConfig = new Asset(file.id, file.sha1, file.size, file.url, path.join(targetPath, file.id))
  1107. if(!AssetGuard._validateLocal(logConfig.to, 'sha1', logConfig.hash)){
  1108. self.files.dlqueue.push(logConfig)
  1109. self.files.dlsize += logConfig.size*1
  1110. fulfill()
  1111. } else {
  1112. fulfill()
  1113. }
  1114. })
  1115. }
  1116. // #endregion
  1117. // Distribution (Category=forge) Validation Functions
  1118. // #region
  1119. /**
  1120. * Validate the distribution.
  1121. *
  1122. * @param {string} serverpackid The id of the server to validate.
  1123. * @returns {Promise.<Object>} A promise which resolves to the server distribution object.
  1124. */
  1125. validateDistribution(serverpackid){
  1126. const self = this
  1127. return new Promise(function(fulfill, reject){
  1128. AssetGuard.retrieveDistributionData(self.basePath, false).then((value) => {
  1129. /*const servers = value.servers
  1130. let serv = null
  1131. for(let i=0; i<servers.length; i++){
  1132. if(servers[i].id === serverpackid){
  1133. serv = servers[i]
  1134. break
  1135. }
  1136. }*/
  1137. const serv = AssetGuard.getServerById(self.basePath, serverpackid)
  1138. if(serv == null) {
  1139. console.error('Invalid server pack id:', serverpackid)
  1140. }
  1141. self.forge = self._parseDistroModules(serv.modules, serv.mc_version)
  1142. //Correct our workaround here.
  1143. let decompressqueue = self.forge.callback
  1144. self.forge.callback = function(asset, self){
  1145. if(asset.to.toLowerCase().endsWith('.pack.xz')){
  1146. AssetGuard._extractPackXZ([asset.to], self.javaexec)
  1147. }
  1148. if(asset.type === 'forge-hosted' || asset.type === 'forge'){
  1149. AssetGuard._finalizeForgeAsset(asset, self.basePath)
  1150. }
  1151. }
  1152. fulfill(serv)
  1153. })
  1154. })
  1155. }
  1156. /*//TODO The file should be hosted, the following code is for local testing.
  1157. _chainValidateDistributionIndex(basePath){
  1158. return new Promise(function(fulfill, reject){
  1159. //const distroURL = 'http://mc.westeroscraft.com/WesterosCraftLauncher/westeroscraft.json'
  1160. //const targetFile = path.join(basePath, 'westeroscraft.json')
  1161. //TEMP WORKAROUND TO TEST WHILE THIS IS NOT HOSTED
  1162. fs.readFile(path.join(__dirname, '..', 'westeroscraft.json'), 'utf-8', (err, data) => {
  1163. fulfill(JSON.parse(data))
  1164. })
  1165. })
  1166. }*/
  1167. _parseDistroModules(modules, version){
  1168. let alist = []
  1169. let asize = 0;
  1170. //This may be removed soon, considering the most efficient way to extract.
  1171. let decompressqueue = []
  1172. for(let i=0; i<modules.length; i++){
  1173. let ob = modules[i]
  1174. let obType = ob.type
  1175. let obArtifact = ob.artifact
  1176. let obPath = obArtifact.path == null ? AssetGuard._resolvePath(ob.id, obArtifact.extension) : obArtifact.path
  1177. switch(obType){
  1178. case 'forge-hosted':
  1179. case 'forge':
  1180. case 'library':
  1181. obPath = path.join(this.basePath, 'libraries', obPath)
  1182. break
  1183. case 'forgemod':
  1184. //obPath = path.join(this.basePath, 'mods', obPath)
  1185. obPath = path.join(this.basePath, 'modstore', obPath)
  1186. break
  1187. case 'litemod':
  1188. //obPath = path.join(this.basePath, 'mods', version, obPath)
  1189. obPath = path.join(this.basePath, 'modstore', obPath)
  1190. break
  1191. case 'file':
  1192. default:
  1193. obPath = path.join(this.basePath, obPath)
  1194. }
  1195. let artifact = new DistroModule(ob.id, obArtifact.MD5, obArtifact.size, obArtifact.url, obPath, obType)
  1196. const validationPath = obPath.toLowerCase().endsWith('.pack.xz') ? obPath.substring(0, obPath.toLowerCase().lastIndexOf('.pack.xz')) : obPath
  1197. if(!AssetGuard._validateLocal(validationPath, 'MD5', artifact.hash)){
  1198. asize += artifact.size*1
  1199. alist.push(artifact)
  1200. if(validationPath !== obPath) decompressqueue.push(obPath)
  1201. }
  1202. //Recursively process the submodules then combine the results.
  1203. if(ob.sub_modules != null){
  1204. let dltrack = this._parseDistroModules(ob.sub_modules, version)
  1205. asize += dltrack.dlsize*1
  1206. alist = alist.concat(dltrack.dlqueue)
  1207. decompressqueue = decompressqueue.concat(dltrack.callback)
  1208. }
  1209. }
  1210. //Since we have no callback at this point, we use this value to store the decompressqueue.
  1211. return new DLTracker(alist, asize, decompressqueue)
  1212. }
  1213. /**
  1214. * Loads Forge's version.json data into memory for the specified server id.
  1215. *
  1216. * @param {string} serverpack The id of the server to load Forge data for.
  1217. * @returns {Promise.<Object>} A promise which resolves to Forge's version.json data.
  1218. */
  1219. loadForgeData(serverpack){
  1220. const self = this
  1221. return new Promise(async function(fulfill, reject){
  1222. let distro = AssetGuard.retrieveDistributionDataSync(self.basePath)
  1223. const servers = distro.servers
  1224. let serv = null
  1225. for(let i=0; i<servers.length; i++){
  1226. if(servers[i].id === serverpack){
  1227. serv = servers[i]
  1228. break
  1229. }
  1230. }
  1231. const modules = serv.modules
  1232. for(let i=0; i<modules.length; i++){
  1233. const ob = modules[i]
  1234. if(ob.type === 'forge-hosted' || ob.type === 'forge'){
  1235. let obArtifact = ob.artifact
  1236. let obPath = obArtifact.path == null ? path.join(self.basePath, 'libraries', AssetGuard._resolvePath(ob.id, obArtifact.extension)) : obArtifact.path
  1237. let asset = new DistroModule(ob.id, obArtifact.MD5, obArtifact.size, obArtifact.url, obPath, ob.type)
  1238. let forgeData = await AssetGuard._finalizeForgeAsset(asset, self.basePath)
  1239. fulfill(forgeData)
  1240. return
  1241. }
  1242. }
  1243. reject('No forge module found!')
  1244. })
  1245. }
  1246. _parseForgeLibraries(){
  1247. /* TODO
  1248. * Forge asset validations are already implemented. When there's nothing much
  1249. * to work on, implement forge downloads using forge's version.json. This is to
  1250. * have the code on standby if we ever need it (since it's half implemented already).
  1251. */
  1252. }
  1253. // #endregion
  1254. // Java (Category=''') Validation (download) Functions
  1255. // #region
  1256. _enqueueOracleJRE(dataDir){
  1257. return new Promise((resolve, reject) => {
  1258. AssetGuard._latestJREOracle().then(verData => {
  1259. if(verData != null){
  1260. const combined = verData.uri + PLATFORM_MAP[process.platform]
  1261. const opts = {
  1262. url: combined,
  1263. headers: {
  1264. 'Cookie': 'oraclelicense=accept-securebackup-cookie'
  1265. }
  1266. }
  1267. request.head(opts, (err, resp, body) => {
  1268. if(err){
  1269. resolve(false)
  1270. } else {
  1271. dataDir = path.join(dataDir, 'runtime', 'x64')
  1272. const name = combined.substring(combined.lastIndexOf('/')+1)
  1273. const fDir = path.join(dataDir, name)
  1274. const jre = new Asset(name, null, resp.headers['content-length'], opts, fDir)
  1275. this.java = new DLTracker([jre], jre.size, (a, self) => {
  1276. let h = null
  1277. fs.createReadStream(a.to)
  1278. .on('error', err => console.log(err))
  1279. .pipe(zlib.createGunzip())
  1280. .on('error', err => console.log(err))
  1281. .pipe(tar.extract(dataDir, {
  1282. map: (header) => {
  1283. if(h == null){
  1284. h = header.name
  1285. }
  1286. }
  1287. }))
  1288. .on('error', err => console.log(err))
  1289. .on('finish', () => {
  1290. fs.unlink(a.to, err => {
  1291. if(err){
  1292. console.log(err)
  1293. }
  1294. if(h.indexOf('/') > -1){
  1295. h = h.substring(0, h.indexOf('/'))
  1296. }
  1297. const pos = path.join(dataDir, h)
  1298. self.emit('jExtracted', AssetGuard.javaExecFromRoot(pos))
  1299. })
  1300. })
  1301. })
  1302. resolve(true)
  1303. }
  1304. })
  1305. } else {
  1306. resolve(false)
  1307. }
  1308. })
  1309. })
  1310. }
  1311. /*_enqueueMojangJRE(dir){
  1312. return new Promise((resolve, reject) => {
  1313. // Mojang does not host the JRE for linux.
  1314. if(process.platform === 'linux'){
  1315. resolve(false)
  1316. }
  1317. AssetGuard.loadMojangLauncherData().then(data => {
  1318. if(data != null) {
  1319. try {
  1320. const mJRE = data[Library.mojangFriendlyOS()]['64'].jre
  1321. const url = mJRE.url
  1322. request.head(url, (err, resp, body) => {
  1323. if(err){
  1324. resolve(false)
  1325. } else {
  1326. const name = url.substring(url.lastIndexOf('/')+1)
  1327. const fDir = path.join(dir, name)
  1328. const jre = new Asset('jre' + mJRE.version, mJRE.sha1, resp.headers['content-length'], url, fDir)
  1329. this.java = new DLTracker([jre], jre.size, a => {
  1330. fs.readFile(a.to, (err, data) => {
  1331. // Data buffer needs to be decompressed from lzma,
  1332. // not really possible using node.js
  1333. })
  1334. })
  1335. }
  1336. })
  1337. } catch (err){
  1338. resolve(false)
  1339. }
  1340. }
  1341. })
  1342. })
  1343. }*/
  1344. // #endregion
  1345. // #endregion
  1346. // Control Flow Functions
  1347. // #region
  1348. /**
  1349. * Initiate an async download process for an AssetGuard DLTracker.
  1350. *
  1351. * @param {string} identifier The identifier of the AssetGuard DLTracker.
  1352. * @param {number} limit Optional. The number of async processes to run in parallel.
  1353. * @returns {boolean} True if the process began, otherwise false.
  1354. */
  1355. startAsyncProcess(identifier, limit = 5){
  1356. const self = this
  1357. let acc = 0
  1358. const concurrentDlTracker = this[identifier]
  1359. const concurrentDlQueue = concurrentDlTracker.dlqueue.slice(0)
  1360. if(concurrentDlQueue.length === 0){
  1361. return false
  1362. } else {
  1363. async.eachLimit(concurrentDlQueue, limit, function(asset, cb){
  1364. let count = 0;
  1365. mkpath.sync(path.join(asset.to, ".."))
  1366. let req = request(asset.from)
  1367. req.pause()
  1368. req.on('response', (resp) => {
  1369. if(resp.statusCode === 200){
  1370. let writeStream = fs.createWriteStream(asset.to)
  1371. writeStream.on('close', () => {
  1372. //console.log('DLResults ' + asset.size + ' ' + count + ' ', asset.size === count)
  1373. if(concurrentDlTracker.callback != null){
  1374. concurrentDlTracker.callback.apply(concurrentDlTracker, [asset, self])
  1375. }
  1376. cb()
  1377. })
  1378. req.pipe(writeStream)
  1379. req.resume()
  1380. } else {
  1381. req.abort()
  1382. const realFrom = typeof asset.from === 'object' ? asset.from.url : asset.from
  1383. console.log('Failed to download ' + realFrom + '. Response code', resp.statusCode)
  1384. self.progress += asset.size*1
  1385. self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize})
  1386. cb()
  1387. }
  1388. })
  1389. req.on('data', function(chunk){
  1390. count += chunk.length
  1391. self.progress += chunk.length
  1392. acc += chunk.length
  1393. self.emit(identifier + 'dlprogress', acc)
  1394. self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize})
  1395. })
  1396. }, function(err){
  1397. if(err){
  1398. self.emit(identifier + 'dlerror')
  1399. console.log('An item in ' + identifier + ' failed to process');
  1400. } else {
  1401. self.emit(identifier + 'dlcomplete')
  1402. console.log('All ' + identifier + ' have been processed successfully')
  1403. }
  1404. self.totaldlsize -= self[identifier].dlsize
  1405. self.progress -= self[identifier].dlsize
  1406. self[identifier] = new DLTracker([], 0)
  1407. if(self.totaldlsize === 0) {
  1408. self.emit('dlcomplete')
  1409. }
  1410. })
  1411. return true
  1412. }
  1413. }
  1414. /**
  1415. * This function will initiate the download processed for the specified identifiers. If no argument is
  1416. * given, all identifiers will be initiated. Note that in order for files to be processed you need to run
  1417. * the processing function corresponding to that identifier. If you run this function without processing
  1418. * the files, it is likely nothing will be enqueued in the object and processing will complete
  1419. * immediately. Once all downloads are complete, this function will fire the 'dlcomplete' event on the
  1420. * global object instance.
  1421. *
  1422. * @param {Array.<{id: string, limit: number}>} identifiers Optional. The identifiers to process and corresponding parallel async task limit.
  1423. */
  1424. processDlQueues(identifiers = [{id:'assets', limit:20}, {id:'libraries', limit:5}, {id:'files', limit:5}, {id:'forge', limit:5}]){
  1425. this.progress = 0;
  1426. let shouldFire = true
  1427. // Assign dltracking variables.
  1428. this.totaldlsize = 0
  1429. this.progress = 0
  1430. for(let i=0; i<identifiers.length; i++){
  1431. this.totaldlsize += this[identifiers[i].id].dlsize
  1432. }
  1433. for(let i=0; i<identifiers.length; i++){
  1434. let iden = identifiers[i]
  1435. let r = this.startAsyncProcess(iden.id, iden.limit)
  1436. if(r) shouldFire = false
  1437. }
  1438. if(shouldFire){
  1439. this.emit('dlcomplete')
  1440. }
  1441. }
  1442. // #endregion
  1443. }
  1444. module.exports = {
  1445. AssetGuard,
  1446. Asset,
  1447. Library
  1448. }