DispatchServer.java 18.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
11
12
13
14
15
16
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsServer;
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
17
import emu.grasscutter.server.dispatch.json.*;
Melledy's avatar
Melledy committed
18
19
20
21
import emu.grasscutter.server.dispatch.json.ComboTokenReqJson.LoginTokenData;
import emu.grasscutter.utils.FileUtils;
import emu.grasscutter.utils.Utils;

Jaida Wu's avatar
Jaida Wu committed
22
23
24
25
26
27
28
29
30
31
32
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLDecoder;
import java.security.KeyStore;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
Melledy's avatar
Melledy committed
33

KingRainbow44's avatar
KingRainbow44 committed
34
public final class DispatchServer {
Jaida Wu's avatar
Jaida Wu committed
35
36
	public static String query_region_list = "";
	public static String query_cur_region = "";
Melledy's avatar
Melledy committed
37
38
39
40
	private final InetSocketAddress address;
	private final Gson gson;
	public String regionListBase64;
	public String regionCurrentBase64;
Jaida Wu's avatar
Jaida Wu committed
41
42
	private QueryCurrRegionHttpRsp currRegion;

Melledy's avatar
Melledy committed
43
44
45
	public DispatchServer() {
		this.address = new InetSocketAddress(Grasscutter.getConfig().DispatchServerIp, Grasscutter.getConfig().DispatchServerPort);
		this.gson = new GsonBuilder().create();
Jaida Wu's avatar
Jaida Wu committed
46

Melledy's avatar
Melledy committed
47
48
49
		this.loadQueries();
		this.initRegion();
	}
Jaida Wu's avatar
Jaida Wu committed
50

Melledy's avatar
Melledy committed
51
52
53
	public InetSocketAddress getAddress() {
		return address;
	}
Jaida Wu's avatar
Jaida Wu committed
54

Melledy's avatar
Melledy committed
55
56
57
58
59
60
61
	public Gson getGsonFactory() {
		return gson;
	}

	public QueryCurrRegionHttpRsp getCurrRegion() {
		return currRegion;
	}
Jaida Wu's avatar
Jaida Wu committed
62

Melledy's avatar
Melledy committed
63
64
	public void loadQueries() {
		File file;
Jaida Wu's avatar
Jaida Wu committed
65

Melledy's avatar
Melledy committed
66
67
68
69
		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
70
			Grasscutter.getLogger().warn("[Dispatch] query_region_list not found! Using default region list.");
Melledy's avatar
Melledy committed
71
		}
Jaida Wu's avatar
Jaida Wu committed
72

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

