PacketOpcodesUtils.java 2.22 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package emu.grasscutter.net.packet;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;

import emu.grasscutter.GameConstants;
import emu.grasscutter.Grasscutter;
15
import emu.grasscutter.utils.Utils;
16
17
18
19
20
21
22
23
24
25
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;

public class PacketOpcodesUtils {
    private static Int2ObjectMap<String> opcodeMap;

    public static final Set<Integer> BANNED_PACKETS = Set.of(
        PacketOpcodes.WindSeedClientNotify,
        PacketOpcodes.PlayerLuaShellNotify
    );
github-actions's avatar
github-actions committed
26

27
28
29
30
31
32
33
34
    public static final Set<Integer> LOOP_PACKETS = Set.of(
        PacketOpcodes.PingReq,
        PacketOpcodes.PingRsp,
        PacketOpcodes.WorldPlayerRTTNotify,
        PacketOpcodes.UnionCmdNotify,
        PacketOpcodes.QueryPathReq
    );

github-actions's avatar
github-actions committed
35
36
37
38
    static {
        opcodeMap = new Int2ObjectOpenHashMap<String>();

        Field[] fields = PacketOpcodes.class.getFields();
39

github-actions's avatar
github-actions committed
40
41
42
43
44
45
46
47
48
49
        for (Field f : fields) {
            if (f.getType().equals(int.class)) {
                try {
                    opcodeMap.put(f.getInt(null), f.getName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
50

github-actions's avatar
github-actions committed
51
52
53
54
    public static String getOpcodeName(int opcode) {
        if (opcode <= 0) return "UNKNOWN";
        return opcodeMap.getOrDefault(opcode, "UNKNOWN");
    }
55

github-actions's avatar
github-actions committed
56
57
58
59
60
61
62
    public static void dumpPacketIds() {
        try (FileWriter writer = new FileWriter("./PacketIds_" + GameConstants.VERSION + ".json")) {
            // Create sorted tree map
            Map<Integer, String> packetIds = opcodeMap.int2ObjectEntrySet().stream()
                    .filter(e -> e.getIntKey() > 0)
                    .collect(Collectors.toMap(Int2ObjectMap.Entry::getIntKey, Int2ObjectMap.Entry::getValue, (k, v) -> v, TreeMap::new));
            // Write to file
63
            writer.write(Utils.jsonEncode(packetIds));
github-actions's avatar
github-actions committed
64
65
66
67
68
            Grasscutter.getLogger().info("Dumped packet ids.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
69
}