DispatchServer.java 22.2 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
9
10
11
12
13
14
import emu.grasscutter.Grasscutter;
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;
Jaida Wu's avatar
Jaida Wu committed
15
import emu.grasscutter.server.dispatch.json.*;
Melledy's avatar
Melledy committed
16
import emu.grasscutter.server.dispatch.json.ComboTokenReqJson.LoginTokenData;
KingRainbow44's avatar
KingRainbow44 committed
17
18
import emu.grasscutter.server.event.dispatch.QueryAllRegionsEvent;
import emu.grasscutter.server.event.dispatch.QueryCurrentRegionEvent;
Melledy's avatar
Melledy committed
19
import emu.grasscutter.utils.FileUtils;
20
21
22
23
24
import express.Express;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.ssl.SslContextFactory;
Melledy's avatar
Melledy committed
25

Jaida Wu's avatar
Jaida Wu committed
26
27
import java.io.*;
import java.net.URLDecoder;
28
import java.util.*;
Melledy's avatar
Melledy committed
29

KingRainbow44's avatar
KingRainbow44 committed
30
public final class DispatchServer {
Jaida Wu's avatar
Jaida Wu committed
31
32
	public static String query_region_list = "";
	public static String query_cur_region = "";
33

Melledy's avatar
Melledy committed
34
	private final Gson gson;
35
	private final String defaultServerName = "os_usa";
36

Melledy's avatar
Melledy committed
37
	public String regionListBase64;
38
	public HashMap<String, RegionData> regions;
39
	private Express httpServer;
40

Melledy's avatar
Melledy committed
41
	public DispatchServer() {
42
		this.regions = new HashMap<String, RegionData>();
Melledy's avatar
Melledy committed
43
		this.gson = new GsonBuilder().create();
44

Melledy's avatar
Melledy committed
45
46
47
		this.loadQueries();
		this.initRegion();
	}
48

49
50
	public Express getServer() {
		return httpServer;
Melledy's avatar
Melledy committed
51
	}
52

Melledy's avatar
Melledy committed
53
54
55
56
	public Gson getGsonFactory() {
		return gson;
	}

57
58
	public QueryCurrRegionHttpRsp getCurrRegion() {
		// Needs to be fixed by having the game servers connect to the dispatch server.
59
		if (Grasscutter.getConfig().RunMode.equalsIgnoreCase("HYBRID")) {
60
			return regions.get(defaultServerName).parsedRegionQuery;
61
62
		}

63
		Grasscutter.getLogger().warn("[Dispatch] Unsupported run mode for getCurrRegion()");
64
		return null;
Melledy's avatar
Melledy committed
65
	}
66

Melledy's avatar
Melledy committed
67
68
	public void loadQueries() {
		File file;
69

Melledy's avatar
Melledy committed
70
71
72
73
		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
74
			Grasscutter.getLogger().warn("[Dispatch] query_region_list not found! Using default region list.");
Melledy's avatar
Melledy committed
75
		}
76

Melledy's avatar
Melledy committed
77
78
79
80
		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
81
			Grasscutter.getLogger().warn("[Dispatch] query_cur_region not found! Using default current region.");
Melledy's avatar
Melledy committed
82
83
84
85
86
87
88
		}
	}

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

Melledy's avatar
Melledy committed
90
91
			byte[] decoded2 = Base64.getDecoder().decode(query_cur_region);
			QueryCurrRegionHttpRsp regionQuery = QueryCurrRegionHttpRsp.parseFrom(decoded2);
92

KingRainbow44's avatar
KingRainbow44 committed
93
94
			List<RegionSimpleInfo> servers = new ArrayList<>();
			List<String> usedNames = new ArrayList<>(); // List to check for potential naming conflicts
95
96
			if (Grasscutter.getConfig().RunMode.equalsIgnoreCase("HYBRID")) { // Automatically add the game server if in
																				// hybrid mode
97
98
99
100
				RegionSimpleInfo server = RegionSimpleInfo.newBuilder()
						.setName("os_usa")
						.setTitle(Grasscutter.getConfig().getGameServerOptions().Name)
						.setType("DEV_PUBLIC")
101
102
103
104
105
106
107
108
109
						.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)
110
										+ "/query_cur_region/" + defaultServerName)
