DispatchServer.java 23.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;
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
33
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLDecoder;
import java.security.KeyStore;
34
import java.util.*;
Melledy's avatar
Melledy committed
35

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

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

Melledy's avatar
Melledy committed
44
	public String regionListBase64;
45
46
	public HashMap<String, RegionData> regions;

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

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

Melledy's avatar
Melledy committed
57
58
59
	public InetSocketAddress getAddress() {
		return address;
	}
60

Melledy's avatar
Melledy committed
61
62
63
64
	public Gson getGsonFactory() {
		return gson;
	}

65
66
	public QueryCurrRegionHttpRsp getCurrRegion() {
		// Needs to be fixed by having the game servers connect to the dispatch server.
67
		if (Grasscutter.getConfig().RunMode.equalsIgnoreCase("HYBRID")) {
68
			return regions.get(defaultServerName).parsedRegionQuery;
69
70
		}

71
		Grasscutter.getLogger().warn("[Dispatch] Unsupported run mode for getCurrRegion()");
72
		return null;
Melledy's avatar
Melledy committed
73
	}
74

Melledy's avatar
Melledy committed
75
76
	public void loadQueries() {
		File file;
77

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

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

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

Melledy's avatar
Melledy committed
98
99
			byte[] decoded2 = Base64.getDecoder().decode(query_cur_region);
			QueryCurrRegionHttpRsp regionQuery = QueryCurrRegionHttpRsp.parseFrom(decoded2);
100

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

				RegionInfo serverRegion = regionQuery.getRegionInfo().toBuilder()
124
125
126
127
128
129
130
131
						.setIp((Grasscutter.getConfig().getGameServerOptions().PublicIp.isEmpty()
								? Grasscutter.getConfig().getGameServerOptions().Ip
								: Grasscutter.getConfig().getGameServerOptions().PublicIp))
						.setPort(Grasscutter.getConfig().getGameServerOptions().PublicPort != 0
								? Grasscutter.getConfig().getGameServerOptions().PublicPort
								: Grasscutter.getConfig().getGameServerOptions().Port)
						.setSecretKey(ByteString
								.copyFrom(FileUtils.read(Grasscutter.getConfig().KEY_FOLDER + "dispatchSeed.bin")))
132
133
134
						.build();

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

			} else {
139
140
141
				if (Grasscutter.getConfig().getDispatchOptions().getGameServers().length == 0) {
					Grasscutter.getLogger()
							.error("[Dispatch] There are no game servers available. Exiting due to unplayable state.");
142
143
144
145
					System.exit(1);
				}
			}

146
147
148
			for (Config.DispatchServerOptions.RegionInfo regionInfo : Grasscutter.getConfig().getDispatchOptions()
					.getGameServers()) {
				if (usedNames.contains(regionInfo.Name)) {
149
150
151
152
153
154
155
					Grasscutter.getLogger().error("Region name already in use.");
					continue;
				}
				RegionSimpleInfo server = RegionSimpleInfo.newBuilder()
						.setName(regionInfo.Name)
						.setTitle(regionInfo.Title)
						.setType("DEV_PUBLIC")
156
157
158
159
160
161
						.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)
162
163
164
165
166
167
168
						.build();
				usedNames.add(regionInfo.Name);
				servers.add(server);

				RegionInfo serverRegion = regionQuery.getRegionInfo().toBuilder()
						.setIp(regionInfo.Ip)
						.setPort(regionInfo.Port)
169
170
						.setSecretKey(ByteString
								.copyFrom(FileUtils.read(Grasscutter.getConfig().KEY_FOLDER + "dispatchSeed.bin")))
171
172
173
						.build();

				QueryCurrRegionHttpRsp parsedRegionQuery = regionQuery.toBuilder().setRegionInfo(serverRegion).build();
174
175
				regions.put(regionInfo.Name, new RegionData(parsedRegionQuery,
						Base64.getEncoder().encodeToString(parsedRegionQuery.toByteString().toByteArray())));
176
177
			}

Melledy's avatar
Melledy committed
178
			QueryRegionListHttpRsp regionList = QueryRegionListHttpRsp.newBuilder()
