DispatchServer.java 22.9 KB
Newer Older
Melledy's avatar
Melledy committed
1
2
3
4
5
6
package emu.grasscutter.server.dispatch;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.protobuf.ByteString;

7
import emu.grasscutter.Config;
Melledy's avatar
Melledy committed
8
import emu.grasscutter.Grasscutter;
9
10
import emu.grasscutter.Grasscutter.ServerDebugMode;
import emu.grasscutter.Grasscutter.ServerRunMode;
Melledy's avatar
Melledy committed
11
12
13
14
15
16
import emu.grasscutter.database.DatabaseHelper;
import emu.grasscutter.game.Account;
import emu.grasscutter.net.proto.QueryCurrRegionHttpRspOuterClass.QueryCurrRegionHttpRsp;
import emu.grasscutter.net.proto.QueryRegionListHttpRspOuterClass.QueryRegionListHttpRsp;
import emu.grasscutter.net.proto.RegionInfoOuterClass.RegionInfo;
import emu.grasscutter.net.proto.RegionSimpleInfoOuterClass.RegionSimpleInfo;
17
18
import emu.grasscutter.server.dispatch.authentication.AuthenticationHandler;
import emu.grasscutter.server.dispatch.authentication.DefaultAuthenticationHandler;
19
import emu.grasscutter.server.dispatch.http.GachaRecordHandler;
Jaida Wu's avatar
Jaida Wu committed
20
import emu.grasscutter.server.dispatch.json.*;
Melledy's avatar
Melledy committed
21
import emu.grasscutter.server.dispatch.json.ComboTokenReqJson.LoginTokenData;
KingRainbow44's avatar
KingRainbow44 committed
22
23
import emu.grasscutter.server.event.dispatch.QueryAllRegionsEvent;
import emu.grasscutter.server.event.dispatch.QueryCurrentRegionEvent;
24
import emu.grasscutter.tools.Tools;
Melledy's avatar
Melledy committed
25
import emu.grasscutter.utils.FileUtils;
26
import emu.grasscutter.utils.Utils;
27
import express.Express;
28
import io.javalin.http.staticfiles.Location;
29
30
31
32
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;
Melledy's avatar
Melledy committed
33

Jaida Wu's avatar
Jaida Wu committed
34
35
import java.io.*;
import java.net.URLDecoder;
36
import java.util.*;
Melledy's avatar
Melledy committed
37

38
39
import static emu.grasscutter.utils.Language.translate;

KingRainbow44's avatar
KingRainbow44 committed
40
public final class DispatchServer {
Jaida Wu's avatar
Jaida Wu committed
41
42
	public static String query_region_list = "";
	public static String query_cur_region = "";
43

Melledy's avatar
Melledy committed
44
	private final Gson gson;
45
	private final String defaultServerName = "os_usa";
46

Melledy's avatar
Melledy committed
47
	public String regionListBase64;
48
	public Map<String, RegionData> regions;
49
	private AuthenticationHandler authHandler;
50
	private Express httpServer;
51

Melledy's avatar
Melledy committed
52
	public DispatchServer() {
53
		this.regions = new HashMap<>();
Melledy's avatar
Melledy committed
54
		this.gson = new GsonBuilder().create();
55

Melledy's avatar
Melledy committed
56
57
58
		this.loadQueries();
		this.initRegion();
	}
59

60
61
	public Express getServer() {
		return httpServer;
Melledy's avatar
Melledy committed
62
	}
63

64
65
66
67
68
69
	public void setHttpServer(Express httpServer) {
		this.httpServer.stop();
		this.httpServer = httpServer;
		this.httpServer.listen(Grasscutter.getConfig().getDispatchOptions().Port);
	}

Melledy's avatar
Melledy committed
70
71
72
73
	public Gson getGsonFactory() {
		return gson;
	}

74
75
	public QueryCurrRegionHttpRsp getCurrRegion() {
		// Needs to be fixed by having the game servers connect to the dispatch server.
76
		if (Grasscutter.getConfig().RunMode == ServerRunMode.HYBRID) {
77
			return regions.get(defaultServerName).parsedRegionQuery;
78
79
		}

80
		Grasscutter.getLogger().warn("[Dispatch] Unsupported run mode for getCurrRegion()");
81
		return null;
Melledy's avatar
Melledy committed
82
	}
83

Melledy's avatar
Melledy committed
84
85
	public void loadQueries() {
		File file;
86

Melledy's avatar
Melledy committed
87
88
89
90
		file = new File(Grasscutter.getConfig().DATA_FOLDER + "query_region_list.txt");
		if (file.exists()) {
			query_region_list = new String(FileUtils.read(file));
		} else {
Jaida Wu's avatar
Jaida Wu committed
91
			Grasscutter.getLogger().warn("[Dispatch] query_region_list not found! Using default region list.");
Melledy's avatar
Melledy committed
92
		}
93

Melledy's avatar
Melledy committed
94
95
96
97
		file = new File(Grasscutter.getConfig().DATA_FOLDER + "query_cur_region.txt");
		if (file.exists()) {
			query_cur_region = new String(FileUtils.read(file));
		} else {
Jaida Wu's avatar
Jaida Wu committed
98
			Grasscutter.getLogger().warn("[Dispatch] query_cur_region not found! Using default current region.");
Melledy's avatar
Melledy committed
99
100
101
102
103
104
105
		}
	}