111
112
113
114
115
						.build();
				usedNames.add(defaultServerName);
				servers.add(server);

				RegionInfo serverRegion = regionQuery.getRegionInfo().toBuilder()
116
						.setGateserverIp((Grasscutter.getConfig().getGameServerOptions().PublicIp.isEmpty()
117
118
								? Grasscutter.getConfig().getGameServerOptions().Ip
								: Grasscutter.getConfig().getGameServerOptions().PublicIp))
119
						.setGateserverPort(Grasscutter.getConfig().getGameServerOptions().PublicPort != 0
120
121
122
123
								? Grasscutter.getConfig().getGameServerOptions().PublicPort
								: Grasscutter.getConfig().getGameServerOptions().Port)
						.setSecretKey(ByteString
								.copyFrom(FileUtils.read(Grasscutter.getConfig().KEY_FOLDER + "dispatchSeed.bin")))
124
125
126
						.build();

				QueryCurrRegionHttpRsp parsedRegionQuery = regionQuery.toBuilder().setRegionInfo(serverRegion).build();
127
128
				regions.put(defaultServerName, new RegionData(parsedRegionQuery,
						Base64.getEncoder().encodeToString(parsedRegionQuery.toByteString().toByteArray())));
129
130

			} else {
131
132
133
				if (Grasscutter.getConfig().getDispatchOptions().getGameServers().length == 0) {
					Grasscutter.getLogger()
							.error("[Dispatch] There are no game servers available. Exiting due to unplayable state.");
134
135
136
137
					System.exit(1);
				}
			}

138
139
140
			for (Config.DispatchServerOptions.RegionInfo regionInfo : Grasscutter.getConfig().getDispatchOptions()
					.getGameServers()) {
				if (usedNames.contains(regionInfo.Name)) {
141
142
143
144
145
146
147
					Grasscutter.getLogger().error("Region name already in use.");
					continue;
				}
				RegionSimpleInfo server = RegionSimpleInfo.newBuilder()
						.setName(regionInfo.Name)
						.setTitle(regionInfo.Title)
						.setType("DEV_PUBLIC")
148
149
150
151
152
						.setDispatchUrl(
								"http" + (Grasscutter.getConfig().getDispatchOptions().FrontHTTPS ? "s" : "") + "://"
										+ (Grasscutter.getConfig().getDispatchOptions().PublicIp.isEmpty()
												? Grasscutter.getConfig().getDispatchOptions().Ip
												: Grasscutter.getConfig().getDispatchOptions().PublicIp)
153
154
155
										+ ":" + (Grasscutter.getConfig().getDispatchOptions().PublicPort != 0
										? Grasscutter.getConfig().getDispatchOptions().PublicPort
										: Grasscutter.getConfig().getDispatchOptions().Port) + "/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
164
						.setSecretKey(ByteString
								.copyFrom(FileUtils.read(Grasscutter.getConfig().KEY_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
180

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

	public void start() throws Exception {
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
		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();
							Grasscutter.getLogger().warn("[Dispatch] Unable to load keystore. Trying default keystore password...");

							try {
								sslContextFactory.setKeyStorePath(keystoreFile.getPath());
								sslContextFactory.setKeyStorePassword("123456");
								Grasscutter.getLogger().warn("[Dispatch] The default keystore password was loaded successfully. Please consider setting the password to 123456 in config.json.");
							} catch (Exception e2) {
								Grasscutter.getLogger().warn("[Dispatch] Error while loading keystore!");
								e2.printStackTrace();
							}
						}

						serverConnector = new ServerConnector(server, sslContextFactory);
					} else {
						Grasscutter.getLogger().warn("[Dispatch] No SSL cert found! Falling back to HTTP server.");
						Grasscutter.getConfig().getDispatchOptions().UseSSL = false;

						serverConnector = new ServerConnector(server);
219
					}
220
221
				} else {
					serverConnector = new ServerConnector(server);
222
				}
223
224
225
226
227
228
229
230
231

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

			config.enforceSsl = Grasscutter.getConfig().getDispatchOptions().UseSSL;
			if(Grasscutter.getConfig().DebugMode.equalsIgnoreCase("ALL")) {
				config.enableDevLogging();
232
			}
233
		});
Jaida Wu's avatar
Jaida Wu committed
234

235
		httpServer.get("/", (req, res) -> res.send("Welcome to Grasscutter"));
Jaida Wu's avatar
Jaida Wu committed
236

237
238
		httpServer.raw().error(404, ctx -> {
			if(Grasscutter.getConfig().DebugMode.equalsIgnoreCase("MISSING")) {
Benjamin Elsdon's avatar
Benjamin Elsdon committed
239
				Grasscutter.getLogger().info(String.format("[Dispatch] Potential unhandled %s request: %s", ctx.method(), ctx.url()));
240
241
242
243
			}
			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.
		});
244

Melledy's avatar
Melledy committed
245
		// Dispatch
246
		httpServer.get("/query_region_list", (req, res) -> {
KingRainbow44's avatar
KingRainbow44 committed
247
			// Log
248
			Grasscutter.getLogger().info(String.format("[Dispatch] Client %s request: query_region_list", req.ip()));
Jaida Wu's avatar
Jaida Wu committed
249

250
251
252
			// Invoke event.
			QueryAllRegionsEvent event = new QueryAllRegionsEvent(regionListBase64); event.call();
			// Respond with event result.
253
			res.send(event.getRegionList());
Melledy's avatar
Melledy committed
254
		});
255

256
257
258
259
260
261
262
263
264
265
		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;
			}
