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

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

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

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

38
import static emu.grasscutter.utils.Language.translate;
39
import static emu.grasscutter.Configuration.*;
40

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

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

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

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

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

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

65
66
67
	public void setHttpServer(Express httpServer) {
		this.httpServer.stop();
		this.httpServer = httpServer;
68
		this.httpServer.listen(DISPATCH_INFO.bindPort);
69
70
	}

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

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

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

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

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

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

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

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

KingRainbow44's avatar
KingRainbow44 committed
111
			List<RegionSimpleInfo> servers = new ArrayList<>();
112
113
			List<String> usedNames = new ArrayList<>(); // List to check for potential naming conflicts.
			if (SERVER.runMode == ServerRunMode.HYBRID) { // Automatically add the game server if in hybrid mode.
114
115
				RegionSimpleInfo server = RegionSimpleInfo.newBuilder()
						.setName("os_usa")
116
						.setTitle(DISPATCH_INFO.defaultName)
117
						.setType("DEV_PUBLIC")
118
						.setDispatchUrl(
119
120
121
								"http" + (DISPATCH_ENCRYPTION.useEncryption ? "s" : "") + "://"
										+ lr(DISPATCH_INFO.accessAddress, DISPATCH_INFO.bindAddress) + ":"
										+ lr(DISPATCH_INFO.accessPort, DISPATCH_INFO.bindPort)
122
										+ "/query_cur_region/" + defaultServerName)
123
124
125
126
127
						.build();
				usedNames.add(defaultServerName);
				servers.add(server);

				RegionInfo serverRegion = regionQuery.getRegionInfo().toBuilder()
mingjun97's avatar
mingjun97 committed
128
129
						.setGateserverIp(lr(GAME_INFO.accessAddress, GAME_INFO.bindAddress))
						.setGateserverPort(lr(GAME_INFO.accessPort, GAME_INFO.bindPort))
130
						.setSecretKey(ByteString.copyFrom(FileUtils.read(KEYS_FOLDER + "/dispatchSeed.bin")))
131
132
133
						.build();

				QueryCurrRegionHttpRsp parsedRegionQuery = regionQuery.toBuilder().setRegionInfo(serverRegion).build();
134
135
				regions.put(defaultServerName, new RegionData(parsedRegionQuery,
						Base64.getEncoder().encodeToString(parsedRegionQuery.toByteString().toByteArray())));
136

137
138
139
			} else if (DISPATCH_INFO.regions.length == 0) {
				Grasscutter.getLogger().error("[Dispatch] There are no game servers available. Exiting due to unplayable state.");
				System.exit(1);
140
141
			}

142
			for (var regionInfo : DISPATCH_INFO.regions) {
143
				if (usedNames.contains(regionInfo.Name)) {
144
145
146
147
148
149
150
					Grasscutter.getLogger().error("Region name already in use.");
					continue;
				}
				RegionSimpleInfo server = RegionSimpleInfo.newBuilder()
						.setName(regionInfo.Name)
						.setTitle(regionInfo.Title)
						.setType("DEV_PUBLIC")
151
						.setDispatchUrl(
152
153
154
155
								"http" + (DISPATCH_ENCRYPTION.useEncryption ? "s" : "") + "://"
										+ lr(DISPATCH_INFO.accessAddress, DISPATCH_INFO.bindAddress) + ":" 
										+ lr(DISPATCH_INFO.accessPort, DISPATCH_INFO.bindPort) 
										+ "/query_cur_region/" + regionInfo.Name)
156
157
158
159
160
						.build();
				usedNames.add(regionInfo.Name);
				servers.add(server);

				RegionInfo serverRegion = regionQuery.getRegionInfo().toBuilder()
161
162
						.setGateserverIp(regionInfo.Ip)
						.setGateserverPort(regionInfo.Port)
163
						.setSecretKey(ByteString
164
								.copyFrom(FileUtils.read(KEYS_FOLDER + "/dispatchSeed.bin")))
165
166
167
						.build();

				QueryCurrRegionHttpRsp parsedRegionQuery = regionQuery.toBuilder().setRegionInfo(serverRegion).build();
168
169
				regions.put(regionInfo.Name, new RegionData(parsedRegionQuery,
						Base64.getEncoder().encodeToString(parsedRegionQuery.toByteString().toByteArray())));
170
171
			}

Melledy's avatar
Melledy committed
172
			QueryRegionListHttpRsp regionList = QueryRegionListHttpRsp.newBuilder()
