DispatchServer.java 23.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;
import com.sun.net.httpserver.HttpExchange;
Jaida Wu's avatar
Jaida Wu committed
7
import com.sun.net.httpserver.HttpServer;
Melledy's avatar
Melledy committed
8
9
10
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsServer;

11
import emu.grasscutter.Config;
Melledy's avatar
Melledy committed
12
13
14
15
16
17
18
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
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;
Melledy's avatar
Melledy committed
23
24
25
import emu.grasscutter.utils.FileUtils;
import emu.grasscutter.utils.Utils;

Jaida Wu's avatar
Jaida Wu committed
26
27
28
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.*;
29
import java.net.BindException;
Jaida Wu's avatar
Jaida Wu committed
30
31
32
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLDecoder;
KingRainbow44's avatar
KingRainbow44 committed
33
import java.nio.charset.StandardCharsets;
Jaida Wu's avatar
Jaida Wu committed
34
import java.security.KeyStore;
35
import java.util.*;
Melledy's avatar
Melledy committed
36

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

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

Melledy's avatar
Melledy committed
45
	public String regionListBase64;
46
	public HashMap<String, RegionData> regions;
47
	private HttpServer server;
48

Melledy's avatar
Melledy committed
49
	public DispatchServer() {
50
		this.regions = new HashMap<String, RegionData>();
51
52
		this.address = new InetSocketAddress(Grasscutter.getConfig().getDispatchOptions().Ip,
				Grasscutter.getConfig().getDispatchOptions().Port);
Melledy's avatar
Melledy committed
53
		this.gson = new GsonBuilder().create();
54

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

59
	@Deprecated
60
61
62
	public HttpServer getServer() {
		return server;
	}
63
64
65
66
	
	public HttpServer getHttpServer() {
		return server;
	}
67

Melledy's avatar
Melledy committed
68
69
70
	public InetSocketAddress getAddress() {
		return address;
	}
71

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

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

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

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

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

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

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

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

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

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

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

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

157
158
159
			for (Config.DispatchServerOptions.RegionInfo regionInfo : Grasscutter.getConfig().getDispatchOptions()
					.getGameServers()) {
				if (usedNames.contains(regionInfo.Name)) {
160
161
162
163
164
165
166
					Grasscutter.getLogger().error("Region name already in use.");
					continue;
				}
				RegionSimpleInfo server = RegionSimpleInfo.newBuilder()
						.setName(regionInfo.Name)
						.setTitle(regionInfo.Title)
						.setType("DEV_PUBLIC")
167
168
169
170
171
172
						.setDispatchUrl(
								"http" + (Grasscutter.getConfig().getDispatchOptions().FrontHTTPS ? "s" : "") + "://"
										+ (Grasscutter.getConfig().getDispatchOptions().PublicIp.isEmpty()
												? Grasscutter.getConfig().getDispatchOptions().Ip
												: Grasscutter.getConfig().getDispatchOptions().PublicIp)
										+ ":" + getAddress().getPort() + "/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
203
204
205
206
207
208
	private HttpServer safelyCreateServer(InetSocketAddress address) {
		try {
			return HttpServer.create(address, 0);
		} catch (BindException ignored) {
			Grasscutter.getLogger().error("Unable to bind to port: " + getAddress().getPort() + " (HTTP)");
		} catch (Exception exception) {
			Grasscutter.getLogger().error("Unable to start HTTP server.", exception);
209
210
		}
		return null;
211
	}
212
	
KingRainbow44's avatar
KingRainbow44 committed
213
	private KeyManagerFactory createKeyManagerFactory(File keystore, String password) {
214
215
216
217
218
219
220
221
222
223
		char[] pass = password.toCharArray();
		KeyManagerFactory kmf = null;
		
		try (FileInputStream fis = new FileInputStream(keystore)) {
			
			KeyStore ks = KeyStore.getInstance("PKCS12");
			ks.load(fis, pass);
			
			kmf = KeyManagerFactory.getInstance("SunX509");
			kmf.init(ks, pass);
KingRainbow44's avatar
KingRainbow44 committed
224
225
		} catch (Exception exception) {
			Grasscutter.getLogger().error("Unable to load keystore.", exception);
226
227
228
229
		}
		
		return kmf;
	}
Melledy's avatar
Melledy committed
230
231

	public void start() throws Exception {
232
		if (Grasscutter.getConfig().getDispatchOptions().UseSSL) {
233
			// Keystore
234
			SSLContext sslContext = SSLContext.getInstance("TLS");
235
236
237
238
			KeyManagerFactory kmf = null;
			File keystoreFile = new File(Grasscutter.getConfig().getDispatchOptions().KeystorePath);
			
			if (keystoreFile.exists()) {
239
				try {
240
241
242
243
					kmf = createKeyManagerFactory(keystoreFile, Grasscutter.getConfig().getDispatchOptions().KeystorePassword);
				} catch (Exception e) {
					Grasscutter.getLogger().warn("[Dispatch] Unable to load keystore. Trying default keystore password...");
					
244
					try {
245
						kmf = createKeyManagerFactory(keystoreFile, "123456");
246
						Grasscutter.getLogger().warn(
KingRainbow44's avatar
KingRainbow44 committed
247
							"[Dispatch] The default keystore password was loaded successfully. Please consider setting the password to '123456' in config.json.");
248
					} catch (Exception e2) {
KingRainbow44's avatar
KingRainbow44 committed
249
						Grasscutter.getLogger().warn("[Dispatch] Error while loading keystore!", e2);
250
					}
251
				}
252
253
254
			}
			
			if (kmf == null) {
Jaida Wu's avatar
Jaida Wu committed
255
				Grasscutter.getLogger().warn("[Dispatch] No SSL cert found! Falling back to HTTP server.");
256
				Grasscutter.getConfig().getDispatchOptions().UseSSL = false;
257
				server = this.safelyCreateServer(this.getAddress());
258
			}
259
			
KingRainbow44's avatar
KingRainbow44 committed
260
			HttpsServer httpsServer;
261
262
263
264
265
266
267
268
269
			
			try {
				httpsServer = HttpsServer.create(getAddress(), 0);
				sslContext.init(kmf.getKeyManagers(), null, null);
				httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));
				server = httpsServer;
			} catch (BindException e) {
				Grasscutter.getLogger().error("Unable to bind to port: " + getAddress().getPort() + " (HTTPS)");
			}
270
		} else {
271
			server = this.safelyCreateServer(this.getAddress());
Melledy's avatar
Melledy committed
272
		}
Jaida Wu's avatar
Jaida Wu committed
273

274
		if (server == null)
275
			throw new NullPointerException("An HTTP server was not created.");
Jaida Wu's avatar
Jaida Wu committed
276

Jaida Wu's avatar
Jaida Wu committed
277
		server.createContext("/", t -> responseHTML(t, "Hello"));
278

Melledy's avatar
Melledy committed
279
		// Dispatch
KingRainbow44's avatar
KingRainbow44 committed
280
281
		server.createContext("/query_region_list", t -> {
			// Log
282
283
			Grasscutter.getLogger()
					.info(String.format("[Dispatch] Client %s request: query_region_list", t.getRemoteAddress()));
Jaida Wu's avatar
Jaida Wu committed
284

285
286
287
288
			// Invoke event.
			QueryAllRegionsEvent event = new QueryAllRegionsEvent(regionListBase64); event.call();
			// Respond with event result.
			responseHTML(t, event.getRegionList());
Melledy's avatar
Melledy committed
289
		});
290
291
292
293
294

		for (String regionName : regions.keySet()) {
			server.createContext("/query_cur_region_" + regionName, t -> {
				String regionCurrentBase64 = regions.get(regionName).Base64;
				// Log
295
296
				Grasscutter.getLogger().info(
						String.format("Client %s request: query_cur_region_%s", t.getRemoteAddress(), regionName));
297
298
299
300
301
302
				// Create a response form the request query parameters
				URI uri = t.getRequestURI();
				String response = "CAESGE5vdCBGb3VuZCB2ZXJzaW9uIGNvbmZpZw==";
				if (uri.getQuery() != null && uri.getQuery().length() > 0) {
					response = regionCurrentBase64;
				}
KingRainbow44's avatar
KingRainbow44 committed
303
304
305
306
307
				
				// Invoke event.
				QueryCurrentRegionEvent event = new QueryCurrentRegionEvent(response); event.call();
				// Respond with event result.
				responseHTML(t, event.getRegionInfo());
308
309
310
			});
		}

Melledy's avatar
Melledy committed
311
		// Login via account
KingRainbow44's avatar
KingRainbow44 committed
312
313
314
315
316
317
		server.createContext("/hk4e_global/mdk/shield/api/login", t -> {
			// Get post data
			LoginAccountRequestJson requestData = null;
			try {
				String body = Utils.toString(t.getRequestBody());
				requestData = getGsonFactory().fromJson(body, LoginAccountRequestJson.class);
318
319
			} catch (Exception ignored) {
			}
320

KingRainbow44's avatar
KingRainbow44 committed
321
322
323
324
325
			// Create response json
			if (requestData == null) {
				return;
			}
			LoginResultJson responseData = new LoginResultJson();
Jaida Wu's avatar
Jaida Wu committed
326

327
328
329
			Grasscutter.getLogger()
					.info(String.format("[Dispatch] Client %s is trying to log in", t.getRemoteAddress()));

KingRainbow44's avatar
KingRainbow44 committed
330
331
			// Login
			Account account = DatabaseHelper.getAccountByName(requestData.account);
332

333
			// Check if account exists, else create a new one.
334
			if (account == null) {
335
336
				// Account doesnt exist, so we can either auto create it if the config value is
				// set
337
				if (Grasscutter.getConfig().getDispatchOptions().AutomaticallyCreateAccounts) {
338
339
					// This account has been created AUTOMATICALLY. There will be no permissions
					// added.
340
					account = DatabaseHelper.createAccountWithId(requestData.account, 0);
Jaida Wu's avatar
Jaida Wu committed
341
342
343
344
345
346

					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
347

348
349
350
						Grasscutter.getLogger()
								.info(String.format("[Dispatch] Client %s failed to log in: Account %s created",
										t.getRemoteAddress(), responseData.data.account.uid));
KingRainbow44's avatar
KingRainbow44 committed
351
352
353
						for (String permission : Grasscutter.getConfig().getDispatchOptions().defaultPermissions) {
							account.addPermission(permission);
						}
Jaida Wu's avatar
Jaida Wu committed
354
355
356
					} else {
						responseData.retcode = -201;
						responseData.message = "Username not found, create failed.";
Jaida Wu's avatar
Jaida Wu committed
357

358
359
						Grasscutter.getLogger().info(String.format(
								"[Dispatch] Client %s failed to log in: Account create failed", t.getRemoteAddress()));
Jaida Wu's avatar
Jaida Wu committed
360
					}
361
362
363
				} else {
					responseData.retcode = -201;
					responseData.message = "Username not found.";
Jaida Wu's avatar
Jaida Wu committed
364

365
366
367
					Grasscutter.getLogger().info(String
							.format("[Dispatch] Client %s failed to log in: Account no found", t.getRemoteAddress()));
				}
KingRainbow44's avatar
KingRainbow44 committed
368
			} else {
369
				// Account was found, log the player in
KingRainbow44's avatar
KingRainbow44 committed
370
371
372
373
				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
374

375
376
				Grasscutter.getLogger().info(String.format("[Dispatch] Client %s logged in as %s", t.getRemoteAddress(),
						responseData.data.account.uid));
KingRainbow44's avatar
KingRainbow44 committed
377
			}
Jaida Wu's avatar
Jaida Wu committed
378

Jaida Wu's avatar
Jaida Wu committed
379
			responseJSON(t, responseData);
Melledy's avatar
Melledy committed
380
381
		});
		// Login via token
KingRainbow44's avatar
KingRainbow44 committed
382
383
384
385
386
387
		server.createContext("/hk4e_global/mdk/shield/api/verify", t -> {
			// Get post data
			LoginTokenRequestJson requestData = null;
			try {
				String body = Utils.toString(t.getRequestBody());
				requestData = getGsonFactory().fromJson(body, LoginTokenRequestJson.class);
388
389
			} catch (Exception ignored) {
			}
390

KingRainbow44's avatar
KingRainbow44 committed
391
392
393
394
395
			// Create response json
			if (requestData == null) {
				return;
			}
			LoginResultJson responseData = new LoginResultJson();
396
397
			Grasscutter.getLogger()
					.info(String.format("[Dispatch] Client %s is trying to log in via token", t.getRemoteAddress()));
KingRainbow44's avatar
KingRainbow44 committed
398
399
400

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

KingRainbow44's avatar
KingRainbow44 committed
402
403
404
405
			// 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
406

407
408
				Grasscutter.getLogger()
						.info(String.format("[Dispatch] Client %s failed to log in via token", t.getRemoteAddress()));
KingRainbow44's avatar
KingRainbow44 committed
409
410
411
412
413
			} 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
414

415
416
				Grasscutter.getLogger().info(String.format("[Dispatch] Client %s logged in via token as %s",
						t.getRemoteAddress(), responseData.data.account.uid));
KingRainbow44's avatar
KingRainbow44 committed
417
			}
Jaida Wu's avatar
Jaida Wu committed
418

Jaida Wu's avatar
Jaida Wu committed
419
			responseJSON(t, responseData);
Melledy's avatar
Melledy committed
420
421
		});
		// Exchange for combo token