179
180
181
182
183
					.addAllServers(servers)
					.setClientSecretKey(rl.getClientSecretKey())
					.setClientCustomConfigEncrypted(rl.getClientCustomConfigEncrypted())
					.setEnableLoginPc(true)
					.build();
Melledy's avatar
Melledy committed
184
185
186

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

191
192
193
194
195
196
197
	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);
198
199
		}
		return null;
200
	}
Melledy's avatar
Melledy committed
201
202

	public void start() throws Exception {
203
		HttpServer server;
204
		if (Grasscutter.getConfig().getDispatchOptions().UseSSL) {
205
			HttpsServer httpsServer = HttpsServer.create(getAddress(), 0);
206
			SSLContext sslContext = SSLContext.getInstance("TLS");
207
208
			try (FileInputStream fis = new FileInputStream(Grasscutter.getConfig().getDispatchOptions().KeystorePath)) {
				char[] keystorePassword = Grasscutter.getConfig().getDispatchOptions().KeystorePassword.toCharArray();
209
				KeyManagerFactory _kmf;
210
211
212
213
				try {
					KeyStore ks = KeyStore.getInstance("PKCS12");
					ks.load(fis, keystorePassword);
					KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
214
					_kmf = kmf;
215
					kmf.init(ks, keystorePassword);
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
				} catch (Exception originalEx) {
					try {
						// try to initialize kmf with the default password
						char[] defaultPassword = "123456".toCharArray();

						Grasscutter.getLogger()
								.warn("[Dispatch] Unable to load keystore. Trying default keystore password...");
						KeyStore ks = KeyStore.getInstance("PKCS12");
						ks.load(fis, defaultPassword);
						KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
						kmf.init(ks, defaultPassword);
						_kmf = kmf;

						Grasscutter.getLogger().warn(
								"[Dispatch] The default keystore password was loaded successfully. Please consider setting the password in config.json.");
					} catch (Exception ignored) {
						Grasscutter.getLogger().warn("[Dispatch] Error while loading keystore!");

						// don't care about the exception for the "123456" default password attempt
						originalEx.printStackTrace();
						throw originalEx;
					}
238
				}
239

240
				sslContext.init(_kmf.getKeyManagers(), null, null);
241

242
243
				httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));
				server = httpsServer;
244
245
246
			} catch (BindException ignored) {
				Grasscutter.getLogger().error("Unable to bind to port: " + getAddress().getPort() + " (HTTPS)");
				server = this.safelyCreateServer(this.getAddress());
247
			} catch (Exception e) {
Jaida Wu's avatar
Jaida Wu committed
248
				Grasscutter.getLogger().warn("[Dispatch] No SSL cert found! Falling back to HTTP server.");
249
				Grasscutter.getConfig().getDispatchOptions().UseSSL = false;
250
				server = this.safelyCreateServer(this.getAddress());
251
252
			}
		} else {
253
			server = this.safelyCreateServer(this.getAddress());
Melledy's avatar
Melledy committed
254
		}
Jaida Wu's avatar
Jaida Wu committed
255

256
		if (server == null)
257
			throw new NullPointerException("An HTTP server was not created.");
Jaida Wu's avatar
Jaida Wu committed
258

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

Melledy's avatar
Melledy committed
261
		// Dispatch
KingRainbow44's avatar
KingRainbow44 committed
262
263
		server.createContext("/query_region_list", t -> {
			// Log
264
265
			Grasscutter.getLogger()
					.info(String.format("[Dispatch] Client %s request: query_region_list", t.getRemoteAddress()));
Jaida Wu's avatar
Jaida Wu committed
266
267

			responseHTML(t, regionListBase64);
Melledy's avatar
Melledy committed
268
		});
269
270
271
272
273

		for (String regionName : regions.keySet()) {
			server.createContext("/query_cur_region_" + regionName, t -> {
				String regionCurrentBase64 = regions.get(regionName).Base64;
				// Log
274
275
				Grasscutter.getLogger().info(
						String.format("Client %s request: query_cur_region_%s", t.getRemoteAddress(), regionName));
276
277
278
279
280
281
				// 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
282
283
284
285
286
				
				// Invoke event.
				QueryCurrentRegionEvent event = new QueryCurrentRegionEvent(response); event.call();
				// Respond with event result.
				responseHTML(t, event.getRegionInfo());
287
288
289
			});
		}