266

267
268
269
270
271
272
273
274
			// Invoke event.
			QueryCurrentRegionEvent event = new QueryCurrentRegionEvent(response); event.call();
			// Respond with event result.
			res.send(event.getRegionInfo());
		});

		// Login
		httpServer.post("/hk4e_global/mdk/shield/api/login", (req, res) -> {
KingRainbow44's avatar
KingRainbow44 committed
275
276
277
			// Get post data
			LoginAccountRequestJson requestData = null;
			try {
278
279
				String body = req.ctx().body();
				Grasscutter.getLogger().info(body);
KingRainbow44's avatar
KingRainbow44 committed
280
				requestData = getGsonFactory().fromJson(body, LoginAccountRequestJson.class);
281
282
			} catch (Exception ignored) {
			}
283

KingRainbow44's avatar
KingRainbow44 committed
284
285
286
287
288
			// Create response json
			if (requestData == null) {
				return;
			}
			LoginResultJson responseData = new LoginResultJson();
Jaida Wu's avatar
Jaida Wu committed
289

290
			Grasscutter.getLogger()
291
					.info(String.format("[Dispatch] Client %s is trying to log in", req.ip()));
292

KingRainbow44's avatar
KingRainbow44 committed
293
294
			// Login
			Account account = DatabaseHelper.getAccountByName(requestData.account);
295

296
			// Check if account exists, else create a new one.
297
			if (account == null) {
298
299
				// Account doesnt exist, so we can either auto create it if the config value is
				// set
300
				if (Grasscutter.getConfig().getDispatchOptions().AutomaticallyCreateAccounts) {
301
302
					// This account has been created AUTOMATICALLY. There will be no permissions
					// added.
303
					account = DatabaseHelper.createAccountWithId(requestData.account, 0);
Jaida Wu's avatar
Jaida Wu committed
304

305
306
307
308
					for (String permission : Grasscutter.getConfig().getDispatchOptions().defaultPermissions) {
						account.addPermission(permission);
					}

Jaida Wu's avatar
Jaida Wu committed
309
310
311
312
313
					if (account != null) {
						responseData.message = "OK";
						responseData.data.account.uid = account.getId();
						responseData.data.account.token = account.generateSessionKey();
						responseData.data.account.email = account.getEmail();
Jaida Wu's avatar
Jaida Wu committed
314

315
316
						Grasscutter.getLogger()
								.info(String.format("[Dispatch] Client %s failed to log in: Account %s created",
317
										req.ip(), responseData.data.account.uid));
Jaida Wu's avatar
Jaida Wu committed
318
319
320
					} else {
						responseData.retcode = -201;
						responseData.message = "Username not found, create failed.";
Jaida Wu's avatar
Jaida Wu committed
321

322
						Grasscutter.getLogger().info(String.format(
323
								"[Dispatch] Client %s failed to log in: Account create failed", req.ip()));
Jaida Wu's avatar
Jaida Wu committed
324
					}
325
326
327
				} else {
					responseData.retcode = -201;
					responseData.message = "Username not found.";
Jaida Wu's avatar
Jaida Wu committed
328

329
					Grasscutter.getLogger().info(String
330
							.format("[Dispatch] Client %s failed to log in: Account no found", req.ip()));
331
				}
KingRainbow44's avatar
KingRainbow44 committed
332
			} else {
333
				// Account was found, log the player in
KingRainbow44's avatar
KingRainbow44 committed
334
335
336
337
				responseData.message = "OK";
				responseData.data.account.uid = account.getId();
				responseData.data.account.token = account.generateSessionKey();
				responseData.data.account.email = account.getEmail();
Jaida Wu's avatar
Jaida Wu committed
338

339
				Grasscutter.getLogger().info(String.format("[Dispatch] Client %s logged in as %s", req.ip(),
340
						responseData.data.account.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
		// Login via token
347
		httpServer.post("/hk4e_global/mdk/shield/api/verify", (req, res) -> {
KingRainbow44's avatar
KingRainbow44 committed
348
349
350
			// Get post data
			LoginTokenRequestJson requestData = null;
			try {
351
				String body = req.ctx().body();
KingRainbow44's avatar
KingRainbow44 committed
352
				requestData = getGsonFactory().fromJson(body, LoginTokenRequestJson.class);
353
354
			} catch (Exception ignored) {
			}
355

KingRainbow44's avatar
KingRainbow44 committed
356
357
358
359
360
			// Create response json
			if (requestData == null) {
				return;
			}
			LoginResultJson responseData = new LoginResultJson();
361
			Grasscutter.getLogger().info(String.format("[Dispatch] Client %s is trying to log in via token", req.ip()));
KingRainbow44's avatar
KingRainbow44 committed
362
363
364

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

KingRainbow44's avatar
KingRainbow44 committed
366
367
368
369
			// Test
			if (account == null || !account.getSessionKey().equals(requestData.token)) {
				responseData.retcode = -111;
				responseData.message = "Game account cache information error";
Jaida Wu's avatar
Jaida Wu committed
370

371
				Grasscutter.getLogger()
372
						.info(String.format("[Dispatch] Client %s failed to log in via token", req.ip()));
KingRainbow44's avatar
KingRainbow44 committed
373
374
375
376
377
			} 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
378

379
				Grasscutter.getLogger().info(String.format("[Dispatch] Client %s logged in via token as %s",
380
						req.ip(), responseData.data.account.uid));
KingRainbow44's avatar
KingRainbow44 committed
381
			}
Jaida Wu's avatar
Jaida Wu committed
382

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

Melledy's avatar
Melledy committed
386
		// Exchange for combo token
387
		httpServer.post("/hk4e_global/combo/granter/login/v2/login", (req, res) -> {
KingRainbow44's avatar
KingRainbow44 committed
388
389
390
			// Get post data
			ComboTokenReqJson requestData = null;
			try {
391
				String body = req.ctx().body();
KingRainbow44's avatar
KingRainbow44 committed
392
				requestData = getGsonFactory().fromJson(body, ComboTokenReqJson.class);
393
394
			} catch (Exception ignored) {
			}
395

KingRainbow44's avatar
KingRainbow44 committed
396
397
398
399
			// Create response json
			if (requestData == null || requestData.data == null) {
				return;
			}
400
			LoginTokenData loginData = getGsonFactory().fromJson(requestData.data, LoginTokenData.class); // Get login
401
			// data
KingRainbow44's avatar
KingRainbow44 committed
402
403
404
405
			ComboTokenResJson responseData = new ComboTokenResJson();

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

KingRainbow44's avatar
KingRainbow44 committed
407
408
409
410
			// Test
			if (account == null || !account.getSessionKey().equals(loginData.token)) {
				responseData.retcode = -201;
				responseData.message = "Wrong session key.";
Jaida Wu's avatar
Jaida Wu committed
411

412
				Grasscutter.getLogger().info(
413
						String.format("[Dispatch] Client %s failed to exchange combo token", req.ip()));
KingRainbow44's avatar
KingRainbow44 committed
414
415
416
417
418
			} 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
419

420
				Grasscutter.getLogger().info(
421
						String.format("[Dispatch] Client %s succeed to exchange combo token", req.ip()));
KingRainbow44's avatar
KingRainbow44 committed
422
			}
Jaida Wu's avatar
Jaida Wu committed
423

424
			res.send(responseData);
Melledy's avatar
Melledy committed
425
		});
426
427
428
429

		// 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
430
		// Agreement and Protocol
431
432
433
434
435
		// 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
		httpServer.post("/hk4e_global/combo/granter/api/compareProtocolVersion", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"modified\":true,\"protocol\":{\"id\":0,\"app_id\":4,\"language\":\"en\",\"user_proto\":\"\",\"priv_proto\":\"\",\"major\":7,\"minimum\":0,\"create_time\":\"0\",\"teenager_proto\":\"\",\"third_proto\":\"\"}}}"));

Melledy's avatar
Melledy committed
436
		// Game data
437
438
439
440
441
442
443
444
445
446
447
		// 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
		httpServer.all("/common/hk4e_global/announcement/api/getAnnList", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"list\":[],\"total\":0,\"type_list\":[],\"alert\":false,\"alert_id\":0,\"timezone\":0,\"t\":\"" + System.currentTimeMillis() + "\"}}"));
		// hk4e-api-os-static.hoyoverse.com
		httpServer.all("/common/hk4e_global/announcement/api/getAnnContent", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"list\":[],\"total\":0}}"));
		// 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
448
		// Captcha
449
450
451
		// 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}}"));

452
		// Config
453
454
455
456
457
		// 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
458
		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
459
		// Test api?
460
		// abtest-api-data-sg.hoyoverse.com
Benjamin Elsdon's avatar
Benjamin Elsdon committed
461
		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\"}}]}"));