KingRainbow44's avatar
KingRainbow44 committed
422
423
424
425
426
427
		server.createContext("/hk4e_global/combo/granter/login/v2/login", t -> {
			// Get post data
			ComboTokenReqJson requestData = null;
			try {
				String body = Utils.toString(t.getRequestBody());
				requestData = getGsonFactory().fromJson(body, ComboTokenReqJson.class);
428
429
			} catch (Exception ignored) {
			}
430

KingRainbow44's avatar
KingRainbow44 committed
431
432
433
434
			// Create response json
			if (requestData == null || requestData.data == null) {
				return;
			}
435
436
			LoginTokenData loginData = getGsonFactory().fromJson(requestData.data, LoginTokenData.class); // Get login
																											// data
KingRainbow44's avatar
KingRainbow44 committed
437
438
439
440
			ComboTokenResJson responseData = new ComboTokenResJson();

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

KingRainbow44's avatar
KingRainbow44 committed
442
443
444
445
			// Test
			if (account == null || !account.getSessionKey().equals(loginData.token)) {
				responseData.retcode = -201;
				responseData.message = "Wrong session key.";
Jaida Wu's avatar
Jaida Wu committed
446

447
448
				Grasscutter.getLogger().info(
						String.format("[Dispatch] Client %s failed to exchange combo token", t.getRemoteAddress()));
KingRainbow44's avatar
KingRainbow44 committed
449
450
451
452
453
			} 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
454

455
456
				Grasscutter.getLogger().info(
						String.format("[Dispatch] Client %s succeed to exchange combo token", t.getRemoteAddress()));
KingRainbow44's avatar
KingRainbow44 committed
457
			}
Jaida Wu's avatar
Jaida Wu committed
458

Jaida Wu's avatar
Jaida Wu committed
459
			responseJSON(t, responseData);
Melledy's avatar
Melledy committed
460
461
462
		});
		// Agreement and Protocol
		server.createContext( // hk4e-sdk-os.hoyoverse.com
463
464
465
				"/hk4e_global/mdk/agreement/api/getAgreementInfos",
				new DispatchHttpJsonHandler(
						"{\"retcode\":0,\"message\":\"OK\",\"data\":{\"marketing_agreements\":[]}}"));
