assetguard.js 60 KB

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