assetguard.js 68 KB

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