GameSession.java 6.09 KB
Newer Older
Melledy's avatar
Melledy committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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
96
97
98
99
100
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
package emu.grasscutter.server.game;

import java.io.File;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;

import emu.grasscutter.Grasscutter;
import emu.grasscutter.game.Account;
import emu.grasscutter.game.GenshinPlayer;
import emu.grasscutter.net.packet.GenshinPacket;
import emu.grasscutter.net.packet.PacketOpcodesUtil;
import emu.grasscutter.netty.MihoyoKcpChannel;
import emu.grasscutter.utils.Crypto;
import emu.grasscutter.utils.FileUtils;
import emu.grasscutter.utils.Utils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;

public class GameSession extends MihoyoKcpChannel {
	private GameServer server;
	
	private Account account;
	private GenshinPlayer player;
	
	private boolean useSecretKey;
	private SessionState state;
	
	private int clientTime;
	private long lastPingTime;
	private int lastClientSeq = 10;
	
	public GameSession(GameServer server) {
		this.server = server;
		this.state = SessionState.WAITING_FOR_TOKEN;
		this.lastPingTime = System.currentTimeMillis();
	}
	
	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();
	}

	public GenshinPlayer getPlayer() {
		return player;
	}

	public synchronized void setPlayer(GenshinPlayer player) {
		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() {
		Grasscutter.getLogger().info("Client connected from " + getAddress().getHostString().toLowerCase());
	}

	@Override
	protected synchronized void onDisconnect() { // Synchronize so we dont add character at the same time
		Grasscutter.getLogger().info("Client disconnected from " + getAddress().getHostString().toLowerCase());

		// Set state so no more packets can be handled
		this.setState(SessionState.INACTIVE);
		
		// Save after disconnecting
		if (this.isLoggedIn()) {
			// Save
			getPlayer().onLogout();
			// Remove from gameserver
126
			getServer().getPlayers().remove(getPlayer().getUid());
Melledy's avatar
Melledy committed
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
		}
	}
	
    protected void logPacket(ByteBuffer buf) {
		ByteBuf b = Unpooled.wrappedBuffer(buf.array());
    	logPacket(b);
    }
    
    public void replayPacket(int opcode, String name) {
    	String filePath = Grasscutter.getConfig().PACKETS_FOLDER + name;
		File p = new File(filePath);
		
		if (!p.exists()) return;

		byte[] packet = FileUtils.read(p);
		
		GenshinPacket genshinPacket = new GenshinPacket(opcode);
		genshinPacket.setData(packet);
		
		// Log
    	logPacket(genshinPacket.getOpcode());
		
		send(genshinPacket);
    }
    
    public void send(GenshinPacket genshinPacket) {
    	// Test
    	if (genshinPacket.getOpcode() <= 0) {
    		Grasscutter.getLogger().warn("Tried to send packet with missing cmd id!");
    		return;
    	}
    	
    	// Header
    	if (genshinPacket.shouldBuildHeader()) {
    		genshinPacket.buildHeader(this.getNextClientSequence());
    	}
    	
    	// Build packet
    	byte[] data = genshinPacket.build();
    	
    	// Log
168
    	if (Grasscutter.getConfig().getGameServerOptions().LOG_PACKETS) {
Melledy's avatar
Melledy committed
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
    		logPacket(genshinPacket);
    	}
    	
    	// Send
    	send(data);
    }
    
    private void logPacket(int opcode) {
    	//Grasscutter.getLogger().info("SEND: " + PacketOpcodesUtil.getOpcodeName(opcode));
    	//System.out.println(Utils.bytesToHex(genshinPacket.getData()));
    }
    
    private void logPacket(GenshinPacket genshinPacket) {
    	Grasscutter.getLogger().info("SEND: " + PacketOpcodesUtil.getOpcodeName(genshinPacket.getOpcode()) + " (" + genshinPacket.getOpcode() + ")");
    	System.out.println(Utils.bytesToHex(genshinPacket.getData()));
    }

	@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
228
				if (Grasscutter.getConfig().getGameServerOptions().LOG_PACKETS) {
Melledy's avatar
Melledy committed
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
					Grasscutter.getLogger().info("RECV: " + PacketOpcodesUtil.getOpcodeName(opcode) + " (" + opcode + ")");
					System.out.println(Utils.bytesToHex(payload));
				}
				
				// Handle
				getServer().getPacketHandler().handle(this, opcode, header, payload);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			packet.release();
		}
	}
	
	public enum SessionState {
		INACTIVE,
		WAITING_FOR_TOKEN,
		WAITING_FOR_LOGIN,
		PICKING_CHARACTER,
		ACTIVE;
	}
}