173
					.addAllRegionList(servers)
174
175
176
177
					.setClientSecretKey(rl.getClientSecretKey())
					.setClientCustomConfigEncrypted(rl.getClientCustomConfigEncrypted())
					.setEnableLoginPc(true)
					.build();
Melledy's avatar
Melledy committed
178
179

			this.regionListBase64 = Base64.getEncoder().encodeToString(regionList.toByteString().toByteArray());
180
181
		} catch (Exception exception) {
			Grasscutter.getLogger().error("[Dispatch] Error while initializing region info!", exception);
Melledy's avatar
Melledy committed
182
183
184
185
		}
	}

	public void start() throws Exception {
186
187
188
189
190
		httpServer = new Express(config -> {
			config.server(() -> {
				Server server = new Server();
				ServerConnector serverConnector;

191
				if(DISPATCH_ENCRYPTION.useEncryption) {
192
					SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
193
					File keystoreFile = new File(DISPATCH_ENCRYPTION.keystore);
194
195
196
197

					if(keystoreFile.exists()) {
						try {
							sslContextFactory.setKeyStorePath(keystoreFile.getPath());
198
							sslContextFactory.setKeyStorePassword(DISPATCH_ENCRYPTION.keystorePassword);
199
200
						} catch (Exception e) {
							e.printStackTrace();
201
							Grasscutter.getLogger().warn(translate("messages.dispatch.keystore.password_error"));
202
203
204
205

							try {
								sslContextFactory.setKeyStorePath(keystoreFile.getPath());
								sslContextFactory.setKeyStorePassword("123456");
206
								Grasscutter.getLogger().warn(translate("messages.dispatch.keystore.default_password"));
207
							} catch (Exception e2) {
208
								Grasscutter.getLogger().warn(translate("messages.dispatch.keystore.general_error"));
209
210
211
212
213
214
								e2.printStackTrace();
							}
						}

						serverConnector = new ServerConnector(server, sslContextFactory);
					} else {
215
						Grasscutter.getLogger().warn(translate("messages.dispatch.keystore.no_keystore_error"));
216
						DISPATCH_ENCRYPTION.useEncryption = false;
217
218

						serverConnector = new ServerConnector(server);
219
					}
220
221
				} else {
					serverConnector = new ServerConnector(server);
222
				}
223

224
				serverConnector.setPort(DISPATCH_INFO.bindPort);
225
226
227
228
				server.setConnectors(new Connector[]{serverConnector});
				return server;
			});

229
230
			config.enforceSsl = DISPATCH_ENCRYPTION.useEncryption;
			if(SERVER.debugLevel == ServerDebugMode.ALL) {
231
				config.enableDevLogging();
232
			}
233
234
235
236
237
			
			if (DISPATCH_POLICIES.cors.enabled) {
				var corsPolicy = DISPATCH_POLICIES.cors;
				if (corsPolicy.allowedOrigins.length > 0) 
					config.enableCorsForOrigin(corsPolicy.allowedOrigins);
238
239
				else config.enableCorsForAllOrigins();
			}
240
		});
241
		httpServer.get("/", (req, res) -> res.send("<!doctype html><html><head><meta charset=\"utf8\"></head><body>" + translate("messages.status.welcome") + "</body></html>"));
Jaida Wu's avatar
Jaida Wu committed
242

243
		httpServer.raw().error(404, ctx -> {
244
			if(SERVER.debugLevel == ServerDebugMode.MISSING) {
245
				Grasscutter.getLogger().info(translate("messages.dispatch.unhandled_request_error", ctx.method(), ctx.url()));
246
247
			}
			ctx.contentType("text/html");
248
			ctx.result("<!doctype html><html><head><meta charset=\"utf8\"></head><body><img src=\"https://http.cat/404\" /></body></html>"); // I'm like 70% sure this won't break anything.
249
		});
250

251
252
253
254
255
256
257
258
259
260
		// 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
261
		// Dispatch
262
		httpServer.get("/query_region_list", (req, res) -> {
KingRainbow44's avatar
KingRainbow44 committed
263
			// Log
264
			Grasscutter.getLogger().info(String.format("[Dispatch] Client %s request: query_region_list", req.ip()));
Jaida Wu's avatar
Jaida Wu committed
265

266
267
268
			// Invoke event.
			QueryAllRegionsEvent event = new QueryAllRegionsEvent(regionListBase64); event.call();
			// Respond with event result.
269
			res.send(event.getRegionList());
Melledy's avatar
Melledy committed
270
		});
271

272
273
274
275
276
277
278
279
280
281
		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;
			}