Melledy's avatar
Melledy committed
290
		// Login via account
KingRainbow44's avatar
KingRainbow44 committed
291
292
293
294
295
296
		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);
297
298
			} catch (Exception ignored) {
			}
299

KingRainbow44's avatar
KingRainbow44 committed
300
301
302
303
304
			// Create response json
			if (requestData == null) {
				return;
			}
			LoginResultJson responseData = new LoginResultJson();
Jaida Wu's avatar
Jaida Wu committed
305

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

KingRainbow44's avatar
KingRainbow44 committed
309
310
			// Login
			Account account = DatabaseHelper.getAccountByName(requestData.account);
311

312
			// Check if account exists, else create a new one.
313
			if (account == null) {
314
315
				// Account doesnt exist, so we can either auto create it if the config value is
				// set
316
				if (Grasscutter.getConfig().getDispatchOptions().AutomaticallyCreateAccounts) {
317
318
					// This account has been created AUTOMATICALLY. There will be no permissions
					// added.
319
					account = DatabaseHelper.createAccountWithId(requestData.account, 0);
Jaida Wu's avatar
Jaida Wu committed
320
321
322
323
324
325

					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
326

327
328
329
						Grasscutter.getLogger()
								.info(String.format("[Dispatch] Client %s failed to log in: Account %s created",
										t.getRemoteAddress(), responseData.data.account.uid));
Jaida Wu's avatar
Jaida Wu committed
330
331
332
					} else {
						responseData.retcode = -201;
						responseData.message = "Username not found, create failed.";
Jaida Wu's avatar
Jaida Wu committed
333

334
335
						Grasscutter.getLogger().info(String.format(
								"[Dispatch] Client %s failed to log in: Account create failed", t.getRemoteAddress()));
Jaida Wu's avatar
Jaida Wu committed
336
					}
337
338
339
				} else {
					responseData.retcode = -201;
					responseData.message = "Username not found.";
Jaida Wu's avatar
Jaida Wu committed
340

341
342
343
					Grasscutter.getLogger().info(String
							.format("[Dispatch] Client %s failed to log in: Account no found", t.getRemoteAddress()));
				}
KingRainbow44's avatar
KingRainbow44 committed
344
			} else {
345
				// Account was found, log the player in
KingRainbow44's avatar
KingRainbow44 committed
346
347
348
349
				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
350

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

Jaida Wu's avatar
Jaida Wu committed
355
			responseJSON(t, responseData);
Melledy's avatar
Melledy committed
356
357
		});
		// Login via token
KingRainbow44's avatar
KingRainbow44 committed
358
359
360
361
362
363
		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);
364
365
			} catch (Exception ignored) {
			}
366

KingRainbow44's avatar
KingRainbow44 committed
367
368
369
370
371
			// Create response json
			if (requestData == null) {
				return;
			}
			LoginResultJson responseData = new LoginResultJson();
372
373
			Grasscutter.getLogger()
					.info(String.format("[Dispatch] Client %s is trying to log in via token", t.getRemoteAddress()));
KingRainbow44's avatar
KingRainbow44 committed
374
375
376

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

KingRainbow44's avatar
KingRainbow44 committed
378
379
380
381
			// 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
382

383
384
				Grasscutter.getLogger()
						.info(String.format("[Dispatch] Client %s failed to log in via token", t.getRemoteAddress()));
KingRainbow44's avatar
KingRainbow44 committed
385
386
387
388
389
			} 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
390

391
392
				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
393
			}
Jaida Wu's avatar
Jaida Wu committed
394

Jaida Wu's avatar
Jaida Wu committed
395
			responseJSON(t, responseData);
Melledy's avatar
Melledy committed
396
397
		});
		// Exchange for combo token
KingRainbow44's avatar
KingRainbow44 committed
398
399
400
401
402
403
		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);
404
405
			} catch (Exception ignored) {
			}
406

