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

import java.io.File;
import java.net.InetSocketAddress;
5
6
import java.nio.file.Path;

Melledy's avatar
Melledy committed
7
import emu.grasscutter.Grasscutter;
8
import emu.grasscutter.Grasscutter.ServerDebugMode;
Melledy's avatar
Melledy committed
9
import emu.grasscutter.game.Account;
Melledy's avatar
Melledy committed
10
import emu.grasscutter.game.player.Player;
11
import emu.grasscutter.net.packet.BasePacket;
12
import emu.grasscutter.net.packet.PacketOpcodes;
13
import emu.grasscutter.net.packet.PacketOpcodesUtils;
14
import emu.grasscutter.server.event.game.SendPacketEvent;
Melledy's avatar
Melledy committed
15
16
17
18
19
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;
20
21
import lombok.Getter;
import lombok.Setter;
Akka's avatar
Akka committed
22

23
import static emu.grasscutter.config.Configuration.*;
24
import static emu.grasscutter.utils.Language.translate;
25

26
public class GameSession implements GameSessionManager.KcpChannel {
github-actions's avatar
github-actions committed
27
28
29
    private final GameServer server;
    private GameSessionManager.KcpTunnel tunnel;

30
31
    @Getter @Setter private Account account;
    @Getter private Player player;
github-actions's avatar
github-actions committed
32

33
34
    @Setter private boolean useSecretKey;
    @Getter @Setter private SessionState state;
github-actions's avatar
github-actions committed
35

36
37
    @Getter private int clientTime;
    @Getter private long lastPingTime;
github-actions's avatar
github-actions committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
    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() {
        try {
            return tunnel.getAddress();
53
        } catch (Throwable ignore) {
github-actions's avatar
github-actions committed
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
            return null;
        }
    }

    public boolean useSecretKey() {
        return useSecretKey;
    }

    public String getAccountId() {
        return this.getAccount().getId();
    }

    public synchronized void setPlayer(Player player) {
        this.player = player;
        this.player.setSession(this);
        this.player.setAccount(this.getAccount());
    }

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

    public void updateLastPingTime(int clientTime) {
        this.clientTime = clientTime;
        this.lastPingTime = System.currentTimeMillis();
    }

    public int getNextClientSequence() {
        return ++lastClientSeq;
    }
84

Melledy's avatar
Melledy committed
85
    public void replayPacket(int opcode, String name) {
86
87
        Path filePath = FileUtils.getPluginPath(name);
        File p = filePath.toFile();
88

github-actions's avatar
github-actions committed
89
        if (!p.exists()) return;
Melledy's avatar
Melledy committed
90

github-actions's avatar
github-actions committed
91
        byte[] packet = FileUtils.read(p);
92

github-actions's avatar
github-actions committed
93
94
        BasePacket basePacket = new BasePacket(opcode);
        basePacket.setData(packet);
95

github-actions's avatar
github-actions committed
96
        send(basePacket);
Melledy's avatar
Melledy committed
97
    }
98

99
    public void logPacket(String sendOrRecv, int opcode, byte[] payload) {
100
        Grasscutter.getLogger().info(sendOrRecv + ": " + PacketOpcodesUtils.getOpcodeName(opcode) + " (" + opcode + ")");
101
102
        System.out.println(Utils.bytesToHex(payload));
    }
103

104
    public void send(BasePacket packet) {
github-actions's avatar
github-actions committed
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
        // Test
        if (packet.getOpcode() <= 0) {
            Grasscutter.getLogger().warn("Tried to send packet with missing cmd id!");
            return;
        }

        // 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 (PacketOpcodesUtils.BANNED_PACKETS.contains(packet.getOpcode())) {
            return;
        }

        // Header
        if (packet.shouldBuildHeader()) {
            packet.buildHeader(this.getNextClientSequence());
        }

        // Log
        switch (GAME_INFO.logPackets) {
            case ALL -> {
                if (!PacketOpcodesUtils.LOOP_PACKETS.contains(packet.getOpcode())) {
                    logPacket("SEND", packet.getOpcode(), packet.getData());
                }
            }
129
            case WHITELIST -> {
github-actions's avatar
github-actions committed
130
                if (SERVER.debugWhitelist.contains(packet.getOpcode())) {
131
132
                    logPacket("SEND", packet.getOpcode(), packet.getData());
                }
github-actions's avatar
github-actions committed
133
            }
134
            case BLACKLIST -> {
135
136
137
138
                if (!SERVER.debugBlacklist.contains(packet.getOpcode())) {
                    logPacket("SEND", packet.getOpcode(), packet.getData());
                }
            }
139
140
            default -> {
            }
github-actions's avatar
github-actions committed
141
142
143
        }