Melledy's avatar
Melledy committed
466
		server.createContext( // hk4e-sdk-os.hoyoverse.com
467
468
469
				"/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
470
471
		// Game data
		server.createContext( // hk4e-api-os.hoyoverse.com
472
473
				"/common/hk4e_global/announcement/api/getAlertPic",
				new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"total\":0,\"list\":[]}}"));
Melledy's avatar
Melledy committed
474
475
		server.createContext( // hk4e-api-os.hoyoverse.com
				"/common/hk4e_global/announcement/api/getAlertAnn",
476
477
				new DispatchHttpJsonHandler(
						"{\"retcode\":0,\"message\":\"OK\",\"data\":{\"alert\":false,\"alert_id\":0,\"remind\":true}}"));
Melledy's avatar
Melledy committed
478
		server.createContext( // hk4e-api-os.hoyoverse.com
479
480
481
482
				"/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() + "\"}}"));
Melledy's avatar
Melledy committed
483
		server.createContext( // hk4e-api-os-static.hoyoverse.com
484
485
				"/common/hk4e_global/announcement/api/getAnnContent",
				new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"list\":[],\"total\":0}}"));
Melledy's avatar
Melledy committed
486
		server.createContext( // hk4e-sdk-os.hoyoverse.com
487
488
489
				"/hk4e_global/mdk/shopwindow/shopwindow/listPriceTier",
				new DispatchHttpJsonHandler(
						"{\"retcode\":0,\"message\":\"OK\",\"data\":{\"suggest_currency\":\"USD\",\"tiers\":[]}}"));
