Commit 934c415d authored by Magix's avatar Magix Committed by GitHub
Browse files

Merge pull request #383 from 4Benj/api

Complete rework of Dispatch, Added DebugModes
parents a62520f9 be507310
...@@ -54,12 +54,14 @@ tmp/ ...@@ -54,12 +54,14 @@ tmp/
# Grasscutter # Grasscutter
resources/* resources/*
logs/* logs/*
plugins/*
data/AbilityEmbryos.json data/AbilityEmbryos.json
data/OpenConfig.json data/OpenConfig.json
GM Handbook.txt GM Handbook.txt
config.json config.json
mitmdump.exe mitmdump.exe
*.jar *.jar
!lib/*.jar
mongod.exe mongod.exe
/src/generated/ /src/generated/
/*.sh /*.sh
...@@ -16,18 +16,22 @@ buildscript { ...@@ -16,18 +16,22 @@ buildscript {
} }
plugins { plugins {
// Apply the application plugin to add support for building a CLI application
id 'application'
// Apply the java plugin to add support for Java // Apply the java plugin to add support for Java
id 'java' id 'java'
// Apply the protobuf auto generator // Apply the protobuf auto generator
id 'com.google.protobuf' version "0.8.18" id 'com.google.protobuf' version "0.8.18"
id 'idea'
// Eclipse Support
id 'eclipse' id 'eclipse'
// Apply the application plugin to add support for building a CLI application // Intelij Support
id 'application' id 'idea'
// Maven
id 'maven-publish' id 'maven-publish'
id 'signing' id 'signing'
} }
......
...@@ -15,6 +15,7 @@ public final class Config { ...@@ -15,6 +15,7 @@ public final class Config {
public String SCRIPTS_FOLDER = "./resources/Scripts/"; public String SCRIPTS_FOLDER = "./resources/Scripts/";
public String PLUGINS_FOLDER = "./plugins/"; public String PLUGINS_FOLDER = "./plugins/";
public String DebugMode = "NONE"; // ALL, MISSING, NONE
public String RunMode = "HYBRID"; // HYBRID, DISPATCH_ONLY, GAME_ONLY public String RunMode = "HYBRID"; // HYBRID, DISPATCH_ONLY, GAME_ONLY
public GameServerOptions GameServer = new GameServerOptions(); public GameServerOptions GameServer = new GameServerOptions();
public DispatchServerOptions DispatchServer = new DispatchServerOptions(); public DispatchServerOptions DispatchServer = new DispatchServerOptions();
...@@ -62,8 +63,6 @@ public final class Config { ...@@ -62,8 +63,6 @@ public final class Config {
public String DispatchServerDatabaseUrl = "mongodb://localhost:27017"; public String DispatchServerDatabaseUrl = "mongodb://localhost:27017";
public String DispatchServerDatabaseCollection = "grasscutter"; public String DispatchServerDatabaseCollection = "grasscutter";
public boolean LOG_PACKETS = false;
public int InventoryLimitWeapon = 2000; public int InventoryLimitWeapon = 2000;
public int InventoryLimitRelic = 2000; public int InventoryLimitRelic = 2000;
public int InventoryLimitMaterial = 2000; public int InventoryLimitMaterial = 2000;
......
...@@ -2,26 +2,41 @@ package emu.grasscutter.server.dispatch; ...@@ -2,26 +2,41 @@ package emu.grasscutter.server.dispatch;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpHandler;
import emu.grasscutter.Grasscutter;
import express.http.HttpContextHandler;
import express.http.Request;
import express.http.Response;
public final class DispatchHttpJsonHandler implements HttpHandler { 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.equalsIgnoreCase("MISSING") && Arrays.stream(missingRoutes).anyMatch(x -> x == req.baseUrl())) {
t.sendResponseHeaders(200, response.getBytes().length); Grasscutter.getLogger().info(String.format("[Dispatch] Client %s %s request: ", req.ip(), req.method(), req.baseUrl()) + (Grasscutter.getConfig().DebugMode.equalsIgnoreCase("MISSING") ? "(MISSING)" : ""));
// Write the response string res.send(response.getBytes());
OutputStream os = t.getResponseBody(); }
os.write(response.getBytes());
os.close();
} }
} }
...@@ -3,10 +3,6 @@ package emu.grasscutter.server.dispatch; ...@@ -3,10 +3,6 @@ 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;
...@@ -21,52 +17,37 @@ import emu.grasscutter.server.dispatch.json.ComboTokenReqJson.LoginTokenData; ...@@ -21,52 +17,37 @@ import emu.grasscutter.server.dispatch.json.ComboTokenReqJson.LoginTokenData;
import emu.grasscutter.server.event.dispatch.QueryAllRegionsEvent; import emu.grasscutter.server.event.dispatch.QueryAllRegionsEvent;
import emu.grasscutter.server.event.dispatch.QueryCurrentRegionEvent; import emu.grasscutter.server.event.dispatch.QueryCurrentRegionEvent;
import emu.grasscutter.utils.FileUtils; import emu.grasscutter.utils.FileUtils;
import emu.grasscutter.utils.Utils; import express.Express;
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.BindException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.util.*; import java.util.*;
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 HashMap<String, RegionData> regions;
private HttpServer server; private Express httpServer;
public DispatchServer() { public DispatchServer() {
this.regions = new HashMap<String, RegionData>(); 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();
this.initRegion(); this.initRegion();
} }
@Deprecated public Express getServer() {
public HttpServer getServer() { return httpServer;
return server;
}
public HttpServer getHttpServer() {
return server;
}
public InetSocketAddress getAddress() {
return address;
} }
public Gson getGsonFactory() { public Gson getGsonFactory() {
...@@ -126,7 +107,7 @@ public final class DispatchServer { ...@@ -126,7 +107,7 @@ public final class DispatchServer {
+ (Grasscutter.getConfig().getDispatchOptions().PublicPort != 0 + (Grasscutter.getConfig().getDispatchOptions().PublicPort != 0
? Grasscutter.getConfig().getDispatchOptions().PublicPort ? Grasscutter.getConfig().getDispatchOptions().PublicPort
: Grasscutter.getConfig().getDispatchOptions().Port) : Grasscutter.getConfig().getDispatchOptions().Port)
+ "/query_cur_region_" + defaultServerName) + "/query_cur_region/" + defaultServerName)
.build(); .build();
usedNames.add(defaultServerName); usedNames.add(defaultServerName);
servers.add(server); servers.add(server);
...@@ -169,7 +150,9 @@ public final class DispatchServer { ...@@ -169,7 +150,9 @@ public final class DispatchServer {
+ (Grasscutter.getConfig().getDispatchOptions().PublicIp.isEmpty() + (Grasscutter.getConfig().getDispatchOptions().PublicIp.isEmpty()
? Grasscutter.getConfig().getDispatchOptions().Ip ? Grasscutter.getConfig().getDispatchOptions().Ip
: Grasscutter.getConfig().getDispatchOptions().PublicIp) : Grasscutter.getConfig().getDispatchOptions().PublicIp)
+ ":" + getAddress().getPort() + "/query_cur_region_" + regionInfo.Name) + ":" + (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);
...@@ -199,121 +182,101 @@ public final class DispatchServer { ...@@ -199,121 +182,101 @@ public final class DispatchServer {
} }
} }
private HttpServer safelyCreateServer(InetSocketAddress address) {
try {
return HttpServer.create(address, 0);
} catch (BindException ignored) {
Grasscutter.getLogger().error("Unable to bind to port: " + getAddress().getPort() + " (HTTP)");
} catch (Exception exception) {
Grasscutter.getLogger().error("Unable to start HTTP server.", exception);
}
return null;
}
private KeyManagerFactory createKeyManagerFactory(File keystore, String password) {
char[] pass = password.toCharArray();
KeyManagerFactory kmf = null;
try (FileInputStream fis = new FileInputStream(keystore)) {
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(fis, pass);
kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, pass);
} catch (Exception exception) {
Grasscutter.getLogger().error("Unable to load keystore.", exception);
}
return kmf;
}
public void start() throws Exception { public void start() throws Exception {
if (Grasscutter.getConfig().getDispatchOptions().UseSSL) { httpServer = new Express(config -> {
// Keystore config.server(() -> {
SSLContext sslContext = SSLContext.getInstance("TLS"); Server server = new Server();
KeyManagerFactory kmf = null; ServerConnector serverConnector;
if(Grasscutter.getConfig().getDispatchOptions().UseSSL) {
SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
File keystoreFile = new File(Grasscutter.getConfig().getDispatchOptions().KeystorePath); File keystoreFile = new File(Grasscutter.getConfig().getDispatchOptions().KeystorePath);
if (keystoreFile.exists()) { if(keystoreFile.exists()) {
try { try {
kmf = createKeyManagerFactory(keystoreFile, Grasscutter.getConfig().getDispatchOptions().KeystorePassword); sslContextFactory.setKeyStorePath(keystoreFile.getPath());
sslContextFactory.setKeyStorePassword(Grasscutter.getConfig().getDispatchOptions().KeystorePassword);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace();
Grasscutter.getLogger().warn("[Dispatch] Unable to load keystore. Trying default keystore password..."); Grasscutter.getLogger().warn("[Dispatch] Unable to load keystore. Trying default keystore password...");
try { try {
kmf = createKeyManagerFactory(keystoreFile, "123456"); sslContextFactory.setKeyStorePath(keystoreFile.getPath());
Grasscutter.getLogger().warn( sslContextFactory.setKeyStorePassword("123456");
"[Dispatch] The default keystore password was loaded successfully. Please consider setting the password to '123456' in config.json."); Grasscutter.getLogger().warn("[Dispatch] The default keystore password was loaded successfully. Please consider setting the password to 123456 in config.json.");
} catch (Exception e2) { } catch (Exception e2) {
Grasscutter.getLogger().warn("[Dispatch] Error while loading keystore!", e2); Grasscutter.getLogger().warn("[Dispatch] Error while loading keystore!");
} e2.printStackTrace();
} }
} }
if (kmf == null) { serverConnector = new ServerConnector(server, sslContextFactory);
} else {
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().getDispatchOptions().UseSSL = false; Grasscutter.getConfig().getDispatchOptions().UseSSL = false;
server = this.safelyCreateServer(this.getAddress());
}
HttpsServer httpsServer;
try { serverConnector = new ServerConnector(server);
httpsServer = HttpsServer.create(getAddress(), 0);
sslContext.init(kmf.getKeyManagers(), null, null);
httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));
server = httpsServer;
} catch (BindException e) {
Grasscutter.getLogger().error("Unable to bind to port: " + getAddress().getPort() + " (HTTPS)");
} }
} else { } else {
server = this.safelyCreateServer(this.getAddress()); serverConnector = new ServerConnector(server);
} }
if (server == null) serverConnector.setPort(Grasscutter.getConfig().getDispatchOptions().Port);
throw new NullPointerException("An HTTP server was not created."); server.setConnectors(new Connector[]{serverConnector});
return server;
});
server.createContext("/", t -> responseHTML(t, "Hello")); config.enforceSsl = Grasscutter.getConfig().getDispatchOptions().UseSSL;
if(Grasscutter.getConfig().DebugMode.equalsIgnoreCase("ALL")) {
config.enableDevLogging();
}
});
httpServer.get("/", (req, res) -> res.send("Welcome to Grasscutter"));
httpServer.raw().error(404, ctx -> {
if(Grasscutter.getConfig().DebugMode.equalsIgnoreCase("MISSING")) {
Grasscutter.getLogger().info(String.format("[Dispatch] Potential unhandled %s request: %s", 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.
});
// Dispatch // Dispatch
server.createContext("/query_region_list", t -> { httpServer.get("/query_region_list", (req, res) -> {
// Log // Log
Grasscutter.getLogger() Grasscutter.getLogger().info(String.format("[Dispatch] Client %s request: query_region_list", req.ip()));
.info(String.format("[Dispatch] Client %s request: query_region_list", t.getRemoteAddress()));
// Invoke event. // Invoke event.
QueryAllRegionsEvent event = new QueryAllRegionsEvent(regionListBase64); event.call(); QueryAllRegionsEvent event = new QueryAllRegionsEvent(regionListBase64); event.call();
// Respond with event result. // Respond with event result.
responseHTML(t, event.getRegionList()); 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 (uri.getQuery() != null && uri.getQuery().length() > 0) { if (req.query().values().size() > 0) {
response = regionCurrentBase64; response = regions.get(regionName).Base64;
} }
// Invoke event. // Invoke event.
QueryCurrentRegionEvent event = new QueryCurrentRegionEvent(response); event.call(); QueryCurrentRegionEvent event = new QueryCurrentRegionEvent(response); event.call();
// Respond with event result. // Respond with event result.
responseHTML(t, event.getRegionInfo()); 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();
Grasscutter.getLogger().info(body);
requestData = getGsonFactory().fromJson(body, LoginAccountRequestJson.class); requestData = getGsonFactory().fromJson(body, LoginAccountRequestJson.class);
} catch (Exception ignored) { } catch (Exception ignored) {
} }
...@@ -325,7 +288,7 @@ public final class DispatchServer { ...@@ -325,7 +288,7 @@ public final class DispatchServer {
LoginResultJson responseData = new LoginResultJson(); LoginResultJson responseData = new LoginResultJson();
Grasscutter.getLogger() Grasscutter.getLogger()
.info(String.format("[Dispatch] Client %s is trying to log in", t.getRemoteAddress())); .info(String.format("[Dispatch] Client %s is trying to log in", req.ip()));
// Login // Login
Account account = DatabaseHelper.getAccountByName(requestData.account); Account account = DatabaseHelper.getAccountByName(requestData.account);
...@@ -339,6 +302,10 @@ public final class DispatchServer { ...@@ -339,6 +302,10 @@ public final class DispatchServer {
// added. // added.
account = DatabaseHelper.createAccountWithId(requestData.account, 0); account = DatabaseHelper.createAccountWithId(requestData.account, 0);
for (String permission : Grasscutter.getConfig().getDispatchOptions().defaultPermissions) {
account.addPermission(permission);
}
if (account != null) { if (account != null) {
responseData.message = "OK"; responseData.message = "OK";
responseData.data.account.uid = account.getId(); responseData.data.account.uid = account.getId();
...@@ -347,23 +314,20 @@ public final class DispatchServer { ...@@ -347,23 +314,20 @@ public final class DispatchServer {
Grasscutter.getLogger() Grasscutter.getLogger()
.info(String.format("[Dispatch] Client %s failed to log in: Account %s created", .info(String.format("[Dispatch] Client %s failed to log in: Account %s created",
t.getRemoteAddress(), responseData.data.account.uid)); req.ip(), responseData.data.account.uid));
for (String permission : Grasscutter.getConfig().getDispatchOptions().defaultPermissions) {
account.addPermission(permission);
}
} else { } else {
responseData.retcode = -201; responseData.retcode = -201;
responseData.message = "Username not found, create failed."; responseData.message = "Username not found, create failed.";
Grasscutter.getLogger().info(String.format( Grasscutter.getLogger().info(String.format(
"[Dispatch] Client %s failed to log in: Account create failed", t.getRemoteAddress())); "[Dispatch] Client %s failed to log in: Account create failed", req.ip()));
} }
} else { } else {
responseData.retcode = -201; responseData.retcode = -201;
responseData.message = "Username not found."; responseData.message = "Username not found.";
Grasscutter.getLogger().info(String Grasscutter.getLogger().info(String
.format("[Dispatch] Client %s failed to log in: Account no found", t.getRemoteAddress())); .format("[Dispatch] Client %s failed to log in: Account no found", req.ip()));
} }
} else { } else {
// Account was found, log the player in // Account was found, log the player in
...@@ -372,18 +336,19 @@ public final class DispatchServer { ...@@ -372,18 +336,19 @@ public final class DispatchServer {
responseData.data.account.token = account.generateSessionKey(); responseData.data.account.token = account.generateSessionKey();
responseData.data.account.email = account.getEmail(); responseData.data.account.email = account.getEmail();
Grasscutter.getLogger().info(String.format("[Dispatch] Client %s logged in as %s", t.getRemoteAddress(), Grasscutter.getLogger().info(String.format("[Dispatch] Client %s logged in as %s", req.ip(),
responseData.data.account.uid)); responseData.data.account.uid));
} }
responseJSON(t, responseData); res.send(responseData);
}); });
// 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) {
} }
...@@ -393,8 +358,7 @@ public final class DispatchServer { ...@@ -393,8 +358,7 @@ public final class DispatchServer {
return; return;
} }
LoginResultJson responseData = new LoginResultJson(); LoginResultJson responseData = new LoginResultJson();
Grasscutter.getLogger() Grasscutter.getLogger().info(String.format("[Dispatch] Client %s is trying to log in via token", req.ip()));
.info(String.format("[Dispatch] Client %s is trying to log in via token", t.getRemoteAddress()));
// Login // Login
Account account = DatabaseHelper.getAccountById(requestData.uid); Account account = DatabaseHelper.getAccountById(requestData.uid);
...@@ -405,7 +369,7 @@ public final class DispatchServer { ...@@ -405,7 +369,7 @@ public final class DispatchServer {
responseData.message = "Game account cache information error"; responseData.message = "Game account cache information error";
Grasscutter.getLogger() Grasscutter.getLogger()
.info(String.format("[Dispatch] Client %s failed to log in via token", t.getRemoteAddress())); .info(String.format("[Dispatch] Client %s failed to log in via token", req.ip()));
} else { } else {
responseData.message = "OK"; responseData.message = "OK";
responseData.data.account.uid = requestData.uid; responseData.data.account.uid = requestData.uid;
...@@ -413,17 +377,18 @@ public final class DispatchServer { ...@@ -413,17 +377,18 @@ public final class DispatchServer {
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", Grasscutter.getLogger().info(String.format("[Dispatch] Client %s logged in via token as %s",
t.getRemoteAddress(), responseData.data.account.uid)); req.ip(), responseData.data.account.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) {
} }
...@@ -445,7 +410,7 @@ public final class DispatchServer { ...@@ -445,7 +410,7 @@ public final class DispatchServer {
responseData.message = "Wrong session key."; responseData.message = "Wrong session key.";
Grasscutter.getLogger().info( Grasscutter.getLogger().info(
String.format("[Dispatch] Client %s failed to exchange combo token", t.getRemoteAddress())); String.format("[Dispatch] Client %s failed to exchange combo token", req.ip()));
} else { } else {
responseData.message = "OK"; responseData.message = "OK";
responseData.data.open_id = loginData.uid; responseData.data.open_id = loginData.uid;
...@@ -453,110 +418,65 @@ public final class DispatchServer { ...@@ -453,110 +418,65 @@ public final class DispatchServer {
responseData.data.combo_token = account.generateLoginToken(); responseData.data.combo_token = account.generateLoginToken();
Grasscutter.getLogger().info( Grasscutter.getLogger().info(
String.format("[Dispatch] Client %s succeed to exchange combo token", t.getRemoteAddress())); String.format("[Dispatch] Client %s succeed to exchange combo token", 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( // hk4e-sdk-os.hoyoverse.com
"{\"retcode\":0,\"message\":\"OK\",\"data\":{\"marketing_agreements\":[]}}")); httpServer.post("/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\":\"\"}}}"));
server.createContext( // hk4e-sdk-os.hoyoverse.com
"/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
server.createContext( // 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}}"));
"/common/hk4e_global/announcement/api/getAlertAnn", // hk4e-api-os.hoyoverse.com
new DispatchHttpJsonHandler( httpServer.all("/common/hk4e_global/announcement/api/getAnnList", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"list\":[],\"total\":0,\"type_list\":[],\"alert\":false,\"alert_id\":0,\"timezone\":0,\"t\":\"" + System.currentTimeMillis() + "\"}}"));
"{\"retcode\":0,\"message\":\"OK\",\"data\":{\"alert\":false,\"alert_id\":0,\"remind\":true}}")); // hk4e-api-os-static.hoyoverse.com
server.createContext( // hk4e-api-os.hoyoverse.com httpServer.all("/common/hk4e_global/announcement/api/getAnnContent", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"list\":[],\"total\":0}}"));
"/common/hk4e_global/announcement/api/getAnnList", // hk4e-sdk-os.hoyoverse.com
new DispatchHttpJsonHandler( httpServer.all("/hk4e_global/mdk/shopwindow/shopwindow/listPriceTier", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"suggest_currency\":\"USD\",\"tiers\":[]}}"));
"{\"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\":\"none\",\"action\":\"ACTION_NONE\",\"geetest\":null}}")
);
// Config // Config
server.createContext( // sdk-os-static.hoyoverse.com // sdk-os-static.hoyoverse.com
"/combo/box/api/config/sdk/combo", 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\"}}}"));
new DispatchHttpJsonHandler( // hk4e-sdk-os-static.hoyoverse.com
"{\"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}}"));
server.createContext( // hk4e-sdk-os-static.hoyoverse.com // hk4e-sdk-os-static.hoyoverse.com
"/hk4e_global/combo/granter/api/getConfig", 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}}}}"));
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
server.createContext( // log-upload-os.mihoyo.com httpServer.all("/perf/config/verify", new DispatchHttpJsonHandler("{\"code\":0}"));
"/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 DispatchHttpJsonHandler("{\"code\":0}"));
new DispatchHttpJsonHandler("{\"code\":0}")); // log-upload-os.mihoyo.com
httpServer.all("/crash/dataUpload", new DispatchHttpJsonHandler("{\"code\":0}"));
server.createContext( // log-upload-os.mihoyo.com
"/crash/dataUpload", httpServer.get("/gacha", (req, res) -> res.send("<!doctype html><html lang=\"en\"><head><title>Gacha</title></head><body></body></html>"));
new DispatchHttpJsonHandler("{\"code\":0}"));
server.createContext("/gacha", t -> responseHTML(t, httpServer.listen(Grasscutter.getConfig().getDispatchOptions().Port);
"<!doctype html><html lang=\"en\"><head><title>Gacha</title></head><body></body></html>")); Grasscutter.getLogger().info("[Dispatch] Dispatch server started on port " + httpServer.raw().port());
// Start server
server.start();
Grasscutter.getLogger().info("[Dispatch] Dispatch server started on port " + getAddress().getPort());
}
private void responseJSON(HttpExchange t, Object data) throws IOException {
// 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 {
// Set the response header status and length
t.getResponseHeaders().put("Content-Type", Collections.singletonList("text/html; charset=UTF-8"));
t.sendResponseHeaders(200, response.getBytes().length);
// Write the response string
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
} }
private Map<String, String> parseQueryString(String qs) { private Map<String, String> parseQueryString(String qs) {
...@@ -574,11 +494,15 @@ public final class DispatchServer { ...@@ -574,11 +494,15 @@ public final class DispatchServer {
if (next > last) { if (next > last) {
int eqPos = qs.indexOf('=', last); int eqPos = qs.indexOf('=', last);
try {
if (eqPos < 0 || eqPos > next) { if (eqPos < 0 || eqPos > next) {
result.put(URLDecoder.decode(qs.substring(last, next), StandardCharsets.UTF_8), ""); result.put(URLDecoder.decode(qs.substring(last, next), "utf-8"), "");
} else { } else {
result.put(URLDecoder.decode(qs.substring(last, eqPos), StandardCharsets.UTF_8), result.put(URLDecoder.decode(qs.substring(last, eqPos), "utf-8"),
URLDecoder.decode(qs.substring(eqPos + 1, next), StandardCharsets.UTF_8)); URLDecoder.decode(qs.substring(eqPos + 1, next), "utf-8"));
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); // will never happen, utf-8 support is mandatory for java
} }
} }
last = next + 1; last = next + 1;
...@@ -587,7 +511,6 @@ public final class DispatchServer { ...@@ -587,7 +511,6 @@ public final class DispatchServer {
} }
public static class RegionData { public static class RegionData {
QueryCurrRegionHttpRsp parsedRegionQuery; QueryCurrRegionHttpRsp parsedRegionQuery;
String Base64; String Base64;
......
...@@ -88,7 +88,7 @@ public class GameServerPacketHandler { ...@@ -88,7 +88,7 @@ public class GameServerPacketHandler {
} }
// Log unhandled packets // Log unhandled packets
if (Grasscutter.getConfig().getGameServerOptions().LOG_PACKETS) { if (Grasscutter.getConfig().DebugMode.equalsIgnoreCase("MISSING")) {
Grasscutter.getLogger().info("Unhandled packet (" + opcode + "): " + emu.grasscutter.net.packet.PacketOpcodesUtil.getOpcodeName(opcode)); Grasscutter.getLogger().info("Unhandled packet (" + opcode + "): " + emu.grasscutter.net.packet.PacketOpcodesUtil.getOpcodeName(opcode));
} }
} }
......
...@@ -163,7 +163,7 @@ public class GameSession extends KcpChannel { ...@@ -163,7 +163,7 @@ public class GameSession extends KcpChannel {
} }
// Log // Log
if (Grasscutter.getConfig().getGameServerOptions().LOG_PACKETS) { if (Grasscutter.getConfig().DebugMode.equalsIgnoreCase("ALL")) {
logPacket(packet); logPacket(packet);
} }
...@@ -230,7 +230,7 @@ public class GameSession extends KcpChannel { ...@@ -230,7 +230,7 @@ public class GameSession extends KcpChannel {
} }
// Log packet // Log packet
if (Grasscutter.getConfig().getGameServerOptions().LOG_PACKETS) { if (Grasscutter.getConfig().DebugMode.equalsIgnoreCase("ALL")) {
if (!loopPacket.contains(opcode)) { if (!loopPacket.contains(opcode)) {
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));
......
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