processbuilder.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. const AdmZip = require('adm-zip')
  2. const child_process = require('child_process')
  3. const crypto = require('crypto')
  4. const fs = require('fs-extra')
  5. const os = require('os')
  6. const path = require('path')
  7. const { URL } = require('url')
  8. const { Util, Library } = require('./assetguard')
  9. const ConfigManager = require('./configmanager')
  10. const DistroManager = require('./distromanager')
  11. const LoggerUtil = require('./loggerutil')
  12. const logger = LoggerUtil('%c[ProcessBuilder]', 'color: #003996; font-weight: bold')
  13. class ProcessBuilder {
  14. constructor(distroServer, versionData, forgeData, authUser, launcherVersion){
  15. this.gameDir = path.join(ConfigManager.getInstanceDirectory(), distroServer.getID())
  16. this.commonDir = ConfigManager.getCommonDirectory()
  17. this.server = distroServer
  18. this.versionData = versionData
  19. this.forgeData = forgeData
  20. this.authUser = authUser
  21. this.launcherVersion = launcherVersion
  22. this.forgeModListFile = path.join(this.gameDir, 'forgeMods.list') // 1.13+
  23. this.fmlDir = path.join(this.gameDir, 'forgeModList.json')
  24. this.llDir = path.join(this.gameDir, 'liteloaderModList.json')
  25. this.libPath = path.join(this.commonDir, 'libraries')
  26. this.usingLiteLoader = false
  27. this.llPath = null
  28. }
  29. /**
  30. * Convienence method to run the functions typically used to build a process.
  31. */
  32. build(){
  33. fs.ensureDirSync(this.gameDir)
  34. const tempNativePath = path.join(os.tmpdir(), ConfigManager.getTempNativeFolder(), crypto.pseudoRandomBytes(16).toString('hex'))
  35. process.throwDeprecation = true
  36. this.setupLiteLoader()
  37. logger.log('Using liteloader:', this.usingLiteLoader)
  38. const modObj = this.resolveModConfiguration(ConfigManager.getModConfiguration(this.server.getID()).mods, this.server.getModules())
  39. // Mod list below 1.13
  40. if(!Util.mcVersionAtLeast('1.13', this.server.getMinecraftVersion())){
  41. this.constructJSONModList('forge', modObj.fMods, true)
  42. if(this.usingLiteLoader){
  43. this.constructJSONModList('liteloader', modObj.lMods, true)
  44. }
  45. }
  46. const uberModArr = modObj.fMods.concat(modObj.lMods)
  47. let args = this.constructJVMArguments(uberModArr, tempNativePath)
  48. if(Util.mcVersionAtLeast('1.13', this.server.getMinecraftVersion())){
  49. //args = args.concat(this.constructModArguments(modObj.fMods))
  50. args = args.concat(this.constructModList(modObj.fMods))
  51. }
  52. logger.log('Launch Arguments:', args)
  53. const child = child_process.spawn(ConfigManager.getJavaExecutable(), args, {
  54. cwd: this.gameDir,
  55. detached: ConfigManager.getLaunchDetached()
  56. })
  57. if(ConfigManager.getLaunchDetached()){
  58. child.unref()
  59. }
  60. child.stdout.setEncoding('utf8')
  61. child.stderr.setEncoding('utf8')
  62. const loggerMCstdout = LoggerUtil('%c[Minecraft]', 'color: #36b030; font-weight: bold')
  63. const loggerMCstderr = LoggerUtil('%c[Minecraft]', 'color: #b03030; font-weight: bold')
  64. child.stdout.on('data', (data) => {
  65. loggerMCstdout.log(data)
  66. })
  67. child.stderr.on('data', (data) => {
  68. loggerMCstderr.log(data)
  69. })
  70. child.on('close', (code, signal) => {
  71. logger.log('Exited with code', code)
  72. fs.remove(tempNativePath, (err) => {
  73. if(err){
  74. logger.warn('Error while deleting temp dir', err)
  75. } else {
  76. logger.log('Temp dir deleted successfully.')
  77. }
  78. })
  79. })
  80. return child
  81. }
  82. /**
  83. * Determine if an optional mod is enabled from its configuration value. If the
  84. * configuration value is null, the required object will be used to
  85. * determine if it is enabled.
  86. *
  87. * A mod is enabled if:
  88. * * The configuration is not null and one of the following:
  89. * * The configuration is a boolean and true.
  90. * * The configuration is an object and its 'value' property is true.
  91. * * The configuration is null and one of the following:
  92. * * The required object is null.
  93. * * The required object's 'def' property is null or true.
  94. *
  95. * @param {Object | boolean} modCfg The mod configuration object.
  96. * @param {Object} required Optional. The required object from the mod's distro declaration.
  97. * @returns {boolean} True if the mod is enabled, false otherwise.
  98. */
  99. static isModEnabled(modCfg, required = null){
  100. return modCfg != null ? ((typeof modCfg === 'boolean' && modCfg) || (typeof modCfg === 'object' && (typeof modCfg.value !== 'undefined' ? modCfg.value : true))) : required != null ? required.isDefault() : true
  101. }
  102. /**
  103. * Function which performs a preliminary scan of the top level
  104. * mods. If liteloader is present here, we setup the special liteloader
  105. * launch options. Note that liteloader is only allowed as a top level
  106. * mod. It must not be declared as a submodule.
  107. */
  108. setupLiteLoader(){
  109. for(let ll of this.server.getModules()){
  110. if(ll.getType() === DistroManager.Types.LiteLoader){
  111. if(!ll.getRequired().isRequired()){
  112. const modCfg = ConfigManager.getModConfiguration(this.server.getID()).mods
  113. if(ProcessBuilder.isModEnabled(modCfg[ll.getVersionlessID()], ll.getRequired())){
  114. if(fs.existsSync(ll.getArtifact().getPath())){
  115. this.usingLiteLoader = true
  116. this.llPath = ll.getArtifact().getPath()
  117. }
  118. }
  119. } else {
  120. if(fs.existsSync(ll.getArtifact().getPath())){
  121. this.usingLiteLoader = true
  122. this.llPath = ll.getArtifact().getPath()
  123. }
  124. }
  125. }
  126. }
  127. }
  128. /**
  129. * Resolve an array of all enabled mods. These mods will be constructed into
  130. * a mod list format and enabled at launch.
  131. *
  132. * @param {Object} modCfg The mod configuration object.
  133. * @param {Array.<Object>} mdls An array of modules to parse.
  134. * @returns {{fMods: Array.<Object>, lMods: Array.<Object>}} An object which contains
  135. * a list of enabled forge mods and litemods.
  136. */
  137. resolveModConfiguration(modCfg, mdls){
  138. let fMods = []
  139. let lMods = []
  140. for(let mdl of mdls){
  141. const type = mdl.getType()
  142. if(type === DistroManager.Types.ForgeMod || type === DistroManager.Types.LiteMod || type === DistroManager.Types.LiteLoader){
  143. const o = !mdl.getRequired().isRequired()
  144. const e = ProcessBuilder.isModEnabled(modCfg[mdl.getVersionlessID()], mdl.getRequired())
  145. if(!o || (o && e)){
  146. if(mdl.hasSubModules()){
  147. const v = this.resolveModConfiguration(modCfg[mdl.getVersionlessID()].mods, mdl.getSubModules())
  148. fMods = fMods.concat(v.fMods)
  149. lMods = lMods.concat(v.lMods)
  150. if(mdl.type === DistroManager.Types.LiteLoader){
  151. continue
  152. }
  153. }
  154. if(mdl.type === DistroManager.Types.ForgeMod){
  155. fMods.push(mdl)
  156. } else {
  157. lMods.push(mdl)
  158. }
  159. }
  160. }
  161. }
  162. return {
  163. fMods,
  164. lMods
  165. }
  166. }
  167. _lteMinorVersion(version) {
  168. return Number(this.forgeData.id.split('-')[0].split('.')[1]) <= Number(version)
  169. }
  170. /**
  171. * Test to see if this version of forge requires the absolute: prefix
  172. * on the modListFile repository field.
  173. */
  174. _requiresAbsolute(){
  175. try {
  176. if(this._lteMinorVersion(9)) {
  177. return false
  178. }
  179. const ver = this.forgeData.id.split('-')[2]
  180. const pts = ver.split('.')
  181. const min = [14, 23, 3, 2655]
  182. for(let i=0; i<pts.length; i++){
  183. const parsed = Number.parseInt(pts[i])
  184. if(parsed < min[i]){
  185. return false
  186. } else if(parsed > min[i]){
  187. return true
  188. }
  189. }
  190. } catch (err) {
  191. // We know old forge versions follow this format.
  192. // Error must be caused by newer version.
  193. }
  194. // Equal or errored
  195. return true
  196. }
  197. /**
  198. * Construct a mod list json object.
  199. *
  200. * @param {'forge' | 'liteloader'} type The mod list type to construct.
  201. * @param {Array.<Object>} mods An array of mods to add to the mod list.
  202. * @param {boolean} save Optional. Whether or not we should save the mod list file.
  203. */
  204. constructJSONModList(type, mods, save = false){
  205. const modList = {
  206. repositoryRoot: ((type === 'forge' && this._requiresAbsolute()) ? 'absolute:' : '') + path.join(this.commonDir, 'modstore')
  207. }
  208. const ids = []
  209. if(type === 'forge'){
  210. for(let mod of mods){
  211. ids.push(mod.getExtensionlessID())
  212. }
  213. } else {
  214. for(let mod of mods){
  215. ids.push(mod.getExtensionlessID() + '@' + mod.getExtension())
  216. }
  217. }
  218. modList.modRef = ids
  219. if(save){
  220. const json = JSON.stringify(modList, null, 4)
  221. fs.writeFileSync(type === 'forge' ? this.fmlDir : this.llDir, json, 'UTF-8')
  222. }
  223. return modList
  224. }
  225. // /**
  226. // * Construct the mod argument list for forge 1.13
  227. // *
  228. // * @param {Array.<Object>} mods An array of mods to add to the mod list.
  229. // */
  230. // constructModArguments(mods){
  231. // const argStr = mods.map(mod => {
  232. // return mod.getExtensionlessID()
  233. // }).join(',')
  234. // if(argStr){
  235. // return [
  236. // '--fml.mavenRoots',
  237. // path.join('..', '..', 'common', 'modstore'),
  238. // '--fml.mods',
  239. // argStr
  240. // ]
  241. // } else {
  242. // return []
  243. // }
  244. // }
  245. /**
  246. * Construct the mod argument list for forge 1.13
  247. *
  248. * @param {Array.<Object>} mods An array of mods to add to the mod list.
  249. */
  250. constructModList(mods) {
  251. const writeBuffer = mods.map(mod => {
  252. return mod.getExtensionlessID()
  253. }).join('\n')
  254. if(writeBuffer) {
  255. fs.writeFileSync(this.forgeModListFile, writeBuffer, 'UTF-8')
  256. return [
  257. '--fml.mavenRoots',
  258. path.join('..', '..', 'common', 'modstore'),
  259. '--fml.modLists',
  260. this.forgeModListFile
  261. ]
  262. } else {
  263. return []
  264. }
  265. }
  266. _processAutoConnectArg(args){
  267. if(ConfigManager.getAutoConnect() && this.server.isAutoConnect()){
  268. const serverURL = new URL('my://' + this.server.getAddress())
  269. args.push('--server')
  270. args.push(serverURL.hostname)
  271. if(serverURL.port){
  272. args.push('--port')
  273. args.push(serverURL.port)
  274. }
  275. }
  276. }
  277. /**
  278. * Construct the argument array that will be passed to the JVM process.
  279. *
  280. * @param {Array.<Object>} mods An array of enabled mods which will be launched with this process.
  281. * @param {string} tempNativePath The path to store the native libraries.
  282. * @returns {Array.<string>} An array containing the full JVM arguments for this process.
  283. */
  284. constructJVMArguments(mods, tempNativePath){
  285. if(Util.mcVersionAtLeast('1.13', this.server.getMinecraftVersion())){
  286. return this._constructJVMArguments113(mods, tempNativePath)
  287. } else {
  288. return this._constructJVMArguments112(mods, tempNativePath)
  289. }
  290. }
  291. /**
  292. * Construct the argument array that will be passed to the JVM process.
  293. * This function is for 1.12 and below.
  294. *
  295. * @param {Array.<Object>} mods An array of enabled mods which will be launched with this process.
  296. * @param {string} tempNativePath The path to store the native libraries.
  297. * @returns {Array.<string>} An array containing the full JVM arguments for this process.
  298. */
  299. _constructJVMArguments112(mods, tempNativePath){
  300. let args = []
  301. // Classpath Argument
  302. args.push('-cp')
  303. args.push(this.classpathArg(mods, tempNativePath).join(process.platform === 'win32' ? ';' : ':'))
  304. // Java Arguments
  305. if(process.platform === 'darwin'){
  306. args.push('-Xdock:name=HeliosLauncher')
  307. args.push('-Xdock:icon=' + path.join(__dirname, '..', 'images', 'minecraft.icns'))
  308. }
  309. args.push('-Xmx' + ConfigManager.getMaxRAM())
  310. args.push('-Xms' + ConfigManager.getMinRAM())
  311. args = args.concat(ConfigManager.getJVMOptions())
  312. args.push('-Djava.library.path=' + tempNativePath)
  313. // Main Java Class
  314. args.push(this.forgeData.mainClass)
  315. // Forge Arguments
  316. args = args.concat(this._resolveForgeArgs())
  317. return args
  318. }
  319. /**
  320. * Construct the argument array that will be passed to the JVM process.
  321. * This function is for 1.13+
  322. *
  323. * Note: Required Libs https://github.com/MinecraftForge/MinecraftForge/blob/af98088d04186452cb364280340124dfd4766a5c/src/fmllauncher/java/net/minecraftforge/fml/loading/LibraryFinder.java#L82
  324. *
  325. * @param {Array.<Object>} mods An array of enabled mods which will be launched with this process.
  326. * @param {string} tempNativePath The path to store the native libraries.
  327. * @returns {Array.<string>} An array containing the full JVM arguments for this process.
  328. */
  329. _constructJVMArguments113(mods, tempNativePath){
  330. const argDiscovery = /\${*(.*)}/
  331. // JVM Arguments First
  332. let args = this.versionData.arguments.jvm
  333. //args.push('-Dlog4j.configurationFile=D:\\WesterosCraft\\game\\common\\assets\\log_configs\\client-1.12.xml')
  334. // Java Arguments
  335. if(process.platform === 'darwin'){
  336. args.push('-Xdock:name=HeliosLauncher')
  337. args.push('-Xdock:icon=' + path.join(__dirname, '..', 'images', 'minecraft.icns'))
  338. }
  339. args.push('-Xmx' + ConfigManager.getMaxRAM())
  340. args.push('-Xms' + ConfigManager.getMinRAM())
  341. args = args.concat(ConfigManager.getJVMOptions())
  342. // Main Java Class
  343. args.push(this.forgeData.mainClass)
  344. // Vanilla Arguments
  345. args = args.concat(this.versionData.arguments.game)
  346. for(let i=0; i<args.length; i++){
  347. if(typeof args[i] === 'object' && args[i].rules != null){
  348. let checksum = 0
  349. for(let rule of args[i].rules){
  350. if(rule.os != null){
  351. if(rule.os.name === Library.mojangFriendlyOS()
  352. && (rule.os.version == null || new RegExp(rule.os.version).test(os.release))){
  353. if(rule.action === 'allow'){
  354. checksum++
  355. }
  356. } else {
  357. if(rule.action === 'disallow'){
  358. checksum++
  359. }
  360. }
  361. } else if(rule.features != null){
  362. // We don't have many 'features' in the index at the moment.
  363. // This should be fine for a while.
  364. if(rule.features.has_custom_resolution != null && rule.features.has_custom_resolution === true){
  365. if(ConfigManager.getFullscreen()){
  366. args[i].value = [
  367. '--fullscreen',
  368. 'true'
  369. ]
  370. }
  371. checksum++
  372. }
  373. }
  374. }
  375. // TODO splice not push
  376. if(checksum === args[i].rules.length){
  377. if(typeof args[i].value === 'string'){
  378. args[i] = args[i].value
  379. } else if(typeof args[i].value === 'object'){
  380. //args = args.concat(args[i].value)
  381. args.splice(i, 1, ...args[i].value)
  382. }
  383. // Decrement i to reprocess the resolved value
  384. i--
  385. } else {
  386. args[i] = null
  387. }
  388. } else if(typeof args[i] === 'string'){
  389. if(argDiscovery.test(args[i])){
  390. const identifier = args[i].match(argDiscovery)[1]
  391. let val = null
  392. switch(identifier){
  393. case 'auth_player_name':
  394. val = this.authUser.displayName.trim()
  395. break
  396. case 'version_name':
  397. //val = versionData.id
  398. val = this.server.getID()
  399. break
  400. case 'game_directory':
  401. val = this.gameDir
  402. break
  403. case 'assets_root':
  404. val = path.join(this.commonDir, 'assets')
  405. break
  406. case 'assets_index_name':
  407. val = this.versionData.assets
  408. break
  409. case 'auth_uuid':
  410. val = this.authUser.uuid.trim()
  411. break
  412. case 'auth_access_token':
  413. val = this.authUser.accessToken
  414. break
  415. case 'user_type':
  416. val = this.authUser.type === 'microsoft' ? 'msa' : 'mojang'
  417. break
  418. case 'version_type':
  419. val = this.versionData.type
  420. break
  421. case 'resolution_width':
  422. val = ConfigManager.getGameWidth()
  423. break
  424. case 'resolution_height':
  425. val = ConfigManager.getGameHeight()
  426. break
  427. case 'natives_directory':
  428. val = args[i].replace(argDiscovery, tempNativePath)
  429. break
  430. case 'launcher_name':
  431. val = args[i].replace(argDiscovery, 'Helios-Launcher')
  432. break
  433. case 'launcher_version':
  434. val = args[i].replace(argDiscovery, this.launcherVersion)
  435. break
  436. case 'classpath':
  437. val = this.classpathArg(mods, tempNativePath).join(process.platform === 'win32' ? ';' : ':')
  438. break
  439. }
  440. if(val != null){
  441. args[i] = val
  442. }
  443. }
  444. }
  445. }
  446. // Autoconnect
  447. let isAutoconnectBroken
  448. try {
  449. isAutoconnectBroken = Util.isAutoconnectBroken(this.forgeData.id.split('-')[2])
  450. } catch(err) {
  451. logger.error(err)
  452. logger.error('Forge version format changed.. assuming autoconnect works.')
  453. logger.debug('Forge version:', this.forgeData.id)
  454. }
  455. if(isAutoconnectBroken) {
  456. logger.error('Server autoconnect disabled on Forge 1.15.2 for builds earlier than 31.2.15 due to OpenGL Stack Overflow issue.')
  457. logger.error('Please upgrade your Forge version to at least 31.2.15!')
  458. } else {
  459. this._processAutoConnectArg(args)
  460. }
  461. // Forge Specific Arguments
  462. args = args.concat(this.forgeData.arguments.game)
  463. // Filter null values
  464. args = args.filter(arg => {
  465. return arg != null
  466. })
  467. return args
  468. }
  469. /**
  470. * Resolve the arguments required by forge.
  471. *
  472. * @returns {Array.<string>} An array containing the arguments required by forge.
  473. */
  474. _resolveForgeArgs(){
  475. const mcArgs = this.forgeData.minecraftArguments.split(' ')
  476. const argDiscovery = /\${*(.*)}/
  477. // Replace the declared variables with their proper values.
  478. for(let i=0; i<mcArgs.length; ++i){
  479. if(argDiscovery.test(mcArgs[i])){
  480. const identifier = mcArgs[i].match(argDiscovery)[1]
  481. let val = null
  482. switch(identifier){
  483. case 'auth_player_name':
  484. val = this.authUser.displayName.trim()
  485. break
  486. case 'version_name':
  487. //val = versionData.id
  488. val = this.server.getID()
  489. break
  490. case 'game_directory':
  491. val = this.gameDir
  492. break
  493. case 'assets_root':
  494. val = path.join(this.commonDir, 'assets')
  495. break
  496. case 'assets_index_name':
  497. val = this.versionData.assets
  498. break
  499. case 'auth_uuid':
  500. val = this.authUser.uuid.trim()
  501. break
  502. case 'auth_access_token':
  503. val = this.authUser.accessToken
  504. break
  505. case 'user_type':
  506. val = this.authUser.type === 'microsoft' ? 'msa' : 'mojang'
  507. break
  508. case 'user_properties': // 1.8.9 and below.
  509. val = '{}'
  510. break
  511. case 'version_type':
  512. val = this.versionData.type
  513. break
  514. }
  515. if(val != null){
  516. mcArgs[i] = val
  517. }
  518. }
  519. }
  520. // Autoconnect to the selected server.
  521. this._processAutoConnectArg(mcArgs)
  522. // Prepare game resolution
  523. if(ConfigManager.getFullscreen()){
  524. mcArgs.push('--fullscreen')
  525. mcArgs.push(true)
  526. } else {
  527. mcArgs.push('--width')
  528. mcArgs.push(ConfigManager.getGameWidth())
  529. mcArgs.push('--height')
  530. mcArgs.push(ConfigManager.getGameHeight())
  531. }
  532. // Mod List File Argument
  533. mcArgs.push('--modListFile')
  534. if(this._lteMinorVersion(9)) {
  535. mcArgs.push(path.basename(this.fmlDir))
  536. } else {
  537. mcArgs.push('absolute:' + this.fmlDir)
  538. }
  539. // LiteLoader
  540. if(this.usingLiteLoader){
  541. mcArgs.push('--modRepo')
  542. mcArgs.push(this.llDir)
  543. // Set first arg to liteloader tweak class
  544. mcArgs.unshift('com.mumfrey.liteloader.launch.LiteLoaderTweaker')
  545. mcArgs.unshift('--tweakClass')
  546. }
  547. return mcArgs
  548. }
  549. /**
  550. * Ensure that the classpath entries all point to jar files.
  551. *
  552. * @param {Array.<String>} list Array of classpath entries.
  553. */
  554. _processClassPathList(list) {
  555. const ext = '.jar'
  556. const extLen = ext.length
  557. for(let i=0; i<list.length; i++) {
  558. const extIndex = list[i].indexOf(ext)
  559. if(extIndex > -1 && extIndex !== list[i].length - extLen) {
  560. list[i] = list[i].substring(0, extIndex + extLen)
  561. }
  562. }
  563. }
  564. /**
  565. * Resolve the full classpath argument list for this process. This method will resolve all Mojang-declared
  566. * libraries as well as the libraries declared by the server. Since mods are permitted to declare libraries,
  567. * this method requires all enabled mods as an input
  568. *
  569. * @param {Array.<Object>} mods An array of enabled mods which will be launched with this process.
  570. * @param {string} tempNativePath The path to store the native libraries.
  571. * @returns {Array.<string>} An array containing the paths of each library required by this process.
  572. */
  573. classpathArg(mods, tempNativePath){
  574. let cpArgs = []
  575. // Add the version.jar to the classpath.
  576. const version = this.versionData.id
  577. cpArgs.push(path.join(this.commonDir, 'versions', version, version + '.jar'))
  578. if(this.usingLiteLoader){
  579. cpArgs.push(this.llPath)
  580. }
  581. // Resolve the Mojang declared libraries.
  582. const mojangLibs = this._resolveMojangLibraries(tempNativePath)
  583. // Resolve the server declared libraries.
  584. const servLibs = this._resolveServerLibraries(mods)
  585. // Merge libraries, server libs with the same
  586. // maven identifier will override the mojang ones.
  587. // Ex. 1.7.10 forge overrides mojang's guava with newer version.
  588. const finalLibs = {...mojangLibs, ...servLibs}
  589. cpArgs = cpArgs.concat(Object.values(finalLibs))
  590. this._processClassPathList(cpArgs)
  591. return cpArgs
  592. }
  593. /**
  594. * Resolve the libraries defined by Mojang's version data. This method will also extract
  595. * native libraries and point to the correct location for its classpath.
  596. *
  597. * TODO - clean up function
  598. *
  599. * @param {string} tempNativePath The path to store the native libraries.
  600. * @returns {{[id: string]: string}} An object containing the paths of each library mojang declares.
  601. */
  602. _resolveMojangLibraries(tempNativePath){
  603. const libs = {}
  604. const libArr = this.versionData.libraries
  605. fs.ensureDirSync(tempNativePath)
  606. for(let i=0; i<libArr.length; i++){
  607. const lib = libArr[i]
  608. if(Library.validateRules(lib.rules, lib.natives)){
  609. if(lib.natives == null){
  610. const dlInfo = lib.downloads
  611. const artifact = dlInfo.artifact
  612. const to = path.join(this.libPath, artifact.path)
  613. const versionIndependentId = lib.name.substring(0, lib.name.lastIndexOf(':'))
  614. libs[versionIndependentId] = to
  615. } else {
  616. // Extract the native library.
  617. const exclusionArr = lib.extract != null ? lib.extract.exclude : ['META-INF/']
  618. const artifact = lib.downloads.classifiers[lib.natives[Library.mojangFriendlyOS()].replace('${arch}', process.arch.replace('x', ''))]
  619. // Location of native zip.
  620. const to = path.join(this.libPath, artifact.path)
  621. let zip = new AdmZip(to)
  622. let zipEntries = zip.getEntries()
  623. // Unzip the native zip.
  624. for(let i=0; i<zipEntries.length; i++){
  625. const fileName = zipEntries[i].entryName
  626. let shouldExclude = false
  627. // Exclude noted files.
  628. exclusionArr.forEach(function(exclusion){
  629. if(fileName.indexOf(exclusion) > -1){
  630. shouldExclude = true
  631. }
  632. })
  633. // Extract the file.
  634. if(!shouldExclude){
  635. fs.writeFile(path.join(tempNativePath, fileName), zipEntries[i].getData(), (err) => {
  636. if(err){
  637. logger.error('Error while extracting native library:', err)
  638. }
  639. })
  640. }
  641. }
  642. }
  643. }
  644. }
  645. return libs
  646. }
  647. /**
  648. * Resolve the libraries declared by this server in order to add them to the classpath.
  649. * This method will also check each enabled mod for libraries, as mods are permitted to
  650. * declare libraries.
  651. *
  652. * @param {Array.<Object>} mods An array of enabled mods which will be launched with this process.
  653. * @returns {{[id: string]: string}} An object containing the paths of each library this server requires.
  654. */
  655. _resolveServerLibraries(mods){
  656. const mdls = this.server.getModules()
  657. let libs = {}
  658. // Locate Forge/Libraries
  659. for(let mdl of mdls){
  660. const type = mdl.getType()
  661. if(type === DistroManager.Types.ForgeHosted || type === DistroManager.Types.Library){
  662. libs[mdl.getVersionlessID()] = mdl.getArtifact().getPath()
  663. if(mdl.hasSubModules()){
  664. const res = this._resolveModuleLibraries(mdl)
  665. if(res.length > 0){
  666. libs = {...libs, ...res}
  667. }
  668. }
  669. }
  670. }
  671. //Check for any libraries in our mod list.
  672. for(let i=0; i<mods.length; i++){
  673. if(mods.sub_modules != null){
  674. const res = this._resolveModuleLibraries(mods[i])
  675. if(res.length > 0){
  676. libs = {...libs, ...res}
  677. }
  678. }
  679. }
  680. return libs
  681. }
  682. /**
  683. * Recursively resolve the path of each library required by this module.
  684. *
  685. * @param {Object} mdl A module object from the server distro index.
  686. * @returns {Array.<string>} An array containing the paths of each library this module requires.
  687. */
  688. _resolveModuleLibraries(mdl){
  689. if(!mdl.hasSubModules()){
  690. return []
  691. }
  692. let libs = []
  693. for(let sm of mdl.getSubModules()){
  694. if(sm.getType() === DistroManager.Types.Library){
  695. libs.push(sm.getArtifact().getPath())
  696. }
  697. // If this module has submodules, we need to resolve the libraries for those.
  698. // To avoid unnecessary recursive calls, base case is checked here.
  699. if(mdl.hasSubModules()){
  700. const res = this._resolveModuleLibraries(sm)
  701. if(res.length > 0){
  702. libs = libs.concat(res)
  703. }
  704. }
  705. }
  706. return libs
  707. }
  708. }
  709. module.exports = ProcessBuilder