282

283
284
285
286
287
288
289
			// Invoke event.
			QueryCurrentRegionEvent event = new QueryCurrentRegionEvent(response); event.call();
			// Respond with event result.
			res.send(event.getRegionInfo());
		});

		// Login
290

291
		httpServer.post("/hk4e_global/mdk/shield/api/login", (req, res) -> {
KingRainbow44's avatar
KingRainbow44 committed
292
293
294
			// Get post data
			LoginAccountRequestJson requestData = null;
			try {
295
				String body = req.ctx().body();
KingRainbow44's avatar
KingRainbow44 committed
296
				requestData = getGsonFactory().fromJson(body, LoginAccountRequestJson.class);
297
			} catch (Exception ignored) { }
298

KingRainbow44's avatar
KingRainbow44 committed
299
300
301
302
			// Create response json
			if (requestData == null) {
				return;
			}
303
			Grasscutter.getLogger().info(translate("messages.dispatch.account.login_attempt", req.ip()));
304

305
			res.send(this.getAuthHandler().handleGameLogin(req, requestData));
Melledy's avatar
Melledy committed
306
		});
307

Melledy's avatar
Melledy committed
308
		// Login via token
309
		httpServer.post("/hk4e_global/mdk/shield/api/verify", (req, res) -> {
KingRainbow44's avatar
KingRainbow44 committed
310
311
312
			// Get post data
			LoginTokenRequestJson requestData = null;
			try {
313
				String body = req.ctx().body();
KingRainbow44's avatar
KingRainbow44 committed
314
				requestData = getGsonFactory().fromJson(body, LoginTokenRequestJson.class);
315
316
			} catch (Exception ignored) {
			}
317

KingRainbow44's avatar
KingRainbow44 committed
318
319
320
321
322
			// Create response json
			if (requestData == null) {
				return;
			}
			LoginResultJson responseData = new LoginResultJson();
KingRainbow44's avatar
KingRainbow44 committed
323
			Grasscutter.getLogger().info(translate("messages.dispatch.account.login_token_attempt", req.ip()));
KingRainbow44's avatar
KingRainbow44 committed
324
325
326

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

KingRainbow44's avatar
KingRainbow44 committed
328
329
330
			// Test
			if (account == null || !account.getSessionKey().equals(requestData.token)) {
				responseData.retcode = -111;
331
				responseData.message = translate("messages.dispatch.account.account_cache_error");
Jaida Wu's avatar
Jaida Wu committed
332

333
				Grasscutter.getLogger().info(translate("messages.dispatch.account.login_token_error", req.ip()));
KingRainbow44's avatar
KingRainbow44 committed
334
335
336
337
338
			} 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
339

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

343
			res.send(responseData);
Melledy's avatar
Melledy committed
344
		});
345

Melledy's avatar
Melledy committed
346
		// Exchange for combo token
347
		httpServer.post("/hk4e_global/combo/granter/login/v2/login", (req, res) -> {
KingRainbow44's avatar
KingRainbow44 committed
348
349
350
			// Get post data
			ComboTokenReqJson requestData = null;
			try {
351
				String body = req.ctx().body();
KingRainbow44's avatar
KingRainbow44 committed
352
				requestData = getGsonFactory().fromJson(body, ComboTokenReqJson.class);
353
354
			} catch (Exception ignored) {
			}
355

KingRainbow44's avatar
KingRainbow44 committed
356
357
358
359
			// Create response json
			if (requestData == null || requestData.data == null) {
				return;
			}
360
			LoginTokenData loginData = getGsonFactory().fromJson(requestData.data, LoginTokenData.class); // Get login
361
			// data
KingRainbow44's avatar
KingRainbow44 committed
362
363
364
365
			ComboTokenResJson responseData = new ComboTokenResJson();

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

KingRainbow44's avatar
KingRainbow44 committed
367
368
369
			// Test
			if (account == null || !account.getSessionKey().equals(loginData.token)) {
				responseData.retcode = -201;
370
				responseData.message = translate("messages.dispatch.account.session_key_error");
Jaida Wu's avatar
Jaida Wu committed
371

372
				Grasscutter.getLogger().info(translate("messages.dispatch.account.combo_token_error", req.ip()));
KingRainbow44's avatar
KingRainbow44 committed
373
374
375
376
377
			} 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
378

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

382
			res.send(responseData);
Melledy's avatar
Melledy committed
383
		});
