Commit 01b190bc authored by Magix's avatar Magix Committed by GitHub
Browse files

UPGRADE TO 1.1.0 POG

Merge `development` into `stable`
parents 6b81b888 1beddf16
package emu.grasscutter.server.dispatch;
import express.http.HttpContextHandler;
import express.http.Request;
import express.http.Response;
import java.io.IOException;
/**
* Used for processing crash dumps and logs generated by the game.
* Logs are in JSON, and are sent to the server for logging.
*/
public final class ClientLogHandler implements HttpContextHandler {
@Override
public void handle(Request request, Response response) throws IOException {
// TODO: Figure out how to dump request body and log to file.
response.send("{\"code\":0}");
}
}
package emu.grasscutter.server.dispatch; package emu.grasscutter.server.dispatch;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.util.Arrays;
import java.util.Collections; import java.util.Objects;
import com.sun.net.httpserver.HttpExchange; import emu.grasscutter.Grasscutter;
import com.sun.net.httpserver.HttpHandler; import emu.grasscutter.Grasscutter.ServerDebugMode;
import express.http.HttpContextHandler;
import express.http.Request;
import express.http.Response;
public final class DispatchHttpJsonHandler implements HttpHandler { import static emu.grasscutter.utils.Language.translate;
public final class DispatchHttpJsonHandler implements HttpContextHandler {
private final String response; private final String response;
private final String[] missingRoutes = { // TODO: When http requests for theses routes are found please remove it from this list and update the route request type in the DispatchServer
"/common/hk4e_global/announcement/api/getAlertPic",
"/common/hk4e_global/announcement/api/getAlertAnn",
"/common/hk4e_global/announcement/api/getAnnList",
"/common/hk4e_global/announcement/api/getAnnContent",
"/hk4e_global/mdk/shopwindow/shopwindow/listPriceTier",
"/log/sdk/upload",
"/sdk/upload",
"/perf/config/verify",
"/log",
"/crash/dataUpload"
};
public DispatchHttpJsonHandler(String response) { public DispatchHttpJsonHandler(String response) {
this.response = response; this.response = response;
} }
@Override @Override
public void handle(HttpExchange t) throws IOException { public void handle(Request req, Response res) throws IOException {
// Set the response header status and length // Checking for ALL here isn't required as when ALL is enabled enableDevLogging() gets enabled
t.getResponseHeaders().put("Content-Type", Collections.singletonList("application/json")); if(Grasscutter.getConfig().DebugMode == ServerDebugMode.MISSING && Arrays.stream(missingRoutes).anyMatch(x -> Objects.equals(x, req.baseUrl()))) {
t.sendResponseHeaders(200, response.getBytes().length); Grasscutter.getLogger().info(translate("messages.dispatch.request", req.ip(), req.method(), req.baseUrl()) + (Grasscutter.getConfig().DebugMode == ServerDebugMode.MISSING ? "(MISSING)" : ""));
// Write the response string }
OutputStream os = t.getResponseBody(); res.send(response);
os.write(response.getBytes());
os.close();
} }
} }
...@@ -3,81 +3,94 @@ package emu.grasscutter.server.dispatch; ...@@ -3,81 +3,94 @@ package emu.grasscutter.server.dispatch;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.protobuf.ByteString; import com.google.protobuf.ByteString;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsServer;
import emu.grasscutter.Config; import emu.grasscutter.Config;
import emu.grasscutter.Grasscutter; import emu.grasscutter.Grasscutter;
import emu.grasscutter.Grasscutter.ServerDebugMode;
import emu.grasscutter.Grasscutter.ServerRunMode;
import emu.grasscutter.database.DatabaseHelper; import emu.grasscutter.database.DatabaseHelper;
import emu.grasscutter.game.Account; import emu.grasscutter.game.Account;
import emu.grasscutter.net.proto.QueryCurrRegionHttpRspOuterClass.QueryCurrRegionHttpRsp; import emu.grasscutter.net.proto.QueryCurrRegionHttpRspOuterClass.QueryCurrRegionHttpRsp;
import emu.grasscutter.net.proto.QueryRegionListHttpRspOuterClass.QueryRegionListHttpRsp; import emu.grasscutter.net.proto.QueryRegionListHttpRspOuterClass.QueryRegionListHttpRsp;
import emu.grasscutter.net.proto.RegionInfoOuterClass.RegionInfo; import emu.grasscutter.net.proto.RegionInfoOuterClass.RegionInfo;
import emu.grasscutter.net.proto.RegionSimpleInfoOuterClass.RegionSimpleInfo; import emu.grasscutter.net.proto.RegionSimpleInfoOuterClass.RegionSimpleInfo;
import emu.grasscutter.server.dispatch.authentication.AuthenticationHandler;
import emu.grasscutter.server.dispatch.authentication.DefaultAuthenticationHandler;
import emu.grasscutter.server.dispatch.http.GachaRecordHandler;
import emu.grasscutter.server.dispatch.json.*; import emu.grasscutter.server.dispatch.json.*;
import emu.grasscutter.server.dispatch.json.ComboTokenReqJson.LoginTokenData; import emu.grasscutter.server.dispatch.json.ComboTokenReqJson.LoginTokenData;
import emu.grasscutter.server.event.dispatch.QueryAllRegionsEvent;
import emu.grasscutter.server.event.dispatch.QueryCurrentRegionEvent;
import emu.grasscutter.tools.Tools;
import emu.grasscutter.utils.FileUtils; import emu.grasscutter.utils.FileUtils;
import emu.grasscutter.utils.Utils; import emu.grasscutter.utils.Utils;
import express.Express;
import io.javalin.http.staticfiles.Location;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.*; import java.io.*;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.security.KeyStore;
import java.util.*; import java.util.*;
import static emu.grasscutter.utils.Language.translate;
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 Gson gson; private final Gson gson;
private final String defaultServerName = "os_usa"; private final String defaultServerName = "os_usa";
public String regionListBase64; public String regionListBase64;
public HashMap<String, RegionData> regions; public Map<String, RegionData> regions;
private AuthenticationHandler authHandler;
private Express httpServer;
public DispatchServer() { public DispatchServer() {
this.regions = new HashMap<String, RegionData>(); this.regions = new HashMap<>();
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();
this.initRegion(); this.initRegion();
} }
public InetSocketAddress getAddress() { public Express getServer() {
return address; return httpServer;
}
public void setHttpServer(Express httpServer) {
this.httpServer.stop();
this.httpServer = httpServer;
this.httpServer.listen(Grasscutter.getConfig().getDispatchOptions().Port);
} }
public Gson getGsonFactory() { public Gson getGsonFactory() {
return gson; return gson;
} }
public QueryCurrRegionHttpRsp getCurrRegion() { public QueryCurrRegionHttpRsp getCurrRegion() {
// Needs to be fixed by having the game servers connect to the dispatch server. // Needs to be fixed by having the game servers connect to the dispatch server.
if(Grasscutter.getConfig().RunMode.equalsIgnoreCase("HYBRID")) { if (Grasscutter.getConfig().RunMode == ServerRunMode.HYBRID) {
return regions.get(defaultServerName).parsedRegionQuery; return regions.get(defaultServerName).parsedRegionQuery;
} }
Grasscutter.getLogger().warn("[Dispatch] Unsupported run mode for getCurrRegion()"); Grasscutter.getLogger().warn("[Dispatch] Unsupported run mode for getCurrRegion()");
return null; return null;
} }
public void loadQueries() { public void loadQueries() {
File file; File file;
file = new File(Grasscutter.getConfig().DATA_FOLDER + "query_region_list.txt"); file = new File(Grasscutter.getConfig().DATA_FOLDER + "query_region_list.txt");
if (file.exists()) { if (file.exists()) {
query_region_list = new String(FileUtils.read(file)); query_region_list = new String(FileUtils.read(file));
} else { } else {
Grasscutter.getLogger().warn("[Dispatch] query_region_list not found! Using default region list."); Grasscutter.getLogger().warn("[Dispatch] query_region_list not found! Using default region list.");
} }
file = new File(Grasscutter.getConfig().DATA_FOLDER + "query_cur_region.txt"); file = new File(Grasscutter.getConfig().DATA_FOLDER + "query_cur_region.txt");
if (file.exists()) { if (file.exists()) {
query_cur_region = new String(FileUtils.read(file)); query_cur_region = new String(FileUtils.read(file));
...@@ -90,40 +103,58 @@ public final class DispatchServer { ...@@ -90,40 +103,58 @@ public final class DispatchServer {
try { try {
byte[] decoded = Base64.getDecoder().decode(query_region_list); byte[] decoded = Base64.getDecoder().decode(query_region_list);
QueryRegionListHttpRsp rl = QueryRegionListHttpRsp.parseFrom(decoded); QueryRegionListHttpRsp rl = QueryRegionListHttpRsp.parseFrom(decoded);
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<RegionSimpleInfo> servers = new ArrayList<>();
List<String> usedNames = new ArrayList<String>(); // List to check for potential naming conflicts List<String> 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 if (Grasscutter.getConfig().RunMode == ServerRunMode.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().getGameServerOptions().Name) .setTitle(Grasscutter.getConfig().getGameServerOptions().Name)
.setType("DEV_PUBLIC") .setType("DEV_PUBLIC")
.setDispatchUrl("https://" + (Grasscutter.getConfig().getDispatchOptions().PublicIp.isEmpty() ? Grasscutter.getConfig().getDispatchOptions().Ip : Grasscutter.getConfig().getDispatchOptions().PublicIp) + ":" + getAddress().getPort() + "/query_cur_region_" + defaultServerName) .setDispatchUrl(
"http" + (Grasscutter.getConfig().getDispatchOptions().FrontHTTPS ? "s" : "") + "://"
+ (Grasscutter.getConfig().getDispatchOptions().PublicIp.isEmpty()
? Grasscutter.getConfig().getDispatchOptions().Ip
: Grasscutter.getConfig().getDispatchOptions().PublicIp)
+ ":"
+ (Grasscutter.getConfig().getDispatchOptions().PublicPort != 0
? Grasscutter.getConfig().getDispatchOptions().PublicPort
: Grasscutter.getConfig().getDispatchOptions().Port)
+ "/query_cur_region/" + defaultServerName)
.build(); .build();
usedNames.add(defaultServerName); usedNames.add(defaultServerName);
servers.add(server); servers.add(server);
RegionInfo serverRegion = regionQuery.getRegionInfo().toBuilder() RegionInfo serverRegion = regionQuery.getRegionInfo().toBuilder()
.setIp((Grasscutter.getConfig().getGameServerOptions().PublicIp.isEmpty() ? Grasscutter.getConfig().getGameServerOptions().Ip : Grasscutter.getConfig().getGameServerOptions().PublicIp)) .setGateserverIp((Grasscutter.getConfig().getGameServerOptions().PublicIp.isEmpty()
.setPort(Grasscutter.getConfig().getGameServerOptions().Port) ? Grasscutter.getConfig().getGameServerOptions().Ip
.setSecretKey(ByteString.copyFrom(FileUtils.read(Grasscutter.getConfig().KEY_FOLDER + "dispatchSeed.bin"))) : Grasscutter.getConfig().getGameServerOptions().PublicIp))
.setGateserverPort(Grasscutter.getConfig().getGameServerOptions().PublicPort != 0
? Grasscutter.getConfig().getGameServerOptions().PublicPort
: Grasscutter.getConfig().getGameServerOptions().Port)
.setSecretKey(ByteString
.copyFrom(FileUtils.read(Grasscutter.getConfig().KEY_FOLDER + "dispatchSeed.bin")))
.build(); .build();
QueryCurrRegionHttpRsp parsedRegionQuery = regionQuery.toBuilder().setRegionInfo(serverRegion).build(); QueryCurrRegionHttpRsp parsedRegionQuery = regionQuery.toBuilder().setRegionInfo(serverRegion).build();
regions.put(defaultServerName, new RegionData(parsedRegionQuery, Base64.getEncoder().encodeToString(parsedRegionQuery.toByteString().toByteArray()))); regions.put(defaultServerName, new RegionData(parsedRegionQuery,
Base64.getEncoder().encodeToString(parsedRegionQuery.toByteString().toByteArray())));
} else { } else {
if(Grasscutter.getConfig().getDispatchOptions().getGameServers().length == 0) { if (Grasscutter.getConfig().getDispatchOptions().getGameServers().length == 0) {
Grasscutter.getLogger().error("[Dispatch] There are no game servers available. Exiting due to unplayable state."); Grasscutter.getLogger()
.error("[Dispatch] There are no game servers available. Exiting due to unplayable state.");
System.exit(1); System.exit(1);
} }
} }
for (Config.DispatchServerOptions.RegionInfo regionInfo : Grasscutter.getConfig().getDispatchOptions().getGameServers()) { for (Config.DispatchServerOptions.RegionInfo regionInfo : Grasscutter.getConfig().getDispatchOptions()
if(usedNames.contains(regionInfo.Name)) { .getGameServers()) {
if (usedNames.contains(regionInfo.Name)) {
Grasscutter.getLogger().error("Region name already in use."); Grasscutter.getLogger().error("Region name already in use.");
continue; continue;
} }
...@@ -131,27 +162,36 @@ public final class DispatchServer { ...@@ -131,27 +162,36 @@ public final class DispatchServer {
.setName(regionInfo.Name) .setName(regionInfo.Name)
.setTitle(regionInfo.Title) .setTitle(regionInfo.Title)
.setType("DEV_PUBLIC") .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) .setDispatchUrl(
"http" + (Grasscutter.getConfig().getDispatchOptions().FrontHTTPS ? "s" : "") + "://"
+ (Grasscutter.getConfig().getDispatchOptions().PublicIp.isEmpty()
? Grasscutter.getConfig().getDispatchOptions().Ip
: Grasscutter.getConfig().getDispatchOptions().PublicIp)
+ ":" + (Grasscutter.getConfig().getDispatchOptions().PublicPort != 0
? Grasscutter.getConfig().getDispatchOptions().PublicPort
: Grasscutter.getConfig().getDispatchOptions().Port) + "/query_cur_region/" + regionInfo.Name)
.build(); .build();
usedNames.add(regionInfo.Name); usedNames.add(regionInfo.Name);
servers.add(server); servers.add(server);
RegionInfo serverRegion = regionQuery.getRegionInfo().toBuilder() RegionInfo serverRegion = regionQuery.getRegionInfo().toBuilder()
.setIp(regionInfo.Ip) .setGateserverIp(regionInfo.Ip)
.setPort(regionInfo.Port) .setGateserverPort(regionInfo.Port)
.setSecretKey(ByteString.copyFrom(FileUtils.read(Grasscutter.getConfig().KEY_FOLDER + "dispatchSeed.bin"))) .setSecretKey(ByteString
.copyFrom(FileUtils.read(Grasscutter.getConfig().KEY_FOLDER + "dispatchSeed.bin")))
.build(); .build();
QueryCurrRegionHttpRsp parsedRegionQuery = regionQuery.toBuilder().setRegionInfo(serverRegion).build(); QueryCurrRegionHttpRsp parsedRegionQuery = regionQuery.toBuilder().setRegionInfo(serverRegion).build();
regions.put(regionInfo.Name, new RegionData(parsedRegionQuery, Base64.getEncoder().encodeToString(parsedRegionQuery.toByteString().toByteArray()))); regions.put(regionInfo.Name, new RegionData(parsedRegionQuery,
Base64.getEncoder().encodeToString(parsedRegionQuery.toByteString().toByteArray())));
} }
QueryRegionListHttpRsp regionList = QueryRegionListHttpRsp.newBuilder() QueryRegionListHttpRsp regionList = QueryRegionListHttpRsp.newBuilder()
.addAllServers(servers) .addAllRegionList(servers)
.setClientSecretKey(rl.getClientSecretKey()) .setClientSecretKey(rl.getClientSecretKey())
.setClientCustomConfigEncrypted(rl.getClientCustomConfigEncrypted()) .setClientCustomConfigEncrypted(rl.getClientCustomConfigEncrypted())
.setEnableLoginPc(true) .setEnableLoginPc(true)
.build(); .build();
this.regionListBase64 = Base64.getEncoder().encodeToString(regionList.toByteString().toByteArray()); this.regionListBase64 = Base64.getEncoder().encodeToString(regionList.toByteString().toByteArray());
} catch (Exception e) { } catch (Exception e) {
...@@ -160,62 +200,113 @@ public final class DispatchServer { ...@@ -160,62 +200,113 @@ public final class DispatchServer {
} }
public void start() throws Exception { public void start() throws Exception {
HttpServer server; httpServer = new Express(config -> {
if (Grasscutter.getConfig().getDispatchOptions().UseSSL) { config.server(() -> {
HttpsServer httpsServer; Server server = new Server();
httpsServer = HttpsServer.create(getAddress(), 0); ServerConnector serverConnector;
SSLContext sslContext = SSLContext.getInstance("TLS");
try (FileInputStream fis = new FileInputStream(Grasscutter.getConfig().getDispatchOptions().KeystorePath)) { if(Grasscutter.getConfig().getDispatchOptions().UseSSL) {
char[] keystorePassword = Grasscutter.getConfig().getDispatchOptions().KeystorePassword.toCharArray(); SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
KeyStore ks = KeyStore.getInstance("PKCS12"); File keystoreFile = new File(Grasscutter.getConfig().getDispatchOptions().KeystorePath);
ks.load(fis, keystorePassword);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); if(keystoreFile.exists()) {
kmf.init(ks, keystorePassword); try {
sslContextFactory.setKeyStorePath(keystoreFile.getPath());
sslContext.init(kmf.getKeyManagers(), null, null); sslContextFactory.setKeyStorePassword(Grasscutter.getConfig().getDispatchOptions().KeystorePassword);
} catch (Exception e) {
httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext)); e.printStackTrace();
server = httpsServer; Grasscutter.getLogger().warn(translate("messages.dispatch.keystore.password_error"));
} catch (Exception e) {
Grasscutter.getLogger().warn("[Dispatch] No SSL cert found! Falling back to HTTP server."); try {
Grasscutter.getConfig().getDispatchOptions().UseSSL = false; sslContextFactory.setKeyStorePath(keystoreFile.getPath());
server = HttpServer.create(getAddress(), 0); sslContextFactory.setKeyStorePassword("123456");
Grasscutter.getLogger().warn(translate("messages.dispatch.keystore.default_password"));
} catch (Exception e2) {
Grasscutter.getLogger().warn(translate("messages.dispatch.keystore.general_error"));
e2.printStackTrace();
}
}
serverConnector = new ServerConnector(server, sslContextFactory);
} else {
Grasscutter.getLogger().warn(translate("messages.dispatch.keystore.no_keystore_error"));
Grasscutter.getConfig().getDispatchOptions().UseSSL = false;
serverConnector = new ServerConnector(server);
}
} else {
serverConnector = new ServerConnector(server);
}
serverConnector.setPort(Grasscutter.getConfig().getDispatchOptions().Port);
server.setConnectors(new Connector[]{serverConnector});
return server;
});
config.enforceSsl = Grasscutter.getConfig().getDispatchOptions().UseSSL;
if(Grasscutter.getConfig().DebugMode == ServerDebugMode.ALL) {
config.enableDevLogging();
} }
} else { if (Grasscutter.getConfig().getDispatchOptions().CORS){
server = HttpServer.create(getAddress(), 0); if (Grasscutter.getConfig().getDispatchOptions().CORSAllowedOrigins.length > 0) config.enableCorsForOrigin(Grasscutter.getConfig().getDispatchOptions().CORSAllowedOrigins);
} else config.enableCorsForAllOrigins();
}
});
httpServer.get("/", (req, res) -> res.send(translate("messages.status.welcome")));
httpServer.raw().error(404, ctx -> {
if(Grasscutter.getConfig().DebugMode == ServerDebugMode.MISSING) {
Grasscutter.getLogger().info(translate("messages.dispatch.unhandled_request_error", ctx.method(), ctx.url()));
}
ctx.contentType("text/html");
ctx.result("<!doctype html><html lang=\"en\"><body><img src=\"https://http.cat/404\" /></body></html>"); // I'm like 70% sure this won't break anything.
});
// Authentication Handler
// These routes are so that authentication routes are always the same no matter what auth system is used.
httpServer.get("/authentication/type", (req, res) -> {
res.send(this.getAuthHandler().getClass().getName());
});
httpServer.post("/authentication/login", (req, res) -> this.getAuthHandler().handleLogin(req, res));
httpServer.post("/authentication/register", (req, res) -> this.getAuthHandler().handleRegister(req, res));
httpServer.post("/authentication/change_password", (req, res) -> this.getAuthHandler().handleChangePassword(req, res));
server.createContext("/", t -> responseHTML(t, "Hello"));
// Dispatch // Dispatch
server.createContext("/query_region_list", t -> { httpServer.get("/query_region_list", (req, res) -> {
// Log // Log
Grasscutter.getLogger().info(String.format("[Dispatch] Client %s request: query_region_list", t.getRemoteAddress())); Grasscutter.getLogger().info(String.format("[Dispatch] Client %s request: query_region_list", req.ip()));
responseHTML(t, regionListBase64); // Invoke event.
QueryAllRegionsEvent event = new QueryAllRegionsEvent(regionListBase64); event.call();
// Respond with event result.
res.send(event.getRegionList());
}); });
for (String regionName : regions.keySet()) { httpServer.get("/query_cur_region/:id", (req, res) -> {
server.createContext("/query_cur_region_" + regionName, t -> { String regionName = req.params("id");
String regionCurrentBase64 = regions.get(regionName).Base64; // Log
// Log Grasscutter.getLogger().info(
Grasscutter.getLogger().info(String.format("Client %s request: query_cur_region_%s", t.getRemoteAddress(), regionName)); String.format("Client %s request: query_cur_region/%s", req.ip(), regionName));
// Create a response form the request query parameters // Create a response form the request query parameters
URI uri = t.getRequestURI(); String response = "CAESGE5vdCBGb3VuZCB2ZXJzaW9uIGNvbmZpZw==";
String response = "CAESGE5vdCBGb3VuZCB2ZXJzaW9uIGNvbmZpZw=="; if (req.query().values().size() > 0) {
if (uri.getQuery() != null && uri.getQuery().length() > 0) { response = regions.get(regionName).Base64;
response = regionCurrentBase64; }
}
responseHTML(t, response); // Invoke event.
}); QueryCurrentRegionEvent event = new QueryCurrentRegionEvent(response); event.call();
} // Respond with event result.
res.send(event.getRegionInfo());
});
// Login via account // Login
server.createContext("/hk4e_global/mdk/shield/api/login", t -> {
httpServer.post("/hk4e_global/mdk/shield/api/login", (req, res) -> {
// Get post data // Get post data
LoginAccountRequestJson requestData = null; LoginAccountRequestJson requestData = null;
try { try {
String body = Utils.toString(t.getRequestBody()); String body = req.ctx().body();
requestData = getGsonFactory().fromJson(body, LoginAccountRequestJson.class); requestData = getGsonFactory().fromJson(body, LoginAccountRequestJson.class);
} catch (Exception ignored) { } } catch (Exception ignored) { }
...@@ -223,229 +314,158 @@ public final class DispatchServer { ...@@ -223,229 +314,158 @@ public final class DispatchServer {
if (requestData == null) { if (requestData == null) {
return; return;
} }
LoginResultJson responseData = new LoginResultJson(); Grasscutter.getLogger().info(translate("messages.dispatch.account.login_attempt", req.ip()));
Grasscutter.getLogger().info(String.format("[Dispatch] Client %s is trying to log in", t.getRemoteAddress()));
// Login
Account account = DatabaseHelper.getAccountByName(requestData.account);
// 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().getDispatchOptions().AutomaticallyCreateAccounts) {
// This account has been created AUTOMATICALLY. There will be no permissions added.
account = DatabaseHelper.createAccountWithId(requestData.account, 0);
if (account != null) {
responseData.message = "OK";
responseData.data.account.uid = account.getId();
responseData.data.account.token = account.generateSessionKey();
responseData.data.account.email = account.getEmail();
Grasscutter.getLogger().info(String.format("[Dispatch] Client %s failed to log in: Account %s created", t.getRemoteAddress(), responseData.data.account.uid));
} else {
responseData.retcode = -201;
responseData.message = "Username not found, create failed.";
Grasscutter.getLogger().info(String.format("[Dispatch] Client %s failed to log in: Account create failed", t.getRemoteAddress()));
}
} else {
responseData.retcode = -201;
responseData.message = "Username not found.";
Grasscutter.getLogger().info(String.format("[Dispatch] Client %s failed to log in: Account no found", t.getRemoteAddress()));
}
} else {
// Account was found, log the player in
responseData.message = "OK";
responseData.data.account.uid = account.getId();
responseData.data.account.token = account.generateSessionKey();
responseData.data.account.email = account.getEmail();
Grasscutter.getLogger().info(String.format("[Dispatch] Client %s logged in as %s", t.getRemoteAddress(), responseData.data.account.uid));
}
responseJSON(t, responseData); res.send(this.getAuthHandler().handleGameLogin(req, requestData));
}); });
// Login via token // Login via token
server.createContext("/hk4e_global/mdk/shield/api/verify", t -> { httpServer.post("/hk4e_global/mdk/shield/api/verify", (req, res) -> {
// Get post data // Get post data
LoginTokenRequestJson requestData = null; LoginTokenRequestJson requestData = null;
try { try {
String body = Utils.toString(t.getRequestBody()); String body = req.ctx().body();
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;
} }
LoginResultJson responseData = new LoginResultJson(); LoginResultJson responseData = new LoginResultJson();
Grasscutter.getLogger().info(String.format("[Dispatch] Client %s is trying to log in via token", t.getRemoteAddress())); Grasscutter.getLogger().info(translate("messages.dispatch.account.login_token_attempt", req.ip()));
// Login // Login
Account account = DatabaseHelper.getAccountById(requestData.uid); Account account = DatabaseHelper.getAccountById(requestData.uid);
// Test // Test
if (account == null || !account.getSessionKey().equals(requestData.token)) { if (account == null || !account.getSessionKey().equals(requestData.token)) {
responseData.retcode = -111; responseData.retcode = -111;
responseData.message = "Game account cache information error"; responseData.message = translate("messages.dispatch.account.account_cache_error");
Grasscutter.getLogger().info(String.format("[Dispatch] Client %s failed to log in via token", t.getRemoteAddress())); Grasscutter.getLogger().info(translate("messages.dispatch.account.login_token_error", req.ip()));
} else { } else {
responseData.message = "OK"; responseData.message = "OK";
responseData.data.account.uid = requestData.uid; responseData.data.account.uid = requestData.uid;
responseData.data.account.token = requestData.token; responseData.data.account.token = requestData.token;
responseData.data.account.email = account.getEmail(); responseData.data.account.email = account.getEmail();
Grasscutter.getLogger().info(String.format("[Dispatch] Client %s logged in via token as %s", t.getRemoteAddress(), responseData.data.account.uid)); Grasscutter.getLogger().info(translate("messages.dispatch.account.login_token_success", req.ip(), requestData.uid));
} }
responseJSON(t, responseData); res.send(responseData);
}); });
// Exchange for combo token // Exchange for combo token
server.createContext("/hk4e_global/combo/granter/login/v2/login", t -> { httpServer.post("/hk4e_global/combo/granter/login/v2/login", (req, res) -> {
// Get post data // Get post data
ComboTokenReqJson requestData = null; ComboTokenReqJson requestData = null;
try { try {
String body = Utils.toString(t.getRequestBody()); String body = req.ctx().body();
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;
} }
LoginTokenData loginData = getGsonFactory().fromJson(requestData.data, LoginTokenData.class); // Get login data LoginTokenData loginData = getGsonFactory().fromJson(requestData.data, LoginTokenData.class); // Get login
// data
ComboTokenResJson responseData = new ComboTokenResJson(); ComboTokenResJson responseData = new ComboTokenResJson();
// Login // Login
Account account = DatabaseHelper.getAccountById(loginData.uid); Account account = DatabaseHelper.getAccountById(loginData.uid);
// Test // Test
if (account == null || !account.getSessionKey().equals(loginData.token)) { if (account == null || !account.getSessionKey().equals(loginData.token)) {
responseData.retcode = -201; responseData.retcode = -201;
responseData.message = "Wrong session key."; responseData.message = translate("messages.dispatch.account.session_key_error");
Grasscutter.getLogger().info(String.format("[Dispatch] Client %s failed to exchange combo token", t.getRemoteAddress())); Grasscutter.getLogger().info(translate("messages.dispatch.account.combo_token_error", req.ip()));
} else { } else {
responseData.message = "OK"; responseData.message = "OK";
responseData.data.open_id = loginData.uid; responseData.data.open_id = loginData.uid;
responseData.data.combo_id = "157795300"; responseData.data.combo_id = "157795300";
responseData.data.combo_token = account.generateLoginToken(); responseData.data.combo_token = account.generateLoginToken();
Grasscutter.getLogger().info(String.format("[Dispatch] Client %s succeed to exchange combo token", t.getRemoteAddress())); Grasscutter.getLogger().info(translate("messages.dispatch.account.combo_token_success", req.ip()));
} }
responseJSON(t, responseData); res.send(responseData);
}); });
// TODO: There are some missing route request types here (You can tell if they are missing if they are .all and not anything else)
// When http requests for theses routes are found please remove it from the list in DispatchHttpJsonHandler and update the route request types here
// Agreement and Protocol // Agreement and Protocol
server.createContext( // hk4e-sdk-os.hoyoverse.com // hk4e-sdk-os.hoyoverse.com
"/hk4e_global/mdk/agreement/api/getAgreementInfos", httpServer.get("/hk4e_global/mdk/agreement/api/getAgreementInfos", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"marketing_agreements\":[]}}"));
new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"marketing_agreements\":[]}}") // hk4e-sdk-os.hoyoverse.com
); // this could be either GET or POST based on the observation of different clients
server.createContext( // hk4e-sdk-os.hoyoverse.com httpServer.all("/hk4e_global/combo/granter/api/compareProtocolVersion", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"modified\":true,\"protocol\":{\"id\":0,\"app_id\":4,\"language\":\"en\",\"user_proto\":\"\",\"priv_proto\":\"\",\"major\":7,\"minimum\":0,\"create_time\":\"0\",\"teenager_proto\":\"\",\"third_proto\":\"\"}}}"));
"/hk4e_global/combo/granter/api/compareProtocolVersion",
new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"modified\":true,\"protocol\":{\"id\":0,\"app_id\":4,\"language\":\"en\",\"user_proto\":\"\",\"priv_proto\":\"\",\"major\":7,\"minimum\":0,\"create_time\":\"0\",\"teenager_proto\":\"\",\"third_proto\":\"\"}}}")
);
// Game data // Game data
server.createContext( // hk4e-api-os.hoyoverse.com // hk4e-api-os.hoyoverse.com
"/common/hk4e_global/announcement/api/getAlertPic", httpServer.all("/common/hk4e_global/announcement/api/getAlertPic", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"total\":0,\"list\":[]}}"));
new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"total\":0,\"list\":[]}}") // hk4e-api-os.hoyoverse.com
); httpServer.all("/common/hk4e_global/announcement/api/getAlertAnn", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"alert\":false,\"alert_id\":0,\"remind\":true}}"));
server.createContext( // hk4e-api-os.hoyoverse.com // hk4e-api-os.hoyoverse.com
"/common/hk4e_global/announcement/api/getAlertAnn", httpServer.all("/common/hk4e_global/announcement/api/getAnnList", new AnnouncementHandler());
new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"alert\":false,\"alert_id\":0,\"remind\":true}}") // hk4e-api-os-static.hoyoverse.com
); httpServer.all("/common/hk4e_global/announcement/api/getAnnContent", new AnnouncementHandler());
server.createContext( // hk4e-api-os.hoyoverse.com // hk4e-sdk-os.hoyoverse.com
"/common/hk4e_global/announcement/api/getAnnList", httpServer.all("/hk4e_global/mdk/shopwindow/shopwindow/listPriceTier", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"suggest_currency\":\"USD\",\"tiers\":[]}}"));
new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"list\":[],\"total\":0,\"type_list\":[],\"alert\":false,\"alert_id\":0,\"timezone\":0,\"t\":\"" + System.currentTimeMillis() + "\"}}")
);
server.createContext( // hk4e-api-os-static.hoyoverse.com
"/common/hk4e_global/announcement/api/getAnnContent",
new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"list\":[],\"total\":0}}")
);
server.createContext( // hk4e-sdk-os.hoyoverse.com
"/hk4e_global/mdk/shopwindow/shopwindow/listPriceTier",
new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"suggest_currency\":\"USD\",\"tiers\":[]}}")
);
// Captcha // Captcha
server.createContext( // api-account-os.hoyoverse.com // api-account-os.hoyoverse.com
"/account/risky/api/check", httpServer.post("/account/risky/api/check", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":\"none\",\"action\":\"ACTION_NONE\",\"geetest\":null}}"));
new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":\"c8820f246a5241ab9973f71df3ddd791\",\"action\":\"\",\"geetest\":{\"challenge\":\"\",\"gt\":\"\",\"new_captcha\":0,\"success\":1}}}")
); // Config
// Config // sdk-os-static.hoyoverse.com
server.createContext( // sdk-os-static.hoyoverse.com httpServer.get("/combo/box/api/config/sdk/combo", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"vals\":{\"disable_email_bind_skip\":\"false\",\"email_bind_remind_interval\":\"7\",\"email_bind_remind\":\"true\"}}}"));
"/combo/box/api/config/sdk/combo", // hk4e-sdk-os-static.hoyoverse.com
new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"vals\":{\"disable_email_bind_skip\":\"false\",\"email_bind_remind_interval\":\"7\",\"email_bind_remind\":\"true\"}}}") httpServer.get("/hk4e_global/combo/granter/api/getConfig", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"protocol\":true,\"qr_enabled\":false,\"log_level\":\"INFO\",\"announce_url\":\"https://webstatic-sea.hoyoverse.com/hk4e/announcement/index.html?sdk_presentation_style=fullscreen\\u0026sdk_screen_transparent=true\\u0026game_biz=hk4e_global\\u0026auth_appid=announcement\\u0026game=hk4e#/\",\"push_alias_type\":2,\"disable_ysdk_guard\":false,\"enable_announce_pic_popup\":true}}"));
); // hk4e-sdk-os-static.hoyoverse.com
server.createContext( // hk4e-sdk-os-static.hoyoverse.com httpServer.get("/hk4e_global/mdk/shield/api/loadConfig", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":6,\"game_key\":\"hk4e_global\",\"client\":\"PC\",\"identity\":\"I_IDENTITY\",\"guest\":false,\"ignore_versions\":\"\",\"scene\":\"S_NORMAL\",\"name\":\"原神海外\",\"disable_regist\":false,\"enable_email_captcha\":false,\"thirdparty\":[\"fb\",\"tw\"],\"disable_mmt\":false,\"server_guest\":false,\"thirdparty_ignore\":{\"tw\":\"\",\"fb\":\"\"},\"enable_ps_bind_account\":false,\"thirdparty_login_configs\":{\"tw\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":604800},\"fb\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":604800}}}}"));
"/hk4e_global/combo/granter/api/getConfig",
new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"protocol\":true,\"qr_enabled\":false,\"log_level\":\"INFO\",\"announce_url\":\"https://webstatic-sea.hoyoverse.com/hk4e/announcement/index.html?sdk_presentation_style=fullscreen\\u0026sdk_screen_transparent=true\\u0026game_biz=hk4e_global\\u0026auth_appid=announcement\\u0026game=hk4e#/\",\"push_alias_type\":2,\"disable_ysdk_guard\":false,\"enable_announce_pic_popup\":true}}")
);
server.createContext( // hk4e-sdk-os-static.hoyoverse.com
"/hk4e_global/mdk/shield/api/loadConfig",
new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":6,\"game_key\":\"hk4e_global\",\"client\":\"PC\",\"identity\":\"I_IDENTITY\",\"guest\":false,\"ignore_versions\":\"\",\"scene\":\"S_NORMAL\",\"name\":\"原神海外\",\"disable_regist\":false,\"enable_email_captcha\":false,\"thirdparty\":[\"fb\",\"tw\"],\"disable_mmt\":false,\"server_guest\":false,\"thirdparty_ignore\":{\"tw\":\"\",\"fb\":\"\"},\"enable_ps_bind_account\":false,\"thirdparty_login_configs\":{\"tw\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":604800},\"fb\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":604800}}}}")
);
// Test api? // Test api?
server.createContext( // abtest-api-data-sg.hoyoverse.com // abtest-api-data-sg.hoyoverse.com
"/data_abtest_api/config/experiment/list", httpServer.post("/data_abtest_api/config/experiment/list", new DispatchHttpJsonHandler("{\"retcode\":0,\"success\":true,\"message\":\"\",\"data\":[{\"code\":1000,\"type\":2,\"config_id\":\"14\",\"period_id\":\"6036_99\",\"version\":\"1\",\"configs\":{\"cardType\":\"old\"}}]}"));
new DispatchHttpJsonHandler("{\"retcode\":0,\"success\":true,\"message\":\"\",\"data\":[{\"code\":1000,\"type\":2,\"config_id\":\"14\",\"period_id\":\"6036_99\",\"version\":\"1\",\"configs\":{\"cardType\":\"old\"}}]}")
); // log-upload-os.mihoyo.com
// Log Server httpServer.all("/log/sdk/upload", new DispatchHttpJsonHandler("{\"code\":0}"));
server.createContext( // log-upload-os.mihoyo.com httpServer.all("/sdk/upload", new DispatchHttpJsonHandler("{\"code\":0}"));
"/log/sdk/upload", httpServer.post("/sdk/dataUpload", new DispatchHttpJsonHandler("{\"code\":0}"));
new DispatchHttpJsonHandler("{\"code\":0}") // /perf/config/verify?device_id=xxx&platform=x&name=xxx
); httpServer.all("/perf/config/verify", new DispatchHttpJsonHandler("{\"code\":0}"));
server.createContext( // log-upload-os.mihoyo.com
"/sdk/upload",
new DispatchHttpJsonHandler("{\"code\":0}")
);
server.createContext( // /perf/config/verify?device_id=xxx&platform=x&name=xxx
"/perf/config/verify",
new DispatchHttpJsonHandler("{\"code\":0}")
);
// Logging servers // Logging servers
server.createContext( // overseauspider.yuanshen.com // overseauspider.yuanshen.com
"/log", httpServer.all("/log", new ClientLogHandler());
new DispatchHttpJsonHandler("{\"code\":0}") // log-upload-os.mihoyo.com
); httpServer.all("/crash/dataUpload", new ClientLogHandler());
server.createContext( // log-upload-os.mihoyo.com // webstatic-sea.hoyoverse.com
"/crash/dataUpload", httpServer.get("/admin/mi18n/plat_oversea/m202003048/m202003048-version.json", new DispatchHttpJsonHandler("{\"version\":51}"));
new DispatchHttpJsonHandler("{\"code\":0}")
); // gacha record.
server.createContext("/gacha", t -> responseHTML(t, "<!doctype html><html lang=\"en\"><head><title>Gacha</title></head><body></body></html>")); String gachaMappingsPath = Utils.toFilePath(Grasscutter.getConfig().DATA_FOLDER + "/gacha_mappings.js");
// TODO: Only serve the html page and have a subsequent request to fetch the gacha data.
// Start server httpServer.get("/gacha", new GachaRecordHandler());
server.start(); if(!(new File(gachaMappingsPath).exists())) {
Grasscutter.getLogger().info("[Dispatch] Dispatch server started on port " + getAddress().getPort()); Tools.createGachaMapping(gachaMappingsPath);
} }
private void responseJSON(HttpExchange t, Object data) throws IOException { httpServer.raw().config.addSinglePageRoot("/gacha/mappings", gachaMappingsPath, Location.EXTERNAL);
// Create a response
String response = getGsonFactory().toJson(data);
// Set the response header status and length
t.getResponseHeaders().put("Content-Type", Collections.singletonList("application/json"));
t.sendResponseHeaders(200, response.getBytes().length);
// Write the response string
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
private void responseHTML(HttpExchange t, String response) throws IOException { // static file support for plugins
// Set the response header status and length httpServer.raw().config.precompressStaticFiles = false; // If this isn't set to false, files such as images may appear corrupted when serving static files
t.getResponseHeaders().put("Content-Type", Collections.singletonList("text/html; charset=UTF-8"));
t.sendResponseHeaders(200, response.getBytes().length); httpServer.listen(Grasscutter.getConfig().getDispatchOptions().Port);
//Write the response string Grasscutter.getLogger().info(translate("messages.dispatch.port_bind", Integer.toString(httpServer.raw().port())));
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
} }
private Map<String, String> parseQueryString(String qs) { private Map<String, String> parseQueryString(String qs) {
Map<String, String> result = new HashMap<>(); Map<String, String> result = new HashMap<>();
if (qs == null) { if (qs == null) {
...@@ -465,7 +485,8 @@ public final class DispatchServer { ...@@ -465,7 +485,8 @@ public final class DispatchServer {
if (eqPos < 0 || eqPos > next) { if (eqPos < 0 || eqPos > next) {
result.put(URLDecoder.decode(qs.substring(last, next), "utf-8"), ""); result.put(URLDecoder.decode(qs.substring(last, next), "utf-8"), "");
} else { } else {
result.put(URLDecoder.decode(qs.substring(last, eqPos), "utf-8"), URLDecoder.decode(qs.substring(eqPos + 1, next), "utf-8")); result.put(URLDecoder.decode(qs.substring(last, eqPos), "utf-8"),
URLDecoder.decode(qs.substring(eqPos + 1, next), "utf-8"));
} }
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); // will never happen, utf-8 support is mandatory for java throw new RuntimeException(e); // will never happen, utf-8 support is mandatory for java
...@@ -476,8 +497,28 @@ public final class DispatchServer { ...@@ -476,8 +497,28 @@ public final class DispatchServer {
return result; return result;
} }
public static class RegionData { public AuthenticationHandler getAuthHandler() {
if(authHandler == null) {
return new DefaultAuthenticationHandler();
}
return authHandler;
}
public boolean registerAuthHandler(AuthenticationHandler authHandler) {
if(this.authHandler != null) {
Grasscutter.getLogger().error(String.format("[Dispatch] Unable to register '%s' authentication handler. \n" +
"The '%s' authentication handler has already been registered", authHandler.getClass().getName(), this.authHandler.getClass().getName()));
return false;
}
this.authHandler = authHandler;
return true;
}
public void resetAuthHandler() {
this.authHandler = null;
}
public static class RegionData {
QueryCurrRegionHttpRsp parsedRegionQuery; QueryCurrRegionHttpRsp parsedRegionQuery;
String Base64; String Base64;
...@@ -485,5 +526,13 @@ public final class DispatchServer { ...@@ -485,5 +526,13 @@ public final class DispatchServer {
this.parsedRegionQuery = prq; this.parsedRegionQuery = prq;
this.Base64 = b64; this.Base64 = b64;
} }
public QueryCurrRegionHttpRsp getParsedRegionQuery() {
return parsedRegionQuery;
}
public String getBase64() {
return Base64;
}
} }
} }
package emu.grasscutter.server.dispatch.authentication;
import emu.grasscutter.server.dispatch.json.LoginAccountRequestJson;
import emu.grasscutter.server.dispatch.json.LoginResultJson;
import express.http.Request;
import express.http.Response;
public interface AuthenticationHandler {
// This is in case plugins also want some sort of authentication
void handleLogin(Request req, Response res);
void handleRegister(Request req, Response res);
void handleChangePassword(Request req, Response res);
LoginResultJson handleGameLogin(Request req, LoginAccountRequestJson requestData);
}
package emu.grasscutter.server.dispatch.authentication;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.database.DatabaseHelper;
import emu.grasscutter.game.Account;
import emu.grasscutter.server.dispatch.json.LoginAccountRequestJson;
import emu.grasscutter.server.dispatch.json.LoginResultJson;
import express.http.Request;
import express.http.Response;
import static emu.grasscutter.utils.Language.translate;
public class DefaultAuthenticationHandler implements AuthenticationHandler {
@Override
public void handleLogin(Request req, Response res) {
res.send("Authentication is not available with the default authentication method");
}
@Override
public void handleRegister(Request req, Response res) {
res.send("Authentication is not available with the default authentication method");
}
@Override
public void handleChangePassword(Request req, Response res) {
res.send("Authentication is not available with the default authentication method");
}
@Override
public LoginResultJson handleGameLogin(Request req, LoginAccountRequestJson requestData) {
LoginResultJson responseData = new LoginResultJson();
// Login
Account account = DatabaseHelper.getAccountByName(requestData.account);
// Check if account exists, else create a new one.
if (account == null) {
// Account doesn't exist, so we can either auto create it if the config value is set.
if (Grasscutter.getConfig().getDispatchOptions().AutomaticallyCreateAccounts) {
// This account has been created AUTOMATICALLY. There will be no permissions added.
account = DatabaseHelper.createAccountWithId(requestData.account, 0);
for (String permission : Grasscutter.getConfig().getDispatchOptions().defaultPermissions) {
account.addPermission(permission);
}
if (account != null) {
responseData.message = "OK";
responseData.data.account.uid = account.getId();
responseData.data.account.token = account.generateSessionKey();
responseData.data.account.email = account.getEmail();
Grasscutter.getLogger().info(translate("messages.dispatch.account.account_login_create_success", req.ip(), responseData.data.account.uid));
} else {
responseData.retcode = -201;
responseData.message = translate("messages.dispatch.account.username_create_error");
Grasscutter.getLogger().info(translate("messages.dispatch.account.account_login_create_error", req.ip()));
}
} else {
responseData.retcode = -201;
responseData.message = translate("messages.dispatch.account.username_error");
Grasscutter.getLogger().info(translate("messages.dispatch.account.account_login_exist_error", req.ip()));
}
} else {
// Account was found, log the player in
responseData.message = "OK";
responseData.data.account.uid = account.getId();
responseData.data.account.token = account.generateSessionKey();
responseData.data.account.email = account.getEmail();
Grasscutter.getLogger().info(translate("messages.dispatch.account.login_success", req.ip(), responseData.data.account.uid));
}
return responseData;
}
}
package emu.grasscutter.server.dispatch.http;
import java.io.File;
import java.io.IOException;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.database.DatabaseHelper;
import emu.grasscutter.game.Account;
import emu.grasscutter.utils.FileUtils;
import emu.grasscutter.utils.Utils;
import express.http.HttpContextHandler;
import express.http.Request;
import express.http.Response;
public final class GachaRecordHandler implements HttpContextHandler {
String render_template;
public GachaRecordHandler() {
File template = new File(Utils.toFilePath(Grasscutter.getConfig().DATA_FOLDER + "/gacha_records.html"));
if (template.exists()) {
// Load from cache
render_template = new String(FileUtils.read(template));
} else {
render_template = "{{REPLACE_RECORD}}";
}
}
@Override
public void handle(Request req, Response res) throws IOException {
// Grasscutter.getLogger().info( req.query().toString() );
String sessionKey = req.query("s");
int page = 0;
int gachaType = 0;
if (req.query("p") != null) {
page = Integer.valueOf(req.query("p"));
}
if (req.query("gachaType") != null) {
gachaType = Integer.valueOf(req.query("gachaType"));
}
Account account = DatabaseHelper.getAccountBySessionKey(sessionKey);
if (account != null) {
String records = DatabaseHelper.getGachaRecords(account.getPlayerUid(), page, gachaType).toString();
// Grasscutter.getLogger().info(records);
String response = render_template.replace("{{REPLACE_RECORD}}", records)
.replace("{{REPLACE_MAXPAGE}}", String.valueOf(DatabaseHelper.getGachaRecordsMaxPage(account.getPlayerUid(), page, gachaType)));
res.send(response);
} else {
res.send("No account found.");
}
}
}
...@@ -16,7 +16,7 @@ public class LoginResultJson { ...@@ -16,7 +16,7 @@ public class LoginResultJson {
public static class VerifyAccountData { public static class VerifyAccountData {
public String uid; public String uid;
public String name = ""; public String name = "";
public String email; public String email = "";
public String mobile = ""; public String mobile = "";
public String is_email_verify = "0"; public String is_email_verify = "0";
public String realname = ""; public String realname = "";
......
package emu.grasscutter.server.event;
/**
* Implementing this interface marks an event as cancellable.
*/
public interface Cancellable {
void cancel();
}
package emu.grasscutter.server.event;
import emu.grasscutter.Grasscutter;
/**
* A generic server event.
*/
public abstract class Event {
private boolean cancelled = false;
/**
* Return the cancelled state of the event.
*/
public boolean isCanceled() {
return this.cancelled;
}
/**
* Cancels the event if possible.
*/
public void cancel() {
if(this instanceof Cancellable)
this.cancelled = true;
}
/**
* Pushes this event to all listeners.
*/
public void call() {
Grasscutter.getPluginManager().invokeEvent(this);
}
}
package emu.grasscutter.server.event;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.utils.EventConsumer;
public final class EventHandler<T extends Event> {
private final Class<T> eventClass;
private EventConsumer<T> listener;
private HandlerPriority priority;
private boolean handleCanceled;
public EventHandler(Class<T> eventClass) {
this.eventClass = eventClass;
}
/**
* Gets which event this handler is handling.
* @return An event class.
*/
public Class<T> handles() {
return this.eventClass;
}
/**
* Returns the callback for the handler.
* @return A consumer callback.
*/
public EventConsumer<T> getCallback() {
return this.listener;
}
/**
* Returns the handler's priority.
* @return The priority of the handler.
*/
public HandlerPriority getPriority() {
return this.priority;
}
/**
* Returns if the handler will ignore cancelled events.
* @return The ignore cancelled state.
*/
public boolean ignoresCanceled() {
return this.handleCanceled;
}
/**
* Sets the callback method for when the event is invoked.
* @param listener An event handler method.
* @return Method chaining.
*/
public EventHandler<T> listener(EventConsumer<T> listener) {
this.listener = listener; return this;
}
/**
* Changes the handler's priority in handling events.
* @param priority The priority of the handler.
* @return Method chaining.
*/
public EventHandler<T> priority(HandlerPriority priority) {
this.priority = priority; return this;
}
/**
* Sets if the handler will ignore cancelled events.
* @param ignore If the handler should ignore cancelled events.
* @return Method chaining.
*/
public EventHandler<T> ignore(boolean ignore) {
this.handleCanceled = ignore; return this;
}
/**
* Registers the handler into the PluginManager.
*/
public void register() {
Grasscutter.getPluginManager().registerListener(this);
}
}
\ No newline at end of file
package emu.grasscutter.server.event;
public enum HandlerPriority {
/**
* The handler will be called before every other handler.
*/
HIGH,
/**
* The handler will be called the same time as other handlers.
*/
NORMAL,
/**
* The handler will be called after every other handler.
*/
LOW
}
package emu.grasscutter.server.event.dispatch;
import emu.grasscutter.server.event.types.ServerEvent;
public final class QueryAllRegionsEvent extends ServerEvent {
private String regionList;
public QueryAllRegionsEvent(String regionList) {
super(Type.DISPATCH);
this.regionList = regionList;
}
public void setRegionList(String regionList) {
this.regionList = regionList;
}
public String getRegionList() {
return this.regionList;
}
}
package emu.grasscutter.server.event.dispatch;
import emu.grasscutter.server.event.types.ServerEvent;
public final class QueryCurrentRegionEvent extends ServerEvent {
private String regionInfo;
public QueryCurrentRegionEvent(String regionInfo) {
super(Type.DISPATCH);
this.regionInfo = regionInfo;
}
public void setRegionInfo(String regionInfo) {
this.regionInfo = regionInfo;
}
public String getRegionInfo() {
return this.regionInfo;
}
}
package emu.grasscutter.server.event.game;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.server.event.types.GameEvent;
import emu.grasscutter.server.game.GameSession;
public final class PlayerCreationEvent extends GameEvent {
private final GameSession session;
private Class<? extends Player> playerClass;
public PlayerCreationEvent(GameSession session, Class<? extends Player> playerClass) {
this.session = session;
this.playerClass = playerClass;
}
public GameSession getSession() {
return this.session;
}
public void setPlayerClass(Class<? extends Player> playerClass) {
this.playerClass = playerClass;
}
public Class<? extends Player> getPlayerClass() {
return this.playerClass;
}
}
package emu.grasscutter.server.event.game;
import emu.grasscutter.server.event.Cancellable;
import emu.grasscutter.server.event.types.ServerEvent;
import emu.grasscutter.server.game.GameSession;
public final class ReceivePacketEvent extends ServerEvent implements Cancellable {
private final GameSession gameSession;
private final int packetId;
private byte[] packetData;
public ReceivePacketEvent(GameSession gameSession, int packetId, byte[] packetData) {
super(Type.GAME);
this.gameSession = gameSession;
this.packetId = packetId;
this.packetData = packetData;
}
public GameSession getGameSession() {
return this.gameSession;
}
public int getPacketId() {
return this.packetId;
}
public void setPacketData(byte[] packetData) {
this.packetData = packetData;
}
public byte[] getPacketData() {
return this.packetData;
}
}
package emu.grasscutter.server.event.game;
import emu.grasscutter.net.packet.BasePacket;
import emu.grasscutter.server.event.Cancellable;
import emu.grasscutter.server.event.types.ServerEvent;
import emu.grasscutter.server.game.GameSession;
public final class SendPacketEvent extends ServerEvent implements Cancellable {
private final GameSession gameSession;
private BasePacket packet;
public SendPacketEvent(GameSession gameSession, BasePacket packet) {
super(Type.GAME);
this.gameSession = gameSession;
this.packet = packet;
}
public GameSession getGameSession() {
return this.gameSession;
}
public void setPacket(BasePacket packet) {
this.packet = packet;
}
public BasePacket getPacket() {
return this.packet;
}
}
package emu.grasscutter.server.event.game;
import emu.grasscutter.server.event.types.ServerEvent;
public final class ServerTickEvent extends ServerEvent {
public ServerTickEvent() {
super(Type.GAME);
}
}
package emu.grasscutter.server.event.internal;
import emu.grasscutter.server.event.types.ServerEvent;
import java.time.OffsetDateTime;
public final class ServerStartEvent extends ServerEvent {
private final OffsetDateTime startTime;
public ServerStartEvent(Type type, OffsetDateTime startTime) {
super(type);
this.startTime = startTime;
}
public OffsetDateTime getStartTime() {
return this.startTime;
}
}
package emu.grasscutter.server.event.internal;
import emu.grasscutter.server.event.types.ServerEvent;
import java.time.OffsetDateTime;
public final class ServerStopEvent extends ServerEvent {
private final OffsetDateTime stopTime;
public ServerStopEvent(Type type, OffsetDateTime stopTime) {
super(type);
this.stopTime = stopTime;
}
public OffsetDateTime getStopTime() {
return this.stopTime;
}
}
package emu.grasscutter.server.event.player;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.server.event.Cancellable;
import emu.grasscutter.server.event.types.PlayerEvent;
public final class PlayerJoinEvent extends PlayerEvent implements Cancellable {
public PlayerJoinEvent(Player player) {
super(player);
}
}
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