	private void initRegion() {
		try {
			byte[] decoded = Base64.getDecoder().decode(query_region_list);
			QueryRegionListHttpRsp rl = QueryRegionListHttpRsp.parseFrom(decoded);
106

Melledy's avatar
Melledy committed
107
108
			byte[] decoded2 = Base64.getDecoder().decode(query_cur_region);
			QueryCurrRegionHttpRsp regionQuery = QueryCurrRegionHttpRsp.parseFrom(decoded2);
109

KingRainbow44's avatar
KingRainbow44 committed
110
111
			List<RegionSimpleInfo> servers = new ArrayList<>();
			List<String> usedNames = new ArrayList<>(); // List to check for potential naming conflicts
112
			if (Grasscutter.getConfig().RunMode == ServerRunMode.HYBRID) { // Automatically add the game server if in
113
																				// hybrid mode
114
115
116
117
				RegionSimpleInfo server = RegionSimpleInfo.newBuilder()
						.setName("os_usa")
						.setTitle(Grasscutter.getConfig().getGameServerOptions().Name)
						.setType("DEV_PUBLIC")
118
119
120
121
122
123
124
125
126
						.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)
127
										+ "/query_cur_region/" + defaultServerName)
128
129
130
131
132
						.build();
				usedNames.add(defaultServerName);
				servers.add(server);

				RegionInfo serverRegion = regionQuery.getRegionInfo().toBuilder()
133
						.setGateserverIp((Grasscutter.getConfig().getGameServerOptions().PublicIp.isEmpty()
134
135
								? Grasscutter.getConfig().getGameServerOptions().Ip
								: Grasscutter.getConfig().getGameServerOptions().PublicIp))
136
						.setGateserverPort(Grasscutter.getConfig().getGameServerOptions().PublicPort != 0
137
138
139
140
								? Grasscutter.getConfig().getGameServerOptions().PublicPort
								: Grasscutter.getConfig().getGameServerOptions().Port)
						.setSecretKey(ByteString
								.copyFrom(FileUtils.read(Grasscutter.getConfig().KEY_FOLDER + "dispatchSeed.bin")))
141
142
143
						.build();

				QueryCurrRegionHttpRsp parsedRegionQuery = regionQuery.toBuilder().setRegionInfo(serverRegion).build();
144
145
				regions.put(defaultServerName, new RegionData(parsedRegionQuery,
						Base64.getEncoder().encodeToString(parsedRegionQuery.toByteString().toByteArray())));
146
147

			} else {
148
149
150
				if (Grasscutter.getConfig().getDispatchOptions().getGameServers().length == 0) {
					Grasscutter.getLogger()
							.error("[Dispatch] There are no game servers available. Exiting due to unplayable state.");
151
152
153
154
					System.exit(1);
				}
			}

155
156
157
			for (Config.DispatchServerOptions.RegionInfo regionInfo : Grasscutter.getConfig().getDispatchOptions()
					.getGameServers()) {
				if (usedNames.contains(regionInfo.Name)) {
158
159
160
161
162
163
164
					Grasscutter.getLogger().error("Region name already in use.");
					continue;
				}
				RegionSimpleInfo server = RegionSimpleInfo.newBuilder()
						.setName(regionInfo.Name)
						.setTitle(regionInfo.Title)
						.setType("DEV_PUBLIC")
165
166
167
168
169
						.setDispatchUrl(
								"http" + (Grasscutter.getConfig().getDispatchOptions().FrontHTTPS ? "s" : "") + "://"
										+ (Grasscutter.getConfig().getDispatchOptions().PublicIp.isEmpty()
												? Grasscutter.getConfig().getDispatchOptions().Ip
												: Grasscutter.getConfig().getDispatchOptions().PublicIp)
170
171
172
										+ ":" + (Grasscutter.getConfig().getDispatchOptions().PublicPort != 0
										? Grasscutter.getConfig().getDispatchOptions().PublicPort
										: Grasscutter.getConfig().getDispatchOptions().Port) + "/query_cur_region/" + regionInfo.Name)
173
174
175
176
177
						.build();
				usedNames.add(regionInfo.Name);
				servers.add(server);

				RegionInfo serverRegion = regionQuery.getRegionInfo().toBuilder()
178
179
						.setGateserverIp(regionInfo.Ip)
						.setGateserverPort(regionInfo.Port)
180
181
						.setSecretKey(ByteString
								.copyFrom(FileUtils.read(Grasscutter.getConfig().KEY_FOLDER + "dispatchSeed.bin")))
182
183
184
						.build();

				QueryCurrRegionHttpRsp parsedRegionQuery = regionQuery.toBuilder().setRegionInfo(serverRegion).build();
185
186
				regions.put(regionInfo.Name, new RegionData(parsedRegionQuery,
						Base64.getEncoder().encodeToString(parsedRegionQuery.toByteString().toByteArray())));
187
188
			}

Melledy's avatar
Melledy committed
189
			QueryRegionListHttpRsp regionList = QueryRegionListHttpRsp.newBuilder()
190
					.addAllRegionList(servers)
191
192
193
194
					.setClientSecretKey(rl.getClientSecretKey())
					.setClientCustomConfigEncrypted(rl.getClientCustomConfigEncrypted())
					.setEnableLoginPc(true)
					.build();
Melledy's avatar
Melledy committed
195
196
197

