assetguard.js 64 KB

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