assetguard.js 63 KB

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