462
463
464
465
466
467
468

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

Melledy's avatar
Melledy committed
470
		// Logging servers
471
472
473
474
		// overseauspider.yuanshen.com
		httpServer.all("/log", new DispatchHttpJsonHandler("{\"code\":0}"));
		// log-upload-os.mihoyo.com
		httpServer.all("/crash/dataUpload", new DispatchHttpJsonHandler("{\"code\":0}"));
Jaida Wu's avatar
Jaida Wu committed
475

476
		httpServer.get("/gacha", (req, res) -> res.send("<!doctype html><html lang=\"en\"><head><title>Gacha</title></head><body></body></html>"));
Jaida Wu's avatar
Jaida Wu committed
477

478
479
		httpServer.listen(Grasscutter.getConfig().getDispatchOptions().Port);
		Grasscutter.getLogger().info("[Dispatch] Dispatch server started on port " + httpServer.raw().port());
Melledy's avatar
Melledy committed
480
	}
481

Melledy's avatar
Melledy committed
482
	private Map<String, String> parseQueryString(String qs) {
Jaida Wu's avatar
Jaida Wu committed
483
		Map<String, String> result = new HashMap<>();
Jaida Wu's avatar
Jaida Wu committed
484
		if (qs == null) {
Jaida Wu's avatar
Jaida Wu committed
485
			return result;
Jaida Wu's avatar
Jaida Wu committed
486
		}
Jaida Wu's avatar
Jaida Wu committed
487
488
489
490

		int last = 0, next, l = qs.length();
		while (last < l) {
			next = qs.indexOf('&', last);
Jaida Wu's avatar
Jaida Wu committed
491
			if (next == -1) {
Jaida Wu's avatar
Jaida Wu committed
492
				next = l;
Jaida Wu's avatar
Jaida Wu committed
493
			}
Jaida Wu's avatar
Jaida Wu committed
494
495
496

			if (next > last) {
				int eqPos = qs.indexOf('=', last);
497
498
499
500
501
502
503
504
505
				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
506
507
508
509
510
				}
			}
			last = next + 1;
		}
		return result;
Melledy's avatar
Melledy committed
511
	}
512
513
514
515
516
517
518
519
520
521

	public static class RegionData {
		QueryCurrRegionHttpRsp parsedRegionQuery;
		String Base64;

		public RegionData(QueryCurrRegionHttpRsp prq, String b64) {
			this.parsedRegionQuery = prq;
			this.Base64 = b64;
		}
	}
Melledy's avatar
Melledy committed
522
}