DispatchServer.java 22.6 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

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

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

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

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

Melledy's avatar
Melledy committed
54
55
56
		this.loadQueries();
		this.initRegion();
	}
57

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

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

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

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

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

Melledy's avatar
Melledy committed
82
83
	public void loadQueries() {
		File file;
84

Melledy's avatar
Melledy committed
85
86
87
88
		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
89
			Grasscutter.getLogger().warn("[Dispatch] query_region_list not found! Using default region list.");
Melledy's avatar
Melledy committed
90
		}
91

Melledy's avatar
Melledy committed
92
93
94
95
		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
96
			Grasscutter.getLogger().warn("[Dispatch] query_cur_region not found! Using default current region.");
Melledy's avatar
Melledy committed
97
98
99
100
101
102
103
		}
	}

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

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

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

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

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

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

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

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

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

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

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

	public void start() throws Exception {
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
		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();
方块君's avatar
方块君 committed
216
							Grasscutter.getLogger().warn(Grasscutter.getLanguage().Not_load_keystore);
217
218
219
220

							try {
								sslContextFactory.setKeyStorePath(keystoreFile.getPath());
								sslContextFactory.setKeyStorePassword("123456");
方块君's avatar
方块君 committed
221
								Grasscutter.getLogger().warn(Grasscutter.getLanguage().Use_default_keystore);
222
							} catch (Exception e2) {
方块君's avatar
方块君 committed
223
								Grasscutter.getLogger().warn(Grasscutter.getLanguage().Load_keystore_error);
224
225
226
227
228
229
								e2.printStackTrace();
							}
						}

						serverConnector = new ServerConnector(server, sslContextFactory);
					} else {
方块君's avatar
方块君 committed
230
						Grasscutter.getLogger().warn(Grasscutter.getLanguage().Not_find_ssl_cert);
231
232
233
						Grasscutter.getConfig().getDispatchOptions().UseSSL = false;

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

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

			config.enforceSsl = Grasscutter.getConfig().getDispatchOptions().UseSSL;
245
			if(Grasscutter.getConfig().DebugMode == ServerDebugMode.ALL) {
246
				config.enableDevLogging();
247
			}
248
		});
Jaida Wu's avatar
Jaida Wu committed
249

方块君's avatar
方块君 committed
250
		httpServer.get("/", (req, res) -> res.send(Grasscutter.getLanguage().Welcome));
Jaida Wu's avatar
Jaida Wu committed
251

252
		httpServer.raw().error(404, ctx -> {
253
			if(Grasscutter.getConfig().DebugMode == ServerDebugMode.MISSING) {
254
				Grasscutter.getLogger().info(Grasscutter.getLanguage().Potential_unhandled_request.replace("{method}", ctx.method()).replace("{url}", ctx.url()));
255
256
257
258
			}
			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.
		});
259

260
261
262
263
264
265
266
267
268
269
		// 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
270
		// Dispatch
271
		httpServer.get("/query_region_list", (req, res) -> {
KingRainbow44's avatar
KingRainbow44 committed
272
			// Log
273
			Grasscutter.getLogger().info(String.format("[Dispatch] Client %s request: query_region_list", req.ip()));
Jaida Wu's avatar
Jaida Wu committed
274

275
276
277
			// Invoke event.
			QueryAllRegionsEvent event = new QueryAllRegionsEvent(regionListBase64); event.call();
			// Respond with event result.
278
			res.send(event.getRegionList());
Melledy's avatar
Melledy committed
279
		});
280

281
282
283
284
285
286
287
288
289
290
		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;
			}
291

292
293
294
295
296
297
298
			// Invoke event.
			QueryCurrentRegionEvent event = new QueryCurrentRegionEvent(response); event.call();
			// Respond with event result.
			res.send(event.getRegionInfo());
		});

		// Login
299

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

KingRainbow44's avatar
KingRainbow44 committed
308
309
310
311
			// Create response json
			if (requestData == null) {
				return;
			}
312
			Grasscutter.getLogger().info(Grasscutter.getLanguage().Client_try_login.replace("{ip}", req.ip()));
313

314
			res.send(this.getAuthHandler().handleGameLogin(req, requestData));
Melledy's avatar
Melledy committed
315
		});
316

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

KingRainbow44's avatar
KingRainbow44 committed
327
328
329
330
331
			// Create response json
			if (requestData == null) {
				return;
			}
			LoginResultJson responseData = new LoginResultJson();
332
			Grasscutter.getLogger().info(Grasscutter.getLanguage().Client_login_token.replace("{ip}", req.ip()));
KingRainbow44's avatar
KingRainbow44 committed
333
334
335

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

KingRainbow44's avatar
KingRainbow44 committed
337
338
339
			// Test
			if (account == null || !account.getSessionKey().equals(requestData.token)) {
				responseData.retcode = -111;
方块君's avatar
方块君 committed
340
				responseData.message = Grasscutter.getLanguage().Game_account_cache_error;
Jaida Wu's avatar
Jaida Wu committed
341

342
				Grasscutter.getLogger().info(Grasscutter.getLanguage().Client_token_login_failed.replace("{ip}", req.ip()));
KingRainbow44's avatar
KingRainbow44 committed
343
344
345
346
347
			} 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
348

349
				Grasscutter.getLogger().info(Grasscutter.getLanguage().Client_login_in_token.replace("{ip}", req.ip()).replace("{uid}", responseData.data.account.uid));