			this.regionListBase64 = Base64.getEncoder().encodeToString(regionList.toByteString().toByteArray());
		} catch (Exception e) {
198
			Grasscutter.getLogger().error("[Dispatch] Error while initializing region info!", e);
Melledy's avatar
Melledy committed
199
200
201
202
		}
	}

	public void start() throws Exception {
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
		httpServer = new Express(config -> {
			config.server(() -> {
				Server server = new Server();
				ServerConnector serverConnector;

				if(Grasscutter.getConfig().getDispatchOptions().UseSSL) {
					SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
					File keystoreFile = new File(Grasscutter.getConfig().getDispatchOptions().KeystorePath);

					if(keystoreFile.exists()) {
						try {
							sslContextFactory.setKeyStorePath(keystoreFile.getPath());
							sslContextFactory.setKeyStorePassword(Grasscutter.getConfig().getDispatchOptions().KeystorePassword);
						} catch (Exception e) {
							e.printStackTrace();
218
							Grasscutter.getLogger().warn(translate("messages.dispatch.keystore.password_error"));
219
220
221
222

							try {
								sslContextFactory.setKeyStorePath(keystoreFile.getPath());
								sslContextFactory.setKeyStorePassword("123456");
223
								Grasscutter.getLogger().warn(translate("messages.dispatch.keystore.default_password"));
224
							} catch (Exception e2) {
225
								Grasscutter.getLogger().warn(translate("messages.dispatch.keystore.general_error"));
226
227
228
229
230
231
								e2.printStackTrace();
							}
						}

						serverConnector = new ServerConnector(server, sslContextFactory);
					} else {
232
						Grasscutter.getLogger().warn(translate("messages.dispatch.keystore.no_keystore_error"));
233
234
235
						Grasscutter.getConfig().getDispatchOptions().UseSSL = false;

						serverConnector = new ServerConnector(server);
236
					}
237
238
				} else {
					serverConnector = new ServerConnector(server);
239
				}
240
241
242
243
244
245
246

				serverConnector.setPort(Grasscutter.getConfig().getDispatchOptions().Port);
				server.setConnectors(new Connector[]{serverConnector});
				return server;
			});

			config.enforceSsl = Grasscutter.getConfig().getDispatchOptions().UseSSL;
247
			if(Grasscutter.getConfig().DebugMode == ServerDebugMode.ALL) {
248
				config.enableDevLogging();
249
			}
250
251
252
253
			if (Grasscutter.getConfig().getDispatchOptions().CORS){
				if (Grasscutter.getConfig().getDispatchOptions().CORSAllowedOrigins.length > 0) config.enableCorsForOrigin(Grasscutter.getConfig().getDispatchOptions().CORSAllowedOrigins);
				else config.enableCorsForAllOrigins();
			}
254
		});
255
		httpServer.get("/", (req, res) -> res.send(translate("messages.status.welcome")));
Jaida Wu's avatar
Jaida Wu committed
256

257
		httpServer.raw().error(404, ctx -> {
258
			if(Grasscutter.getConfig().DebugMode == ServerDebugMode.MISSING) {
259
				Grasscutter.getLogger().info(translate("messages.dispatch.unhandled_request_error", ctx.method(), ctx.url()));
260
261
262
263
			}
			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.
		});
264

265
266
267
268
269
270
271
272
273
274
		// 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));

Melledy's avatar
Melledy committed
275
		// Dispatch
276
		httpServer.get("/query_region_list", (req, res) -> {
KingRainbow44's avatar
KingRainbow44 committed
277
			// Log
278
			Grasscutter.getLogger().info(String.format("[Dispatch] Client %s request: query_region_list", req.ip()));
Jaida Wu's avatar
Jaida Wu committed
279

280
281
282
			// Invoke event.
			QueryAllRegionsEvent event = new QueryAllRegionsEvent(regionListBase64); event.call();
			// Respond with event result.
283
			res.send(event.getRegionList());
Melledy's avatar
Melledy committed
284
		});
285

286
287
288
289
290
291
292
293
294
295
		httpServer.get("/query_cur_region/:id", (req, res) -> {
			String regionName = req.params("id");
			// Log
			Grasscutter.getLogger().info(
					String.format("Client %s request: query_cur_region/%s", req.ip(), regionName));
			// Create a response form the request query parameters
			String response = "CAESGE5vdCBGb3VuZCB2ZXJzaW9uIGNvbmZpZw==";
			if (req.query().values().size() > 0) {
				response = regions.get(regionName).Base64;
			}
296

297
298
299
300
301
302
303
			// Invoke event.
			QueryCurrentRegionEvent event = new QueryCurrentRegionEvent(response); event.call();
			// Respond with event result.
			res.send(event.getRegionInfo());
		});

		// Login
304

305
		httpServer.post("/hk4e_global/mdk/shield/api/login", (req, res) -> {
KingRainbow44's avatar
KingRainbow44 committed
306
307
308
			// Get post data
			LoginAccountRequestJson requestData = null;
			try {
309
				String body = req.ctx().body();
KingRainbow44's avatar
KingRainbow44 committed
310
				requestData = getGsonFactory().fromJson(body, LoginAccountRequestJson.class);
311
			} catch (Exception ignored) { }
312

KingRainbow44's avatar
KingRainbow44 committed
313
314
315
316
			// Create response json
			if (requestData == null) {
				return;
			}
317
			Grasscutter.getLogger().info(translate("messages.dispatch.account.login_attempt", req.ip()));
318

319
			res.send(this.getAuthHandler().handleGameLogin(req, requestData));
Melledy's avatar
Melledy committed
320
		});
321

Melledy's avatar
Melledy committed
322
		// Login via token
323
		httpServer.post("/hk4e_global/mdk/shield/api/verify", (req, res) -> {
KingRainbow44's avatar
KingRainbow44 committed
324
325
326
			// Get post data
			LoginTokenRequestJson requestData = null;
			try {
327
				String body = req.ctx().body();
KingRainbow44's avatar
KingRainbow44 committed
328
				requestData = getGsonFactory().fromJson(body, LoginTokenRequestJson.class);
329
330
			} catch (Exception ignored) {
			}
331

KingRainbow44's avatar
KingRainbow44 committed
332
333
334
335
336
			// Create response json
			if (requestData == null) {
				return;
			}
			LoginResultJson responseData = new LoginResultJson();
337
			Grasscutter.getLogger().info(translate("messages.dispatch.account.login_token_attempt"));
KingRainbow44's avatar
KingRainbow44 committed
338
339
340

			// Login
			Account account = DatabaseHelper.getAccountById(requestData.uid);
341

KingRainbow44's avatar
KingRainbow44 committed
342
343
344
			// Test
			if (account == null || !account.getSessionKey().equals(requestData.token)) {
				responseData.retcode = -111;
345
				responseData.message = translate("messages.dispatch.account.account_cache_error");
Jaida Wu's avatar
Jaida Wu committed
346

347
				Grasscutter.getLogger().info(translate("messages.dispatch.account.login_token_error", req.ip()));
KingRainbow44's avatar
KingRainbow44 committed
348
349
350
351
352
			} else {
				responseData.message = "OK";
				responseData.data.account.uid = requestData.uid;
				responseData.data.account.token = requestData.token;
				responseData.data.account.email = account.getEmail();
Jaida Wu's avatar
Jaida Wu committed
353

354
				Grasscutter.getLogger().info(translate("messages.dispatch.account.login_token_success", req.ip(), requestData.uid));
KingRainbow44's avatar
KingRainbow44 committed
355
			}
Jaida Wu's avatar
Jaida Wu committed
356

357
			res.send(responseData);
Melledy's avatar
Melledy committed
358
		});
359

Melledy's avatar
Melledy committed
360
		// Exchange for combo token
361
		httpServer.post("/hk4e_global/combo/granter/login/v2/login", (req, res) -> {
KingRainbow44's avatar
KingRainbow44 committed
362
363
364
			// Get post data
			ComboTokenReqJson requestData = null;
			try {
365
				String body = req.ctx().body();
KingRainbow44's avatar
KingRainbow44 committed
366
				requestData = getGsonFactory().fromJson(body, ComboTokenReqJson.class);
367
368
			} catch (Exception ignored) {
			}
369

KingRainbow44's avatar
KingRainbow44 committed
370
371
372
373
			// Create response json
			if (requestData == null || requestData.data == null) {
				return;
			}
374
			LoginTokenData loginData = getGsonFactory().fromJson(requestData.data, LoginTokenData.class); // Get login
375
			// data
KingRainbow44's avatar
KingRainbow44 committed
376
377
378
379
			ComboTokenResJson responseData = new ComboTokenResJson();

			// Login
			Account account = DatabaseHelper.getAccountById(loginData.uid);
380

KingRainbow44's avatar
KingRainbow44 committed
381
382
383
			// Test
			if (account == null || !account.getSessionKey().equals(loginData.token)) {
				responseData.retcode = -201;
384
				responseData.message = translate("messages.dispatch.account.session_key_error");
Jaida Wu's avatar
Jaida Wu committed
385

386
				Grasscutter.getLogger().info(translate("messages.dispatch.account.combo_token_error", req.ip()));
KingRainbow44's avatar
KingRainbow44 committed
387
388
389
390
391
			} else {
				responseData.message = "OK";
				responseData.data.open_id = loginData.uid;
				responseData.data.combo_id = "157795300";
				responseData.data.combo_token = account.generateLoginToken();
Jaida Wu's avatar
Jaida Wu committed
392

393
				Grasscutter.getLogger().info(translate("messages.dispatch.account.combo_token_success", req.ip()));
KingRainbow44's avatar
KingRainbow44 committed
394
			}
Jaida Wu's avatar
Jaida Wu committed
395

396
			res.send(responseData);
Melledy's avatar
Melledy committed
397
		});
398
399
400
401

		// 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

Melledy's avatar
Melledy committed
402
		// Agreement and Protocol
403
404
405
		// hk4e-sdk-os.hoyoverse.com
		httpServer.get("/hk4e_global/mdk/agreement/api/getAgreementInfos", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"marketing_agreements\":[]}}"));
		// hk4e-sdk-os.hoyoverse.com