Melledy's avatar
Melledy committed
490
491
		// Captcha
		server.createContext( // api-account-os.hoyoverse.com
492
493
494
495
				"/account/risky/api/check",
				new DispatchHttpJsonHandler(
						"{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":\"c8820f246a5241ab9973f71df3ddd791\",\"action\":\"\",\"geetest\":{\"challenge\":\"\",\"gt\":\"\",\"new_captcha\":0,\"success\":1}}}"));
		// Config
Melledy's avatar
Melledy committed
496
		server.createContext( // sdk-os-static.hoyoverse.com
497
498
499
				"/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\"}}}"));
Melledy's avatar
Melledy committed
500
		server.createContext( // hk4e-sdk-os-static.hoyoverse.com
501
502
503
				"/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}}"));
Melledy's avatar
Melledy committed
504
		server.createContext( // hk4e-sdk-os-static.hoyoverse.com
505
506
507
				"/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
508
509
		// Test api?
		server.createContext( // abtest-api-data-sg.hoyoverse.com
510
511
512
513
				"/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\"}}]}"));
		// Log Server
Melledy's avatar
Melledy committed
514
		server.createContext( // log-upload-os.mihoyo.com
515
516
				"/log/sdk/upload",
				new DispatchHttpJsonHandler("{\"code\":0}"));
