GameSession.java 7.24 KB
Newer Older
Melledy's avatar
Melledy committed
1
2
3
4
5
package emu.grasscutter.server.game;

import java.io.File;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
6
7
import java.util.Iterator;
import java.util.Map;
8
import java.util.Set;
Melledy's avatar
Melledy committed
9
10

import emu.grasscutter.Grasscutter;
11
import emu.grasscutter.Grasscutter.ServerDebugMode;
Melledy's avatar
Melledy committed
12
import emu.grasscutter.game.Account;
Melledy's avatar
Melledy committed
13
import emu.grasscutter.game.player.Player;
14
import emu.grasscutter.net.packet.BasePacket;
15
import emu.grasscutter.net.packet.PacketOpcodes;
Melledy's avatar
Melledy committed
16
import emu.grasscutter.net.packet.PacketOpcodesUtil;
17
import emu.grasscutter.netty.KcpChannel;
18
import emu.grasscutter.server.event.game.SendPacketEvent;
Melledy's avatar
Melledy committed
19
20
21
import emu.grasscutter.utils.Crypto;
import emu.grasscutter.utils.FileUtils;
import emu.grasscutter.utils.Utils;
22
import io.jpower.kcp.netty.UkcpChannel;
Melledy's avatar
Melledy committed
23
24
25
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
26
import io.netty.channel.ChannelPipeline;
Melledy's avatar
Melledy committed
27

28
import static emu.grasscutter.utils.Language.translate;
29
import static emu.grasscutter.Configuration.*;
30

31
public class GameSession extends KcpChannel {
32
	private final GameServer server;
Melledy's avatar
Melledy committed
33
34
	
	private Account account;
35
	private Player player;
Melledy's avatar
Melledy committed
36
37
38
39
40
41
42
	
	private boolean useSecretKey;
	private SessionState state;
	
	private int clientTime;
	private long lastPingTime;
	private int lastClientSeq = 10;
43
44
45
46
47
48
49
50
51
52
53
54
55

	private final ChannelPipeline pipeline;
	@Override
	public void close() {
		setState(SessionState.INACTIVE);
		//send disconnection pack in case of reconnection
		try {
			send(new BasePacket(PacketOpcodes.ServerDisconnectClientNotify));
		}catch (Throwable ignore){

		}
		super.close();
	}
Melledy's avatar
Melledy committed
56
	public GameSession(GameServer server) {
57
58
59
		this(server,null);
	}
	public GameSession(GameServer server, ChannelPipeline pipeline) {
Melledy's avatar
Melledy committed
60
61
62
		this.server = server;
		this.state = SessionState.WAITING_FOR_TOKEN;
		this.lastPingTime = System.currentTimeMillis();
63
64
65
66
		this.pipeline = pipeline;
		if(pipeline!=null) {
			pipeline.addLast(this);
		}
Melledy's avatar
Melledy committed
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
	}
	
	public GameServer getServer() {
		return server;
	}
	
	public InetSocketAddress getAddress() {
		if (this.getChannel() == null) {
			return null;
		}
		return this.getChannel().remoteAddress();
	}

	public boolean useSecretKey() {
		return useSecretKey;
	}
	
	public Account getAccount() {
		return account;
	}

	public void setAccount(Account account) {
		this.account = account;
	}
	
	public String getAccountId() {
		return this.getAccount().getId();
	}

96
	public Player getPlayer() {
Melledy's avatar
Melledy committed
97
98
99
		return player;
	}

100
	public synchronized void setPlayer(Player player) {
Melledy's avatar
Melledy committed
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
		this.player = player;
		this.player.setSession(this);
		this.player.setAccount(this.getAccount());
	}

	public SessionState getState() {
		return state;
	}

	public void setState(SessionState state) {
		this.state = state;
	}

	public boolean isLoggedIn() {
		return this.getPlayer() != null;
	}

	public void setUseSecretKey(boolean useSecretKey) {
		this.useSecretKey = useSecretKey;
	}
	
	public int getClientTime() {
		return this.clientTime;
	}

	public long getLastPingTime() {
		return lastPingTime;
	}
	
	public void updateLastPingTime(int clientTime) {
		this.clientTime = clientTime;
		this.lastPingTime = System.currentTimeMillis();
	}
	
	public int getNextClientSequence() {
		return ++lastClientSeq;
	}
	
	@Override
	protected void onConnect() {
141
		Grasscutter.getLogger().info(translate("messages.game.connect", this.getAddress().getHostString().toLowerCase()));
Melledy's avatar
Melledy committed
142
143
144
	}

	@Override
145
146
	protected synchronized void onDisconnect() { // Synchronize so we don't add character at the same time.
		Grasscutter.getLogger().info(translate("messages.game.disconnect", this.getAddress().getHostString().toLowerCase()));
Melledy's avatar
Melledy committed
147
148
149

		// Set state so no more packets can be handled
		this.setState(SessionState.INACTIVE);
150

Melledy's avatar
Melledy committed
151
152
		// Save after disconnecting
		if (this.isLoggedIn()) {
153
			Player player = getPlayer();
154
			// Call logout event.
155
156
157
158
159
160
			player.onLogout();
		}
		try {
			pipeline.remove(this);
		} catch (Throwable ignore) {

Melledy's avatar
Melledy committed
161
162
163
164
165
166
167
168
169
		}
	}
	
