assetguard.js 61 KB

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