assetguard.js 61 KB

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