assetguard.js 70 KB

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