processbuilder.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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 { 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){
  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.fmlDir = path.join(this.gameDir, 'forgeModList.json')
  22. this.llDir = path.join(this.gameDir, 'liteloaderModList.json')
  23. this.libPath = path.join(this.commonDir, 'libraries')
  24. this.usingLiteLoader = false
  25. this.llPath = null
  26. }
  27. /**
  28. * Convienence method to run the functions typically used to build a process.
  29. */
  30. build(){
  31. fs.ensureDirSync(this.gameDir)
  32. const tempNativePath = path.join(os.tmpdir(), ConfigManager.getTempNativeFolder(), crypto.pseudoRandomBytes(16).toString('hex'))
  33. process.throwDeprecation = true
  34. this.setupLiteLoader()
  35. logger.log('Using liteloader:', this.usingLiteLoader)
  36. const modObj = this.resolveModConfiguration(ConfigManager.getModConfiguration(this.server.getID()).mods, this.server.getModules())
  37. this.constructModList('forge', modObj.fMods, true)
  38. if(this.usingLiteLoader){
  39. this.constructModList('liteloader', modObj.lMods, true)
  40. }
  41. const uberModArr = modObj.fMods.concat(modObj.lMods)
  42. const args = this.constructJVMArguments(uberModArr, tempNativePath)
  43. logger.log('Launch Arguments:', args)
  44. const child = child_process.spawn(ConfigManager.getJavaExecutable(), args, {
  45. cwd: this.gameDir,
  46. detached: ConfigManager.getLaunchDetached()
  47. })
  48. if(ConfigManager.getLaunchDetached()){
  49. child.unref()
  50. }
  51. child.stdout.setEncoding('utf8')
  52. child.stderr.setEncoding('utf8')
  53. const loggerMCstdout = LoggerUtil('%c[Minecraft]', 'color: #36b030; font-weight: bold')
  54. const loggerMCstderr = LoggerUtil('%c[Minecraft]', 'color: #b03030; font-weight: bold')
  55. child.stdout.on('data', (data) => {
  56. loggerMCstdout.log(data)
  57. })
  58. child.stderr.on('data', (data) => {
  59. loggerMCstderr.log(data)
  60. })
  61. child.on('close', (code, signal) => {
  62. logger.log('Exited with code', code)
  63. fs.remove(tempNativePath, (err) => {
  64. if(err){
  65. logger.warn('Error while deleting temp dir', err)
  66. } else {
  67. logger.log('Temp dir deleted successfully.')
  68. }
  69. })
  70. })
  71. return child
  72. }
  73. /**
  74. * Determine if an optional mod is enabled from its configuration value. If the
  75. * configuration value is null, the required object will be used to
  76. * determine if it is enabled.
  77. *
  78. * A mod is enabled if:
  79. * * The configuration is not null and one of the following:
  80. * * The configuration is a boolean and true.
  81. * * The configuration is an object and its 'value' property is true.
  82. * * The configuration is null and one of the following:
  83. * * The required object is null.
  84. * * The required object's 'def' property is null or true.
  85. *
  86. * @param {Object | boolean} modCfg The mod configuration object.
  87. * @param {Object} required Optional. The required object from the mod's distro declaration.
  88. * @returns {boolean} True if the mod is enabled, false otherwise.
  89. */
  90. static isModEnabled(modCfg, required = null){
  91. return modCfg != null ? ((typeof modCfg === 'boolean' && modCfg) || (typeof modCfg === 'object' && (typeof modCfg.value !== 'undefined' ? modCfg.value : true))) : required != null ? required.isDefault() : true
  92. }
  93. /**
  94. * Function which performs a preliminary scan of the top level
  95. * mods. If liteloader is present here, we setup the special liteloader
  96. * launch options. Note that liteloader is only allowed as a top level
  97. * mod. It must not be declared as a submodule.
  98. */
  99. setupLiteLoader(){
  100. for(let ll of this.server.getModules()){
  101. if(ll.getType() === DistroManager.Types.LiteLoader){
  102. if(!ll.getRequired().isRequired()){
  103. const modCfg = ConfigManager.getModConfiguration(this.server.getID()).mods
  104. if(ProcessBuilder.isModEnabled(modCfg[ll.getVersionlessID()], ll.getRequired())){
  105. if(fs.existsSync(ll.getArtifact().getPath())){
  106. this.usingLiteLoader = true
  107. this.llPath = ll.getArtifact().getPath()
  108. }
  109. }
  110. } else {
  111. if(fs.existsSync(ll.getArtifact().getPath())){
  112. this.usingLiteLoader = true
  113. this.llPath = ll.getArtifact().getPath()
  114. }
  115. }
  116. }
  117. }
  118. }
  119. /**
  120. * Resolve an array of all enabled mods. These mods will be constructed into
  121. * a mod list format and enabled at launch.
  122. *
  123. * @param {Object} modCfg The mod configuration object.
  124. * @param {Array.<Object>} mdls An array of modules to parse.
  125. * @returns {{fMods: Array.<Object>, lMods: Array.<Object>}} An object which contains
  126. * a list of enabled forge mods and litemods.
  127. */
  128. resolveModConfiguration(modCfg, mdls){
  129. let fMods = []
  130. let lMods = []
  131. for(let mdl of mdls){
  132. const type = mdl.getType()
  133. if(type === DistroManager.Types.ForgeMod || type === DistroManager.Types.LiteMod || type === DistroManager.Types.LiteLoader){
  134. const o = !mdl.getRequired().isRequired()
  135. const e = ProcessBuilder.isModEnabled(modCfg[mdl.getVersionlessID()], mdl.getRequired())
  136. if(!o || (o && e)){
  137. if(mdl.hasSubModules()){
  138. const v = this.resolveModConfiguration(modCfg[mdl.getVersionlessID()].mods, mdl.getSubModules())
  139. fMods = fMods.concat(v.fMods)
  140. lMods = lMods.concat(v.lMods)
  141. if(mdl.type === DistroManager.Types.LiteLoader){
  142. continue
  143. }
  144. }
  145. if(mdl.type === DistroManager.Types.ForgeMod){
  146. fMods.push(mdl)
  147. } else {
  148. lMods.push(mdl)
  149. }
  150. }
  151. }
  152. }
  153. return {
  154. fMods,
  155. lMods
  156. }
  157. }
  158. /**
  159. * Construct a mod list json object.
  160. *
  161. * @param {'forge' | 'liteloader'} type The mod list type to construct.
  162. * @param {Array.<Object>} mods An array of mods to add to the mod list.
  163. * @param {boolean} save Optional. Whether or not we should save the mod list file.
  164. */
  165. constructModList(type, mods, save = false){
  166. const modList = {
  167. repositoryRoot: path.join(this.commonDir, 'modstore')
  168. }
  169. const ids = []
  170. if(type === 'forge'){
  171. for(let mod of mods){
  172. ids.push(mod.getExtensionlessID())
  173. }
  174. } else {
  175. for(let mod of mods){
  176. ids.push(mod.getExtensionlessID() + '@' + mod.getExtension())
  177. }
  178. }
  179. modList.modRef = ids
  180. if(save){
  181. const json = JSON.stringify(modList, null, 4)
  182. fs.writeFileSync(type === 'forge' ? this.fmlDir : this.llDir, json, 'UTF-8')
  183. }
  184. return modList
  185. }
  186. /**
  187. * Construct the argument array that will be passed to the JVM process.
  188. *
  189. * @param {Array.<Object>} mods An array of enabled mods which will be launched with this process.
  190. * @param {string} tempNativePath The path to store the native libraries.
  191. * @returns {Array.<string>} An array containing the full JVM arguments for this process.
  192. */
  193. constructJVMArguments(mods, tempNativePath){
  194. let args = ['-Xmx' + ConfigManager.getMaxRAM(),
  195. '-Xms' + ConfigManager.getMinRAM(),
  196. '-Djava.library.path=' + tempNativePath,
  197. '-cp',
  198. this.classpathArg(mods, tempNativePath).join(process.platform === 'win32' ? ';' : ':'),
  199. this.forgeData.mainClass]
  200. if(process.platform === 'darwin'){
  201. args.unshift('-Xdock:name=WesterosCraft')
  202. args.unshift('-Xdock:icon=' + path.join(__dirname, '..', 'images', 'minecraft.icns'))
  203. }
  204. args.splice(2, 0, ...ConfigManager.getJVMOptions())
  205. args = args.concat(this._resolveForgeArgs())
  206. return args
  207. }
  208. /**
  209. * Resolve the arguments required by forge.
  210. *
  211. * @returns {Array.<string>} An array containing the arguments required by forge.
  212. */
  213. _resolveForgeArgs(){
  214. const mcArgs = this.forgeData.minecraftArguments.split(' ')
  215. const argDiscovery = /\${*(.*)}/
  216. // Replace the declared variables with their proper values.
  217. for(let i=0; i<mcArgs.length; ++i){
  218. if(argDiscovery.test(mcArgs[i])){
  219. const identifier = mcArgs[i].match(argDiscovery)[1]
  220. let val = null
  221. switch(identifier){
  222. case 'auth_player_name':
  223. val = this.authUser.displayName.trim()
  224. break
  225. case 'version_name':
  226. //val = versionData.id
  227. val = this.server.getID()
  228. break
  229. case 'game_directory':
  230. val = this.gameDir
  231. break
  232. case 'assets_root':
  233. val = path.join(this.commonDir, 'assets')
  234. break
  235. case 'assets_index_name':
  236. val = this.versionData.assets
  237. break
  238. case 'auth_uuid':
  239. val = this.authUser.uuid.trim()
  240. break
  241. case 'auth_access_token':
  242. val = this.authUser.accessToken
  243. break
  244. case 'user_type':
  245. val = 'MOJANG'
  246. break
  247. case 'version_type':
  248. val = this.versionData.type
  249. break
  250. }
  251. if(val != null){
  252. mcArgs[i] = val
  253. }
  254. }
  255. }
  256. mcArgs.push('--modListFile')
  257. mcArgs.push('absolute:' + this.fmlDir)
  258. if(this.usingLiteLoader){
  259. mcArgs.push('--modRepo')
  260. mcArgs.push(this.llDir)
  261. mcArgs.unshift('com.mumfrey.liteloader.launch.LiteLoaderTweaker')
  262. mcArgs.unshift('--tweakClass')
  263. }
  264. // Prepare game resolution
  265. if(ConfigManager.getFullscreen()){
  266. mcArgs.unshift('--fullscreen')
  267. } else {
  268. mcArgs.unshift(ConfigManager.getGameWidth())
  269. mcArgs.unshift('--width')
  270. mcArgs.unshift(ConfigManager.getGameHeight())
  271. mcArgs.unshift('--height')
  272. }
  273. // Prepare autoconnect
  274. if(ConfigManager.getAutoConnect() && this.server.isAutoConnect()){
  275. const serverURL = new URL('my://' + this.server.getAddress())
  276. mcArgs.unshift(serverURL.hostname)
  277. mcArgs.unshift('--server')
  278. if(serverURL.port){
  279. mcArgs.unshift(serverURL.port)
  280. mcArgs.unshift('--port')
  281. }
  282. }
  283. return mcArgs
  284. }
  285. /**
  286. * Resolve the full classpath argument list for this process. This method will resolve all Mojang-declared
  287. * libraries as well as the libraries declared by the server. Since mods are permitted to declare libraries,
  288. * this method requires all enabled mods as an input
  289. *
  290. * @param {Array.<Object>} mods An array of enabled mods which will be launched with this process.
  291. * @param {string} tempNativePath The path to store the native libraries.
  292. * @returns {Array.<string>} An array containing the paths of each library required by this process.
  293. */
  294. classpathArg(mods, tempNativePath){
  295. let cpArgs = []
  296. // Add the version.jar to the classpath.
  297. const version = this.versionData.id
  298. cpArgs.push(path.join(this.commonDir, 'versions', version, version + '.jar'))
  299. if(this.usingLiteLoader){
  300. cpArgs.push(this.llPath)
  301. }
  302. // Resolve the Mojang declared libraries.
  303. const mojangLibs = this._resolveMojangLibraries(tempNativePath)
  304. cpArgs = cpArgs.concat(mojangLibs)
  305. // Resolve the server declared libraries.
  306. const servLibs = this._resolveServerLibraries(mods)
  307. cpArgs = cpArgs.concat(servLibs)
  308. return cpArgs
  309. }
  310. /**
  311. * Resolve the libraries defined by Mojang's version data. This method will also extract
  312. * native libraries and point to the correct location for its classpath.
  313. *
  314. * TODO - clean up function
  315. *
  316. * @param {string} tempNativePath The path to store the native libraries.
  317. * @returns {Array.<string>} An array containing the paths of each library mojang declares.
  318. */
  319. _resolveMojangLibraries(tempNativePath){
  320. const libs = []
  321. const libArr = this.versionData.libraries
  322. fs.ensureDirSync(tempNativePath)
  323. for(let i=0; i<libArr.length; i++){
  324. const lib = libArr[i]
  325. if(Library.validateRules(lib.rules, lib.natives)){
  326. if(lib.natives == null){
  327. const dlInfo = lib.downloads
  328. const artifact = dlInfo.artifact
  329. const to = path.join(this.libPath, artifact.path)
  330. libs.push(to)
  331. } else {
  332. // Extract the native library.
  333. const extractInst = lib.extract
  334. const exclusionArr = extractInst.exclude
  335. const artifact = lib.downloads.classifiers[lib.natives[Library.mojangFriendlyOS()].replace('${arch}', process.arch.replace('x', ''))]
  336. // Location of native zip.
  337. const to = path.join(this.libPath, artifact.path)
  338. let zip = new AdmZip(to)
  339. let zipEntries = zip.getEntries()
  340. // Unzip the native zip.
  341. for(let i=0; i<zipEntries.length; i++){
  342. const fileName = zipEntries[i].entryName
  343. let shouldExclude = false
  344. // Exclude noted files.
  345. exclusionArr.forEach(function(exclusion){
  346. if(fileName.indexOf(exclusion) > -1){
  347. shouldExclude = true
  348. }
  349. })
  350. // Extract the file.
  351. if(!shouldExclude){
  352. fs.writeFile(path.join(tempNativePath, fileName), zipEntries[i].getData(), (err) => {
  353. if(err){
  354. logger.error('Error while extracting native library:', err)
  355. }
  356. })
  357. }
  358. }
  359. }
  360. }
  361. }
  362. return libs
  363. }
  364. /**
  365. * Resolve the libraries declared by this server in order to add them to the classpath.
  366. * This method will also check each enabled mod for libraries, as mods are permitted to
  367. * declare libraries.
  368. *
  369. * @param {Array.<Object>} mods An array of enabled mods which will be launched with this process.
  370. * @returns {Array.<string>} An array containing the paths of each library this server requires.
  371. */
  372. _resolveServerLibraries(mods){
  373. const mdls = this.server.getModules()
  374. let libs = []
  375. // Locate Forge/Libraries
  376. for(let mdl of mdls){
  377. const type = mdl.getType()
  378. if(type === DistroManager.Types.ForgeHosted || type === DistroManager.Types.Library){
  379. libs.push(mdl.getArtifact().getPath())
  380. if(mdl.hasSubModules()){
  381. const res = this._resolveModuleLibraries(mdl)
  382. if(res.length > 0){
  383. libs = libs.concat(res)
  384. }
  385. }
  386. }
  387. }
  388. //Check for any libraries in our mod list.
  389. for(let i=0; i<mods.length; i++){
  390. if(mods.sub_modules != null){
  391. const res = this._resolveModuleLibraries(mods[i])
  392. if(res.length > 0){
  393. libs = libs.concat(res)
  394. }
  395. }
  396. }
  397. return libs
  398. }
  399. /**
  400. * Recursively resolve the path of each library required by this module.
  401. *
  402. * @param {Object} mdl A module object from the server distro index.
  403. * @returns {Array.<string>} An array containing the paths of each library this module requires.
  404. */
  405. _resolveModuleLibraries(mdl){
  406. if(!mdl.hasSubModules()){
  407. return []
  408. }
  409. let libs = []
  410. for(let sm of mdl.getSubModules()){
  411. if(sm.getType() === DistroManager.Types.Library){
  412. libs.push(sm.getArtifact().getPath())
  413. }
  414. // If this module has submodules, we need to resolve the libraries for those.
  415. // To avoid unnecessary recursive calls, base case is checked here.
  416. if(mdl.hasSubModules()){
  417. const res = this._resolveModuleLibraries(sm)
  418. if(res.length > 0){
  419. libs = libs.concat(res)
  420. }
  421. }
  422. }
  423. return libs
  424. }
  425. }
  426. module.exports = ProcessBuilder