	private void initRegion() {
		try {
			byte[] decoded = Base64.getDecoder().decode(query_region_list);
			QueryRegionListHttpRsp rl = QueryRegionListHttpRsp.parseFrom(decoded);
Jaida Wu's avatar
Jaida Wu committed
85

Melledy's avatar
Melledy committed
86
87
			byte[] decoded2 = Base64.getDecoder().decode(query_cur_region);
			QueryCurrRegionHttpRsp regionQuery = QueryCurrRegionHttpRsp.parseFrom(decoded2);
Jaida Wu's avatar
Jaida Wu committed
88

Melledy's avatar
Melledy committed
89
90
91
92
			RegionSimpleInfo server = RegionSimpleInfo.newBuilder()
					.setName("os_usa")
					.setTitle(Grasscutter.getConfig().GameServerName)
					.setType("DEV_PUBLIC")
93
					.setDispatchUrl("https://" + (Grasscutter.getConfig().DispatchServerPublicIp.isEmpty() ? Grasscutter.getConfig().DispatchServerIp : Grasscutter.getConfig().DispatchServerPublicIp) + ":" + getAddress().getPort() + "/query_cur_region")
Melledy's avatar
Melledy committed
94
					.build();
Jaida Wu's avatar
Jaida Wu committed
95

Melledy's avatar
Melledy committed
96
97
98
99
			RegionSimpleInfo serverTest2 = RegionSimpleInfo.newBuilder()
					.setName("os_euro")
					.setTitle("Grasscutter")
					.setType("DEV_PUBLIC")
100
					.setDispatchUrl("https://" + (Grasscutter.getConfig().DispatchServerPublicIp.isEmpty() ? Grasscutter.getConfig().DispatchServerIp : Grasscutter.getConfig().DispatchServerPublicIp) + ":" + getAddress().getPort() + "/query_cur_region")
Melledy's avatar
Melledy committed
101
					.build();
Jaida Wu's avatar
Jaida Wu committed
102

Melledy's avatar
Melledy committed
103
			QueryRegionListHttpRsp regionList = QueryRegionListHttpRsp.newBuilder()
Jaida Wu's avatar
Jaida Wu committed
104
105
106
107
108
109
110
					.addServers(server)
					.addServers(serverTest2)
					.setClientSecretKey(rl.getClientSecretKey())
					.setClientCustomConfigEncrypted(rl.getClientCustomConfigEncrypted())
					.setEnableLoginPc(true)
					.build();

Melledy's avatar
Melledy committed
111
			RegionInfo currentRegion = regionQuery.getRegionInfo().toBuilder()
112
					.setIp((Grasscutter.getConfig().GameServerPublicIp.isEmpty() ? Grasscutter.getConfig().GameServerIp : Grasscutter.getConfig().GameServerPublicIp))
Melledy's avatar
Melledy committed
113
114
115
					.setPort(Grasscutter.getConfig().GameServerPort)
					.setSecretKey(ByteString.copyFrom(FileUtils.read(Grasscutter.getConfig().KEY_FOLDER + "dispatchSeed.bin")))
					.build();
Jaida Wu's avatar
Jaida Wu committed
116

Melledy's avatar
Melledy committed
117
118
119
120
121
122
			QueryCurrRegionHttpRsp parsedRegionQuery = regionQuery.toBuilder().setRegionInfo(currentRegion).build();

			this.regionListBase64 = Base64.getEncoder().encodeToString(regionList.toByteString().toByteArray());
			this.regionCurrentBase64 = Base64.getEncoder().encodeToString(parsedRegionQuery.toByteString().toByteArray());
			this.currRegion = parsedRegionQuery;
		} catch (Exception e) {
Jaida Wu's avatar
Jaida Wu committed
123
			Grasscutter.getLogger().error("[Dispatch] Error while initializing region info!", e);
Melledy's avatar
Melledy committed
124
125
126
127
		}
	}

	public void start() throws Exception {
128
		HttpServer server;
Jaida Wu's avatar
Jaida Wu committed
129
		if (Grasscutter.getConfig().UseSSL) {
130
131
132
133
134
135
136
137
138
			HttpsServer httpsServer;
			httpsServer = HttpsServer.create(getAddress(), 0);
			SSLContext sslContext = SSLContext.getInstance("TLS");
			try (FileInputStream fis = new FileInputStream(Grasscutter.getConfig().DispatchServerKeystorePath)) {
				char[] keystorePassword = Grasscutter.getConfig().DispatchServerKeystorePassword.toCharArray();
				KeyStore ks = KeyStore.getInstance("PKCS12");
				ks.load(fis, keystorePassword);
				KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
				kmf.init(ks, keystorePassword);
Jaida Wu's avatar
Jaida Wu committed
139

140
				sslContext.init(kmf.getKeyManagers(), null, null);
Jaida Wu's avatar
Jaida Wu committed
141

142
143
144
				httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));
				server = httpsServer;
			} catch (Exception e) {
Jaida Wu's avatar
Jaida Wu committed
145
				Grasscutter.getLogger().warn("[Dispatch] No SSL cert found! Falling back to HTTP server.");
Jaida Wu's avatar
Jaida Wu committed
146
147
				Grasscutter.getConfig().UseSSL = false;
				server = HttpServer.create(getAddress(), 0);
148
149
150
			}
		} else {
			server = HttpServer.create(getAddress(), 0);
Melledy's avatar
Melledy committed
151
		}