mingjun97's avatar
mingjun97 committed
406
407
		// this could be either GET or POST based on the observation of different clients
		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\":\"\"}}}"));
408

Melledy's avatar
Melledy committed
409
		// Game data
410
411
412
413
414
		// hk4e-api-os.hoyoverse.com
		httpServer.all("/common/hk4e_global/announcement/api/getAlertPic", 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}}"));
		// hk4e-api-os.hoyoverse.com
BaiSugar's avatar
BaiSugar committed
415
		httpServer.all("/common/hk4e_global/announcement/api/getAnnList", new AnnouncementHandler());
416
		// hk4e-api-os-static.hoyoverse.com
BaiSugar's avatar
BaiSugar committed
417
		httpServer.all("/common/hk4e_global/announcement/api/getAnnContent", new AnnouncementHandler());
418
419
420
		// hk4e-sdk-os.hoyoverse.com
		httpServer.all("/hk4e_global/mdk/shopwindow/shopwindow/listPriceTier", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"suggest_currency\":\"USD\",\"tiers\":[]}}"));

Melledy's avatar
Melledy committed
421
		// Captcha
422
423
424
		// api-account-os.hoyoverse.com
		httpServer.post("/account/risky/api/check", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":\"none\",\"action\":\"ACTION_NONE\",\"geetest\":null}}"));

