Commit 16318b37 authored by Melledy's avatar Melledy Committed by GitHub
Browse files

Merge pull request #74 from 4Benj/development

Server run modes and multi-server dispatch support
parents 8b5d7855 23caf994
package emu.grasscutter; package emu.grasscutter;
public final class Config { import java.util.ArrayList;
public String DispatchServerIp = "0.0.0.0";
public String DispatchServerPublicIp = "127.0.0.1";
public int DispatchServerPort = 443;
public String DispatchServerKeystorePath = "./keystore.p12";
public String DispatchServerKeystorePassword = "";
public Boolean UseSSL = true;
public String GameServerName = "Test"; public final class Config {
public String GameServerIp = "0.0.0.0";
public String GameServerPublicIp = "127.0.0.1";
public int GameServerPort = 22102;
public String DatabaseUrl = "mongodb://localhost:27017"; public String DatabaseUrl = "mongodb://localhost:27017";
public String DatabaseCollection = "grasscutter"; public String DatabaseCollection = "grasscutter";
...@@ -21,26 +12,52 @@ public final class Config { ...@@ -21,26 +12,52 @@ public final class Config {
public String PACKETS_FOLDER = "./packets/"; public String PACKETS_FOLDER = "./packets/";
public String DUMPS_FOLDER = "./dumps/"; public String DUMPS_FOLDER = "./dumps/";
public String KEY_FOLDER = "./keys/"; public String KEY_FOLDER = "./keys/";
public boolean LOG_PACKETS = false;
public GameRates Game = new GameRates(); public String RunMode = "HYBRID"; // HYBRID, DISPATCH_ONLY, GAME_ONLY
public ServerOptions ServerOptions = new ServerOptions(); public GameServerOptions GameServer = new GameServerOptions();
public DispatchServerOptions DispatchServer = new DispatchServerOptions();
public GameRates getGameRates() { public GameServerOptions getGameServerOptions() {
return Game; return GameServer;
} }
public ServerOptions getServerOptions() { public DispatchServerOptions getDispatchOptions() { return DispatchServer; }
return ServerOptions;
public static class DispatchServerOptions {
public String Ip = "0.0.0.0";
public String PublicIp = "127.0.0.1";
public int Port = 443;
public String KeystorePath = "./keystore.p12";
public String KeystorePassword = "";
public Boolean UseSSL = true;
public boolean AutomaticallyCreateAccounts = false;
public RegionInfo[] GameServers = {};
public RegionInfo[] getGameServers() {
return GameServers;
} }
public static class GameRates { public static class RegionInfo {
public float ADVENTURE_EXP_RATE = 1.0f; public String Name = "os_usa";
public float MORA_RATE = 1.0f; public String Title = "Test";
public float DOMAIN_DROP_RATE = 1.0f; public String Ip = "127.0.0.1";
public int Port = 22102;
} }
}
public static class GameServerOptions {
public String Name = "Test";
public String Ip = "0.0.0.0";
public String PublicIp = "127.0.0.1";
public int Port = 22102;
public String DispatchServerDatabaseUrl = "mongodb://localhost:27017";
public String DispatchServerDatabaseCollection = "grasscutter";
public boolean LOG_PACKETS = false;
public static class ServerOptions {
public int InventoryLimitWeapon = 2000; public int InventoryLimitWeapon = 2000;
public int InventoryLimitRelic = 2000; public int InventoryLimitRelic = 2000;
public int InventoryLimitMaterial = 2000; public int InventoryLimitMaterial = 2000;
...@@ -52,6 +69,15 @@ public final class Config { ...@@ -52,6 +69,15 @@ public final class Config {
public boolean WatchGacha = false; public boolean WatchGacha = false;
public int[] WelcomeEmotes = {2007, 1002, 4010}; public int[] WelcomeEmotes = {2007, 1002, 4010};
public String WelcomeMotd = "Welcome to Grasscutter emu"; 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;
}
} }
} }
...@@ -73,11 +73,26 @@ public final class Grasscutter { ...@@ -73,11 +73,26 @@ public final class Grasscutter {
DatabaseManager.initialize(); DatabaseManager.initialize();
// Start servers. // Start servers.
if(getConfig().RunMode.equalsIgnoreCase("HYBRID")) {
dispatchServer = new DispatchServer(); dispatchServer = new DispatchServer();
dispatchServer.start(); dispatchServer.start();
gameServer = new GameServer(new InetSocketAddress(getConfig().GameServerIp, getConfig().GameServerPort)); gameServer = new GameServer(new InetSocketAddress(getConfig().getGameServerOptions().Ip, getConfig().getGameServerOptions().Port));
gameServer.start(); 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. // Open console.
startConsole(); startConsole();
...@@ -106,9 +121,14 @@ public final class Grasscutter { ...@@ -106,9 +121,14 @@ public final class Grasscutter {
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
while ((input = br.readLine()) != null) { while ((input = br.readLine()) != null) {
try { try {
if(getConfig().RunMode.equalsIgnoreCase("DISPATCH_ONLY")) {
getLogger().error("Commands are not supported in dispatch only mode");
return;
}
CommandMap.getInstance().invoke(null, input); CommandMap.getInstance().invoke(null, input);
} catch (Exception e) { } catch (Exception e) {
Grasscutter.getLogger().error("Command error: " + e.getMessage()); Grasscutter.getLogger().error("Command error: ");
e.printStackTrace();
} }
} }
} catch (Exception e) { } catch (Exception e) {
......
...@@ -74,36 +74,36 @@ public class DatabaseHelper { ...@@ -74,36 +74,36 @@ public class DatabaseHelper {
} }
public static void saveAccount(Account account) { public static void saveAccount(Account account) {
DatabaseManager.getDatastore().save(account); DatabaseManager.getAccountDatastore().save(account);
} }
public static Account getAccountByName(String username) { public static Account getAccountByName(String username) {
MorphiaCursor<Account> cursor = DatabaseManager.getDatastore().createQuery(Account.class).field("username").equalIgnoreCase(username).find(FIND_ONE); MorphiaCursor<Account> cursor = DatabaseManager.getAccountDatastore().createQuery(Account.class).field("username").equalIgnoreCase(username).find(FIND_ONE);
if (!cursor.hasNext()) return null; if (!cursor.hasNext()) return null;
return cursor.next(); return cursor.next();
} }
public static Account getAccountByToken(String token) { public static Account getAccountByToken(String token) {
if (token == null) return null; if (token == null) return null;
MorphiaCursor<Account> cursor = DatabaseManager.getDatastore().createQuery(Account.class).field("token").equal(token).find(FIND_ONE); MorphiaCursor<Account> cursor = DatabaseManager.getAccountDatastore().createQuery(Account.class).field("token").equal(token).find(FIND_ONE);
if (!cursor.hasNext()) return null; if (!cursor.hasNext()) return null;
return cursor.next(); return cursor.next();
} }
public static Account getAccountById(String uid) { public static Account getAccountById(String uid) {
MorphiaCursor<Account> cursor = DatabaseManager.getDatastore().createQuery(Account.class).field("_id").equal(uid).find(FIND_ONE); MorphiaCursor<Account> cursor = DatabaseManager.getAccountDatastore().createQuery(Account.class).field("_id").equal(uid).find(FIND_ONE);
if (!cursor.hasNext()) return null; if (!cursor.hasNext()) return null;
return cursor.next(); return cursor.next();
} }
public static Account getAccountByPlayerId(int playerId) { public static Account getAccountByPlayerId(int playerId) {
MorphiaCursor<Account> cursor = DatabaseManager.getDatastore().createQuery(Account.class).field("playerId").equal(playerId).find(FIND_ONE); MorphiaCursor<Account> cursor = DatabaseManager.getAccountDatastore().createQuery(Account.class).field("playerId").equal(playerId).find(FIND_ONE);
if (!cursor.hasNext()) return null; if (!cursor.hasNext()) return null;
return cursor.next(); return cursor.next();
} }
public static boolean deleteAccount(String username) { public static boolean deleteAccount(String username) {
Query<Account> q = DatabaseManager.getDatastore().createQuery(Account.class).field("username").equalIgnoreCase(username); Query<Account> q = DatabaseManager.getAccountDatastore().createQuery(Account.class).field("username").equalIgnoreCase(username);
return DatabaseManager.getDatastore().findAndDelete(q) != null; return DatabaseManager.getDatastore().findAndDelete(q) != null;
} }
......
...@@ -17,7 +17,10 @@ import emu.grasscutter.game.inventory.GenshinItem; ...@@ -17,7 +17,10 @@ import emu.grasscutter.game.inventory.GenshinItem;
public final class DatabaseManager { public final class DatabaseManager {
private static MongoClient mongoClient; private static MongoClient mongoClient;
private static MongoClient dispatchMongoClient;
private static Datastore datastore; private static Datastore datastore;
private static Datastore dispatchDatastore;
private static final Class<?>[] mappedClasses = new Class<?>[] { private static final Class<?>[] mappedClasses = new Class<?>[] {
DatabaseCounter.class, Account.class, GenshinPlayer.class, GenshinAvatar.class, GenshinItem.class, Friendship.class DatabaseCounter.class, Account.class, GenshinPlayer.class, GenshinAvatar.class, GenshinItem.class, Friendship.class
...@@ -35,6 +38,16 @@ public final class DatabaseManager { ...@@ -35,6 +38,16 @@ public final class DatabaseManager {
return getDatastore().getDatabase(); return getDatastore().getDatabase();
} }
// 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;
} else {
return datastore;
}
}
public static void initialize() { public static void initialize() {
// Initialize // Initialize
mongoClient = new MongoClient(new MongoClientURI(Grasscutter.getConfig().DatabaseUrl)); mongoClient = new MongoClient(new MongoClientURI(Grasscutter.getConfig().DatabaseUrl));
...@@ -67,6 +80,28 @@ public final class DatabaseManager { ...@@ -67,6 +80,28 @@ public final class DatabaseManager {
datastore.ensureIndexes(); datastore.ensureIndexes();
} }
} }
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<String> 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) { public static synchronized int getNextId(Class<?> c) {
......
...@@ -293,7 +293,7 @@ public class GenshinPlayer { ...@@ -293,7 +293,7 @@ public class GenshinPlayer {
} }
private float getExpModifier() { private float getExpModifier() {
return Grasscutter.getConfig().getGameRates().ADVENTURE_EXP_RATE; return Grasscutter.getConfig().getGameServerOptions().getGameRates().ADVENTURE_EXP_RATE;
} }
// Affected by exp rate // Affected by exp rate
......
...@@ -13,7 +13,7 @@ public class TeamInfo { ...@@ -13,7 +13,7 @@ public class TeamInfo {
public TeamInfo() { public TeamInfo() {
this.name = ""; this.name = "";
this.avatars = new ArrayList<>(Grasscutter.getConfig().getServerOptions().MaxAvatarsInTeam); this.avatars = new ArrayList<>(Grasscutter.getConfig().getGameServerOptions().MaxAvatarsInTeam);
} }
public String getName() { public String getName() {
...@@ -37,7 +37,7 @@ public class TeamInfo { ...@@ -37,7 +37,7 @@ public class TeamInfo {
} }
public boolean addAvatar(GenshinAvatar avatar) { public boolean addAvatar(GenshinAvatar avatar) {
if (size() >= Grasscutter.getConfig().getServerOptions().MaxAvatarsInTeam || contains(avatar)) { if (size() >= Grasscutter.getConfig().getGameServerOptions().MaxAvatarsInTeam || contains(avatar)) {
return false; return false;
} }
...@@ -57,7 +57,7 @@ public class TeamInfo { ...@@ -57,7 +57,7 @@ public class TeamInfo {
} }
public void copyFrom(TeamInfo team) { public void copyFrom(TeamInfo team) {
copyFrom(team, Grasscutter.getConfig().getServerOptions().MaxAvatarsInTeam); copyFrom(team, Grasscutter.getConfig().getGameServerOptions().MaxAvatarsInTeam);
} }
public void copyFrom(TeamInfo team, int maxTeamSize) { public void copyFrom(TeamInfo team, int maxTeamSize) {
......
...@@ -164,13 +164,13 @@ public class TeamManager { ...@@ -164,13 +164,13 @@ public class TeamManager {
public int getMaxTeamSize() { public int getMaxTeamSize() {
if (getPlayer().isInMultiplayer()) { if (getPlayer().isInMultiplayer()) {
int max = Grasscutter.getConfig().getServerOptions().MaxAvatarsInTeamMultiplayer; int max = Grasscutter.getConfig().getGameServerOptions().MaxAvatarsInTeamMultiplayer;
if (getPlayer().getWorld().getHost() == this.getPlayer()) { if (getPlayer().getWorld().getHost() == this.getPlayer()) {
return Math.max(1, (int) Math.ceil(max / (double) getWorld().getPlayerCount())); return Math.max(1, (int) Math.ceil(max / (double) getWorld().getPlayerCount()));
} }
return Math.max(1, (int) Math.floor(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 // Methods
......
...@@ -92,7 +92,7 @@ public class GachaBanner { ...@@ -92,7 +92,7 @@ public class GachaBanner {
} }
public GachaInfo toProto() { 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() GachaInfo.Builder info = GachaInfo.newBuilder()
.setGachaType(this.getGachaType()) .setGachaType(this.getGachaType())
......
...@@ -299,7 +299,7 @@ public class GachaManager { ...@@ -299,7 +299,7 @@ public class GachaManager {
@Subscribe @Subscribe
public synchronized void watchBannerJson(GameServerTickEvent tickEvent) { public synchronized void watchBannerJson(GameServerTickEvent tickEvent) {
if(Grasscutter.getConfig().getServerOptions().WatchGacha) { if(Grasscutter.getConfig().getGameServerOptions().WatchGacha) {
try { try {
WatchKey watchKey = watchService.take(); WatchKey watchKey = watchService.take();
......
...@@ -37,10 +37,10 @@ public class Inventory implements Iterable<GenshinItem> { ...@@ -37,10 +37,10 @@ public class Inventory implements Iterable<GenshinItem> {
this.store = new Long2ObjectOpenHashMap<>(); this.store = new Long2ObjectOpenHashMap<>();
this.inventoryTypes = new Int2ObjectOpenHashMap<>(); this.inventoryTypes = new Int2ObjectOpenHashMap<>();
this.createInventoryTab(ItemType.ITEM_WEAPON, new EquipInventoryTab(Grasscutter.getConfig().getServerOptions().InventoryLimitWeapon)); this.createInventoryTab(ItemType.ITEM_WEAPON, new EquipInventoryTab(Grasscutter.getConfig().getGameServerOptions().InventoryLimitWeapon));
this.createInventoryTab(ItemType.ITEM_RELIQUARY, new EquipInventoryTab(Grasscutter.getConfig().getServerOptions().InventoryLimitRelic)); this.createInventoryTab(ItemType.ITEM_RELIQUARY, new EquipInventoryTab(Grasscutter.getConfig().getGameServerOptions().InventoryLimitRelic));
this.createInventoryTab(ItemType.ITEM_MATERIAL, new MaterialInventoryTab(Grasscutter.getConfig().getServerOptions().InventoryLimitMaterial)); this.createInventoryTab(ItemType.ITEM_MATERIAL, new MaterialInventoryTab(Grasscutter.getConfig().getGameServerOptions().InventoryLimitMaterial));
this.createInventoryTab(ItemType.ITEM_FURNITURE, new MaterialInventoryTab(Grasscutter.getConfig().getServerOptions().InventoryLimitFurniture)); this.createInventoryTab(ItemType.ITEM_FURNITURE, new MaterialInventoryTab(Grasscutter.getConfig().getGameServerOptions().InventoryLimitFurniture));
} }
public GenshinPlayer getPlayer() { public GenshinPlayer getPlayer() {
......
...@@ -7,6 +7,8 @@ import com.sun.net.httpserver.HttpExchange; ...@@ -7,6 +7,8 @@ import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsServer; import com.sun.net.httpserver.HttpsServer;
import emu.grasscutter.Config;
import emu.grasscutter.Grasscutter; import emu.grasscutter.Grasscutter;
import emu.grasscutter.database.DatabaseHelper; import emu.grasscutter.database.DatabaseHelper;
import emu.grasscutter.game.Account; import emu.grasscutter.game.Account;
...@@ -26,22 +28,22 @@ import java.net.InetSocketAddress; ...@@ -26,22 +28,22 @@ import java.net.InetSocketAddress;
import java.net.URI; import java.net.URI;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.security.KeyStore; import java.security.KeyStore;
import java.util.Base64; import java.util.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public final class DispatchServer { public final class DispatchServer {
public static String query_region_list = ""; public static String query_region_list = "";
public static String query_cur_region = ""; public static String query_cur_region = "";
private final InetSocketAddress address; private final InetSocketAddress address;
private final Gson gson; private final Gson gson;
private final String defaultServerName = "os_usa";
public String regionListBase64; public String regionListBase64;
public String regionCurrentBase64; public HashMap<String, RegionData> regions;
private QueryCurrRegionHttpRsp currRegion;
public DispatchServer() { public DispatchServer() {
this.address = new InetSocketAddress(Grasscutter.getConfig().DispatchServerIp, Grasscutter.getConfig().DispatchServerPort); this.regions = new HashMap<String, RegionData>();
this.address = new InetSocketAddress(Grasscutter.getConfig().getDispatchOptions().Ip, Grasscutter.getConfig().getDispatchOptions().Port);
this.gson = new GsonBuilder().create(); this.gson = new GsonBuilder().create();
this.loadQueries(); this.loadQueries();
...@@ -57,7 +59,13 @@ public final class DispatchServer { ...@@ -57,7 +59,13 @@ public final class DispatchServer {
} }
public QueryCurrRegionHttpRsp getCurrRegion() { public QueryCurrRegionHttpRsp getCurrRegion() {
return currRegion; // 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().warn("[Dispatch] Unsupported run mode for getCurrRegion()");
return null;
} }
public void loadQueries() { public void loadQueries() {
...@@ -86,39 +94,66 @@ public final class DispatchServer { ...@@ -86,39 +94,66 @@ public final class DispatchServer {
byte[] decoded2 = Base64.getDecoder().decode(query_cur_region); byte[] decoded2 = Base64.getDecoder().decode(query_cur_region);
QueryCurrRegionHttpRsp regionQuery = QueryCurrRegionHttpRsp.parseFrom(decoded2); QueryCurrRegionHttpRsp regionQuery = QueryCurrRegionHttpRsp.parseFrom(decoded2);
List<RegionSimpleInfo> servers = new ArrayList<RegionSimpleInfo>();
List<String> usedNames = new ArrayList<String>(); // List to check for potential naming conflicts
if(Grasscutter.getConfig().RunMode.equalsIgnoreCase("HYBRID")) { // Automatically add the game server if in hybrid mode
RegionSimpleInfo server = RegionSimpleInfo.newBuilder() RegionSimpleInfo server = RegionSimpleInfo.newBuilder()
.setName("os_usa") .setName("os_usa")
.setTitle(Grasscutter.getConfig().GameServerName) .setTitle(Grasscutter.getConfig().getGameServerOptions().Name)
.setType("DEV_PUBLIC") .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_" + defaultServerName)
.build(); .build();
usedNames.add(defaultServerName);
servers.add(server);
RegionSimpleInfo serverTest2 = RegionSimpleInfo.newBuilder() RegionInfo serverRegion = regionQuery.getRegionInfo().toBuilder()
.setName("os_euro") .setIp((Grasscutter.getConfig().getGameServerOptions().PublicIp.isEmpty() ? Grasscutter.getConfig().getGameServerOptions().Ip : Grasscutter.getConfig().getGameServerOptions().PublicIp))
.setTitle("Grasscutter") .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] There are 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") .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_" + 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(); .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() QueryRegionListHttpRsp regionList = QueryRegionListHttpRsp.newBuilder()
.addServers(server) .addAllServers(servers)
.addServers(serverTest2)
.setClientSecretKey(rl.getClientSecretKey()) .setClientSecretKey(rl.getClientSecretKey())
.setClientCustomConfigEncrypted(rl.getClientCustomConfigEncrypted()) .setClientCustomConfigEncrypted(rl.getClientCustomConfigEncrypted())
.setEnableLoginPc(true) .setEnableLoginPc(true)
.build(); .build();
RegionInfo currentRegion = regionQuery.getRegionInfo().toBuilder()
.setIp((Grasscutter.getConfig().GameServerPublicIp.isEmpty() ? Grasscutter.getConfig().GameServerIp : Grasscutter.getConfig().GameServerPublicIp))
.setPort(Grasscutter.getConfig().GameServerPort)
.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.regionListBase64 = Base64.getEncoder().encodeToString(regionList.toByteString().toByteArray());
this.regionCurrentBase64 = Base64.getEncoder().encodeToString(parsedRegionQuery.toByteString().toByteArray());
this.currRegion = parsedRegionQuery;
} catch (Exception e) { } catch (Exception e) {
Grasscutter.getLogger().error("[Dispatch] Error while initializing region info!", e); Grasscutter.getLogger().error("[Dispatch] Error while initializing region info!", e);
} }
...@@ -126,12 +161,12 @@ public final class DispatchServer { ...@@ -126,12 +161,12 @@ public final class DispatchServer {
public void start() throws Exception { public void start() throws Exception {
HttpServer server; HttpServer server;
if (Grasscutter.getConfig().UseSSL) { if (Grasscutter.getConfig().getDispatchOptions().UseSSL) {
HttpsServer httpsServer; HttpsServer httpsServer;
httpsServer = HttpsServer.create(getAddress(), 0); httpsServer = HttpsServer.create(getAddress(), 0);
SSLContext sslContext = SSLContext.getInstance("TLS"); SSLContext sslContext = SSLContext.getInstance("TLS");
try (FileInputStream fis = new FileInputStream(Grasscutter.getConfig().DispatchServerKeystorePath)) { try (FileInputStream fis = new FileInputStream(Grasscutter.getConfig().getDispatchOptions().KeystorePath)) {
char[] keystorePassword = Grasscutter.getConfig().DispatchServerKeystorePassword.toCharArray(); char[] keystorePassword = Grasscutter.getConfig().getDispatchOptions().KeystorePassword.toCharArray();
KeyStore ks = KeyStore.getInstance("PKCS12"); KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(fis, keystorePassword); ks.load(fis, keystorePassword);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
...@@ -143,7 +178,7 @@ public final class DispatchServer { ...@@ -143,7 +178,7 @@ public final class DispatchServer {
server = httpsServer; server = httpsServer;
} catch (Exception e) { } catch (Exception e) {
Grasscutter.getLogger().warn("[Dispatch] No SSL cert found! Falling back to HTTP server."); Grasscutter.getLogger().warn("[Dispatch] No SSL cert found! Falling back to HTTP server.");
Grasscutter.getConfig().UseSSL = false; Grasscutter.getConfig().getDispatchOptions().UseSSL = false;
server = HttpServer.create(getAddress(), 0); server = HttpServer.create(getAddress(), 0);
} }
} else { } else {
...@@ -159,18 +194,22 @@ public final class DispatchServer { ...@@ -159,18 +194,22 @@ public final class DispatchServer {
responseHTML(t, regionListBase64); responseHTML(t, regionListBase64);
}); });
server.createContext("/query_cur_region", t -> {
for (String regionName : regions.keySet()) {
server.createContext("/query_cur_region_" + regionName, t -> {
String regionCurrentBase64 = regions.get(regionName).Base64;
// Log // Log
Grasscutter.getLogger().info(String.format("[Dispatch] Client %s request: query_cur_region", t.getRemoteAddress())); Grasscutter.getLogger().info(String.format("Client %s request: query_cur_region_%s", t.getRemoteAddress(), regionName));
// Create a response form the request query parameters // Create a response form the request query parameters
URI uri = t.getRequestURI(); URI uri = t.getRequestURI();
String response = "CAESGE5vdCBGb3VuZCB2ZXJzaW9uIGNvbmZpZw=="; String response = "CAESGE5vdCBGb3VuZCB2ZXJzaW9uIGNvbmZpZw==";
if (uri.getQuery() != null && uri.getQuery().length() > 0) { if (uri.getQuery() != null && uri.getQuery().length() > 0) {
response = regionCurrentBase64; response = regionCurrentBase64;
} }
responseHTML(t, response); responseHTML(t, response);
}); });
}
// Login via account // Login via account
server.createContext("/hk4e_global/mdk/shield/api/login", t -> { server.createContext("/hk4e_global/mdk/shield/api/login", t -> {
// Get post data // Get post data
...@@ -178,8 +217,8 @@ public final class DispatchServer { ...@@ -178,8 +217,8 @@ public final class DispatchServer {
try { try {
String body = Utils.toString(t.getRequestBody()); String body = Utils.toString(t.getRequestBody());
requestData = getGsonFactory().fromJson(body, LoginAccountRequestJson.class); requestData = getGsonFactory().fromJson(body, LoginAccountRequestJson.class);
} catch (Exception ignored) { } catch (Exception ignored) { }
}
// Create response json // Create response json
if (requestData == null) { if (requestData == null) {
return; return;
...@@ -194,7 +233,7 @@ public final class DispatchServer { ...@@ -194,7 +233,7 @@ public final class DispatchServer {
// Check if account exists, else create a new one. // Check if account exists, else create a new one.
if (account == null) { if (account == null) {
// Account doesnt exist, so we can either auto create it if the config value is set // 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. // This account has been created AUTOMATICALLY. There will be no permissions added.
account = DatabaseHelper.createAccountWithId(requestData.account, 0); account = DatabaseHelper.createAccountWithId(requestData.account, 0);
...@@ -229,7 +268,6 @@ public final class DispatchServer { ...@@ -229,7 +268,6 @@ public final class DispatchServer {
responseJSON(t, responseData); responseJSON(t, responseData);
}); });
// Login via token // Login via token
server.createContext("/hk4e_global/mdk/shield/api/verify", t -> { server.createContext("/hk4e_global/mdk/shield/api/verify", t -> {
// Get post data // Get post data
...@@ -237,8 +275,8 @@ public final class DispatchServer { ...@@ -237,8 +275,8 @@ public final class DispatchServer {
try { try {
String body = Utils.toString(t.getRequestBody()); String body = Utils.toString(t.getRequestBody());
requestData = getGsonFactory().fromJson(body, LoginTokenRequestJson.class); requestData = getGsonFactory().fromJson(body, LoginTokenRequestJson.class);
} catch (Exception ignored) { } catch (Exception ignored) { }
}
// Create response json // Create response json
if (requestData == null) { if (requestData == null) {
return; return;
...@@ -273,8 +311,8 @@ public final class DispatchServer { ...@@ -273,8 +311,8 @@ public final class DispatchServer {
try { try {
String body = Utils.toString(t.getRequestBody()); String body = Utils.toString(t.getRequestBody());
requestData = getGsonFactory().fromJson(body, ComboTokenReqJson.class); requestData = getGsonFactory().fromJson(body, ComboTokenReqJson.class);
} catch (Exception ignored) { } catch (Exception ignored) { }
}
// Create response json // Create response json
if (requestData == null || requestData.data == null) { if (requestData == null || requestData.data == null) {
return; return;
...@@ -380,6 +418,7 @@ public final class DispatchServer { ...@@ -380,6 +418,7 @@ public final class DispatchServer {
new DispatchHttpJsonHandler("{\"code\":0}") new DispatchHttpJsonHandler("{\"code\":0}")
); );
server.createContext("/gacha", t -> responseHTML(t, "<!doctype html><html lang=\"en\"><head><title>Gacha</title></head><body></body></html>")); server.createContext("/gacha", t -> responseHTML(t, "<!doctype html><html lang=\"en\"><head><title>Gacha</title></head><body></body></html>"));
// Start server // Start server
server.start(); server.start();
Grasscutter.getLogger().info("[Dispatch] Dispatch server started on port " + getAddress().getPort()); Grasscutter.getLogger().info("[Dispatch] Dispatch server started on port " + getAddress().getPort());
...@@ -436,4 +475,15 @@ public final class DispatchServer { ...@@ -436,4 +475,15 @@ public final class DispatchServer {
} }
return result; return result;
} }
public static class RegionData {
QueryCurrRegionHttpRsp parsedRegionQuery;
String Base64;
public RegionData(QueryCurrRegionHttpRsp prq, String b64) {
this.parsedRegionQuery = prq;
this.Base64 = b64;
}
}
} }
...@@ -87,7 +87,7 @@ public class GameServerPacketHandler { ...@@ -87,7 +87,7 @@ public class GameServerPacketHandler {
} }
// Log unhandled packets // Log unhandled packets
if (Grasscutter.getConfig().LOG_PACKETS) { if (Grasscutter.getConfig().getGameServerOptions().LOG_PACKETS) {
//Grasscutter.getLogger().info("Unhandled packet (" + opcode + "): " + PacketOpcodesUtil.getOpcodeName(opcode)); //Grasscutter.getLogger().info("Unhandled packet (" + opcode + "): " + PacketOpcodesUtil.getOpcodeName(opcode));
} }
} }
......
...@@ -165,7 +165,7 @@ public class GameSession extends MihoyoKcpChannel { ...@@ -165,7 +165,7 @@ public class GameSession extends MihoyoKcpChannel {
byte[] data = genshinPacket.build(); byte[] data = genshinPacket.build();
// Log // Log
if (Grasscutter.getConfig().LOG_PACKETS) { if (Grasscutter.getConfig().getGameServerOptions().LOG_PACKETS) {
logPacket(genshinPacket); logPacket(genshinPacket);
} }
...@@ -225,7 +225,7 @@ public class GameSession extends MihoyoKcpChannel { ...@@ -225,7 +225,7 @@ public class GameSession extends MihoyoKcpChannel {
} }
// Log packet // Log packet
if (Grasscutter.getConfig().LOG_PACKETS) { if (Grasscutter.getConfig().getGameServerOptions().LOG_PACKETS) {
Grasscutter.getLogger().info("RECV: " + PacketOpcodesUtil.getOpcodeName(opcode) + " (" + opcode + ")"); Grasscutter.getLogger().info("RECV: " + PacketOpcodesUtil.getOpcodeName(opcode) + " (" + opcode + ")");
System.out.println(Utils.bytesToHex(payload)); System.out.println(Utils.bytesToHex(payload));
} }
......
package emu.grasscutter.server.packet.send; package emu.grasscutter.server.packet.send;
import com.google.protobuf.ByteString;
import emu.grasscutter.Grasscutter; import emu.grasscutter.Grasscutter;
import emu.grasscutter.net.packet.GenshinPacket; import emu.grasscutter.net.packet.GenshinPacket;
import emu.grasscutter.net.packet.PacketOpcodes; import emu.grasscutter.net.packet.PacketOpcodes;
import emu.grasscutter.net.proto.PlayerLoginRspOuterClass.PlayerLoginRsp; import emu.grasscutter.net.proto.PlayerLoginRspOuterClass.PlayerLoginRsp;
import emu.grasscutter.net.proto.QueryCurrRegionHttpRspOuterClass;
import emu.grasscutter.net.proto.RegionInfoOuterClass.RegionInfo; import emu.grasscutter.net.proto.RegionInfoOuterClass.RegionInfo;
import emu.grasscutter.server.game.GameSession; 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 { public class PacketPlayerLoginRsp extends GenshinPacket {
private static QueryCurrRegionHttpRspOuterClass.QueryCurrRegionHttpRsp regionCache;
public PacketPlayerLoginRsp(GameSession session) { public PacketPlayerLoginRsp(GameSession session) {
super(PacketOpcodes.PlayerLoginRsp, 1); super(PacketOpcodes.PlayerLoginRsp, 1);
this.setUseDispatchKey(true); 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() PlayerLoginRsp p = PlayerLoginRsp.newBuilder()
.setIsUseAbilityHash(true) // true .setIsUseAbilityHash(true) // true
......
...@@ -19,7 +19,7 @@ public class PacketPlayerStoreNotify extends GenshinPacket { ...@@ -19,7 +19,7 @@ public class PacketPlayerStoreNotify extends GenshinPacket {
PlayerStoreNotify.Builder p = PlayerStoreNotify.newBuilder() PlayerStoreNotify.Builder p = PlayerStoreNotify.newBuilder()
.setStoreType(StoreType.StorePack) .setStoreType(StoreType.StorePack)
.setWeightLimit(Grasscutter.getConfig().getServerOptions().InventoryLimitAll); .setWeightLimit(Grasscutter.getConfig().getGameServerOptions().InventoryLimitAll);
for (GenshinItem item : player.getInventory()) { for (GenshinItem item : player.getInventory()) {
Item itemProto = item.toProto(); Item itemProto = item.toProto();
......
package emu.grasscutter.server.packet.send; package emu.grasscutter.server.packet.send;
import emu.grasscutter.Config.ServerOptions; import emu.grasscutter.Config.GameServerOptions;
import emu.grasscutter.GenshinConstants; import emu.grasscutter.GenshinConstants;
import emu.grasscutter.Grasscutter; import emu.grasscutter.Grasscutter;
import emu.grasscutter.game.GenshinPlayer; import emu.grasscutter.game.GenshinPlayer;
...@@ -14,7 +14,7 @@ public class PacketPullRecentChatRsp extends GenshinPacket { ...@@ -14,7 +14,7 @@ public class PacketPullRecentChatRsp extends GenshinPacket {
public PacketPullRecentChatRsp(GenshinPlayer player) { public PacketPullRecentChatRsp(GenshinPlayer player) {
super(PacketOpcodes.PullRecentChatRsp); super(PacketOpcodes.PullRecentChatRsp);
ServerOptions serverOptions = Grasscutter.getConfig().getServerOptions(); GameServerOptions serverOptions = Grasscutter.getConfig().getGameServerOptions();
PullRecentChatRsp.Builder proto = PullRecentChatRsp.newBuilder(); PullRecentChatRsp.Builder proto = PullRecentChatRsp.newBuilder();
if (serverOptions.WelcomeEmotes != null && serverOptions.WelcomeEmotes.length > 0) { if (serverOptions.WelcomeEmotes != null && serverOptions.WelcomeEmotes.length > 0) {
...@@ -33,7 +33,7 @@ public class PacketPullRecentChatRsp extends GenshinPacket { ...@@ -33,7 +33,7 @@ public class PacketPullRecentChatRsp extends GenshinPacket {
.setTime((int) (System.currentTimeMillis() / 1000)) .setTime((int) (System.currentTimeMillis() / 1000))
.setUid(GenshinConstants.SERVER_CONSOLE_UID) .setUid(GenshinConstants.SERVER_CONSOLE_UID)
.setToUid(player.getUid()) .setToUid(player.getUid())
.setText(Grasscutter.getConfig().getServerOptions().WelcomeMotd) .setText(Grasscutter.getConfig().getGameServerOptions().WelcomeMotd)
.build(); .build();
proto.addChatInfo(welcomeMotd); proto.addChatInfo(welcomeMotd);
......
...@@ -13,11 +13,11 @@ public class PacketStoreWeightLimitNotify extends GenshinPacket { ...@@ -13,11 +13,11 @@ public class PacketStoreWeightLimitNotify extends GenshinPacket {
StoreWeightLimitNotify p = StoreWeightLimitNotify.newBuilder() StoreWeightLimitNotify p = StoreWeightLimitNotify.newBuilder()
.setStoreType(StoreType.StorePack) .setStoreType(StoreType.StorePack)
.setWeightLimit(Grasscutter.getConfig().getServerOptions().InventoryLimitAll) .setWeightLimit(Grasscutter.getConfig().getGameServerOptions().InventoryLimitAll)
.setWeaponCountLimit(Grasscutter.getConfig().getServerOptions().InventoryLimitWeapon) .setWeaponCountLimit(Grasscutter.getConfig().getGameServerOptions().InventoryLimitWeapon)
.setReliquaryCountLimit(Grasscutter.getConfig().getServerOptions().InventoryLimitRelic) .setReliquaryCountLimit(Grasscutter.getConfig().getGameServerOptions().InventoryLimitRelic)
.setMaterialCountLimit(Grasscutter.getConfig().getServerOptions().InventoryLimitMaterial) .setMaterialCountLimit(Grasscutter.getConfig().getGameServerOptions().InventoryLimitMaterial)
.setFurnitureCountLimit(Grasscutter.getConfig().getServerOptions().InventoryLimitFurniture) .setFurnitureCountLimit(Grasscutter.getConfig().getGameServerOptions().InventoryLimitFurniture)
.build(); .build();
this.setData(p); this.setData(p);
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment