assetguard.js 70 KB

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