425
		// Config
426
427
428
429
430
		// 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\"}}}"));
		// hk4e-sdk-os-static.hoyoverse.com
		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
Magix's avatar
Magix committed
431
		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}}}}"));
Melledy's avatar
Melledy committed
432
		// Test api?
433
		// abtest-api-data-sg.hoyoverse.com
Benjamin Elsdon's avatar
Benjamin Elsdon committed
434
		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\"}}]}"));
435
436
437
438

		// log-upload-os.mihoyo.com
		httpServer.all("/log/sdk/upload", new DispatchHttpJsonHandler("{\"code\":0}"));
		httpServer.all("/sdk/upload", new DispatchHttpJsonHandler("{\"code\":0}"));
439
		httpServer.post("/sdk/dataUpload", new DispatchHttpJsonHandler("{\"code\":0}"));
440
441
		// /perf/config/verify?device_id=xxx&platform=x&name=xxx
		httpServer.all("/perf/config/verify", new DispatchHttpJsonHandler("{\"code\":0}"));
442

Melledy's avatar
Melledy committed
443
		// Logging servers
444
		// overseauspider.yuanshen.com
445
		httpServer.all("/log", new ClientLogHandler());
446
		// log-upload-os.mihoyo.com
447
		httpServer.all("/crash/dataUpload", new ClientLogHandler());