Jaida Wu's avatar
Jaida Wu committed
152

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

Melledy's avatar
Melledy committed
155
		// Dispatch
KingRainbow44's avatar
KingRainbow44 committed
156
157
		server.createContext("/query_region_list", t -> {
			// Log
Jaida Wu's avatar
Jaida Wu committed
158
			Grasscutter.getLogger().info(String.format("[Dispatch] Client %s request: query_region_list", t.getRemoteAddress()));
Jaida Wu's avatar
Jaida Wu committed
159
160

			responseHTML(t, regionListBase64);
Melledy's avatar
Melledy committed
161
		});
KingRainbow44's avatar
KingRainbow44 committed
162
163
		server.createContext("/query_cur_region", t -> {
			// Log
Jaida Wu's avatar
Jaida Wu committed
164
			Grasscutter.getLogger().info(String.format("[Dispatch] Client %s request: query_cur_region", t.getRemoteAddress()));
KingRainbow44's avatar
KingRainbow44 committed
165
166
167
168
169
			// 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;
Melledy's avatar
Melledy committed
170
			}
Jaida Wu's avatar
Jaida Wu committed
171
172

			responseHTML(t, response);
Melledy's avatar
Melledy committed
173
174
		});
		// Login via account
KingRainbow44's avatar
KingRainbow44 committed
175
176
177
178
179
180
		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);
Jaida Wu's avatar
Jaida Wu committed
181
			} catch (Exception ignored) {
Melledy's avatar
Melledy committed
182
			}
KingRainbow44's avatar
KingRainbow44 committed
183
184
185
186
187
			// Create response json
			if (requestData == null) {
				return;
			}
			LoginResultJson responseData = new LoginResultJson();
Jaida Wu's avatar
Jaida Wu committed
188

Jaida Wu's avatar
Jaida Wu committed
189
			Grasscutter.getLogger().info(String.format("[Dispatch] Client %s is trying to log in", t.getRemoteAddress()));
Jaida Wu's avatar
Jaida Wu committed
190

KingRainbow44's avatar
KingRainbow44 committed
191
192
			// Login
			Account account = DatabaseHelper.getAccountByName(requestData.account);
Jaida Wu's avatar
Jaida Wu committed
193

194
			// Check if account exists, else create a new one.
195
196
197
198
199
			if (account == null) {
				// Account doesnt exist, so we can either auto create it if the config value is set
				if (Grasscutter.getConfig().ServerOptions.AutomaticallyCreateAccounts) {
					// This account has been created AUTOMATICALLY. There will be no permissions added.
					account = DatabaseHelper.createAccountWithId(requestData.account, 0);
Jaida Wu's avatar
Jaida Wu committed
200
201
202
203
204
205

					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
206

Jaida Wu's avatar
Jaida Wu committed
207
						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
208
209
210
					} else {
						responseData.retcode = -201;
						responseData.message = "Username not found, create failed.";
Jaida Wu's avatar
Jaida Wu committed
211

Jaida Wu's avatar
Jaida Wu committed
212
						Grasscutter.getLogger().info(String.format("[Dispatch] Client %s failed to log in: Account create failed", t.getRemoteAddress()));
Jaida Wu's avatar
Jaida Wu committed
213
					}
214
215
216
				} else {
					responseData.retcode = -201;
					responseData.message = "Username not found.";
Jaida Wu's avatar
Jaida Wu committed
217

Jaida Wu's avatar
Jaida Wu committed
218
					Grasscutter.getLogger().info(String.format("[Dispatch] Client %s failed to log in: Account no found", t.getRemoteAddress()));
Jaida Wu's avatar
Jaida Wu committed
219
				}