Melledy's avatar
Melledy committed
517
		server.createContext( // log-upload-os.mihoyo.com
518
519
				"/sdk/upload",
				new DispatchHttpJsonHandler("{\"code\":0}"));
OtakuNekoP's avatar
OtakuNekoP committed
520
		server.createContext( // /perf/config/verify?device_id=xxx&platform=x&name=xxx
521
522
523
				"/perf/config/verify",
				new DispatchHttpJsonHandler("{\"code\":0}"));

Melledy's avatar
Melledy committed
524
		// Logging servers
Jaida Wu's avatar
Jaida Wu committed
525
		server.createContext( // overseauspider.yuanshen.com
Jaida Wu's avatar
Jaida Wu committed
526
				"/log",
527
				new DispatchHttpJsonHandler("{\"code\":0}"));
Jaida Wu's avatar
Jaida Wu committed
528

Jaida Wu's avatar
Jaida Wu committed
529
		server.createContext( // log-upload-os.mihoyo.com
Jaida Wu's avatar
Jaida Wu committed
530
				"/crash/dataUpload",
531
532
533
				new DispatchHttpJsonHandler("{\"code\":0}"));
		server.createContext("/gacha", t -> responseHTML(t,
				"<!doctype html><html lang=\"en\"><head><title>Gacha</title></head><body></body></html>"));
534

Jaida Wu's avatar
Jaida Wu committed
535
536
		// Start server
		server.start();
Jaida Wu's avatar
Jaida Wu committed
537
		Grasscutter.getLogger().info("[Dispatch] Dispatch server started on port " + getAddress().getPort());
Melledy's avatar
Melledy committed
538
	}
Jaida Wu's avatar
Jaida Wu committed
539

Jaida Wu's avatar
Jaida Wu committed
540
	private void responseJSON(HttpExchange t, Object data) throws IOException {
Jaida Wu's avatar
Jaida Wu committed
541
542
543
544
545
546
547
548
549
550
551
		// Create a response
		String response = getGsonFactory().toJson(data);
		// Set the response header status and length
		t.getResponseHeaders().put("Content-Type", Collections.singletonList("application/json"));
		t.sendResponseHeaders(200, response.getBytes().length);
		// Write the response string
		OutputStream os = t.getResponseBody();
		os.write(response.getBytes());
		os.close();
	}

Jaida Wu's avatar
Jaida Wu committed
552
553
554
555
	private void responseHTML(HttpExchange t, String response) throws IOException {
		// Set the response header status and length
		t.getResponseHeaders().put("Content-Type", Collections.singletonList("text/html; charset=UTF-8"));
		t.sendResponseHeaders(200, response.getBytes().length);
556
		// Write the response string
Jaida Wu's avatar
Jaida Wu committed
557
558
559
		OutputStream os = t.getResponseBody();
		os.write(response.getBytes());
		os.close();
Melledy's avatar
Melledy committed
560
	}
561

Melledy's avatar
Melledy committed
562
	private Map<String, String> parseQueryString(String qs) {
Jaida Wu's avatar
Jaida Wu committed
563
		Map<String, String> result = new HashMap<>();
Jaida Wu's avatar
Jaida Wu committed
564
		if (qs == null) {
Jaida Wu's avatar
Jaida Wu committed
565
			return result;
Jaida Wu's avatar
Jaida Wu committed
566
		}
Jaida Wu's avatar
Jaida Wu committed
567
568
569
570

		int last = 0, next, l = qs.length();
		while (last < l) {
			next = qs.indexOf('&', last);
Jaida Wu's avatar
Jaida Wu committed
571
			if (next == -1) {
Jaida Wu's avatar
Jaida Wu committed
572
				next = l;
Jaida Wu's avatar
Jaida Wu committed
573
			}
Jaida Wu's avatar
Jaida Wu committed
574
575
576

			if (next > last) {
				int eqPos = qs.indexOf('=', last);
KingRainbow44's avatar
KingRainbow44 committed
577
578
579
580
581
				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
582
583
584
585
586
				}
			}
			last = next + 1;
		}
		return result;
Melledy's avatar
Melledy committed
587
	}
588
589
590
591
592
593
594
595
596
597
598

	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
599
}