        // Invoke event.
144
145
        SendPacketEvent event = new SendPacketEvent(this, packet);
        event.call();
github-actions's avatar
github-actions committed
146
147
148
149
150
151
152
153
154
        if (!event.isCanceled()) { // If event is not cancelled, continue.
            tunnel.writeData(event.getPacket().build());
        }
    }

    @Override
    public void onConnected(GameSessionManager.KcpTunnel tunnel) {
        this.tunnel = tunnel;
        Grasscutter.getLogger().info(translate("messages.game.connect", this.getAddress().toString()));
Melledy's avatar
Melledy committed
155
    }
156

github-actions's avatar
github-actions committed
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177

    @Override
    public void handleReceive(byte[] bytes) {
        // Decrypt and turn back into a packet
        Crypto.xor(bytes, useSecretKey() ? Crypto.ENCRYPT_KEY : Crypto.DISPATCH_KEY);
        ByteBuf packet = Unpooled.wrappedBuffer(bytes);

        // Log
        //logPacket(packet);
        // Handle
        try {
            boolean allDebug = GAME_INFO.logPackets == ServerDebugMode.ALL;
            while (packet.readableBytes() > 0) {
                // Length
                if (packet.readableBytes() < 12) {
                    return;
                }
                // Packet sanity check
                int const1 = packet.readShort();
                if (const1 != 17767) {
                    if (allDebug) {
178
                        Grasscutter.getLogger().error("Bad Data Package Received: got {} ,expect 17767", const1);
github-actions's avatar
github-actions committed
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
                    }
                    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) {
                    if (allDebug) {
195
                        Grasscutter.getLogger().error("Bad Data Package Received: got {} ,expect -30293", const2);
github-actions's avatar
github-actions committed
196
197
198
199
200
201
202
203
                    }
                    return; // Bad packet
                }

                // Log packet
                switch (GAME_INFO.logPackets) {
                    case ALL -> {
                        if (!PacketOpcodesUtils.LOOP_PACKETS.contains(opcode)) {
204
                            logPacket("RECV", opcode, payload);
205
                        }
github-actions's avatar
github-actions committed
206
                    }
207
                    case WHITELIST -> {
github-actions's avatar
github-actions committed
208
                        if (SERVER.debugWhitelist.contains(opcode)) {
209
                            logPacket("RECV", opcode, payload);
github-actions's avatar
github-actions committed
210
211
                        }
                    }
212
                    case BLACKLIST -> {
github-actions's avatar
github-actions committed
213
                        if (!(SERVER.debugBlacklist.contains(opcode))) {
214
                            logPacket("RECV", opcode, payload);
github-actions's avatar
github-actions committed
215
216
                        }
                    }
217
218
                    default -> {
                    }
github-actions's avatar
github-actions committed
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
                }

                // Handle
                getServer().getPacketHandler().handle(this, opcode, header, payload);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //byteBuf.release(); //Needn't
            packet.release();
        }
    }

    @Override
    public void handleClose() {
        setState(SessionState.INACTIVE);
        //send disconnection pack in case of reconnection
        Grasscutter.getLogger().info(translate("messages.game.disconnect", this.getAddress().toString()));
        // Save after disconnecting
        if (this.isLoggedIn()) {
            Player player = getPlayer();
            // Call logout event.
            player.onLogout();
        }
        try {
            send(new BasePacket(PacketOpcodes.ServerDisconnectClientNotify));
245
246
        } catch (Throwable ignore) {
            Grasscutter.getLogger().warn("closing {} error", getAddress().getAddress().getHostAddress());
github-actions's avatar
github-actions committed
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
        }
        tunnel = null;
    }

    public void close() {
        tunnel.close();
    }

    public boolean isActive() {
        return getState() == SessionState.ACTIVE;
    }

    public enum SessionState {
        INACTIVE,
        WAITING_FOR_TOKEN,
        WAITING_FOR_LOGIN,
        PICKING_CHARACTER,
264
265
        ACTIVE,
        ACCOUNT_BANNED
github-actions's avatar
github-actions committed
266
    }
Melledy's avatar
Melledy committed
267
}