KingRainbow44's avatar
KingRainbow44 committed
220
			} else {
221
				// Account was found, log the player in
KingRainbow44's avatar
KingRainbow44 committed
222
223
224
225
				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
226

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

Jaida Wu's avatar
Jaida Wu committed
230
			responseJSON(t, responseData);
Melledy's avatar
Melledy committed
231
		});
Jaida Wu's avatar
Jaida Wu committed
232

Melledy's avatar
Melledy committed
233
		// Login via token
KingRainbow44's avatar
KingRainbow44 committed
234
235
236
237
238
239
		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);
Jaida Wu's avatar
Jaida Wu committed
240
			} catch (Exception ignored) {
Melledy's avatar
Melledy committed
241
			}
KingRainbow44's avatar
KingRainbow44 committed
242
243
244
245
246
			// Create response json
			if (requestData == null) {
				return;
			}
			LoginResultJson responseData = new LoginResultJson();
Jaida Wu's avatar
Jaida Wu committed
247
			Grasscutter.getLogger().info(String.format("[Dispatch] Client %s is trying to log in via token", t.getRemoteAddress()));
KingRainbow44's avatar
KingRainbow44 committed
248
249
250

			// Login
			Account account = DatabaseHelper.getAccountById(requestData.uid);
Jaida Wu's avatar
Jaida Wu committed
251

KingRainbow44's avatar
KingRainbow44 committed
252
253
254
255
			// 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
256

Jaida Wu's avatar
Jaida Wu committed
257
				Grasscutter.getLogger().info(String.format("[Dispatch] Client %s failed to log in via token", t.getRemoteAddress()));
KingRainbow44's avatar
KingRainbow44 committed
258
259
260
261
262
			} 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
263

Jaida Wu's avatar
Jaida Wu committed
264
				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
265
			}
Jaida Wu's avatar
Jaida Wu committed
266

Jaida Wu's avatar
Jaida Wu committed
267
			responseJSON(t, responseData);
Melledy's avatar
Melledy committed
268
269
		});
		// Exchange for combo token
KingRainbow44's avatar
KingRainbow44 committed
270
271
272
273
274
275
		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);
Jaida Wu's avatar
Jaida Wu committed
276
			} catch (Exception ignored) {
Melledy's avatar
Melledy committed
277
			}
KingRainbow44's avatar
KingRainbow44 committed
278
279
280
281
282
283
284
285
286
			// Create response json
			if (requestData == null || requestData.data == null) {
				return;
			}
			LoginTokenData loginData = getGsonFactory().fromJson(requestData.data, LoginTokenData.class); // Get login data
			ComboTokenResJson responseData = new ComboTokenResJson();

			// Login
			Account account = DatabaseHelper.getAccountById(loginData.uid);
Jaida Wu's avatar
Jaida Wu committed
287

KingRainbow44's avatar
KingRainbow44 committed
288
289
290
291
			// Test
			if (account == null || !account.getSessionKey().equals(loginData.token)) {
				responseData.retcode = -201;
				responseData.message = "Wrong session key.";
Jaida Wu's avatar
Jaida Wu committed
292

Jaida Wu's avatar
Jaida Wu committed
293
				Grasscutter.getLogger().info(String.format("[Dispatch] Client %s failed to exchange combo token", t.getRemoteAddress()));
KingRainbow44's avatar
KingRainbow44 committed
294
295
296
297
298
			} 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
299

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

Jaida Wu's avatar
Jaida Wu committed
303
			responseJSON(t, responseData);
