assetguard.js 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973
  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 _scanFileSystem(scanDir){
  627. return new Promise((resolve, reject) => {
  628. fs.exists(scanDir, (e) => {
  629. let res = new Set()
  630. if(e){
  631. fs.readdir(scanDir, (err, files) => {
  632. if(err){
  633. resolve(res)
  634. console.log(err)
  635. } else {
  636. let pathsDone = 0
  637. for(let i=0; i<files.length; i++){
  638. const combinedPath = path.join(scanDir, files[i])
  639. const execPath = JavaGuard.javaExecFromRoot(combinedPath)
  640. fs.exists(execPath, (v) => {
  641. if(v){
  642. res.add(combinedPath)
  643. }
  644. ++pathsDone
  645. if(pathsDone === files.length){
  646. resolve(res)
  647. }
  648. })
  649. }
  650. if(pathsDone === files.length){
  651. resolve(res)
  652. }
  653. }
  654. })
  655. } else {
  656. resolve(res)
  657. }
  658. })
  659. })
  660. }
  661. /**
  662. *
  663. * @param {Set.<string>} rootSet A set of JVM root strings to validate.
  664. * @returns {Promise.<Object[]>} A promise which resolves to an array of meta objects
  665. * for each valid JVM root directory.
  666. */
  667. async _validateJavaRootSet(rootSet){
  668. const rootArr = Array.from(rootSet)
  669. const validArr = []
  670. for(let i=0; i<rootArr.length; i++){
  671. const execPath = JavaGuard.javaExecFromRoot(rootArr[i])
  672. const metaOb = await this._validateJavaBinary(execPath)
  673. if(metaOb.valid){
  674. metaOb.execPath = execPath
  675. validArr.push(metaOb)
  676. }
  677. }
  678. return validArr
  679. }
  680. /**
  681. * Sort an array of JVM meta objects. Best candidates are placed before all others.
  682. * Sorts based on version and gives priority to JREs over JDKs if versions match.
  683. *
  684. * @param {Object[]} validArr An array of JVM meta objects.
  685. * @returns {Object[]} A sorted array of JVM meta objects.
  686. */
  687. static _sortValidJavaArray(validArr){
  688. const retArr = validArr.sort((a, b) => {
  689. if(a.version.major === b.version.major){
  690. if(a.version.major < 9){
  691. // Java 8
  692. if(a.version.update === b.version.update){
  693. if(a.version.build === b.version.build){
  694. // Same version, give priority to JRE.
  695. if(a.execPath.toLowerCase().indexOf('jdk') > -1){
  696. return b.execPath.toLowerCase().indexOf('jdk') > -1 ? 0 : 1
  697. } else {
  698. return -1
  699. }
  700. } else {
  701. return a.version.build > b.version.build ? -1 : 1
  702. }
  703. } else {
  704. return a.version.update > b.version.update ? -1 : 1
  705. }
  706. } else {
  707. // Java 9+
  708. if(a.version.minor === b.version.minor){
  709. if(a.version.revision === b.version.revision){
  710. // Same version, give priority to JRE.
  711. if(a.execPath.toLowerCase().indexOf('jdk') > -1){
  712. return b.execPath.toLowerCase().indexOf('jdk') > -1 ? 0 : 1
  713. } else {
  714. return -1
  715. }
  716. } else {
  717. return a.version.revision > b.version.revision ? -1 : 1
  718. }
  719. } else {
  720. return a.version.minor > b.version.minor ? -1 : 1
  721. }
  722. }
  723. } else {
  724. return a.version.major > b.version.major ? -1 : 1
  725. }
  726. })
  727. return retArr
  728. }
  729. /**
  730. * Attempts to find a valid x64 installation of Java on Windows machines.
  731. * Possible paths will be pulled from the registry and the JAVA_HOME environment
  732. * variable. The paths will be sorted with higher versions preceeding lower, and
  733. * JREs preceeding JDKs. The binaries at the sorted paths will then be validated.
  734. * The first validated is returned.
  735. *
  736. * Higher versions > Lower versions
  737. * If versions are equal, JRE > JDK.
  738. *
  739. * @param {string} dataDir The base launcher directory.
  740. * @returns {Promise.<string>} A Promise which resolves to the executable path of a valid
  741. * x64 Java installation. If none are found, null is returned.
  742. */
  743. async _win32JavaValidate(dataDir){
  744. // Get possible paths from the registry.
  745. let pathSet1 = await JavaGuard._scanRegistry()
  746. if(pathSet1.length === 0){
  747. // Do a manual file system scan of program files.
  748. pathSet1 = JavaGuard._scanFileSystem('C:\\Program Files\\Java')
  749. }
  750. // Get possible paths from the data directory.
  751. const pathSet2 = await JavaGuard._scanFileSystem(path.join(dataDir, 'runtime', 'x64'))
  752. // Merge the results.
  753. const uberSet = new Set([...pathSet1, ...pathSet2])
  754. // Validate JAVA_HOME.
  755. const jHome = JavaGuard._scanJavaHome()
  756. if(jHome != null && jHome.indexOf('(x86)') === -1){
  757. uberSet.add(jHome)
  758. }
  759. let pathArr = await this._validateJavaRootSet(uberSet)
  760. pathArr = JavaGuard._sortValidJavaArray(pathArr)
  761. if(pathArr.length > 0){
  762. return pathArr[0].execPath
  763. } else {
  764. return null
  765. }
  766. }
  767. /**
  768. * Attempts to find a valid x64 installation of Java on MacOS.
  769. * The system JVM directory is scanned for possible installations.
  770. * The JAVA_HOME enviroment variable and internet plugins directory
  771. * are also scanned and validated.
  772. *
  773. * Higher versions > Lower versions
  774. * If versions are equal, JRE > JDK.
  775. *
  776. * @param {string} dataDir The base launcher directory.
  777. * @returns {Promise.<string>} A Promise which resolves to the executable path of a valid
  778. * x64 Java installation. If none are found, null is returned.
  779. */
  780. async _darwinJavaValidate(dataDir){
  781. const pathSet1 = await JavaGuard._scanFileSystem('/Library/Java/JavaVirtualMachines')
  782. const pathSet2 = await JavaGuard._scanFileSystem(path.join(dataDir, 'runtime', 'x64'))
  783. const uberSet = new Set([...pathSet1, ...pathSet2])
  784. // Check Internet Plugins folder.
  785. const iPPath = JavaGuard._scanInternetPlugins()
  786. if(iPPath != null){
  787. uberSet.add(iPPath)
  788. }
  789. // Check the JAVA_HOME environment variable.
  790. let jHome = JavaGuard._scanJavaHome()
  791. if(jHome != null){
  792. // Ensure we are at the absolute root.
  793. if(jHome.contains('/Contents/Home')){
  794. jHome = jHome.substring(0, jHome.indexOf('/Contents/Home'))
  795. }
  796. uberSet.add(jHome)
  797. }
  798. let pathArr = await this._validateJavaRootSet(uberSet)
  799. pathArr = JavaGuard._sortValidJavaArray(pathArr)
  800. if(pathArr.length > 0){
  801. return pathArr[0].execPath
  802. } else {
  803. return null
  804. }
  805. }
  806. /**
  807. * Attempts to find a valid x64 installation of Java on Linux.
  808. * The system JVM directory is scanned for possible installations.
  809. * The JAVA_HOME enviroment variable is also scanned and validated.
  810. *
  811. * Higher versions > Lower versions
  812. * If versions are equal, JRE > JDK.
  813. *
  814. * @param {string} dataDir The base launcher directory.
  815. * @returns {Promise.<string>} A Promise which resolves to the executable path of a valid
  816. * x64 Java installation. If none are found, null is returned.
  817. */
  818. async _linuxJavaValidate(dataDir){
  819. const pathSet1 = await JavaGuard._scanFileSystem('/usr/lib/jvm')
  820. const pathSet2 = await JavaGuard._scanFileSystem(path.join(dataDir, 'runtime', 'x64'))
  821. const uberSet = new Set([...pathSet1, ...pathSet2])
  822. // Validate JAVA_HOME
  823. const jHome = JavaGuard._scanJavaHome()
  824. if(jHome != null){
  825. uberSet.add(jHome)
  826. }
  827. let pathArr = await this._validateJavaRootSet(uberSet)
  828. pathArr = JavaGuard._sortValidJavaArray(pathArr)
  829. if(pathArr.length > 0){
  830. return pathArr[0].execPath
  831. } else {
  832. return null
  833. }
  834. }
  835. /**
  836. * Retrieve the path of a valid x64 Java installation.
  837. *
  838. * @param {string} dataDir The base launcher directory.
  839. * @returns {string} A path to a valid x64 Java installation, null if none found.
  840. */
  841. async validateJava(dataDir){
  842. return await this['_' + process.platform + 'JavaValidate'](dataDir)
  843. }
  844. }
  845. /**
  846. * Central object class used for control flow. This object stores data about
  847. * categories of downloads. Each category is assigned an identifier with a
  848. * DLTracker object as its value. Combined information is also stored, such as
  849. * the total size of all the queued files in each category. This event is used
  850. * to emit events so that external modules can listen into processing done in
  851. * this module.
  852. */
  853. class AssetGuard extends EventEmitter {
  854. /**
  855. * Create an instance of AssetGuard.
  856. * On creation the object's properties are never-null default
  857. * values. Each identifier is resolved to an empty DLTracker.
  858. *
  859. * @param {string} commonPath The common path for shared game files.
  860. * @param {string} javaexec The path to a java executable which will be used
  861. * to finalize installation.
  862. */
  863. constructor(commonPath, javaexec){
  864. super()
  865. this.totaldlsize = 0
  866. this.progress = 0
  867. this.assets = new DLTracker([], 0)
  868. this.libraries = new DLTracker([], 0)
  869. this.files = new DLTracker([], 0)
  870. this.forge = new DLTracker([], 0)
  871. this.java = new DLTracker([], 0)
  872. this.extractQueue = []
  873. this.commonPath = commonPath
  874. this.javaexec = javaexec
  875. }
  876. // Static Utility Functions
  877. // #region
  878. // Static Hash Validation Functions
  879. // #region
  880. /**
  881. * Calculates the hash for a file using the specified algorithm.
  882. *
  883. * @param {Buffer} buf The buffer containing file data.
  884. * @param {string} algo The hash algorithm.
  885. * @returns {string} The calculated hash in hex.
  886. */
  887. static _calculateHash(buf, algo){
  888. return crypto.createHash(algo).update(buf).digest('hex')
  889. }
  890. /**
  891. * Used to parse a checksums file. This is specifically designed for
  892. * the checksums.sha1 files found inside the forge scala dependencies.
  893. *
  894. * @param {string} content The string content of the checksums file.
  895. * @returns {Object} An object with keys being the file names, and values being the hashes.
  896. */
  897. static _parseChecksumsFile(content){
  898. let finalContent = {}
  899. let lines = content.split('\n')
  900. for(let i=0; i<lines.length; i++){
  901. let bits = lines[i].split(' ')
  902. if(bits[1] == null) {
  903. continue
  904. }
  905. finalContent[bits[1]] = bits[0]
  906. }
  907. return finalContent
  908. }
  909. /**
  910. * Validate that a file exists and matches a given hash value.
  911. *
  912. * @param {string} filePath The path of the file to validate.
  913. * @param {string} algo The hash algorithm to check against.
  914. * @param {string} hash The existing hash to check against.
  915. * @returns {boolean} True if the file exists and calculated hash matches the given hash, otherwise false.
  916. */
  917. static _validateLocal(filePath, algo, hash){
  918. if(fs.existsSync(filePath)){
  919. //No hash provided, have to assume it's good.
  920. if(hash == null){
  921. return true
  922. }
  923. let buf = fs.readFileSync(filePath)
  924. let calcdhash = AssetGuard._calculateHash(buf, algo)
  925. return calcdhash === hash.toLowerCase()
  926. }
  927. return false
  928. }
  929. /**
  930. * Validates a file in the style used by forge's version index.
  931. *
  932. * @param {string} filePath The path of the file to validate.
  933. * @param {Array.<string>} checksums The checksums listed in the forge version index.
  934. * @returns {boolean} True if the file exists and the hashes match, otherwise false.
  935. */
  936. static _validateForgeChecksum(filePath, checksums){
  937. if(fs.existsSync(filePath)){
  938. if(checksums == null || checksums.length === 0){
  939. return true
  940. }
  941. let buf = fs.readFileSync(filePath)
  942. let calcdhash = AssetGuard._calculateHash(buf, 'sha1')
  943. let valid = checksums.includes(calcdhash)
  944. if(!valid && filePath.endsWith('.jar')){
  945. valid = AssetGuard._validateForgeJar(filePath, checksums)
  946. }
  947. return valid
  948. }
  949. return false
  950. }
  951. /**
  952. * Validates a forge jar file dependency who declares a checksums.sha1 file.
  953. * This can be an expensive task as it usually requires that we calculate thousands
  954. * of hashes.
  955. *
  956. * @param {Buffer} buf The buffer of the jar file.
  957. * @param {Array.<string>} checksums The checksums listed in the forge version index.
  958. * @returns {boolean} True if all hashes declared in the checksums.sha1 file match the actual hashes.
  959. */
  960. static _validateForgeJar(buf, checksums){
  961. // Double pass method was the quickest I found. I tried a version where we store data
  962. // to only require a single pass, plus some quick cleanup but that seemed to take slightly more time.
  963. const hashes = {}
  964. let expected = {}
  965. const zip = new AdmZip(buf)
  966. const zipEntries = zip.getEntries()
  967. //First pass
  968. for(let i=0; i<zipEntries.length; i++){
  969. let entry = zipEntries[i]
  970. if(entry.entryName === 'checksums.sha1'){
  971. expected = AssetGuard._parseChecksumsFile(zip.readAsText(entry))
  972. }
  973. hashes[entry.entryName] = AssetGuard._calculateHash(entry.getData(), 'sha1')
  974. }
  975. if(!checksums.includes(hashes['checksums.sha1'])){
  976. return false
  977. }
  978. //Check against expected
  979. const expectedEntries = Object.keys(expected)
  980. for(let i=0; i<expectedEntries.length; i++){
  981. if(expected[expectedEntries[i]] !== hashes[expectedEntries[i]]){
  982. return false
  983. }
  984. }
  985. return true
  986. }
  987. // #endregion
  988. // Miscellaneous Static Functions
  989. // #region
  990. /**
  991. * Extracts and unpacks a file from .pack.xz format.
  992. *
  993. * @param {Array.<string>} filePaths The paths of the files to be extracted and unpacked.
  994. * @returns {Promise.<void>} An empty promise to indicate the extraction has completed.
  995. */
  996. static _extractPackXZ(filePaths, javaExecutable){
  997. console.log('[PackXZExtract] Starting')
  998. return new Promise((resolve, reject) => {
  999. let libPath
  1000. if(isDev){
  1001. libPath = path.join(process.cwd(), 'libraries', 'java', 'PackXZExtract.jar')
  1002. } else {
  1003. if(process.platform === 'darwin'){
  1004. libPath = path.join(process.cwd(),'Contents', 'Resources', 'libraries', 'java', 'PackXZExtract.jar')
  1005. } else {
  1006. libPath = path.join(process.cwd(), 'resources', 'libraries', 'java', 'PackXZExtract.jar')
  1007. }
  1008. }
  1009. const filePath = filePaths.join(',')
  1010. const child = child_process.spawn(javaExecutable, ['-jar', libPath, '-packxz', filePath])
  1011. child.stdout.on('data', (data) => {
  1012. console.log('[PackXZExtract]', data.toString('utf8'))
  1013. })
  1014. child.stderr.on('data', (data) => {
  1015. console.log('[PackXZExtract]', data.toString('utf8'))
  1016. })
  1017. child.on('close', (code, signal) => {
  1018. console.log('[PackXZExtract]', 'Exited with code', code)
  1019. resolve()
  1020. })
  1021. })
  1022. }
  1023. /**
  1024. * Function which finalizes the forge installation process. This creates a 'version'
  1025. * instance for forge and saves its version.json file into that instance. If that
  1026. * instance already exists, the contents of the version.json file are read and returned
  1027. * in a promise.
  1028. *
  1029. * @param {Asset} asset The Asset object representing Forge.
  1030. * @param {string} commonPath The common path for shared game files.
  1031. * @returns {Promise.<Object>} A promise which resolves to the contents of forge's version.json.
  1032. */
  1033. static _finalizeForgeAsset(asset, commonPath){
  1034. return new Promise((resolve, reject) => {
  1035. fs.readFile(asset.to, (err, data) => {
  1036. const zip = new AdmZip(data)
  1037. const zipEntries = zip.getEntries()
  1038. for(let i=0; i<zipEntries.length; i++){
  1039. if(zipEntries[i].entryName === 'version.json'){
  1040. const forgeVersion = JSON.parse(zip.readAsText(zipEntries[i]))
  1041. const versionPath = path.join(commonPath, 'versions', forgeVersion.id)
  1042. const versionFile = path.join(versionPath, forgeVersion.id + '.json')
  1043. if(!fs.existsSync(versionFile)){
  1044. fs.ensureDirSync(versionPath)
  1045. fs.writeFileSync(path.join(versionPath, forgeVersion.id + '.json'), zipEntries[i].getData())
  1046. resolve(forgeVersion)
  1047. } else {
  1048. //Read the saved file to allow for user modifications.
  1049. resolve(JSON.parse(fs.readFileSync(versionFile, 'utf-8')))
  1050. }
  1051. return
  1052. }
  1053. }
  1054. //We didn't find forge's version.json.
  1055. reject('Unable to finalize Forge processing, version.json not found! Has forge changed their format?')
  1056. })
  1057. })
  1058. }
  1059. // #endregion
  1060. // #endregion
  1061. // Validation Functions
  1062. // #region
  1063. /**
  1064. * Loads the version data for a given minecraft version.
  1065. *
  1066. * @param {string} version The game version for which to load the index data.
  1067. * @param {boolean} force Optional. If true, the version index will be downloaded even if it exists locally. Defaults to false.
  1068. * @returns {Promise.<Object>} Promise which resolves to the version data object.
  1069. */
  1070. loadVersionData(version, force = false){
  1071. const self = this
  1072. return new Promise(async (resolve, reject) => {
  1073. const versionPath = path.join(self.commonPath, 'versions', version)
  1074. const versionFile = path.join(versionPath, version + '.json')
  1075. if(!fs.existsSync(versionFile) || force){
  1076. const url = await self._getVersionDataUrl(version)
  1077. //This download will never be tracked as it's essential and trivial.
  1078. console.log('Preparing download of ' + version + ' assets.')
  1079. fs.ensureDirSync(versionPath)
  1080. const stream = request(url).pipe(fs.createWriteStream(versionFile))
  1081. stream.on('finish', () => {
  1082. resolve(JSON.parse(fs.readFileSync(versionFile)))
  1083. })
  1084. } else {
  1085. resolve(JSON.parse(fs.readFileSync(versionFile)))
  1086. }
  1087. })
  1088. }
  1089. /**
  1090. * Parses Mojang's version manifest and retrieves the url of the version
  1091. * data index.
  1092. *
  1093. * @param {string} version The version to lookup.
  1094. * @returns {Promise.<string>} Promise which resolves to the url of the version data index.
  1095. * If the version could not be found, resolves to null.
  1096. */
  1097. _getVersionDataUrl(version){
  1098. return new Promise((resolve, reject) => {
  1099. request('https://launchermeta.mojang.com/mc/game/version_manifest.json', (error, resp, body) => {
  1100. if(error){
  1101. reject(error)
  1102. } else {
  1103. const manifest = JSON.parse(body)
  1104. for(let v of manifest.versions){
  1105. if(v.id === version){
  1106. resolve(v.url)
  1107. }
  1108. }
  1109. resolve(null)
  1110. }
  1111. })
  1112. })
  1113. }
  1114. // Asset (Category=''') Validation Functions
  1115. // #region
  1116. /**
  1117. * Public asset validation function. This function will handle the validation of assets.
  1118. * It will parse the asset index specified in the version data, analyzing each
  1119. * asset entry. In this analysis it will check to see if the local file exists and is valid.
  1120. * If not, it will be added to the download queue for the 'assets' identifier.
  1121. *
  1122. * @param {Object} versionData The version data for the assets.
  1123. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  1124. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1125. */
  1126. validateAssets(versionData, force = false){
  1127. const self = this
  1128. return new Promise((resolve, reject) => {
  1129. self._assetChainIndexData(versionData, force).then(() => {
  1130. resolve()
  1131. })
  1132. })
  1133. }
  1134. //Chain the asset tasks to provide full async. The below functions are private.
  1135. /**
  1136. * Private function used to chain the asset validation process. This function retrieves
  1137. * the index data.
  1138. * @param {Object} versionData
  1139. * @param {boolean} force
  1140. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1141. */
  1142. _assetChainIndexData(versionData, force = false){
  1143. const self = this
  1144. return new Promise((resolve, reject) => {
  1145. //Asset index constants.
  1146. const assetIndex = versionData.assetIndex
  1147. const name = assetIndex.id + '.json'
  1148. const indexPath = path.join(self.commonPath, 'assets', 'indexes')
  1149. const assetIndexLoc = path.join(indexPath, name)
  1150. let data = null
  1151. if(!fs.existsSync(assetIndexLoc) || force){
  1152. console.log('Downloading ' + versionData.id + ' asset index.')
  1153. fs.ensureDirSync(indexPath)
  1154. const stream = request(assetIndex.url).pipe(fs.createWriteStream(assetIndexLoc))
  1155. stream.on('finish', () => {
  1156. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  1157. self._assetChainValidateAssets(versionData, data).then(() => {
  1158. resolve()
  1159. })
  1160. })
  1161. } else {
  1162. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  1163. self._assetChainValidateAssets(versionData, data).then(() => {
  1164. resolve()
  1165. })
  1166. }
  1167. })
  1168. }
  1169. /**
  1170. * Private function used to chain the asset validation process. This function processes
  1171. * the assets and enqueues missing or invalid files.
  1172. * @param {Object} versionData
  1173. * @param {boolean} force
  1174. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1175. */
  1176. _assetChainValidateAssets(versionData, indexData){
  1177. const self = this
  1178. return new Promise((resolve, reject) => {
  1179. //Asset constants
  1180. const resourceURL = 'http://resources.download.minecraft.net/'
  1181. const localPath = path.join(self.commonPath, 'assets')
  1182. const objectPath = path.join(localPath, 'objects')
  1183. const assetDlQueue = []
  1184. let dlSize = 0
  1185. let acc = 0
  1186. const total = Object.keys(indexData.objects).length
  1187. //const objKeys = Object.keys(data.objects)
  1188. async.forEachOfLimit(indexData.objects, 10, (value, key, cb) => {
  1189. acc++
  1190. self.emit('progress', 'assets', acc, total)
  1191. const hash = value.hash
  1192. const assetName = path.join(hash.substring(0, 2), hash)
  1193. const urlName = hash.substring(0, 2) + '/' + hash
  1194. const ast = new Asset(key, hash, value.size, resourceURL + urlName, path.join(objectPath, assetName))
  1195. if(!AssetGuard._validateLocal(ast.to, 'sha1', ast.hash)){
  1196. dlSize += (ast.size*1)
  1197. assetDlQueue.push(ast)
  1198. }
  1199. cb()
  1200. }, (err) => {
  1201. self.assets = new DLTracker(assetDlQueue, dlSize)
  1202. resolve()
  1203. })
  1204. })
  1205. }
  1206. // #endregion
  1207. // Library (Category=''') Validation Functions
  1208. // #region
  1209. /**
  1210. * Public library validation function. This function will handle the validation of libraries.
  1211. * It will parse the version data, analyzing each library entry. In this analysis, it will
  1212. * check to see if the local file exists and is valid. If not, it will be added to the download
  1213. * queue for the 'libraries' identifier.
  1214. *
  1215. * @param {Object} versionData The version data for the assets.
  1216. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1217. */
  1218. validateLibraries(versionData){
  1219. const self = this
  1220. return new Promise((resolve, reject) => {
  1221. const libArr = versionData.libraries
  1222. const libPath = path.join(self.commonPath, 'libraries')
  1223. const libDlQueue = []
  1224. let dlSize = 0
  1225. //Check validity of each library. If the hashs don't match, download the library.
  1226. async.eachLimit(libArr, 5, (lib, cb) => {
  1227. if(Library.validateRules(lib.rules, lib.natives)){
  1228. let artifact = (lib.natives == null) ? lib.downloads.artifact : lib.downloads.classifiers[lib.natives[Library.mojangFriendlyOS()].replace('${arch}', process.arch.replace('x', ''))]
  1229. const libItm = new Library(lib.name, artifact.sha1, artifact.size, artifact.url, path.join(libPath, artifact.path))
  1230. if(!AssetGuard._validateLocal(libItm.to, 'sha1', libItm.hash)){
  1231. dlSize += (libItm.size*1)
  1232. libDlQueue.push(libItm)
  1233. }
  1234. }
  1235. cb()
  1236. }, (err) => {
  1237. self.libraries = new DLTracker(libDlQueue, dlSize)
  1238. resolve()
  1239. })
  1240. })
  1241. }
  1242. // #endregion
  1243. // Miscellaneous (Category=files) Validation Functions
  1244. // #region
  1245. /**
  1246. * Public miscellaneous mojang file validation function. These files will be enqueued under
  1247. * the 'files' identifier.
  1248. *
  1249. * @param {Object} versionData The version data for the assets.
  1250. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1251. */
  1252. validateMiscellaneous(versionData){
  1253. const self = this
  1254. return new Promise(async (resolve, reject) => {
  1255. await self.validateClient(versionData)
  1256. await self.validateLogConfig(versionData)
  1257. resolve()
  1258. })
  1259. }
  1260. /**
  1261. * Validate client file - artifact renamed from client.jar to '{version}'.jar.
  1262. *
  1263. * @param {Object} versionData The version data for the assets.
  1264. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  1265. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1266. */
  1267. validateClient(versionData, force = false){
  1268. const self = this
  1269. return new Promise((resolve, reject) => {
  1270. const clientData = versionData.downloads.client
  1271. const version = versionData.id
  1272. const targetPath = path.join(self.commonPath, 'versions', version)
  1273. const targetFile = version + '.jar'
  1274. let client = new Asset(version + ' client', clientData.sha1, clientData.size, clientData.url, path.join(targetPath, targetFile))
  1275. if(!AssetGuard._validateLocal(client.to, 'sha1', client.hash) || force){
  1276. self.files.dlqueue.push(client)
  1277. self.files.dlsize += client.size*1
  1278. resolve()
  1279. } else {
  1280. resolve()
  1281. }
  1282. })
  1283. }
  1284. /**
  1285. * Validate log config.
  1286. *
  1287. * @param {Object} versionData The version data for the assets.
  1288. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  1289. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  1290. */
  1291. validateLogConfig(versionData){
  1292. const self = this
  1293. return new Promise((resolve, reject) => {
  1294. const client = versionData.logging.client
  1295. const file = client.file
  1296. const targetPath = path.join(self.commonPath, 'assets', 'log_configs')
  1297. let logConfig = new Asset(file.id, file.sha1, file.size, file.url, path.join(targetPath, file.id))
  1298. if(!AssetGuard._validateLocal(logConfig.to, 'sha1', logConfig.hash)){
  1299. self.files.dlqueue.push(logConfig)
  1300. self.files.dlsize += logConfig.size*1
  1301. resolve()
  1302. } else {
  1303. resolve()
  1304. }
  1305. })
  1306. }
  1307. // #endregion
  1308. // Distribution (Category=forge) Validation Functions
  1309. // #region
  1310. /**
  1311. * Validate the distribution.
  1312. *
  1313. * @param {Server} server The Server to validate.
  1314. * @returns {Promise.<Object>} A promise which resolves to the server distribution object.
  1315. */
  1316. validateDistribution(server){
  1317. const self = this
  1318. return new Promise((resolve, reject) => {
  1319. self.forge = self._parseDistroModules(server.getModules(), server.getMinecraftVersion(), server.getID())
  1320. resolve(server)
  1321. })
  1322. }
  1323. _parseDistroModules(modules, version, servid){
  1324. let alist = []
  1325. let asize = 0
  1326. for(let ob of modules){
  1327. let obArtifact = ob.getArtifact()
  1328. let obPath = obArtifact.getPath()
  1329. let artifact = new DistroModule(ob.getIdentifier(), obArtifact.getHash(), obArtifact.getSize(), obArtifact.getURL(), obPath, ob.getType())
  1330. const validationPath = obPath.toLowerCase().endsWith('.pack.xz') ? obPath.substring(0, obPath.toLowerCase().lastIndexOf('.pack.xz')) : obPath
  1331. if(!AssetGuard._validateLocal(validationPath, 'MD5', artifact.hash)){
  1332. asize += artifact.size*1
  1333. alist.push(artifact)
  1334. if(validationPath !== obPath) this.extractQueue.push(obPath)
  1335. }
  1336. //Recursively process the submodules then combine the results.
  1337. if(ob.getSubModules() != null){
  1338. let dltrack = this._parseDistroModules(ob.getSubModules(), version, servid)
  1339. asize += dltrack.dlsize*1
  1340. alist = alist.concat(dltrack.dlqueue)
  1341. }
  1342. }
  1343. return new DLTracker(alist, asize)
  1344. }
  1345. /**
  1346. * Loads Forge's version.json data into memory for the specified server id.
  1347. *
  1348. * @param {string} server The Server to load Forge data for.
  1349. * @returns {Promise.<Object>} A promise which resolves to Forge's version.json data.
  1350. */
  1351. loadForgeData(server){
  1352. const self = this
  1353. return new Promise(async (resolve, reject) => {
  1354. const modules = server.getModules()
  1355. for(let ob of modules){
  1356. const type = ob.getType()
  1357. if(type === DistroManager.Types.ForgeHosted || type === DistroManager.Types.Forge){
  1358. if(Util.isForgeGradle3(server.getMinecraftVersion(), ob.getVersion())){
  1359. // Read Manifest
  1360. for(let sub of ob.getSubModules()){
  1361. if(sub.getType() === DistroManager.Types.VersionManifest){
  1362. resolve(JSON.parse(fs.readFileSync(sub.getArtifact().getPath(), 'utf-8')))
  1363. return
  1364. }
  1365. }
  1366. reject('No forge version manifest found!')
  1367. return
  1368. } else {
  1369. let obArtifact = ob.getArtifact()
  1370. let obPath = obArtifact.getPath()
  1371. let asset = new DistroModule(ob.getIdentifier(), obArtifact.getHash(), obArtifact.getSize(), obArtifact.getURL(), obPath, type)
  1372. try {
  1373. let forgeData = await AssetGuard._finalizeForgeAsset(asset, self.commonPath)
  1374. resolve(forgeData)
  1375. } catch (err){
  1376. reject(err)
  1377. }
  1378. return
  1379. }
  1380. }
  1381. }
  1382. reject('No forge module found!')
  1383. })
  1384. }
  1385. _parseForgeLibraries(){
  1386. /* TODO
  1387. * Forge asset validations are already implemented. When there's nothing much
  1388. * to work on, implement forge downloads using forge's version.json. This is to
  1389. * have the code on standby if we ever need it (since it's half implemented already).
  1390. */
  1391. }
  1392. // #endregion
  1393. // Java (Category=''') Validation (download) Functions
  1394. // #region
  1395. _enqueueOpenJDK(dataDir){
  1396. return new Promise((resolve, reject) => {
  1397. JavaGuard._latestOpenJDK('8').then(verData => {
  1398. if(verData != null){
  1399. dataDir = path.join(dataDir, 'runtime', 'x64')
  1400. const fDir = path.join(dataDir, verData.name)
  1401. const jre = new Asset(verData.name, null, verData.size, verData.uri, fDir)
  1402. this.java = new DLTracker([jre], jre.size, (a, self) => {
  1403. if(verData.name.endsWith('zip')){
  1404. const zip = new AdmZip(a.to)
  1405. const pos = path.join(dataDir, zip.getEntries()[0].entryName)
  1406. zip.extractAllToAsync(dataDir, true, (err) => {
  1407. if(err){
  1408. console.log(err)
  1409. self.emit('complete', 'java', JavaGuard.javaExecFromRoot(pos))
  1410. } else {
  1411. fs.unlink(a.to, err => {
  1412. if(err){
  1413. console.log(err)
  1414. }
  1415. self.emit('complete', 'java', JavaGuard.javaExecFromRoot(pos))
  1416. })
  1417. }
  1418. })
  1419. } else {
  1420. // Tar.gz
  1421. let h = null
  1422. fs.createReadStream(a.to)
  1423. .on('error', err => console.log(err))
  1424. .pipe(zlib.createGunzip())
  1425. .on('error', err => console.log(err))
  1426. .pipe(tar.extract(dataDir, {
  1427. map: (header) => {
  1428. if(h == null){
  1429. h = header.name
  1430. }
  1431. }
  1432. }))
  1433. .on('error', err => console.log(err))
  1434. .on('finish', () => {
  1435. fs.unlink(a.to, err => {
  1436. if(err){
  1437. console.log(err)
  1438. }
  1439. if(h.indexOf('/') > -1){
  1440. h = h.substring(0, h.indexOf('/'))
  1441. }
  1442. const pos = path.join(dataDir, h)
  1443. self.emit('complete', 'java', JavaGuard.javaExecFromRoot(pos))
  1444. })
  1445. })
  1446. }
  1447. })
  1448. resolve(true)
  1449. } else {
  1450. resolve(false)
  1451. }
  1452. })
  1453. })
  1454. }
  1455. // _enqueueOracleJRE(dataDir){
  1456. // return new Promise((resolve, reject) => {
  1457. // JavaGuard._latestJREOracle().then(verData => {
  1458. // if(verData != null){
  1459. // const combined = verData.uri + PLATFORM_MAP[process.platform]
  1460. // const opts = {
  1461. // url: combined,
  1462. // headers: {
  1463. // 'Cookie': 'oraclelicense=accept-securebackup-cookie'
  1464. // }
  1465. // }
  1466. // request.head(opts, (err, resp, body) => {
  1467. // if(err){
  1468. // resolve(false)
  1469. // } else {
  1470. // dataDir = path.join(dataDir, 'runtime', 'x64')
  1471. // const name = combined.substring(combined.lastIndexOf('/')+1)
  1472. // const fDir = path.join(dataDir, name)
  1473. // const jre = new Asset(name, null, parseInt(resp.headers['content-length']), opts, fDir)
  1474. // this.java = new DLTracker([jre], jre.size, (a, self) => {
  1475. // let h = null
  1476. // fs.createReadStream(a.to)
  1477. // .on('error', err => console.log(err))
  1478. // .pipe(zlib.createGunzip())
  1479. // .on('error', err => console.log(err))
  1480. // .pipe(tar.extract(dataDir, {
  1481. // map: (header) => {
  1482. // if(h == null){
  1483. // h = header.name
  1484. // }
  1485. // }
  1486. // }))
  1487. // .on('error', err => console.log(err))
  1488. // .on('finish', () => {
  1489. // fs.unlink(a.to, err => {
  1490. // if(err){
  1491. // console.log(err)
  1492. // }
  1493. // if(h.indexOf('/') > -1){
  1494. // h = h.substring(0, h.indexOf('/'))
  1495. // }
  1496. // const pos = path.join(dataDir, h)
  1497. // self.emit('complete', 'java', JavaGuard.javaExecFromRoot(pos))
  1498. // })
  1499. // })
  1500. // })
  1501. // resolve(true)
  1502. // }
  1503. // })
  1504. // } else {
  1505. // resolve(false)
  1506. // }
  1507. // })
  1508. // })
  1509. // }
  1510. // _enqueueMojangJRE(dir){
  1511. // return new Promise((resolve, reject) => {
  1512. // // Mojang does not host the JRE for linux.
  1513. // if(process.platform === 'linux'){
  1514. // resolve(false)
  1515. // }
  1516. // AssetGuard.loadMojangLauncherData().then(data => {
  1517. // if(data != null) {
  1518. // try {
  1519. // const mJRE = data[Library.mojangFriendlyOS()]['64'].jre
  1520. // const url = mJRE.url
  1521. // request.head(url, (err, resp, body) => {
  1522. // if(err){
  1523. // resolve(false)
  1524. // } else {
  1525. // const name = url.substring(url.lastIndexOf('/')+1)
  1526. // const fDir = path.join(dir, name)
  1527. // const jre = new Asset('jre' + mJRE.version, mJRE.sha1, resp.headers['content-length'], url, fDir)
  1528. // this.java = new DLTracker([jre], jre.size, a => {
  1529. // fs.readFile(a.to, (err, data) => {
  1530. // // Data buffer needs to be decompressed from lzma,
  1531. // // not really possible using node.js
  1532. // })
  1533. // })
  1534. // }
  1535. // })
  1536. // } catch (err){
  1537. // resolve(false)
  1538. // }
  1539. // }
  1540. // })
  1541. // })
  1542. // }
  1543. // #endregion
  1544. // #endregion
  1545. // Control Flow Functions
  1546. // #region
  1547. /**
  1548. * Initiate an async download process for an AssetGuard DLTracker.
  1549. *
  1550. * @param {string} identifier The identifier of the AssetGuard DLTracker.
  1551. * @param {number} limit Optional. The number of async processes to run in parallel.
  1552. * @returns {boolean} True if the process began, otherwise false.
  1553. */
  1554. startAsyncProcess(identifier, limit = 5){
  1555. const self = this
  1556. const dlTracker = this[identifier]
  1557. const dlQueue = dlTracker.dlqueue
  1558. if(dlQueue.length > 0){
  1559. console.log('DLQueue', dlQueue)
  1560. async.eachLimit(dlQueue, limit, (asset, cb) => {
  1561. fs.ensureDirSync(path.join(asset.to, '..'))
  1562. let req = request(asset.from)
  1563. req.pause()
  1564. req.on('response', (resp) => {
  1565. if(resp.statusCode === 200){
  1566. let doHashCheck = false
  1567. const contentLength = parseInt(resp.headers['content-length'])
  1568. if(contentLength !== asset.size){
  1569. console.log(`WARN: Got ${contentLength} bytes for ${asset.id}: Expected ${asset.size}`)
  1570. doHashCheck = true
  1571. // Adjust download
  1572. this.totaldlsize -= asset.size
  1573. this.totaldlsize += contentLength
  1574. }
  1575. let writeStream = fs.createWriteStream(asset.to)
  1576. writeStream.on('close', () => {
  1577. if(dlTracker.callback != null){
  1578. dlTracker.callback.apply(dlTracker, [asset, self])
  1579. }
  1580. if(doHashCheck){
  1581. const v = AssetGuard._validateLocal(asset.to, asset.type != null ? 'md5' : 'sha1', asset.hash)
  1582. if(v){
  1583. console.log(`Hashes match for ${asset.id}, byte mismatch is an issue in the distro index.`)
  1584. } else {
  1585. console.error(`Hashes do not match, ${asset.id} may be corrupted.`)
  1586. }
  1587. }
  1588. cb()
  1589. })
  1590. req.pipe(writeStream)
  1591. req.resume()
  1592. } else {
  1593. req.abort()
  1594. console.log(`Failed to download ${asset.id}(${typeof asset.from === 'object' ? asset.from.url : asset.from}). Response code ${resp.statusCode}`)
  1595. self.progress += asset.size*1
  1596. self.emit('progress', 'download', self.progress, self.totaldlsize)
  1597. cb()
  1598. }
  1599. })
  1600. req.on('error', (err) => {
  1601. self.emit('error', 'download', err)
  1602. })
  1603. req.on('data', (chunk) => {
  1604. self.progress += chunk.length
  1605. self.emit('progress', 'download', self.progress, self.totaldlsize)
  1606. })
  1607. }, (err) => {
  1608. if(err){
  1609. console.log('An item in ' + identifier + ' failed to process')
  1610. } else {
  1611. console.log('All ' + identifier + ' have been processed successfully')
  1612. }
  1613. //self.totaldlsize -= dlTracker.dlsize
  1614. //self.progress -= dlTracker.dlsize
  1615. self[identifier] = new DLTracker([], 0)
  1616. if(self.progress >= self.totaldlsize) {
  1617. if(self.extractQueue.length > 0){
  1618. self.emit('progress', 'extract', 1, 1)
  1619. //self.emit('extracting')
  1620. AssetGuard._extractPackXZ(self.extractQueue, self.javaexec).then(() => {
  1621. self.extractQueue = []
  1622. self.emit('complete', 'download')
  1623. })
  1624. } else {
  1625. self.emit('complete', 'download')
  1626. }
  1627. }
  1628. })
  1629. return true
  1630. } else {
  1631. return false
  1632. }
  1633. }
  1634. /**
  1635. * This function will initiate the download processed for the specified identifiers. If no argument is
  1636. * given, all identifiers will be initiated. Note that in order for files to be processed you need to run
  1637. * the processing function corresponding to that identifier. If you run this function without processing
  1638. * the files, it is likely nothing will be enqueued in the object and processing will complete
  1639. * immediately. Once all downloads are complete, this function will fire the 'complete' event on the
  1640. * global object instance.
  1641. *
  1642. * @param {Array.<{id: string, limit: number}>} identifiers Optional. The identifiers to process and corresponding parallel async task limit.
  1643. */
  1644. processDlQueues(identifiers = [{id:'assets', limit:20}, {id:'libraries', limit:5}, {id:'files', limit:5}, {id:'forge', limit:5}]){
  1645. return new Promise((resolve, reject) => {
  1646. let shouldFire = true
  1647. // Assign dltracking variables.
  1648. this.totaldlsize = 0
  1649. this.progress = 0
  1650. for(let iden of identifiers){
  1651. this.totaldlsize += this[iden.id].dlsize
  1652. }
  1653. this.once('complete', (data) => {
  1654. resolve()
  1655. })
  1656. for(let iden of identifiers){
  1657. let r = this.startAsyncProcess(iden.id, iden.limit)
  1658. if(r) shouldFire = false
  1659. }
  1660. if(shouldFire){
  1661. this.emit('complete', 'download')
  1662. }
  1663. })
  1664. }
  1665. async validateEverything(serverid, dev = false){
  1666. try {
  1667. if(!ConfigManager.isLoaded()){
  1668. ConfigManager.load()
  1669. }
  1670. DistroManager.setDevMode(dev)
  1671. const dI = await DistroManager.pullLocal()
  1672. const server = dI.getServer(serverid)
  1673. // Validate Everything
  1674. await this.validateDistribution(server)
  1675. this.emit('validate', 'distribution')
  1676. const versionData = await this.loadVersionData(server.getMinecraftVersion())
  1677. this.emit('validate', 'version')
  1678. await this.validateAssets(versionData)
  1679. this.emit('validate', 'assets')
  1680. await this.validateLibraries(versionData)
  1681. this.emit('validate', 'libraries')
  1682. await this.validateMiscellaneous(versionData)
  1683. this.emit('validate', 'files')
  1684. await this.processDlQueues()
  1685. //this.emit('complete', 'download')
  1686. const forgeData = await this.loadForgeData(server)
  1687. return {
  1688. versionData,
  1689. forgeData
  1690. }
  1691. } catch (err){
  1692. return {
  1693. versionData: null,
  1694. forgeData: null,
  1695. error: err
  1696. }
  1697. }
  1698. }
  1699. // #endregion
  1700. }
  1701. module.exports = {
  1702. Util,
  1703. AssetGuard,
  1704. JavaGuard,
  1705. Asset,
  1706. Library
  1707. }