assetguard.js 71 KB

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