384
385
386
387

		// 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
388
		// Agreement and Protocol
389
390
391
		// 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
392
393
		// 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\":\"\"}}}"));
394

Melledy's avatar
Melledy committed
395
		// Game data
396
397
398
399
400
		// 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
401
		httpServer.all("/common/hk4e_global/announcement/api/getAnnList", new AnnouncementHandler());
402
		// hk4e-api-os-static.hoyoverse.com
BaiSugar's avatar
BaiSugar committed
403
		httpServer.all("/common/hk4e_global/announcement/api/getAnnContent", new AnnouncementHandler());
404
405
406
		// 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
407
		// Captcha
408
409
410
		// 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}}"));

411
		// Config
412
413
414
415
416
		// 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
417
		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
418
		// Test api?
419
		// abtest-api-data-sg.hoyoverse.com
Benjamin Elsdon's avatar
Benjamin Elsdon committed
420
		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\"}}]}"));
421
422
423
424

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

Melledy's avatar
Melledy committed
429
		// Logging servers
430
		// overseauspider.yuanshen.com
431
		httpServer.all("/log", new ClientLogHandler());
432
		// log-upload-os.mihoyo.com
433
		httpServer.all("/crash/dataUpload", new ClientLogHandler());
Jaida Wu's avatar
Jaida Wu committed
434

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

438
		// gacha record.
439
		String gachaMappingsPath = Utils.toFilePath(DATA("/gacha_mappings.js"));
440
		// TODO: Only serve the html page and have a subsequent request to fetch the gacha data.
441
		httpServer.get("/gacha", new GachaRecordHandler());
442
443
444
445
446
		if(!(new File(gachaMappingsPath).exists())) {
			Tools.createGachaMapping(gachaMappingsPath);
		}

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

448
449
		// 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
450

451
		httpServer.listen(DISPATCH_INFO.bindPort);
452
		Grasscutter.getLogger().info(translate("messages.dispatch.port_bind", Integer.toString(httpServer.raw().port())));
Melledy's avatar
Melledy committed
453
	}
454

Melledy's avatar
Melledy committed
455
	private Map<String, String> parseQueryString(String qs) {
Jaida Wu's avatar
Jaida Wu committed
456
		Map<String, String> result = new HashMap<>();
Jaida Wu's avatar
Jaida Wu committed
457
		if (qs == null) {
Jaida Wu's avatar
Jaida Wu committed
458
			return result;
Jaida Wu's avatar
Jaida Wu committed
459
		}
Jaida Wu's avatar
Jaida Wu committed
460
461
462
463

		int last = 0, next, l = qs.length();
		while (last < l) {
			next = qs.indexOf('&', last);
Jaida Wu's avatar
Jaida Wu committed
464
			if (next == -1) {
Jaida Wu's avatar
Jaida Wu committed
465
				next = l;
Jaida Wu's avatar
Jaida Wu committed
466
			}
Jaida Wu's avatar
Jaida Wu committed
467
468
469

			if (next > last) {
				int eqPos = qs.indexOf('=', last);
470
471
472
473
474
				if (eqPos < 0 || eqPos > next) {
					result.put(URLDecoder.decode(qs.substring(last, next), StandardCharsets.UTF_8), "");
				} else {
					result.put(URLDecoder.decode(qs.substring(last, eqPos), StandardCharsets.UTF_8),
							URLDecoder.decode(qs.substring(eqPos + 1, next), StandardCharsets.UTF_8));
Jaida Wu's avatar
Jaida Wu committed
475
476
477
478
479
				}
			}
			last = next + 1;
		}
		return result;
Melledy's avatar
Melledy committed
480
	}
481

482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
	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;
	}

503
504
505
506
507
508
509
510
	public static class RegionData {
		QueryCurrRegionHttpRsp parsedRegionQuery;
		String Base64;

		public RegionData(QueryCurrRegionHttpRsp prq, String b64) {
			this.parsedRegionQuery = prq;
			this.Base64 = b64;
		}
511
512
513
514
515
516
517
518

		public QueryCurrRegionHttpRsp getParsedRegionQuery() {
			return parsedRegionQuery;
		}

		public String getBase64() {
			return Base64;
		}
519
	}
Melledy's avatar
Melledy committed
520
}