assetguard.js 71 KB

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