assetguard.js 71 KB

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