Jaida Wu's avatar
Jaida Wu committed
448

mingjun97's avatar
mingjun97 committed
449
450
451
		// webstatic-sea.hoyoverse.com
		httpServer.get("/admin/mi18n/plat_oversea/m202003048/m202003048-version.json", new DispatchHttpJsonHandler("{\"version\":51}"));

452
453
454
		// gacha record.
		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.
455
		httpServer.get("/gacha", new GachaRecordHandler());
456
457
458
459
460
		if(!(new File(gachaMappingsPath).exists())) {
			Tools.createGachaMapping(gachaMappingsPath);
		}

		httpServer.raw().config.addSinglePageRoot("/gacha/mappings", gachaMappingsPath, Location.EXTERNAL);
Jaida Wu's avatar
Jaida Wu committed
461

462
463
		// static file support for plugins
		httpServer.raw().config.precompressStaticFiles = false; // If this isn't set to false, files such as images may appear corrupted when serving static files
464

465
		httpServer.listen(Grasscutter.getConfig().getDispatchOptions().Port);
466
		Grasscutter.getLogger().info(translate("messages.dispatch.port_bind", Integer.toString(httpServer.raw().port())));
Melledy's avatar
Melledy committed
467
	}
468

Melledy's avatar
Melledy committed
469
	private Map<String, String> parseQueryString(String qs) {
Jaida Wu's avatar
Jaida Wu committed
470
		Map<String, String> result = new HashMap<>();
Jaida Wu's avatar
Jaida Wu committed
471
		if (qs == null) {
Jaida Wu's avatar
Jaida Wu committed
472
			return result;
Jaida Wu's avatar
Jaida Wu committed
473
		}
Jaida Wu's avatar
Jaida Wu committed
474
475
476
477

		int last = 0, next, l = qs.length();
		while (last < l) {
			next = qs.indexOf('&', last);
Jaida Wu's avatar
Jaida Wu committed
478
			if (next == -1) {
Jaida Wu's avatar
Jaida Wu committed
479
				next = l;
Jaida Wu's avatar
Jaida Wu committed
480
			}
Jaida Wu's avatar
Jaida Wu committed
481
482
483

			if (next > last) {
				int eqPos = qs.indexOf('=', last);
484
485
486
487
488
489
490
491
492
				try {
					if (eqPos < 0 || eqPos > next) {
						result.put(URLDecoder.decode(qs.substring(last, next), "utf-8"), "");
					} else {
						result.put(URLDecoder.decode(qs.substring(last, eqPos), "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
Jaida Wu's avatar
Jaida Wu committed
493
494
495
496
497
				}
			}
			last = next + 1;
		}
		return result;
Melledy's avatar
Melledy committed
498
	}
499

500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
	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;
	}

521
522
523
524
525
526
527
528
	public static class RegionData {
		QueryCurrRegionHttpRsp parsedRegionQuery;
		String Base64;

		public RegionData(QueryCurrRegionHttpRsp prq, String b64) {
			this.parsedRegionQuery = prq;
			this.Base64 = b64;
		}
529
530
531
532
533
534
535
536

		public QueryCurrRegionHttpRsp getParsedRegionQuery() {
			return parsedRegionQuery;
		}

		public String getBase64() {
			return Base64;
		}
537
	}
Melledy's avatar
Melledy committed
538
}