KingRainbow44's avatar
KingRainbow44 committed
407
408
409
410
			// Create response json
			if (requestData == null || requestData.data == null) {
				return;
			}
411
412
			LoginTokenData loginData = getGsonFactory().fromJson(requestData.data, LoginTokenData.class); // Get login
																											// data
KingRainbow44's avatar
KingRainbow44 committed
413
414
415
416
			ComboTokenResJson responseData = new ComboTokenResJson();

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

KingRainbow44's avatar
KingRainbow44 committed
418
419
420
421
			// Test
			if (account == null || !account.getSessionKey().equals(loginData.token)) {
				responseData.retcode = -201;
				responseData.message = "Wrong session key.";
Jaida Wu's avatar
Jaida Wu committed
422

423
424
				Grasscutter.getLogger().info(
						String.format("[Dispatch] Client %s failed to exchange combo token", t.getRemoteAddress()));
KingRainbow44's avatar
KingRainbow44 committed
425
426
427
428
429
			} 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
430

431
432
				Grasscutter.getLogger().info(
						String.format("[Dispatch] Client %s succeed to exchange combo token", t.getRemoteAddress()));
KingRainbow44's avatar
KingRainbow44 committed
433
			}
Jaida Wu's avatar
Jaida Wu committed
434

Jaida Wu's avatar
Jaida Wu committed
435
			responseJSON(t, responseData);
Melledy's avatar
Melledy committed
436
437
438
		});
		// Agreement and Protocol
		server.createContext( // hk4e-sdk-os.hoyoverse.com
439
440
441
				"/hk4e_global/mdk/agreement/api/getAgreementInfos",
				new DispatchHttpJsonHandler(
						"{\"retcode\":0,\"message\":\"OK\",\"data\":{\"marketing_agreements\":[]}}"));
Melledy's avatar
Melledy committed
442
		server.createContext( // hk4e-sdk-os.hoyoverse.com
443
444
445
				"/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
446
447
		// Game data
		server.createContext( // hk4e-api-os.hoyoverse.com
448
449
				"/common/hk4e_global/announcement/api/getAlertPic",
				new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"total\":0,\"list\":[]}}"));
Melledy's avatar
Melledy committed
450
451
		server.createContext( // hk4e-api-os.hoyoverse.com
				"/common/hk4e_global/announcement/api/getAlertAnn",
452
453
				new DispatchHttpJsonHandler(
						"{\"retcode\":0,\"message\":\"OK\",\"data\":{\"alert\":false,\"alert_id\":0,\"remind\":true}}"));
Melledy's avatar
Melledy committed
454
		server.createContext( // hk4e-api-os.hoyoverse.com
455
456
457
458
				"/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
459
		server.createContext( // hk4e-api-os-static.hoyoverse.com
460
461
				"/common/hk4e_global/announcement/api/getAnnContent",
				new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"list\":[],\"total\":0}}"));
Melledy's avatar
Melledy committed
462
		server.createContext( // hk4e-sdk-os.hoyoverse.com
463
464
465
				"/hk4e_global/mdk/shopwindow/shopwindow/listPriceTier",
				new DispatchHttpJsonHandler(
						"{\"retcode\":0,\"message\":\"OK\",\"data\":{\"suggest_currency\":\"USD\",\"tiers\":[]}}"));
