assetguard.js 72 KB

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