From 83fe5818dcddeaa2fe45d56d7f13f029a15222a4 Mon Sep 17 00:00:00 2001 From: Benjamin Elsdon Date: Thu, 21 Apr 2022 13:53:50 +0800 Subject: [PATCH 1/8] Restructured the config file in preperation for server run modes --- src/main/java/emu/grasscutter/Config.java | 70 ++++++++++--------- .../java/emu/grasscutter/Grasscutter.java | 2 +- .../emu/grasscutter/game/GenshinPlayer.java | 2 +- .../java/emu/grasscutter/game/TeamInfo.java | 6 +- .../emu/grasscutter/game/TeamManager.java | 4 +- .../grasscutter/game/gacha/GachaBanner.java | 2 +- .../grasscutter/game/gacha/GachaManager.java | 2 +- .../grasscutter/game/inventory/Inventory.java | 8 +-- .../server/dispatch/DispatchServer.java | 28 ++++---- .../server/game/GameServerPacketHandler.java | 2 +- .../grasscutter/server/game/GameSession.java | 4 +- .../packet/send/PacketPlayerStoreNotify.java | 2 +- .../packet/send/PacketPullRecentChatRsp.java | 6 +- .../send/PacketStoreWeightLimitNotify.java | 10 +-- 14 files changed, 77 insertions(+), 71 deletions(-) diff --git a/src/main/java/emu/grasscutter/Config.java b/src/main/java/emu/grasscutter/Config.java index dddbbfa9e..c6748fb41 100644 --- a/src/main/java/emu/grasscutter/Config.java +++ b/src/main/java/emu/grasscutter/Config.java @@ -1,20 +1,7 @@ package emu.grasscutter; public final class Config { - public String DispatchServerIp = "127.0.0.1"; - public String DispatchServerPublicIp = ""; - public int DispatchServerPort = 443; - public String DispatchServerKeystorePath = "./keystore.p12"; - public String DispatchServerKeystorePassword = ""; - public Boolean UseSSL = true; - - public String GameServerName = "Test"; - public String GameServerIp = "127.0.0.1"; - public String GameServerPublicIp = ""; - public int GameServerPort = 22102; - - public int UploadLogPort = 80; - + public String DatabaseUrl = "mongodb://localhost:27017"; public String DatabaseCollection = "grasscutter"; @@ -23,26 +10,36 @@ public final class Config { public String PACKETS_FOLDER = "./packets/"; public String DUMPS_FOLDER = "./dumps/"; public String KEY_FOLDER = "./keys/"; - public boolean LOG_PACKETS = false; - public GameRates Game = new GameRates(); - public ServerOptions ServerOptions = new ServerOptions(); - - public GameRates getGameRates() { - return Game; + public GameServerOptions GameServer = new GameServerOptions(); + public DispatchServerOptions DispatchServer = new DispatchServerOptions(); + + public GameServerOptions getGameServerOptions() { + return GameServer; + } + + public DispatchServerOptions getDispatchOptions() { return DispatchServer; } + + public static class DispatchServerOptions { + public String Ip = "127.0.0.1"; + public String PublicIp = ""; + public int Port = 443; + public int UploadLogPort = 80; + public String KeystorePath = "./keystore.p12"; + public String KeystorePassword = ""; + public Boolean UseSSL = true; + + public boolean AutomaticallyCreateAccounts = false; } - public ServerOptions getServerOptions() { - return ServerOptions; - } - - public static class GameRates { - public float ADVENTURE_EXP_RATE = 1.0f; - public float MORA_RATE = 1.0f; - public float DOMAIN_DROP_RATE = 1.0f; - } - - public static class ServerOptions { + public static class GameServerOptions { + public String Name = "Test"; + public String Ip = "127.0.0.1"; + public String PublicIp = ""; + public int Port = 22102; + + public boolean LOG_PACKETS = false; + public int InventoryLimitWeapon = 2000; public int InventoryLimitRelic = 2000; public int InventoryLimitMaterial = 2000; @@ -54,6 +51,15 @@ public final class Config { public boolean WatchGacha = false; public int[] WelcomeEmotes = {2007, 1002, 4010}; public String WelcomeMotd = "Welcome to Grasscutter emu"; - public boolean AutomaticallyCreateAccounts = false; + + public GameRates Game = new GameRates(); + + public GameRates getGameRates() { return Game; } + + public static class GameRates { + public float ADVENTURE_EXP_RATE = 1.0f; + public float MORA_RATE = 1.0f; + public float DOMAIN_DROP_RATE = 1.0f; + } } } diff --git a/src/main/java/emu/grasscutter/Grasscutter.java b/src/main/java/emu/grasscutter/Grasscutter.java index 0e34c120d..0b8f1efd8 100644 --- a/src/main/java/emu/grasscutter/Grasscutter.java +++ b/src/main/java/emu/grasscutter/Grasscutter.java @@ -76,7 +76,7 @@ public final class Grasscutter { dispatchServer = new DispatchServer(); dispatchServer.start(); - gameServer = new GameServer(new InetSocketAddress(getConfig().GameServerIp, getConfig().GameServerPort)); + gameServer = new GameServer(new InetSocketAddress(getConfig().getGameServerOptions().Ip, getConfig().getGameServerOptions().Port)); gameServer.start(); // Open console. diff --git a/src/main/java/emu/grasscutter/game/GenshinPlayer.java b/src/main/java/emu/grasscutter/game/GenshinPlayer.java index 1d8650e54..bf841090e 100644 --- a/src/main/java/emu/grasscutter/game/GenshinPlayer.java +++ b/src/main/java/emu/grasscutter/game/GenshinPlayer.java @@ -288,7 +288,7 @@ public class GenshinPlayer { } private float getExpModifier() { - return Grasscutter.getConfig().getGameRates().ADVENTURE_EXP_RATE; + return Grasscutter.getConfig().getGameServerOptions().getGameRates().ADVENTURE_EXP_RATE; } // Affected by exp rate diff --git a/src/main/java/emu/grasscutter/game/TeamInfo.java b/src/main/java/emu/grasscutter/game/TeamInfo.java index 0a12b1d2c..c60ce8cc0 100644 --- a/src/main/java/emu/grasscutter/game/TeamInfo.java +++ b/src/main/java/emu/grasscutter/game/TeamInfo.java @@ -13,7 +13,7 @@ public class TeamInfo { public TeamInfo() { this.name = ""; - this.avatars = new ArrayList<>(Grasscutter.getConfig().getServerOptions().MaxAvatarsInTeam); + this.avatars = new ArrayList<>(Grasscutter.getConfig().getGameServerOptions().MaxAvatarsInTeam); } public String getName() { @@ -37,7 +37,7 @@ public class TeamInfo { } public boolean addAvatar(GenshinAvatar avatar) { - if (size() >= Grasscutter.getConfig().getServerOptions().MaxAvatarsInTeam || contains(avatar)) { + if (size() >= Grasscutter.getConfig().getGameServerOptions().MaxAvatarsInTeam || contains(avatar)) { return false; } @@ -57,7 +57,7 @@ public class TeamInfo { } public void copyFrom(TeamInfo team) { - copyFrom(team, Grasscutter.getConfig().getServerOptions().MaxAvatarsInTeam); + copyFrom(team, Grasscutter.getConfig().getGameServerOptions().MaxAvatarsInTeam); } public void copyFrom(TeamInfo team, int maxTeamSize) { diff --git a/src/main/java/emu/grasscutter/game/TeamManager.java b/src/main/java/emu/grasscutter/game/TeamManager.java index 4cd7bfcdf..065c3bd28 100644 --- a/src/main/java/emu/grasscutter/game/TeamManager.java +++ b/src/main/java/emu/grasscutter/game/TeamManager.java @@ -164,13 +164,13 @@ public class TeamManager { public int getMaxTeamSize() { if (getPlayer().isInMultiplayer()) { - int max = Grasscutter.getConfig().getServerOptions().MaxAvatarsInTeamMultiplayer; + int max = Grasscutter.getConfig().getGameServerOptions().MaxAvatarsInTeamMultiplayer; if (getPlayer().getWorld().getHost() == this.getPlayer()) { return Math.max(1, (int) Math.ceil(max / (double) getWorld().getPlayerCount())); } return Math.max(1, (int) Math.floor(max / (double) getWorld().getPlayerCount())); } - return Grasscutter.getConfig().getServerOptions().MaxAvatarsInTeam; + return Grasscutter.getConfig().getGameServerOptions().MaxAvatarsInTeam; } // Methods diff --git a/src/main/java/emu/grasscutter/game/gacha/GachaBanner.java b/src/main/java/emu/grasscutter/game/gacha/GachaBanner.java index 3e6bcdf7e..ed5492b62 100644 --- a/src/main/java/emu/grasscutter/game/gacha/GachaBanner.java +++ b/src/main/java/emu/grasscutter/game/gacha/GachaBanner.java @@ -92,7 +92,7 @@ public class GachaBanner { } public GachaInfo toProto() { - String record = "http://" + (Grasscutter.getConfig().DispatchServerPublicIp.isEmpty() ? Grasscutter.getConfig().DispatchServerIp : Grasscutter.getConfig().DispatchServerPublicIp) + "/gacha"; + String record = "http://" + (Grasscutter.getConfig().getDispatchOptions().PublicIp.isEmpty() ? Grasscutter.getConfig().getDispatchOptions().Ip : Grasscutter.getConfig().getDispatchOptions().PublicIp) + "/gacha"; GachaInfo.Builder info = GachaInfo.newBuilder() .setGachaType(this.getGachaType()) diff --git a/src/main/java/emu/grasscutter/game/gacha/GachaManager.java b/src/main/java/emu/grasscutter/game/gacha/GachaManager.java index a38b91812..079f0dda3 100644 --- a/src/main/java/emu/grasscutter/game/gacha/GachaManager.java +++ b/src/main/java/emu/grasscutter/game/gacha/GachaManager.java @@ -299,7 +299,7 @@ public class GachaManager { @Subscribe public synchronized void watchBannerJson(GameServerTickEvent tickEvent) { - if(Grasscutter.getConfig().getServerOptions().WatchGacha) { + if(Grasscutter.getConfig().getGameServerOptions().WatchGacha) { try { WatchKey watchKey = watchService.take(); diff --git a/src/main/java/emu/grasscutter/game/inventory/Inventory.java b/src/main/java/emu/grasscutter/game/inventory/Inventory.java index 19bdcc525..8954b1031 100644 --- a/src/main/java/emu/grasscutter/game/inventory/Inventory.java +++ b/src/main/java/emu/grasscutter/game/inventory/Inventory.java @@ -37,10 +37,10 @@ public class Inventory implements Iterable { this.store = new Long2ObjectOpenHashMap<>(); this.inventoryTypes = new Int2ObjectOpenHashMap<>(); - this.createInventoryTab(ItemType.ITEM_WEAPON, new EquipInventoryTab(Grasscutter.getConfig().getServerOptions().InventoryLimitWeapon)); - this.createInventoryTab(ItemType.ITEM_RELIQUARY, new EquipInventoryTab(Grasscutter.getConfig().getServerOptions().InventoryLimitRelic)); - this.createInventoryTab(ItemType.ITEM_MATERIAL, new MaterialInventoryTab(Grasscutter.getConfig().getServerOptions().InventoryLimitMaterial)); - this.createInventoryTab(ItemType.ITEM_FURNITURE, new MaterialInventoryTab(Grasscutter.getConfig().getServerOptions().InventoryLimitFurniture)); + this.createInventoryTab(ItemType.ITEM_WEAPON, new EquipInventoryTab(Grasscutter.getConfig().getGameServerOptions().InventoryLimitWeapon)); + this.createInventoryTab(ItemType.ITEM_RELIQUARY, new EquipInventoryTab(Grasscutter.getConfig().getGameServerOptions().InventoryLimitRelic)); + this.createInventoryTab(ItemType.ITEM_MATERIAL, new MaterialInventoryTab(Grasscutter.getConfig().getGameServerOptions().InventoryLimitMaterial)); + this.createInventoryTab(ItemType.ITEM_FURNITURE, new MaterialInventoryTab(Grasscutter.getConfig().getGameServerOptions().InventoryLimitFurniture)); } public GenshinPlayer getPlayer() { diff --git a/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java b/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java index f13b9dc2f..cda908480 100644 --- a/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java +++ b/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java @@ -55,7 +55,7 @@ public final class DispatchServer { public static String query_cur_region = ""; public DispatchServer() { - this.address = new InetSocketAddress(Grasscutter.getConfig().DispatchServerIp, Grasscutter.getConfig().DispatchServerPort); + this.address = new InetSocketAddress(Grasscutter.getConfig().getDispatchOptions().Ip, Grasscutter.getConfig().getDispatchOptions().Port); this.gson = new GsonBuilder().create(); this.loadQueries(); @@ -99,19 +99,19 @@ public final class DispatchServer { byte[] decoded2 = Base64.getDecoder().decode(query_cur_region); QueryCurrRegionHttpRsp regionQuery = QueryCurrRegionHttpRsp.parseFrom(decoded2); - + RegionSimpleInfo server = RegionSimpleInfo.newBuilder() .setName("os_usa") - .setTitle(Grasscutter.getConfig().GameServerName) + .setTitle(Grasscutter.getConfig().getGameServerOptions().Name) .setType("DEV_PUBLIC") - .setDispatchUrl("https://" + (Grasscutter.getConfig().DispatchServerPublicIp.isEmpty() ? Grasscutter.getConfig().DispatchServerIp : Grasscutter.getConfig().DispatchServerPublicIp) + ":" + getAddress().getPort() + "/query_cur_region") + .setDispatchUrl("https://" + (Grasscutter.getConfig().getDispatchOptions().PublicIp.isEmpty() ? Grasscutter.getConfig().getDispatchOptions().Ip : Grasscutter.getConfig().getDispatchOptions().PublicIp) + ":" + getAddress().getPort() + "/query_cur_region") .build(); RegionSimpleInfo serverTest2 = RegionSimpleInfo.newBuilder() .setName("os_euro") .setTitle("Grasscutter") .setType("DEV_PUBLIC") - .setDispatchUrl("https://" + (Grasscutter.getConfig().DispatchServerPublicIp.isEmpty() ? Grasscutter.getConfig().DispatchServerIp : Grasscutter.getConfig().DispatchServerPublicIp) + ":" + getAddress().getPort() + "/query_cur_region") + .setDispatchUrl("https://" + (Grasscutter.getConfig().getDispatchOptions().PublicIp.isEmpty() ? Grasscutter.getConfig().getDispatchOptions().Ip : Grasscutter.getConfig().getDispatchOptions().PublicIp) + ":" + getAddress().getPort() + "/query_cur_region") .build(); QueryRegionListHttpRsp regionList = QueryRegionListHttpRsp.newBuilder() @@ -123,8 +123,8 @@ public final class DispatchServer { .build(); RegionInfo currentRegion = regionQuery.getRegionInfo().toBuilder() - .setIp((Grasscutter.getConfig().GameServerPublicIp.isEmpty() ? Grasscutter.getConfig().GameServerIp : Grasscutter.getConfig().GameServerPublicIp)) - .setPort(Grasscutter.getConfig().GameServerPort) + .setIp((Grasscutter.getConfig().getGameServerOptions().PublicIp.isEmpty() ? Grasscutter.getConfig().getGameServerOptions().Ip : Grasscutter.getConfig().getGameServerOptions().PublicIp)) + .setPort(Grasscutter.getConfig().getGameServerOptions().Port) .setSecretKey(ByteString.copyFrom(FileUtils.read(Grasscutter.getConfig().KEY_FOLDER + "dispatchSeed.bin"))) .build(); @@ -140,12 +140,12 @@ public final class DispatchServer { public void start() throws Exception { HttpServer server; - if(Grasscutter.getConfig().UseSSL) { + if(Grasscutter.getConfig().getDispatchOptions().UseSSL) { HttpsServer httpsServer; httpsServer = HttpsServer.create(getAddress(), 0); SSLContext sslContext = SSLContext.getInstance("TLS"); - try (FileInputStream fis = new FileInputStream(Grasscutter.getConfig().DispatchServerKeystorePath)) { - char[] keystorePassword = Grasscutter.getConfig().DispatchServerKeystorePassword.toCharArray(); + try (FileInputStream fis = new FileInputStream(Grasscutter.getConfig().getDispatchOptions().KeystorePath)) { + char[] keystorePassword = Grasscutter.getConfig().getDispatchOptions().KeystorePassword.toCharArray(); KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(fis, keystorePassword); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); @@ -228,7 +228,7 @@ public final class DispatchServer { // Check if account exists, else create a new one. if (account == null) { // Account doesnt exist, so we can either auto create it if the config value is set - if (Grasscutter.getConfig().ServerOptions.AutomaticallyCreateAccounts) { + if (Grasscutter.getConfig().getDispatchOptions().AutomaticallyCreateAccounts) { // This account has been created AUTOMATICALLY. There will be no permissions added. account = DatabaseHelper.createAccountWithId(requestData.account, 0); @@ -410,7 +410,7 @@ public final class DispatchServer { Grasscutter.getLogger().info("Dispatch server started on port " + getAddress().getPort()); // Logging servers - HttpServer overseaLogServer = HttpServer.create(new InetSocketAddress(Grasscutter.getConfig().DispatchServerIp, 8888), 0); + HttpServer overseaLogServer = HttpServer.create(new InetSocketAddress(Grasscutter.getConfig().getDispatchOptions().Ip, 8888), 0); overseaLogServer.createContext( // overseauspider.yuanshen.com "/log", new DispatchHttpJsonHandler("{\"code\":0}") @@ -418,7 +418,7 @@ public final class DispatchServer { overseaLogServer.start(); Grasscutter.getLogger().info("Log server (overseauspider) started on port " + 8888); - HttpServer uploadLogServer = HttpServer.create(new InetSocketAddress(Grasscutter.getConfig().DispatchServerIp, Grasscutter.getConfig().UploadLogPort), 0); + HttpServer uploadLogServer = HttpServer.create(new InetSocketAddress(Grasscutter.getConfig().getDispatchOptions().Ip, Grasscutter.getConfig().getDispatchOptions().UploadLogPort), 0); uploadLogServer.createContext( // log-upload-os.mihoyo.com "/crash/dataUpload", new DispatchHttpJsonHandler("{\"code\":0}") @@ -435,7 +435,7 @@ public final class DispatchServer { os.close(); }); uploadLogServer.start(); - Grasscutter.getLogger().info("Log server (log-upload-os) started on port " + Grasscutter.getConfig().UploadLogPort); + Grasscutter.getLogger().info("Log server (log-upload-os) started on port " + Grasscutter.getConfig().getDispatchOptions().UploadLogPort); } private Map parseQueryString(String qs) { diff --git a/src/main/java/emu/grasscutter/server/game/GameServerPacketHandler.java b/src/main/java/emu/grasscutter/server/game/GameServerPacketHandler.java index 118637668..62a57df91 100644 --- a/src/main/java/emu/grasscutter/server/game/GameServerPacketHandler.java +++ b/src/main/java/emu/grasscutter/server/game/GameServerPacketHandler.java @@ -87,7 +87,7 @@ public class GameServerPacketHandler { } // Log unhandled packets - if (Grasscutter.getConfig().LOG_PACKETS) { + if (Grasscutter.getConfig().getGameServerOptions().LOG_PACKETS) { //Grasscutter.getLogger().info("Unhandled packet (" + opcode + "): " + PacketOpcodesUtil.getOpcodeName(opcode)); } } diff --git a/src/main/java/emu/grasscutter/server/game/GameSession.java b/src/main/java/emu/grasscutter/server/game/GameSession.java index 1a54f31ba..ebd66dc20 100644 --- a/src/main/java/emu/grasscutter/server/game/GameSession.java +++ b/src/main/java/emu/grasscutter/server/game/GameSession.java @@ -165,7 +165,7 @@ public class GameSession extends MihoyoKcpChannel { byte[] data = genshinPacket.build(); // Log - if (Grasscutter.getConfig().LOG_PACKETS) { + if (Grasscutter.getConfig().getGameServerOptions().LOG_PACKETS) { logPacket(genshinPacket); } @@ -225,7 +225,7 @@ public class GameSession extends MihoyoKcpChannel { } // Log packet - if (Grasscutter.getConfig().LOG_PACKETS) { + if (Grasscutter.getConfig().getGameServerOptions().LOG_PACKETS) { Grasscutter.getLogger().info("RECV: " + PacketOpcodesUtil.getOpcodeName(opcode) + " (" + opcode + ")"); System.out.println(Utils.bytesToHex(payload)); } diff --git a/src/main/java/emu/grasscutter/server/packet/send/PacketPlayerStoreNotify.java b/src/main/java/emu/grasscutter/server/packet/send/PacketPlayerStoreNotify.java index c21a15351..a3309a5c1 100644 --- a/src/main/java/emu/grasscutter/server/packet/send/PacketPlayerStoreNotify.java +++ b/src/main/java/emu/grasscutter/server/packet/send/PacketPlayerStoreNotify.java @@ -19,7 +19,7 @@ public class PacketPlayerStoreNotify extends GenshinPacket { PlayerStoreNotify.Builder p = PlayerStoreNotify.newBuilder() .setStoreType(StoreType.StorePack) - .setWeightLimit(Grasscutter.getConfig().getServerOptions().InventoryLimitAll); + .setWeightLimit(Grasscutter.getConfig().getGameServerOptions().InventoryLimitAll); for (GenshinItem item : player.getInventory()) { Item itemProto = item.toProto(); diff --git a/src/main/java/emu/grasscutter/server/packet/send/PacketPullRecentChatRsp.java b/src/main/java/emu/grasscutter/server/packet/send/PacketPullRecentChatRsp.java index 8048e4b0d..5af6999d5 100644 --- a/src/main/java/emu/grasscutter/server/packet/send/PacketPullRecentChatRsp.java +++ b/src/main/java/emu/grasscutter/server/packet/send/PacketPullRecentChatRsp.java @@ -1,6 +1,6 @@ package emu.grasscutter.server.packet.send; -import emu.grasscutter.Config.ServerOptions; +import emu.grasscutter.Config.GameServerOptions; import emu.grasscutter.GenshinConstants; import emu.grasscutter.Grasscutter; import emu.grasscutter.game.GenshinPlayer; @@ -14,7 +14,7 @@ public class PacketPullRecentChatRsp extends GenshinPacket { public PacketPullRecentChatRsp(GenshinPlayer player) { super(PacketOpcodes.PullRecentChatRsp); - ServerOptions serverOptions = Grasscutter.getConfig().getServerOptions(); + GameServerOptions serverOptions = Grasscutter.getConfig().getGameServerOptions(); PullRecentChatRsp.Builder proto = PullRecentChatRsp.newBuilder(); if (serverOptions.WelcomeEmotes != null && serverOptions.WelcomeEmotes.length > 0) { @@ -33,7 +33,7 @@ public class PacketPullRecentChatRsp extends GenshinPacket { .setTime((int) (System.currentTimeMillis() / 1000)) .setUid(GenshinConstants.SERVER_CONSOLE_UID) .setToUid(player.getUid()) - .setText(Grasscutter.getConfig().getServerOptions().WelcomeMotd) + .setText(Grasscutter.getConfig().getGameServerOptions().WelcomeMotd) .build(); proto.addChatInfo(welcomeMotd); diff --git a/src/main/java/emu/grasscutter/server/packet/send/PacketStoreWeightLimitNotify.java b/src/main/java/emu/grasscutter/server/packet/send/PacketStoreWeightLimitNotify.java index b93130388..04668b00e 100644 --- a/src/main/java/emu/grasscutter/server/packet/send/PacketStoreWeightLimitNotify.java +++ b/src/main/java/emu/grasscutter/server/packet/send/PacketStoreWeightLimitNotify.java @@ -13,11 +13,11 @@ public class PacketStoreWeightLimitNotify extends GenshinPacket { StoreWeightLimitNotify p = StoreWeightLimitNotify.newBuilder() .setStoreType(StoreType.StorePack) - .setWeightLimit(Grasscutter.getConfig().getServerOptions().InventoryLimitAll) - .setWeaponCountLimit(Grasscutter.getConfig().getServerOptions().InventoryLimitWeapon) - .setReliquaryCountLimit(Grasscutter.getConfig().getServerOptions().InventoryLimitRelic) - .setMaterialCountLimit(Grasscutter.getConfig().getServerOptions().InventoryLimitMaterial) - .setFurnitureCountLimit(Grasscutter.getConfig().getServerOptions().InventoryLimitFurniture) + .setWeightLimit(Grasscutter.getConfig().getGameServerOptions().InventoryLimitAll) + .setWeaponCountLimit(Grasscutter.getConfig().getGameServerOptions().InventoryLimitWeapon) + .setReliquaryCountLimit(Grasscutter.getConfig().getGameServerOptions().InventoryLimitRelic) + .setMaterialCountLimit(Grasscutter.getConfig().getGameServerOptions().InventoryLimitMaterial) + .setFurnitureCountLimit(Grasscutter.getConfig().getGameServerOptions().InventoryLimitFurniture) .build(); this.setData(p); From 9ce436022d84a8856a77463ec504604a8ec25fbb Mon Sep 17 00:00:00 2001 From: Benjamin Elsdon Date: Thu, 21 Apr 2022 18:04:00 +0800 Subject: [PATCH 2/8] Multi-server dispatch support and server run modes --- src/main/java/emu/grasscutter/Config.java | 19 +++ .../java/emu/grasscutter/Grasscutter.java | 32 +++- .../grasscutter/database/DatabaseHelper.java | 12 +- .../grasscutter/database/DatabaseManager.java | 43 ++++- .../server/dispatch/DispatchServer.java | 161 ++++++++++++------ .../packet/send/PacketPlayerLoginRsp.java | 2 +- 6 files changed, 198 insertions(+), 71 deletions(-) diff --git a/src/main/java/emu/grasscutter/Config.java b/src/main/java/emu/grasscutter/Config.java index c6748fb41..938cbec77 100644 --- a/src/main/java/emu/grasscutter/Config.java +++ b/src/main/java/emu/grasscutter/Config.java @@ -1,5 +1,7 @@ package emu.grasscutter; +import java.util.ArrayList; + public final class Config { public String DatabaseUrl = "mongodb://localhost:27017"; @@ -11,6 +13,7 @@ public final class Config { public String DUMPS_FOLDER = "./dumps/"; public String KEY_FOLDER = "./keys/"; + public String RunMode = "HYBRID"; // HYBRID, DISPATCH_ONLY, GAME_ONLY public GameServerOptions GameServer = new GameServerOptions(); public DispatchServerOptions DispatchServer = new DispatchServerOptions(); @@ -30,6 +33,19 @@ public final class Config { public Boolean UseSSL = true; public boolean AutomaticallyCreateAccounts = false; + + public RegionInfo[] GameServers = {}; + + public RegionInfo[] getGameServers() { + return GameServers; + } + + public static class RegionInfo { + public String Name = "os_usa"; + public String Title = "Test"; + public String Ip = "127.0.0.1"; + public int Port = 22102; + } } public static class GameServerOptions { @@ -38,6 +54,9 @@ public final class Config { public String PublicIp = ""; public int Port = 22102; + public String DispatchServerDatabaseUrl = "mongodb://localhost:27017"; + public String DispatchServerDatabaseCollection = "grasscutter"; + public boolean LOG_PACKETS = false; public int InventoryLimitWeapon = 2000; diff --git a/src/main/java/emu/grasscutter/Grasscutter.java b/src/main/java/emu/grasscutter/Grasscutter.java index 0b8f1efd8..614b67ca1 100644 --- a/src/main/java/emu/grasscutter/Grasscutter.java +++ b/src/main/java/emu/grasscutter/Grasscutter.java @@ -73,11 +73,26 @@ public final class Grasscutter { DatabaseManager.initialize(); // Start servers. - dispatchServer = new DispatchServer(); - dispatchServer.start(); - - gameServer = new GameServer(new InetSocketAddress(getConfig().getGameServerOptions().Ip, getConfig().getGameServerOptions().Port)); - gameServer.start(); + if(getConfig().RunMode.equalsIgnoreCase("HYBRID")) { + dispatchServer = new DispatchServer(); + dispatchServer.start(); + + gameServer = new GameServer(new InetSocketAddress(getConfig().getGameServerOptions().Ip, getConfig().getGameServerOptions().Port)); + gameServer.start(); + } else if(getConfig().RunMode.equalsIgnoreCase("DISPATCH_ONLY")) { + dispatchServer = new DispatchServer(); + dispatchServer.start(); + } else if(getConfig().RunMode.equalsIgnoreCase("GAME_ONLY")) { + gameServer = new GameServer(new InetSocketAddress(getConfig().getGameServerOptions().Ip, getConfig().getGameServerOptions().Port)); + gameServer.start(); + } else { + getLogger().error("Invalid server run mode. " + getConfig().RunMode); + getLogger().error("Server run mode must be 'HYBRID', 'DISPATCH_ONLY', or 'GAME_ONLY'. Unable to start Grasscutter..."); + getLogger().error("Shutting down..."); + System.exit(1); + } + + // Open console. startConsole(); @@ -104,9 +119,14 @@ public final class Grasscutter { try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { while ((input = br.readLine()) != null) { try { + if(getConfig().RunMode.equalsIgnoreCase("DISPATCH_ONLY")) { + getLogger().error("Commands are not supported in dispatch only mode"); + return; + } CommandMap.getInstance().invoke(null, input); } catch (Exception e) { - Grasscutter.getLogger().error("Command error: " + e.getMessage()); + Grasscutter.getLogger().error("Command error: "); + e.printStackTrace(); } } } catch (Exception e) { diff --git a/src/main/java/emu/grasscutter/database/DatabaseHelper.java b/src/main/java/emu/grasscutter/database/DatabaseHelper.java index 0289c3e71..ed092e976 100644 --- a/src/main/java/emu/grasscutter/database/DatabaseHelper.java +++ b/src/main/java/emu/grasscutter/database/DatabaseHelper.java @@ -74,36 +74,36 @@ public class DatabaseHelper { } public static void saveAccount(Account account) { - DatabaseManager.getDatastore().save(account); + DatabaseManager.getAccountDatastore().save(account); } public static Account getAccountByName(String username) { - MorphiaCursor cursor = DatabaseManager.getDatastore().createQuery(Account.class).field("username").equalIgnoreCase(username).find(FIND_ONE); + MorphiaCursor cursor = DatabaseManager.getAccountDatastore().createQuery(Account.class).field("username").equalIgnoreCase(username).find(FIND_ONE); if (!cursor.hasNext()) return null; return cursor.next(); } public static Account getAccountByToken(String token) { if (token == null) return null; - MorphiaCursor cursor = DatabaseManager.getDatastore().createQuery(Account.class).field("token").equal(token).find(FIND_ONE); + MorphiaCursor cursor = DatabaseManager.getAccountDatastore().createQuery(Account.class).field("token").equal(token).find(FIND_ONE); if (!cursor.hasNext()) return null; return cursor.next(); } public static Account getAccountById(String uid) { - MorphiaCursor cursor = DatabaseManager.getDatastore().createQuery(Account.class).field("_id").equal(uid).find(FIND_ONE); + MorphiaCursor cursor = DatabaseManager.getAccountDatastore().createQuery(Account.class).field("_id").equal(uid).find(FIND_ONE); if (!cursor.hasNext()) return null; return cursor.next(); } public static Account getAccountByPlayerId(int playerId) { - MorphiaCursor cursor = DatabaseManager.getDatastore().createQuery(Account.class).field("playerId").equal(playerId).find(FIND_ONE); + MorphiaCursor cursor = DatabaseManager.getAccountDatastore().createQuery(Account.class).field("playerId").equal(playerId).find(FIND_ONE); if (!cursor.hasNext()) return null; return cursor.next(); } public static boolean deleteAccount(String username) { - Query q = DatabaseManager.getDatastore().createQuery(Account.class).field("username").equalIgnoreCase(username); + Query q = DatabaseManager.getAccountDatastore().createQuery(Account.class).field("username").equalIgnoreCase(username); return DatabaseManager.getDatastore().findAndDelete(q) != null; } diff --git a/src/main/java/emu/grasscutter/database/DatabaseManager.java b/src/main/java/emu/grasscutter/database/DatabaseManager.java index 97e27a81a..530581517 100644 --- a/src/main/java/emu/grasscutter/database/DatabaseManager.java +++ b/src/main/java/emu/grasscutter/database/DatabaseManager.java @@ -17,7 +17,10 @@ import emu.grasscutter.game.inventory.GenshinItem; public final class DatabaseManager { private static MongoClient mongoClient; + private static MongoClient dispatchMongoClient; + private static Datastore datastore; + private static Datastore dispatchDatastore; private static final Class[] mappedClasses = new Class[] { DatabaseCounter.class, Account.class, GenshinPlayer.class, GenshinAvatar.class, GenshinItem.class, Friendship.class @@ -26,18 +29,28 @@ public final class DatabaseManager { public static MongoClient getMongoClient() { return mongoClient; } - - public static Datastore getDatastore() { - return datastore; - } - - public static MongoDatabase getDatabase() { + + public static Datastore getDatastore() { + return datastore; + } + + public static MongoDatabase getDatabase() { return getDatastore().getDatabase(); } + + // Yes. I very dislike this method also but I'm lazy. Probably replace it by making the game server connect to the dispatch server instead. + public static Datastore getAccountDatastore() { + if(Grasscutter.getConfig().RunMode.equalsIgnoreCase("GAME_ONLY")) { + return dispatchDatastore; + } else { + return datastore; + } + } public static void initialize() { // Initialize mongoClient = new MongoClient(new MongoClientURI(Grasscutter.getConfig().DatabaseUrl)); + dispatchMongoClient = new MongoClient(new MongoClientURI(Grasscutter.getConfig().getGameServerOptions().DispatchServerDatabaseUrl)); Morphia morphia = new Morphia(); // TODO Update when migrating to Morphia 2.0 @@ -50,6 +63,7 @@ public final class DatabaseManager { // Build datastore datastore = morphia.createDatastore(mongoClient, Grasscutter.getConfig().DatabaseCollection); + dispatchDatastore = morphia.createDatastore(dispatchMongoClient, Grasscutter.getConfig().getGameServerOptions().DispatchServerDatabaseCollection); // Ensure indexes try { @@ -67,6 +81,23 @@ public final class DatabaseManager { datastore.ensureIndexes(); } } + + // Ensure indexes for dispatch server + try { + dispatchDatastore.ensureIndexes(); + } catch (MongoCommandException e) { + Grasscutter.getLogger().info("Mongo index error: ", e); + // Duplicate index error + if (e.getCode() == 85) { + // Drop all indexes and re add them + MongoIterable collections = dispatchDatastore.getDatabase().listCollectionNames(); + for (String name : collections) { + dispatchDatastore.getDatabase().getCollection(name).dropIndexes(); + } + // Add back indexes + dispatchDatastore.ensureIndexes(); + } + } } public static synchronized int getNextId(Class c) { diff --git a/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java b/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java index cda908480..53699b05b 100644 --- a/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java +++ b/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java @@ -9,10 +9,7 @@ import java.net.InetSocketAddress; import java.net.URI; import java.net.URLDecoder; import java.security.KeyStore; -import java.util.Base64; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; +import java.util.*; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; @@ -25,6 +22,7 @@ import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; +import emu.grasscutter.Config; import emu.grasscutter.Grasscutter; import emu.grasscutter.database.DatabaseHelper; import emu.grasscutter.game.Account; @@ -46,15 +44,18 @@ import com.sun.net.httpserver.HttpServer; public final class DispatchServer { private final InetSocketAddress address; private final Gson gson; - private QueryCurrRegionHttpRsp currRegion; + //private QueryCurrRegionHttpRsp currRegion; public String regionListBase64; - public String regionCurrentBase64; - + public HashMap regions; + public HashMap usersIngame; + public static String query_region_list = ""; public static String query_cur_region = ""; - + public DispatchServer() { + this.regions = new HashMap(); + this.usersIngame = new HashMap(); this.address = new InetSocketAddress(Grasscutter.getConfig().getDispatchOptions().Ip, Grasscutter.getConfig().getDispatchOptions().Port); this.gson = new GsonBuilder().create(); @@ -70,8 +71,13 @@ public final class DispatchServer { return gson; } - public QueryCurrRegionHttpRsp getCurrRegion() { - return currRegion; + public QueryCurrRegionHttpRsp getCurrRegion(InetSocketAddress address) { + if(usersIngame.containsKey(address)) { + return regions.get(usersIngame.get(address)).parsedRegionQuery; + } + + Grasscutter.getLogger().error("User is not logged in to dispatch server. " + address.getAddress() + ":" + address.getPort()); + return null; } public void loadQueries() { @@ -100,39 +106,67 @@ public final class DispatchServer { byte[] decoded2 = Base64.getDecoder().decode(query_cur_region); QueryCurrRegionHttpRsp regionQuery = QueryCurrRegionHttpRsp.parseFrom(decoded2); - RegionSimpleInfo server = RegionSimpleInfo.newBuilder() - .setName("os_usa") - .setTitle(Grasscutter.getConfig().getGameServerOptions().Name) - .setType("DEV_PUBLIC") - .setDispatchUrl("https://" + (Grasscutter.getConfig().getDispatchOptions().PublicIp.isEmpty() ? Grasscutter.getConfig().getDispatchOptions().Ip : Grasscutter.getConfig().getDispatchOptions().PublicIp) + ":" + getAddress().getPort() + "/query_cur_region") - .build(); - - RegionSimpleInfo serverTest2 = RegionSimpleInfo.newBuilder() - .setName("os_euro") - .setTitle("Grasscutter") - .setType("DEV_PUBLIC") - .setDispatchUrl("https://" + (Grasscutter.getConfig().getDispatchOptions().PublicIp.isEmpty() ? Grasscutter.getConfig().getDispatchOptions().Ip : Grasscutter.getConfig().getDispatchOptions().PublicIp) + ":" + getAddress().getPort() + "/query_cur_region") - .build(); - + List servers = new ArrayList(); + List usedNames = new ArrayList(); // List to check for potential naming conflicts + if(Grasscutter.getConfig().RunMode.equalsIgnoreCase("HYBRID")) { // Automatically add the game server if in hybrid mode + String defaultServerName = "os_usa"; + RegionSimpleInfo server = RegionSimpleInfo.newBuilder() + .setName("os_usa") + .setTitle(Grasscutter.getConfig().getGameServerOptions().Name) + .setType("DEV_PUBLIC") + .setDispatchUrl("https://" + (Grasscutter.getConfig().getDispatchOptions().PublicIp.isEmpty() ? Grasscutter.getConfig().getDispatchOptions().Ip : Grasscutter.getConfig().getDispatchOptions().PublicIp) + ":" + getAddress().getPort() + "/query_cur_region_" + defaultServerName) + .build(); + usedNames.add(defaultServerName); + servers.add(server); + + RegionInfo serverRegion = regionQuery.getRegionInfo().toBuilder() + .setIp((Grasscutter.getConfig().getGameServerOptions().PublicIp.isEmpty() ? Grasscutter.getConfig().getGameServerOptions().Ip : Grasscutter.getConfig().getGameServerOptions().PublicIp)) + .setPort(Grasscutter.getConfig().getGameServerOptions().Port) + .setSecretKey(ByteString.copyFrom(FileUtils.read(Grasscutter.getConfig().KEY_FOLDER + "dispatchSeed.bin"))) + .build(); + + QueryCurrRegionHttpRsp parsedRegionQuery = regionQuery.toBuilder().setRegionInfo(serverRegion).build(); + regions.put(defaultServerName, new RegionData(parsedRegionQuery, Base64.getEncoder().encodeToString(parsedRegionQuery.toByteString().toByteArray()))); + + } else { + if(Grasscutter.getConfig().getDispatchOptions().getGameServers().length == 0) { + Grasscutter.getLogger().error("Dispatch server has no game servers available. Exiting due to unplayable state."); + System.exit(1); + } + } + + for (Config.DispatchServerOptions.RegionInfo regionInfo : Grasscutter.getConfig().getDispatchOptions().getGameServers()) { + if(usedNames.contains(regionInfo.Name)) { + Grasscutter.getLogger().error("Region name already in use."); + continue; + } + RegionSimpleInfo server = RegionSimpleInfo.newBuilder() + .setName(regionInfo.Name) + .setTitle(regionInfo.Title) + .setType("DEV_PUBLIC") + .setDispatchUrl("https://" + (Grasscutter.getConfig().getDispatchOptions().PublicIp.isEmpty() ? Grasscutter.getConfig().getDispatchOptions().Ip : Grasscutter.getConfig().getDispatchOptions().PublicIp) + ":" + getAddress().getPort() + "/query_cur_region_" + regionInfo.Name) + .build(); + usedNames.add(regionInfo.Name); + servers.add(server); + + RegionInfo serverRegion = regionQuery.getRegionInfo().toBuilder() + .setIp(regionInfo.Ip) + .setPort(regionInfo.Port) + .setSecretKey(ByteString.copyFrom(FileUtils.read(Grasscutter.getConfig().KEY_FOLDER + "dispatchSeed.bin"))) + .build(); + + QueryCurrRegionHttpRsp parsedRegionQuery = regionQuery.toBuilder().setRegionInfo(serverRegion).build(); + regions.put(regionInfo.Name, new RegionData(parsedRegionQuery, Base64.getEncoder().encodeToString(parsedRegionQuery.toByteString().toByteArray()))); + } + QueryRegionListHttpRsp regionList = QueryRegionListHttpRsp.newBuilder() - .addServers(server) - .addServers(serverTest2) + .addAllServers(servers) .setClientSecretKey(rl.getClientSecretKey()) .setClientCustomConfigEncrypted(rl.getClientCustomConfigEncrypted()) .setEnableLoginPc(true) .build(); - - RegionInfo currentRegion = regionQuery.getRegionInfo().toBuilder() - .setIp((Grasscutter.getConfig().getGameServerOptions().PublicIp.isEmpty() ? Grasscutter.getConfig().getGameServerOptions().Ip : Grasscutter.getConfig().getGameServerOptions().PublicIp)) - .setPort(Grasscutter.getConfig().getGameServerOptions().Port) - .setSecretKey(ByteString.copyFrom(FileUtils.read(Grasscutter.getConfig().KEY_FOLDER + "dispatchSeed.bin"))) - .build(); - - QueryCurrRegionHttpRsp parsedRegionQuery = regionQuery.toBuilder().setRegionInfo(currentRegion).build(); this.regionListBase64 = Base64.getEncoder().encodeToString(regionList.toByteString().toByteArray()); - this.regionCurrentBase64 = Base64.getEncoder().encodeToString(parsedRegionQuery.toByteString().toByteArray()); - this.currRegion = parsedRegionQuery; } catch (Exception e) { Grasscutter.getLogger().error("Error while initializing region info!", e); } @@ -188,24 +222,36 @@ public final class DispatchServer { OutputStream os = t.getResponseBody(); os.write(response.getBytes()); os.close(); - }); - server.createContext("/query_cur_region", t -> { - // Log - Grasscutter.getLogger().info("Client request: query_cur_region"); - // Create a response form the request query parameters - URI uri = t.getRequestURI(); - String response = "CAESGE5vdCBGb3VuZCB2ZXJzaW9uIGNvbmZpZw=="; - if (uri.getQuery() != null && uri.getQuery().length() > 0) { - response = regionCurrentBase64; + + if(usersIngame.containsKey(t.getRemoteAddress())) { + usersIngame.remove(t.getRemoteAddress()); } - // Set the response header status and length - t.getResponseHeaders().put("Content-Type", Collections.singletonList("text/html; charset=UTF-8")); - t.sendResponseHeaders(200, response.getBytes().length); - // Write the response string - OutputStream os = t.getResponseBody(); - os.write(response.getBytes()); - os.close(); }); + + for (String regionName : regions.keySet()) { + server.createContext("/query_cur_region_" + regionName, t -> { + String regionCurrentBase64 = regions.get(regionName).Base64; + + // Log + Grasscutter.getLogger().info("Client request: query_cur_region_" + regionName); + // Create a response form the request query parameters + URI uri = t.getRequestURI(); + String response = "CAESGE5vdCBGb3VuZCB2ZXJzaW9uIGNvbmZpZw=="; + if (uri.getQuery() != null && uri.getQuery().length() > 0) { + response = regionCurrentBase64; + } + // Set the response header status and length + t.getResponseHeaders().put("Content-Type", Collections.singletonList("text/html; charset=UTF-8")); + t.sendResponseHeaders(200, response.getBytes().length); + // Write the response string + OutputStream os = t.getResponseBody(); + os.write(response.getBytes()); + os.close(); + //Save region info to hashmap for user, this for getCurrRegion(); + usersIngame.put(t.getRemoteAddress(), regionName); + }); + } + // Login via account server.createContext("/hk4e_global/mdk/shield/api/login", t -> { // Get post data @@ -464,4 +510,15 @@ public final class DispatchServer { } return result; } + + public static class RegionData { + + QueryCurrRegionHttpRsp parsedRegionQuery; + String Base64; + + public RegionData(QueryCurrRegionHttpRsp prq, String b64) { + this.parsedRegionQuery = prq; + this.Base64 = b64; + } + } } diff --git a/src/main/java/emu/grasscutter/server/packet/send/PacketPlayerLoginRsp.java b/src/main/java/emu/grasscutter/server/packet/send/PacketPlayerLoginRsp.java index 0d0871ca9..eef1a03e6 100644 --- a/src/main/java/emu/grasscutter/server/packet/send/PacketPlayerLoginRsp.java +++ b/src/main/java/emu/grasscutter/server/packet/send/PacketPlayerLoginRsp.java @@ -14,7 +14,7 @@ public class PacketPlayerLoginRsp extends GenshinPacket { this.setUseDispatchKey(true); - RegionInfo info = Grasscutter.getDispatchServer().getCurrRegion().getRegionInfo(); + RegionInfo info = Grasscutter.getDispatchServer().getCurrRegion(session.getAddress()).getRegionInfo(); PlayerLoginRsp p = PlayerLoginRsp.newBuilder() .setIsUseAbilityHash(true) // true From 127559274762356f05b7b5e1aefb14b032cba523 Mon Sep 17 00:00:00 2001 From: Benjamin Elsdon Date: Thu, 21 Apr 2022 19:20:49 +0800 Subject: [PATCH 3/8] Fixed null pointer exception in hybrid mode. --- .../server/dispatch/DispatchServer.java | 27 +++++++++---------- .../packet/send/PacketPlayerLoginRsp.java | 2 +- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java b/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java index 6b2661def..37ed6c5ac 100644 --- a/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java +++ b/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java @@ -5,6 +5,7 @@ import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; +import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.URI; import java.net.URLDecoder; @@ -44,18 +45,18 @@ import com.sun.net.httpserver.HttpServer; public final class DispatchServer { private final InetSocketAddress address; private final Gson gson; + private final String defaultServerName = "os_usa"; //private QueryCurrRegionHttpRsp currRegion; public String regionListBase64; public HashMap regions; - public HashMap usersIngame; + public HashMap usersConnected; public static String query_region_list = ""; public static String query_cur_region = ""; public DispatchServer() { this.regions = new HashMap(); - this.usersIngame = new HashMap(); this.address = new InetSocketAddress(Grasscutter.getConfig().getDispatchOptions().Ip, Grasscutter.getConfig().getDispatchOptions().Port); this.gson = new GsonBuilder().create(); @@ -71,12 +72,13 @@ public final class DispatchServer { return gson; } - public QueryCurrRegionHttpRsp getCurrRegion(InetSocketAddress address) { - if(usersIngame.containsKey(address)) { - return regions.get(usersIngame.get(address)).parsedRegionQuery; + public QueryCurrRegionHttpRsp getCurrRegion() { + // Needs to be fixed by having the game servers connect to the dispatch server. + if(Grasscutter.getConfig().RunMode.equalsIgnoreCase("HYBRID")) { + return regions.get(defaultServerName).parsedRegionQuery; } - Grasscutter.getLogger().error("User is not logged in to dispatch server. " + address.getAddress() + ":" + address.getPort()); + Grasscutter.getLogger().error("Ignore the error below"); return null; } @@ -109,7 +111,6 @@ public final class DispatchServer { List servers = new ArrayList(); List usedNames = new ArrayList(); // List to check for potential naming conflicts if(Grasscutter.getConfig().RunMode.equalsIgnoreCase("HYBRID")) { // Automatically add the game server if in hybrid mode - String defaultServerName = "os_usa"; RegionSimpleInfo server = RegionSimpleInfo.newBuilder() .setName("os_usa") .setTitle(Grasscutter.getConfig().getGameServerOptions().Name) @@ -222,16 +223,11 @@ public final class DispatchServer { OutputStream os = t.getResponseBody(); os.write(response.getBytes()); os.close(); - - if(usersIngame.containsKey(t.getRemoteAddress())) { - usersIngame.remove(t.getRemoteAddress()); - } }); for (String regionName : regions.keySet()) { server.createContext("/query_cur_region_" + regionName, t -> { String regionCurrentBase64 = regions.get(regionName).Base64; - // Log Grasscutter.getLogger().info("Client request: query_cur_region_" + regionName); // Create a response form the request query parameters @@ -247,8 +243,6 @@ public final class DispatchServer { OutputStream os = t.getResponseBody(); os.write(response.getBytes()); os.close(); - //Save region info to hashmap for user, this for getCurrRegion(); - usersIngame.put(t.getRemoteAddress(), regionName); }); } @@ -521,4 +515,9 @@ public final class DispatchServer { this.Base64 = b64; } } + + public static class UserConnnectionData { + public InetAddress dispatchConnectedAddress; + public String connectedRegion; + } } diff --git a/src/main/java/emu/grasscutter/server/packet/send/PacketPlayerLoginRsp.java b/src/main/java/emu/grasscutter/server/packet/send/PacketPlayerLoginRsp.java index eef1a03e6..0d0871ca9 100644 --- a/src/main/java/emu/grasscutter/server/packet/send/PacketPlayerLoginRsp.java +++ b/src/main/java/emu/grasscutter/server/packet/send/PacketPlayerLoginRsp.java @@ -14,7 +14,7 @@ public class PacketPlayerLoginRsp extends GenshinPacket { this.setUseDispatchKey(true); - RegionInfo info = Grasscutter.getDispatchServer().getCurrRegion(session.getAddress()).getRegionInfo(); + RegionInfo info = Grasscutter.getDispatchServer().getCurrRegion().getRegionInfo(); PlayerLoginRsp p = PlayerLoginRsp.newBuilder() .setIsUseAbilityHash(true) // true From 77fcce6510a55f52297220d178e28a11cd391393 Mon Sep 17 00:00:00 2001 From: Benjamin Elsdon Date: Thu, 21 Apr 2022 22:38:01 +0800 Subject: [PATCH 4/8] Fixed null pointer exception in game only mode PacketPlayerLoginRsp now creates the required QuerryCurrRegionHttpRsp itself. --- .../packet/send/PacketPlayerLoginRsp.java | 46 +++++++++++++++++-- 1 file changed, 43 insertions(+), 3 deletions(-) diff --git a/src/main/java/emu/grasscutter/server/packet/send/PacketPlayerLoginRsp.java b/src/main/java/emu/grasscutter/server/packet/send/PacketPlayerLoginRsp.java index 0d0871ca9..a5e167100 100644 --- a/src/main/java/emu/grasscutter/server/packet/send/PacketPlayerLoginRsp.java +++ b/src/main/java/emu/grasscutter/server/packet/send/PacketPlayerLoginRsp.java @@ -1,21 +1,61 @@ package emu.grasscutter.server.packet.send; +import com.google.protobuf.ByteString; import emu.grasscutter.Grasscutter; import emu.grasscutter.net.packet.GenshinPacket; import emu.grasscutter.net.packet.PacketOpcodes; import emu.grasscutter.net.proto.PlayerLoginRspOuterClass.PlayerLoginRsp; +import emu.grasscutter.net.proto.QueryCurrRegionHttpRspOuterClass; import emu.grasscutter.net.proto.RegionInfoOuterClass.RegionInfo; import emu.grasscutter.server.game.GameSession; +import emu.grasscutter.utils.FileUtils; + +import java.io.File; +import java.net.URL; +import java.util.Base64; public class PacketPlayerLoginRsp extends GenshinPacket { + private static QueryCurrRegionHttpRspOuterClass.QueryCurrRegionHttpRsp regionCache; + public PacketPlayerLoginRsp(GameSession session) { super(PacketOpcodes.PlayerLoginRsp, 1); this.setUseDispatchKey(true); - - RegionInfo info = Grasscutter.getDispatchServer().getCurrRegion().getRegionInfo(); - + + RegionInfo info; + + if(Grasscutter.getConfig().RunMode.equalsIgnoreCase("GAME_ONLY")) { + if (regionCache == null) { + try { + File file = new File(Grasscutter.getConfig().DATA_FOLDER + "query_cur_region.txt"); + String query_cur_region = ""; + if (file.exists()) { + query_cur_region = new String(FileUtils.read(file)); + } else { + Grasscutter.getLogger().warn("query_cur_region not found! Using default current region."); + } + + byte[] decodedCurRegion = Base64.getDecoder().decode(query_cur_region); + QueryCurrRegionHttpRspOuterClass.QueryCurrRegionHttpRsp regionQuery = QueryCurrRegionHttpRspOuterClass.QueryCurrRegionHttpRsp.parseFrom(decodedCurRegion); + + RegionInfo serverRegion = regionQuery.getRegionInfo().toBuilder() + .setIp((Grasscutter.getConfig().getGameServerOptions().PublicIp.isEmpty() ? Grasscutter.getConfig().getGameServerOptions().Ip : Grasscutter.getConfig().getGameServerOptions().PublicIp)) + .setPort(Grasscutter.getConfig().getGameServerOptions().Port) + .setSecretKey(ByteString.copyFrom(FileUtils.read(Grasscutter.getConfig().KEY_FOLDER + "dispatchSeed.bin"))) + .build(); + + regionCache = regionQuery.toBuilder().setRegionInfo(serverRegion).build(); + } catch (Exception e) { + Grasscutter.getLogger().error("Error while initializing region cache!", e); + } + } + + info = regionCache.getRegionInfo(); + } else { + info = Grasscutter.getDispatchServer().getCurrRegion().getRegionInfo(); + } + PlayerLoginRsp p = PlayerLoginRsp.newBuilder() .setIsUseAbilityHash(true) // true .setAbilityHashCode(1844674) // 1844674 From 1969d38e06bbda9b04f438ea1f1bb672812bbe1a Mon Sep 17 00:00:00 2001 From: Benjamin Elsdon Date: Thu, 21 Apr 2022 22:50:06 +0800 Subject: [PATCH 5/8] DatabaseManager clean up --- .../grasscutter/database/DatabaseManager.java | 36 ++++++++++--------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/src/main/java/emu/grasscutter/database/DatabaseManager.java b/src/main/java/emu/grasscutter/database/DatabaseManager.java index 530581517..46dad537d 100644 --- a/src/main/java/emu/grasscutter/database/DatabaseManager.java +++ b/src/main/java/emu/grasscutter/database/DatabaseManager.java @@ -38,7 +38,8 @@ public final class DatabaseManager { return getDatastore().getDatabase(); } - // Yes. I very dislike this method also but I'm lazy. Probably replace it by making the game server connect to the dispatch server instead. + // Yes. I very dislike this method. However, this will be good for now. + // TODO: Add dispatch routes for player account management public static Datastore getAccountDatastore() { if(Grasscutter.getConfig().RunMode.equalsIgnoreCase("GAME_ONLY")) { return dispatchDatastore; @@ -50,7 +51,6 @@ public final class DatabaseManager { public static void initialize() { // Initialize mongoClient = new MongoClient(new MongoClientURI(Grasscutter.getConfig().DatabaseUrl)); - dispatchMongoClient = new MongoClient(new MongoClientURI(Grasscutter.getConfig().getGameServerOptions().DispatchServerDatabaseUrl)); Morphia morphia = new Morphia(); // TODO Update when migrating to Morphia 2.0 @@ -63,7 +63,6 @@ public final class DatabaseManager { // Build datastore datastore = morphia.createDatastore(mongoClient, Grasscutter.getConfig().DatabaseCollection); - dispatchDatastore = morphia.createDatastore(dispatchMongoClient, Grasscutter.getConfig().getGameServerOptions().DispatchServerDatabaseCollection); // Ensure indexes try { @@ -82,20 +81,25 @@ public final class DatabaseManager { } } - // Ensure indexes for dispatch server - try { - dispatchDatastore.ensureIndexes(); - } catch (MongoCommandException e) { - Grasscutter.getLogger().info("Mongo index error: ", e); - // Duplicate index error - if (e.getCode() == 85) { - // Drop all indexes and re add them - MongoIterable collections = dispatchDatastore.getDatabase().listCollectionNames(); - for (String name : collections) { - dispatchDatastore.getDatabase().getCollection(name).dropIndexes(); - } - // Add back indexes + if(Grasscutter.getConfig().RunMode.equalsIgnoreCase("GAME_ONLY")) { + dispatchMongoClient = new MongoClient(new MongoClientURI(Grasscutter.getConfig().getGameServerOptions().DispatchServerDatabaseUrl)); + dispatchDatastore = morphia.createDatastore(dispatchMongoClient, Grasscutter.getConfig().getGameServerOptions().DispatchServerDatabaseCollection); + + // Ensure indexes for dispatch server + try { dispatchDatastore.ensureIndexes(); + } catch (MongoCommandException e) { + Grasscutter.getLogger().info("Mongo index error: ", e); + // Duplicate index error + if (e.getCode() == 85) { + // Drop all indexes and re add them + MongoIterable collections = dispatchDatastore.getDatabase().listCollectionNames(); + for (String name : collections) { + dispatchDatastore.getDatabase().getCollection(name).dropIndexes(); + } + // Add back indexes + dispatchDatastore.ensureIndexes(); + } } } } From 2c509237a5d8f11f9382dbb153d9efd5df5b4555 Mon Sep 17 00:00:00 2001 From: Benjamin Elsdon Date: Thu, 21 Apr 2022 23:00:36 +0800 Subject: [PATCH 6/8] Removed class left over from testing --- .../java/emu/grasscutter/server/dispatch/DispatchServer.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java b/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java index 37ed6c5ac..1978e6b08 100644 --- a/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java +++ b/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java @@ -515,9 +515,4 @@ public final class DispatchServer { this.Base64 = b64; } } - - public static class UserConnnectionData { - public InetAddress dispatchConnectedAddress; - public String connectedRegion; - } } From beb8675190000de00e2ae40b6e524b4ae5ad4b5c Mon Sep 17 00:00:00 2001 From: Benjamin Elsdon Date: Thu, 21 Apr 2022 23:04:02 +0800 Subject: [PATCH 7/8] Should probably remove this as well... --- .../java/emu/grasscutter/server/dispatch/DispatchServer.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java b/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java index 1978e6b08..f77c264eb 100644 --- a/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java +++ b/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java @@ -50,7 +50,6 @@ public final class DispatchServer { public String regionListBase64; public HashMap regions; - public HashMap usersConnected; public static String query_region_list = ""; public static String query_cur_region = ""; From 23caf994c79c27d6c6e4f03af311ec52eb48cf40 Mon Sep 17 00:00:00 2001 From: Benjamin Elsdon Date: Fri, 22 Apr 2022 01:15:05 +0800 Subject: [PATCH 8/8] Forgot a dispatch prefix on error while merging --- .../java/emu/grasscutter/server/dispatch/DispatchServer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java b/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java index a058bed6b..ad8354867 100644 --- a/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java +++ b/src/main/java/emu/grasscutter/server/dispatch/DispatchServer.java @@ -155,7 +155,7 @@ public final class DispatchServer { this.regionListBase64 = Base64.getEncoder().encodeToString(regionList.toByteString().toByteArray()); } catch (Exception e) { - Grasscutter.getLogger().error("Error while initializing region info!", e); + Grasscutter.getLogger().error("[Dispatch] Error while initializing region info!", e); } }