Melledy's avatar
Melledy committed
466
467
		// Captcha
		server.createContext( // api-account-os.hoyoverse.com
468
469
470
471
				"/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
472
		server.createContext( // sdk-os-static.hoyoverse.com
473
474
475
				"/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
476
		server.createContext( // hk4e-sdk-os-static.hoyoverse.com
477
478
479
				"/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
480
		server.createContext( // hk4e-sdk-os-static.hoyoverse.com
481
482
483
				"/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
484
485
		// Test api?
		server.createContext( // abtest-api-data-sg.hoyoverse.com
486
487
488
489
				"/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
490
		server.createContext( // log-upload-os.mihoyo.com
491
492
				"/log/sdk/upload",
				new DispatchHttpJsonHandler("{\"code\":0}"));
Melledy's avatar
Melledy committed
493
		server.createContext( // log-upload-os.mihoyo.com
494
495
				"/sdk/upload",
				new DispatchHttpJsonHandler("{\"code\":0}"));
OtakuNekoP's avatar
OtakuNekoP committed
496
		server.createContext( // /perf/config/verify?device_id=xxx&platform=x&name=xxx
497
498
499
				"/perf/config/verify",
				new DispatchHttpJsonHandler("{\"code\":0}"));

Melledy's avatar
Melledy committed
500
		// Logging servers
Jaida Wu's avatar
Jaida Wu committed
501
		server.createContext( // overseauspider.yuanshen.com
Jaida Wu's avatar
Jaida Wu committed
502
				"/log",
503
				new DispatchHttpJsonHandler("{\"code\":0}"));
Jaida Wu's avatar
Jaida Wu committed
504

Jaida Wu's avatar
Jaida Wu committed
505
		server.createContext( // log-upload-os.mihoyo.com
Jaida Wu's avatar
Jaida Wu committed
506
				"/crash/dataUpload",
507
508
509
				new DispatchHttpJsonHandler("{\"code\":0}"));
		server.createContext("/gacha", t -> responseHTML(t,
				"<!doctype html><html lang=\"en\"><head><title>Gacha</title></head><body></body></html>"));
510

Jaida Wu's avatar
Jaida Wu committed
511
512
		// Start server
		server.start();
Jaida Wu's avatar
Jaida Wu committed
513
		Grasscutter.getLogger().info("[Dispatch] Dispatch server started on port " + getAddress().getPort());
Melledy's avatar
Melledy committed
514
	}
Jaida Wu's avatar
Jaida Wu committed
515

Jaida Wu's avatar
Jaida Wu committed
516
	private void responseJSON(HttpExchange t, Object data) throws IOException {
Jaida Wu's avatar
Jaida Wu committed
517
518
519
520
521
522
523
524
525
526
527
		// 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
528
529
530
531
	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);
532
		// Write the response string
Jaida Wu's avatar
Jaida Wu committed
533
534
535
		OutputStream os = t.getResponseBody();
		os.write(response.getBytes());
		os.close();
Melledy's avatar
Melledy committed
536
	}
537

Melledy's avatar
Melledy committed
538
	private Map<String, String> parseQueryString(String qs) {
Jaida Wu's avatar
Jaida Wu committed
539
		Map<String, String> result = new HashMap<>();
Jaida Wu's avatar
Jaida Wu committed
540
		if (qs == null) {
Jaida Wu's avatar
Jaida Wu committed
541
			return result;
Jaida Wu's avatar
Jaida Wu committed
542
		}
Jaida Wu's avatar
Jaida Wu committed
543
544
545
546

		int last = 0, next, l = qs.length();
		while (last < l) {
			next = qs.indexOf('&', last);
Jaida Wu's avatar
Jaida Wu committed
547
			if (next == -1) {
Jaida Wu's avatar
Jaida Wu committed
548
				next = l;
Jaida Wu's avatar
Jaida Wu committed
549
			}
Jaida Wu's avatar
Jaida Wu committed
550
551
552
553

			if (next > last) {
				int eqPos = qs.indexOf('=', last);
				try {
Jaida Wu's avatar
Jaida Wu committed
554
					if (eqPos < 0 || eqPos > next) {
Jaida Wu's avatar
Jaida Wu committed
555
						result.put(URLDecoder.decode(qs.substring(last, next), "utf-8"), "");
Jaida Wu's avatar
Jaida Wu committed
556
					} else {
557
558
						result.put(URLDecoder.decode(qs.substring(last, eqPos), "utf-8"),
								URLDecoder.decode(qs.substring(eqPos + 1, next), "utf-8"));
Jaida Wu's avatar
Jaida Wu committed
559
					}
Jaida Wu's avatar
Jaida Wu committed
560
561
562
563
564
565
566
				} catch (UnsupportedEncodingException e) {
					throw new RuntimeException(e); // will never happen, utf-8 support is mandatory for java
				}
			}
			last = next + 1;
		}
		return result;
Melledy's avatar
Melledy committed
567
	}
568
569
570
571
572
573
574
575
576
577
578

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