Melledy's avatar
Melledy committed
304
305
306
		});
		// Agreement and Protocol
		server.createContext( // hk4e-sdk-os.hoyoverse.com
Jaida Wu's avatar
Jaida Wu committed
307
				"/hk4e_global/mdk/agreement/api/getAgreementInfos",
Melledy's avatar
Melledy committed
308
309
310
				new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"marketing_agreements\":[]}}")
		);
		server.createContext( // hk4e-sdk-os.hoyoverse.com
Jaida Wu's avatar
Jaida Wu committed
311
				"/hk4e_global/combo/granter/api/compareProtocolVersion",
Melledy's avatar
Melledy committed
312
313
314
315
				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\":\"\"}}}")
		);
		// Game data
		server.createContext( // hk4e-api-os.hoyoverse.com
Jaida Wu's avatar
Jaida Wu committed
316
				"/common/hk4e_global/announcement/api/getAlertPic",
Melledy's avatar
Melledy committed
317
318
319
320
321
322
323
				new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"total\":0,\"list\":[]}}")
		);
		server.createContext( // hk4e-api-os.hoyoverse.com
				"/common/hk4e_global/announcement/api/getAlertAnn",
				new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"alert\":false,\"alert_id\":0,\"remind\":true}}")
		);
		server.createContext( // hk4e-api-os.hoyoverse.com
Jaida Wu's avatar
Jaida Wu committed
324
				"/common/hk4e_global/announcement/api/getAnnList",
Melledy's avatar
Melledy committed
325
326
327
				new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"list\":[],\"total\":0,\"type_list\":[],\"alert\":false,\"alert_id\":0,\"timezone\":0,\"t\":\"" + System.currentTimeMillis() + "\"}}")
		);
		server.createContext( // hk4e-api-os-static.hoyoverse.com
Jaida Wu's avatar
Jaida Wu committed
328
				"/common/hk4e_global/announcement/api/getAnnContent",
Melledy's avatar
Melledy committed
329
330
331
				new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"list\":[],\"total\":0}}")
		);
		server.createContext( // hk4e-sdk-os.hoyoverse.com
Jaida Wu's avatar
Jaida Wu committed
332
				"/hk4e_global/mdk/shopwindow/shopwindow/listPriceTier",
Melledy's avatar
Melledy committed
333
334
335
336
				new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"suggest_currency\":\"USD\",\"tiers\":[]}}")
		);
		// Captcha
		server.createContext( // api-account-os.hoyoverse.com
Jaida Wu's avatar
Jaida Wu committed
337
				"/account/risky/api/check",
Melledy's avatar
Melledy committed
338
339
340
341
				new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":\"c8820f246a5241ab9973f71df3ddd791\",\"action\":\"\",\"geetest\":{\"challenge\":\"\",\"gt\":\"\",\"new_captcha\":0,\"success\":1}}}")
		);
		// Config	
		server.createContext( // sdk-os-static.hoyoverse.com
Jaida Wu's avatar
Jaida Wu committed
342
				"/combo/box/api/config/sdk/combo",
Melledy's avatar
Melledy committed
343
344
345
				new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"vals\":{\"disable_email_bind_skip\":\"false\",\"email_bind_remind_interval\":\"7\",\"email_bind_remind\":\"true\"}}}")
		);
		server.createContext( // hk4e-sdk-os-static.hoyoverse.com
Jaida Wu's avatar
Jaida Wu committed
346
				"/hk4e_global/combo/granter/api/getConfig",
Melledy's avatar
Melledy committed
347
348
349
				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}}")
		);
		server.createContext( // hk4e-sdk-os-static.hoyoverse.com
Jaida Wu's avatar
Jaida Wu committed
350
				"/hk4e_global/mdk/shield/api/loadConfig",
Melledy's avatar
Melledy committed
351
352
353
354
				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}}}}")
		);
		// Test api?
		server.createContext( // abtest-api-data-sg.hoyoverse.com
Jaida Wu's avatar
Jaida Wu committed
355
				"/data_abtest_api/config/experiment/list",
Melledy's avatar
Melledy committed
356
357
358
359
				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 
		server.createContext( // log-upload-os.mihoyo.com
Jaida Wu's avatar
Jaida Wu committed
360
				"/log/sdk/upload",
Melledy's avatar
Melledy committed
361
362
363
				new DispatchHttpJsonHandler("{\"code\":0}")
		);
		server.createContext( // log-upload-os.mihoyo.com
Jaida Wu's avatar
Jaida Wu committed
364
				"/sdk/upload",
Melledy's avatar
Melledy committed
365
366
				new DispatchHttpJsonHandler("{\"code\":0}")
		);
OtakuNekoP's avatar
OtakuNekoP committed
367
		server.createContext( // /perf/config/verify?device_id=xxx&platform=x&name=xxx
Jaida Wu's avatar
Jaida Wu committed
368
				"/perf/config/verify",
OtakuNekoP's avatar
OtakuNekoP committed
369
370
				new DispatchHttpJsonHandler("{\"code\":0}")
		);
Jaida Wu's avatar
Jaida Wu committed
371

Melledy's avatar
Melledy committed
372
		// Logging servers
Jaida Wu's avatar
Jaida Wu committed
373
		server.createContext( // overseauspider.yuanshen.com
Jaida Wu's avatar
Jaida Wu committed
374
				"/log",
Melledy's avatar
Melledy committed
375
376
				new DispatchHttpJsonHandler("{\"code\":0}")
		);
Jaida Wu's avatar
Jaida Wu committed
377

Jaida Wu's avatar
Jaida Wu committed
378
		server.createContext( // log-upload-os.mihoyo.com
Jaida Wu's avatar
Jaida Wu committed
379
				"/crash/dataUpload",
Melledy's avatar
Melledy committed
380
381
				new DispatchHttpJsonHandler("{\"code\":0}")
		);
Jaida Wu's avatar
Jaida Wu committed
382
		server.createContext("/gacha", t -> responseHTML(t, "<!doctype html><html lang=\"en\"><head><title>Gacha</title></head><body></body></html>"));
Jaida Wu's avatar
Jaida Wu committed
383
384
		// Start server
		server.start();
Jaida Wu's avatar
Jaida Wu committed
385
		Grasscutter.getLogger().info("[Dispatch] Dispatch server started on port " + getAddress().getPort());
Melledy's avatar
Melledy committed
386
	}
