mirror of
https://github.com/Grasscutters/Grasscutter.git
synced 2026-05-25 23:49:57 +08:00
Separate the dispatch and game servers (pt. 1)
gacha is still broken, handbook still needs to be done
This commit is contained in:
@@ -0,0 +1,138 @@
|
||||
package emu.grasscutter.server.dispatch;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.server.game.GameServer;
|
||||
import emu.grasscutter.server.http.handlers.GachaHandler;
|
||||
import emu.grasscutter.utils.Crypto;
|
||||
import lombok.Getter;
|
||||
import org.java_websocket.WebSocket;
|
||||
import org.java_websocket.client.WebSocketClient;
|
||||
import org.java_websocket.handshake.ServerHandshake;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.net.ConnectException;
|
||||
import java.net.URI;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.DISPATCH_INFO;
|
||||
|
||||
public final class DispatchClient extends WebSocketClient implements IDispatcher {
|
||||
@Getter private final Logger logger
|
||||
= Grasscutter.getLogger();
|
||||
@Getter private final Map<Integer, BiConsumer<WebSocket, JsonElement>> handlers
|
||||
= new HashMap<>();
|
||||
|
||||
@Getter private final Map<Integer, List<Consumer<JsonElement>>> callbacks
|
||||
= new HashMap<>();
|
||||
|
||||
public DispatchClient(URI serverUri) {
|
||||
super(serverUri);
|
||||
|
||||
// Mark this client as authenticated.
|
||||
this.setAttachment(true);
|
||||
|
||||
this.registerHandler(PacketIds.GachaHistoryReq, this::fetchGachaHistory);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the gacha history request packet sent by the client.
|
||||
*
|
||||
* @param socket The socket the packet was received from.
|
||||
* @param object The packet data.
|
||||
*/
|
||||
private void fetchGachaHistory(WebSocket socket, JsonElement object) {
|
||||
var message = IDispatcher.decode(object);
|
||||
var accountId = message.get("accountId").getAsString();
|
||||
var page = message.get("page").getAsInt();
|
||||
var type = message.get("gachaType").getAsInt();
|
||||
|
||||
// Create a response object.
|
||||
var response = new JsonObject();
|
||||
|
||||
// Find a player with the specified account ID.
|
||||
var player = Grasscutter.getGameServer()
|
||||
.getPlayerByAccountId(accountId);
|
||||
if (player == null) {
|
||||
response.addProperty("retcode", 1);
|
||||
this.sendMessage(PacketIds.GachaHistoryRsp, response);
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch the gacha records.
|
||||
GachaHandler.fetchGachaRecords(
|
||||
player, response, page, type);
|
||||
|
||||
// Send the response.
|
||||
this.sendMessage(PacketIds.GachaHistoryRsp, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a serialized encrypted message to the server.
|
||||
*
|
||||
* @param message The message to send.
|
||||
*/
|
||||
public void sendMessage(int packetId, Object message) {
|
||||
var serverMessage = this.encodeMessage(packetId, message);
|
||||
// Serialize the message into JSON.
|
||||
var serialized = JSON.toJson(serverMessage)
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
// Encrypt the message.
|
||||
Crypto.xor(serialized, DISPATCH_INFO.encryptionKey);
|
||||
// Send the message.
|
||||
this.send(serialized);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onOpen(ServerHandshake handshake) {
|
||||
// Attempt to handshake with the server.
|
||||
this.sendMessage(PacketIds.LoginNotify, DISPATCH_INFO.dispatchKey);
|
||||
|
||||
this.getLogger().info("Dispatch connection opened.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(String message) {
|
||||
this.getLogger().debug("Received dispatch message from server:\n{}",
|
||||
message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(ByteBuffer bytes) {
|
||||
this.handleMessage(this, bytes.array());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClose(int code, String reason, boolean remote) {
|
||||
this.getLogger().info("Dispatch connection closed.");
|
||||
|
||||
// Attempt to reconnect.
|
||||
new Thread(() -> {
|
||||
try {
|
||||
// Wait 5 seconds before reconnecting.
|
||||
Thread.sleep(5000L);
|
||||
} catch (Exception ignored) { }
|
||||
|
||||
// Attempt to reconnect.
|
||||
Grasscutter.getGameServer().setDispatchClient(
|
||||
new DispatchClient(GameServer.getDispatchUrl()));
|
||||
Grasscutter.getGameServer().getDispatchClient().connect();
|
||||
}).start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Exception ex) {
|
||||
if (ex instanceof ConnectException) {
|
||||
this.getLogger().info("Failed to reconnect, trying again in 5s...");
|
||||
} else {
|
||||
this.getLogger().error("Dispatch connection error.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package emu.grasscutter.server.dispatch;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.database.DatabaseHelper;
|
||||
import emu.grasscutter.utils.Crypto;
|
||||
import lombok.Getter;
|
||||
import org.java_websocket.WebSocket;
|
||||
import org.java_websocket.handshake.ClientHandshake;
|
||||
import org.java_websocket.server.WebSocketServer;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.DISPATCH_INFO;
|
||||
|
||||
/* Internal communications server. */
|
||||
public final class DispatchServer extends WebSocketServer implements IDispatcher {
|
||||
@Getter private final Logger logger
|
||||
= Grasscutter.getLogger();
|
||||
@Getter private final Map<Integer, BiConsumer<WebSocket, JsonElement>> handlers
|
||||
= new HashMap<>();
|
||||
|
||||
@Getter private final Map<Integer, List<Consumer<JsonElement>>> callbacks
|
||||
= new HashMap<>();
|
||||
|
||||
/**
|
||||
* Constructs a new {@code DispatchServer} instance.
|
||||
*
|
||||
* @param address The address to bind to.
|
||||
* @param port The port to bind to.
|
||||
*/
|
||||
public DispatchServer(String address, int port) {
|
||||
super(new InetSocketAddress(address, port));
|
||||
|
||||
this.registerHandler(PacketIds.LoginNotify, this::handleLogin);
|
||||
this.registerHandler(PacketIds.TokenValidateReq, this::validateToken);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the login packet sent by the client.
|
||||
*
|
||||
* @param socket The socket the packet was received from.
|
||||
* @param object The packet data.
|
||||
*/
|
||||
private void handleLogin(WebSocket socket, JsonElement object) {
|
||||
var dispatchKey = object.getAsString()
|
||||
.replaceAll("\"", "");
|
||||
|
||||
// Check if the dispatch key is valid.
|
||||
if (!dispatchKey.equals(DISPATCH_INFO.dispatchKey)) {
|
||||
this.getLogger().warn("Invalid dispatch key received from {}.",
|
||||
socket.getRemoteSocketAddress());
|
||||
this.getLogger().debug("Expected: {}, Received: {}",
|
||||
DISPATCH_INFO.dispatchKey, dispatchKey);
|
||||
socket.close();
|
||||
} else {
|
||||
socket.setAttachment(true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the token validation packet sent by the client.
|
||||
*
|
||||
* @param socket The socket the packet was received from.
|
||||
* @param object The packet data.
|
||||
*/
|
||||
private void validateToken(WebSocket socket, JsonElement object) {
|
||||
var message = IDispatcher.decode(object);
|
||||
var accountId = message.get("uid").getAsString();
|
||||
var token = message.get("token").getAsString();
|
||||
|
||||
// Get the account from the database.
|
||||
var account = DatabaseHelper.getAccountById(accountId);
|
||||
var valid = account != null && account.getToken().equals(token);
|
||||
// Create the response message.
|
||||
var response = new JsonObject();
|
||||
response.addProperty("valid", valid);
|
||||
if (valid) response.add("account",
|
||||
JSON.toJsonTree(account));
|
||||
|
||||
// Send the response.
|
||||
this.sendMessage(socket, PacketIds.TokenValidateRsp, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Broadcasts an encrypted message to all connected clients.
|
||||
*
|
||||
* @param message The message to broadcast.
|
||||
*/
|
||||
public void sendMessage(int packetId, Object message) {
|
||||
var serverMessage = this.encodeMessage(packetId, message);
|
||||
this.getConnections().forEach(
|
||||
socket -> this.sendMessage(socket, serverMessage));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a serialized encrypted message to the client.
|
||||
*
|
||||
* @param socket The socket to send the message to.
|
||||
* @param message The message to send.
|
||||
*/
|
||||
public void sendMessage(WebSocket socket, Object message) {
|
||||
// Serialize the message into JSON.
|
||||
var serialized = JSON.toJson(message)
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
// Encrypt the message.
|
||||
Crypto.xor(serialized, DISPATCH_INFO.encryptionKey);
|
||||
// Send the message.
|
||||
socket.send(serialized);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a serialized encrypted message to the client.
|
||||
*
|
||||
* @param socket The socket to send the message to.
|
||||
* @param packetId The packet ID to send.
|
||||
* @param message The message to send.
|
||||
*/
|
||||
public void sendMessage(WebSocket socket, int packetId, Object message) {
|
||||
this.sendMessage(socket, this.encodeMessage(packetId, message));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStart() {
|
||||
this.getLogger().info("Dispatch server started on port {}.",
|
||||
this.getPort());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onOpen(WebSocket conn, ClientHandshake handshake) {
|
||||
this.getLogger().debug("Dispatch client connected from {}.",
|
||||
conn.getRemoteSocketAddress());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(WebSocket conn, String message) {
|
||||
this.getLogger().debug("Received dispatch message from {}:\n{}",
|
||||
conn.getRemoteSocketAddress(), message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(WebSocket conn, ByteBuffer message) {
|
||||
this.handleMessage(conn, message.array());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
|
||||
this.getLogger().debug("Dispatch client disconnected from {}.",
|
||||
conn.getRemoteSocketAddress());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(WebSocket conn, Exception ex) {
|
||||
this.getLogger().warn("Dispatch server error.", ex);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package emu.grasscutter.server.dispatch;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import emu.grasscutter.utils.Crypto;
|
||||
import emu.grasscutter.utils.JsonAdapters.ByteArrayAdapter;
|
||||
import org.java_websocket.WebSocket;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.DISPATCH_INFO;
|
||||
|
||||
public interface IDispatcher {
|
||||
Gson JSON = new GsonBuilder()
|
||||
.disableHtmlEscaping()
|
||||
.registerTypeAdapter(byte[].class, new ByteArrayAdapter())
|
||||
.create();
|
||||
|
||||
/**
|
||||
* Decodes an escaped JSON message.
|
||||
*
|
||||
* @param element The element to decode.
|
||||
* @return The decoded JSON object.
|
||||
*/
|
||||
static JsonObject decode(JsonElement element) {
|
||||
return IDispatcher.decode(element, JsonObject.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes an escaped JSON message.
|
||||
*
|
||||
* @param element The element to decode.
|
||||
* @return The decoded JSON object.
|
||||
*/
|
||||
static <T> T decode(JsonElement element, Class<T> type) {
|
||||
if (element.isJsonObject()) {
|
||||
return JSON.fromJson(element, type);
|
||||
} else {
|
||||
var data = element.getAsString();
|
||||
|
||||
// Check if the element starts and ends with quotes.
|
||||
if (data.startsWith("\"")
|
||||
&& data.endsWith("\"")) {
|
||||
// Remove the quotes.
|
||||
data = data.substring(1, data.length() - 1);
|
||||
}
|
||||
|
||||
// Un-escape the data.
|
||||
data = data.replaceAll("\"", "");
|
||||
data = data.replaceAll("\\\\", "");
|
||||
|
||||
// De-serialize the data.
|
||||
return JSON.fromJson(data, type);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes a message from the client.
|
||||
*
|
||||
* @param message The message to decode.
|
||||
* @return The decoded message.
|
||||
*/
|
||||
default JsonObject decodeMessage(byte[] message) {
|
||||
// Decrypt the message.
|
||||
Crypto.xor(message, DISPATCH_INFO.encryptionKey);
|
||||
// Deserialize the message.
|
||||
return JSON.fromJson(new String(
|
||||
message, StandardCharsets.UTF_8), JsonObject.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an encoded message.
|
||||
*
|
||||
* @param packetId The packet ID.
|
||||
* @param message The message data.
|
||||
* @return The encoded message.
|
||||
*/
|
||||
default JsonObject encodeMessage(int packetId, Object message) {
|
||||
// Create a message from the message data.
|
||||
var serverMessage = new JsonObject();
|
||||
serverMessage.addProperty("packetId", packetId);
|
||||
serverMessage.addProperty("message", JSON.toJson(message));
|
||||
|
||||
return serverMessage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a message from the client.
|
||||
*
|
||||
* @param socket The socket the message was received from.
|
||||
* @param messageData The message data.
|
||||
*/
|
||||
default void handleMessage(WebSocket socket, byte[] messageData) {
|
||||
// Decode the message.
|
||||
var decoded = this.decodeMessage(messageData);
|
||||
if (decoded == null) {
|
||||
this.getLogger().warn("Received invalid message.");
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the packet ID.
|
||||
var packetId = decoded.get("packetId").getAsInt();
|
||||
// Get the packet data.
|
||||
var packetData = decoded.get("message");
|
||||
|
||||
// Check to see if the client has authenticated.
|
||||
if (packetId != PacketIds.LoginNotify) {
|
||||
if (socket.getAttachment() instanceof Boolean authenticated) {
|
||||
if (!authenticated) {
|
||||
this.getLogger().warn("Received packet ID {} from unauthenticated client.",
|
||||
packetId);
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
} else return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Check if the packet ID is registered.
|
||||
if (this.getHandlers().containsKey(packetId)) {
|
||||
// Get the handler.
|
||||
var handler = this.getHandlers().get(packetId);
|
||||
// Handle the packet.
|
||||
handler.accept(socket, packetData);
|
||||
}
|
||||
|
||||
// Check if the packet ID has callbacks.
|
||||
if (this.getCallbacks().containsKey(packetId)) {
|
||||
// Get the callbacks.
|
||||
var callbacks = this.getCallbacks().get(packetId);
|
||||
// Call the callbacks.
|
||||
callbacks.forEach(callback ->
|
||||
callback.accept(packetData));
|
||||
callbacks.clear();
|
||||
}
|
||||
} catch (Exception exception) {
|
||||
this.getLogger().warn("Exception occurred while handling packet {}.",
|
||||
packetId);
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a message handler.
|
||||
*
|
||||
* @param packetId The packet ID to register.
|
||||
* @param handler The handler to register.
|
||||
*/
|
||||
default void registerHandler(int packetId, BiConsumer<WebSocket, JsonElement> handler) {
|
||||
// Check if the packet ID is already registered.
|
||||
if (this.getHandlers().containsKey(packetId))
|
||||
throw new IllegalArgumentException("Packet ID already registered.");
|
||||
|
||||
// Register the handler.
|
||||
this.getHandlers().put(packetId, handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a callback.
|
||||
*
|
||||
* @param packetId The packet ID to register.
|
||||
* @param callback The callback to register.
|
||||
*/
|
||||
default void registerCallback(int packetId, Consumer<JsonElement> callback) {
|
||||
// Check if the packet ID has a list for callbacks.
|
||||
if (!this.getCallbacks().containsKey(packetId))
|
||||
this.getCallbacks().put(packetId, new LinkedList<>());
|
||||
|
||||
// Register the callback.
|
||||
this.getCallbacks().get(packetId).add(callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The logger for the dispatcher.
|
||||
*/
|
||||
Logger getLogger();
|
||||
|
||||
/**
|
||||
* @return The message handlers.
|
||||
*/
|
||||
Map<Integer, BiConsumer<WebSocket, JsonElement>> getHandlers();
|
||||
|
||||
/**
|
||||
* @return The callbacks.
|
||||
*/
|
||||
Map<Integer, List<Consumer<JsonElement>>> getCallbacks();
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package emu.grasscutter.server.dispatch;
|
||||
|
||||
/* Packet IDs for the dispatch server. */
|
||||
public interface PacketIds {
|
||||
int LoginNotify = 1;
|
||||
int TokenValidateReq = 2;
|
||||
int TokenValidateRsp = 3;
|
||||
int GachaHistoryReq = 4;
|
||||
int GachaHistoryRsp = 5;
|
||||
}
|
||||
Reference in New Issue
Block a user