    protected void logPacket(ByteBuffer buf) {
		ByteBuf b = Unpooled.wrappedBuffer(buf.array());
    	logPacket(b);
    }
    
    public void replayPacket(int opcode, String name) {
170
    	String filePath = PACKET(name);
Melledy's avatar
Melledy committed
171
172
173
174
175
176
		File p = new File(filePath);
		
		if (!p.exists()) return;

		byte[] packet = FileUtils.read(p);
		
177
178
		BasePacket basePacket = new BasePacket(opcode);
		basePacket.setData(packet);
Melledy's avatar
Melledy committed
179
		
180
		send(basePacket);
Melledy's avatar
Melledy committed
181
182
    }
    
183
    public void send(BasePacket packet) {
Melledy's avatar
Melledy committed
184
    	// Test
185
    	if (packet.getOpcode() <= 0) {
Melledy's avatar
Melledy committed
186
187
188
    		Grasscutter.getLogger().warn("Tried to send packet with missing cmd id!");
    		return;
    	}
189
190
191
192
193
194

		// DO NOT REMOVE (unless we find a way to validate code before sending to client which I don't think we can)
		// Stop WindSeedClientNotify from being sent for security purposes.
		if(PacketOpcodes.BANNED_PACKETS.contains(packet.getOpcode())) {
			return;
		}
Melledy's avatar
Melledy committed
195
196
    	
    	// Header
197
198
    	if (packet.shouldBuildHeader()) {
    		packet.buildHeader(this.getNextClientSequence());
Melledy's avatar
Melledy committed
199
200
201
    	}
    	
    	// Log
202
    	if (SERVER.debugLevel == ServerDebugMode.ALL) {
203
    		logPacket(packet);
Melledy's avatar
Melledy committed
204
    	}
205
206
		
		// Invoke event.
207
		SendPacketEvent event = new SendPacketEvent(this, packet); event.call();
208
209
    	if(!event.isCanceled()) // If event is not cancelled, continue.
			this.send(event.getPacket().build());
Melledy's avatar
Melledy committed
210
211
    }
    
212
213
214
215
216
217
218
219
	private static final Set<Integer> loopPacket = Set.of(
			PacketOpcodes.PingReq,
			PacketOpcodes.PingRsp,
			PacketOpcodes.WorldPlayerRTTNotify,
			PacketOpcodes.UnionCmdNotify,
			PacketOpcodes.QueryPathReq
	);

220
221
222
223
    private void logPacket(BasePacket packet) {
		if (!loopPacket.contains(packet.getOpcode())) {
			Grasscutter.getLogger().info("SEND: " + PacketOpcodesUtil.getOpcodeName(packet.getOpcode()) + " (" + packet.getOpcode() + ")");
			System.out.println(Utils.bytesToHex(packet.getData()));
224
		}
Melledy's avatar
Melledy committed
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
    }

	@Override
	public void onMessage(ChannelHandlerContext ctx, ByteBuf data) {
		// Decrypt and turn back into a packet
		byte[] byteData = Utils.byteBufToArray(data);
		Crypto.xor(byteData, useSecretKey() ? Crypto.ENCRYPT_KEY : Crypto.DISPATCH_KEY);
		ByteBuf packet = Unpooled.wrappedBuffer(byteData);
		
		// Log
		//logPacket(packet);
		
		// Handle
		try {
			while (packet.readableBytes() > 0) {
				// Length
				if (packet.readableBytes() < 12) {
					return;
				}
				
				// Packet sanity check
				int const1 = packet.readShort();
				if (const1 != 17767) {
					return; // Bad packet
				}

				// Data
				int opcode = packet.readShort();
				int headerLength = packet.readShort();
				int payloadLength = packet.readInt();
				
				byte[] header = new byte[headerLength];
				byte[] payload = new byte[payloadLength];
				
				packet.readBytes(header);
				packet.readBytes(payload);
				
				// Sanity check #2
				int const2 = packet.readShort();
				if (const2 != -30293) {
					return; // Bad packet
				}
				
				// Log packet
269
				if (SERVER.debugLevel == ServerDebugMode.ALL) {
270
271
272
273
					if (!loopPacket.contains(opcode)) {
						Grasscutter.getLogger().info("RECV: " + PacketOpcodesUtil.getOpcodeName(opcode) + " (" + opcode + ")");
						System.out.println(Utils.bytesToHex(payload));
					}
Melledy's avatar
Melledy committed
274
275
276
277
278
279
280
281
				}
				
				// Handle
				getServer().getPacketHandler().handle(this, opcode, header, payload);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
282
			data.release();
Melledy's avatar
Melledy committed
283
284
285
286
287
288
289
290
291
292
293
294
			packet.release();
		}
	}
	
	public enum SessionState {
		INACTIVE,
		WAITING_FOR_TOKEN,
		WAITING_FOR_LOGIN,
		PICKING_CHARACTER,
		ACTIVE;
	}
}