KingRainbow44's avatar
KingRainbow44 committed
350
			}
Jaida Wu's avatar
Jaida Wu committed
351

352
			res.send(responseData);
Melledy's avatar
Melledy committed
353
		});
354

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

KingRainbow44's avatar
KingRainbow44 committed
365
366
367
368
			// Create response json
			if (requestData == null || requestData.data == null) {
				return;
			}
369
			LoginTokenData loginData = getGsonFactory().fromJson(requestData.data, LoginTokenData.class); // Get login
370
			// data
KingRainbow44's avatar
KingRainbow44 committed
371
372
373
374
			ComboTokenResJson responseData = new ComboTokenResJson();

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

KingRainbow44's avatar
KingRainbow44 committed
376
377
378
			// Test
			if (account == null || !account.getSessionKey().equals(loginData.token)) {
				responseData.retcode = -201;
方块君's avatar
方块君 committed
379
				responseData.message = Grasscutter.getLanguage().Wrong_session_key;
Jaida Wu's avatar
Jaida Wu committed
380

381
				Grasscutter.getLogger().info(Grasscutter.getLanguage().Client_failed_exchange_combo_token.replace("{ip}", req.ip()));
KingRainbow44's avatar
KingRainbow44 committed
382
383
384
385
386
			} 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
387

388
				Grasscutter.getLogger().info(Grasscutter.getLanguage().Client_exchange_combo_token.replace("{ip}", req.ip()));
KingRainbow44's avatar
KingRainbow44 committed
389
			}
Jaida Wu's avatar
Jaida Wu committed
390

391
			res.send(responseData);
Melledy's avatar
Melledy committed
392
		});
393
394
395
396

		// 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
397
		// Agreement and Protocol
398
399
400
		// 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
401
402
		// 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\":\"\"}}}"));
403

Melledy's avatar
Melledy committed
404
		// Game data
405
406
407
408
409
		// 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
410
		httpServer.all("/common/hk4e_global/announcement/api/getAnnList", new AnnouncementHandler());
411
		// hk4e-api-os-static.hoyoverse.com
BaiSugar's avatar
BaiSugar committed
412
		httpServer.all("/common/hk4e_global/announcement/api/getAnnContent", new AnnouncementHandler());
413
414
415
		// 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
416
		// Captcha
417
418
419
		// 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}}"));

420
		// Config
421
422
423
424
425
		// 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
426
		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
427
		// Test api?
428
		// abtest-api-data-sg.hoyoverse.com
Benjamin Elsdon's avatar
Benjamin Elsdon committed
429
		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\"}}]}"));
430
431
432
433

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

Melledy's avatar
Melledy committed
438
		// Logging servers
439
		// overseauspider.yuanshen.com
440
		httpServer.all("/log", new ClientLogHandler());
441
		// log-upload-os.mihoyo.com
442
		httpServer.all("/crash/dataUpload", new ClientLogHandler());
Jaida Wu's avatar
Jaida Wu committed
443

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

447
448
449
		// 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.
450
		httpServer.get("/gacha", new GachaRecordHandler());
451
452
453
454
455
		if(!(new File(gachaMappingsPath).exists())) {
			Tools.createGachaMapping(gachaMappingsPath);
		}

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

457
458
		// 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
459

460
		httpServer.listen(Grasscutter.getConfig().getDispatchOptions().Port);
461
		Grasscutter.getLogger().info(Grasscutter.getLanguage().Dispatch_start_server_port.replace("{port}", Integer.toString(httpServer.raw().port())));
Melledy's avatar
Melledy committed
462
	}
463

Melledy's avatar
Melledy committed
464
	private Map<String, String> parseQueryString(String qs) {
Jaida Wu's avatar
Jaida Wu committed
465
		Map<String, String> result = new HashMap<>();
Jaida Wu's avatar
Jaida Wu committed
466
		if (qs == null) {
Jaida Wu's avatar
Jaida Wu committed
467
			return result;
Jaida Wu's avatar
Jaida Wu committed
468
		}
Jaida Wu's avatar
Jaida Wu committed
469
470
471
472

		int last = 0, next, l = qs.length();
		while (last < l) {
			next = qs.indexOf('&', last);
Jaida Wu's avatar
Jaida Wu committed
473
			if (next == -1) {
Jaida Wu's avatar
Jaida Wu committed
474
				next = l;
Jaida Wu's avatar
Jaida Wu committed
475
			}
Jaida Wu's avatar
Jaida Wu committed
476
477
478

			if (next > last) {
				int eqPos = qs.indexOf('=', last);
479
480
481
482
483
484
485
486
487
				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
488
489
490
491
492
				}
			}
			last = next + 1;
		}
		return result;
Melledy's avatar
Melledy committed
493
	}
494

495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
	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;
	}

516
517
518
519
520
521
522
523
	public static class RegionData {
		QueryCurrRegionHttpRsp parsedRegionQuery;
		String Base64;

		public RegionData(QueryCurrRegionHttpRsp prq, String b64) {
			this.parsedRegionQuery = prq;
			this.Base64 = b64;
		}
524
525
526
527
528
529
530
531

		public QueryCurrRegionHttpRsp getParsedRegionQuery() {
			return parsedRegionQuery;
		}

		public String getBase64() {
			return Base64;
		}
532
	}
Melledy's avatar
Melledy committed
533
}