Jaida Wu's avatar
Jaida Wu committed
387

Jaida Wu's avatar
Jaida Wu committed
388
	private void responseJSON(HttpExchange t, Object data) throws IOException {
Jaida Wu's avatar
Jaida Wu committed
389
390
391
392
393
394
395
396
397
398
399
		// 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
400
401
402
403
404
405
406
407
408
409
	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);
		//Write the response string
		OutputStream os = t.getResponseBody();
		os.write(response.getBytes());
		os.close();
	}

Melledy's avatar
Melledy committed
410
	private Map<String, String> parseQueryString(String qs) {
Jaida Wu's avatar
Jaida Wu committed
411
		Map<String, String> result = new HashMap<>();
Jaida Wu's avatar
Jaida Wu committed
412
		if (qs == null) {
Jaida Wu's avatar
Jaida Wu committed
413
			return result;
Jaida Wu's avatar
Jaida Wu committed
414
		}
Jaida Wu's avatar
Jaida Wu committed
415
416
417
418

		int last = 0, next, l = qs.length();
		while (last < l) {
			next = qs.indexOf('&', last);
Jaida Wu's avatar
Jaida Wu committed
419
			if (next == -1) {
Jaida Wu's avatar
Jaida Wu committed
420
				next = l;
Jaida Wu's avatar
Jaida Wu committed
421
			}
Jaida Wu's avatar
Jaida Wu committed
422
423
424
425

			if (next > last) {
				int eqPos = qs.indexOf('=', last);
				try {
Jaida Wu's avatar
Jaida Wu committed
426
					if (eqPos < 0 || eqPos > next) {
Jaida Wu's avatar
Jaida Wu committed
427
						result.put(URLDecoder.decode(qs.substring(last, next), "utf-8"), "");
Jaida Wu's avatar
Jaida Wu committed
428
					} else {
Jaida Wu's avatar
Jaida Wu committed
429
						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
430
					}
Jaida Wu's avatar
Jaida Wu committed
431
432
433
434
435
436
437
				} 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
438
439
	}
}