packet-logger module

packet-logger: Minecraft 26.3 cheat module, full source for every implementation (1 client: Meteor Client).

1 implementationMisc

Clients with this module

Full module source: 1 implementation

Every implementation below is the complete module file, verbatim. Expand a client to read its code.

Meteor ClientMiscsrc/main/java/meteordevelopment/meteorclient/systems/modules/misc/PacketLogger.javaJava · 298 lines · 10.7 KB

Allows you to log certain packets.

SettingsS2C-packetsC2S-packetsshow-timestampshow-packet-datashow-countshow-summarylog-to-chatlog-to-fileflush-intervalmax-file-size-mbmax-total-logs-mb
PacketLogger.javaJava · Minecraft 26.2 · 298 lines · 10.7 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of the Meteor Client distribution (https://github.com/MeteorDevelopment/meteor-client).
3
 * Copyright (c) Meteor Development.
4
 */
5
6
package meteordevelopment.meteorclient.systems.modules.misc;
7
8
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
9
import meteordevelopment.meteorclient.MeteorClient;
10
import meteordevelopment.meteorclient.events.packets.PacketEvent;
11
import meteordevelopment.meteorclient.settings.*;
12
import meteordevelopment.meteorclient.systems.modules.Categories;
13
import meteordevelopment.meteorclient.systems.modules.Module;
14
import meteordevelopment.orbit.EventHandler;
15
import meteordevelopment.orbit.EventPriority;
16
import net.minecraft.network.protocol.Packet;
17
import net.minecraft.network.protocol.PacketType;
18
import org.jspecify.annotations.NullMarked;
19
import org.jspecify.annotations.Nullable;
20
21
import java.io.BufferedWriter;
22
import java.io.IOException;
23
import java.nio.charset.StandardCharsets;
24
import java.nio.file.Files;
25
import java.nio.file.Path;
26
import java.nio.file.StandardOpenOption;
27
import java.time.LocalDateTime;
28
import java.time.format.DateTimeFormatter;
29
import java.util.ArrayList;
30
import java.util.Comparator;
31
import java.util.List;
32
import java.util.Set;
33
34
@NullMarked
35
public class PacketLogger extends Module {
36
    private final SettingGroup sgGeneral = settings.getDefaultGroup();
37
    private final SettingGroup sgOutput = settings.createGroup("Output");
38
39
    private final Setting<Set<PacketType<? extends Packet<?>>>> s2cPackets = sgGeneral.add(new PacketListSetting.Builder()
40
        .name("S2C-packets")
41
        .description("Server-to-client packets to log.")
42
        .clientbound()
43
        .build()
44
    );
45
46
    private final Setting<Set<PacketType<? extends Packet<?>>>> c2sPackets = sgGeneral.add(new PacketListSetting.Builder()
47
        .name("C2S-packets")
48
        .description("Client-to-server packets to log.")
49
        .serverbound()
50
        .build()
51
    );
52
53
    private final Setting<Boolean> showTimestamp = sgOutput.add(new BoolSetting.Builder()
54
        .name("show-timestamp")
55
        .description("Show timestamp for each logged packet.")
56
        .defaultValue(true)
57
        .build()
58
    );
59
60
    private final Setting<Boolean> showPacketData = sgOutput.add(new BoolSetting.Builder()
61
        .name("show-packet-data")
62
        .description("Show the packet's toString() data for debugging.")
63
        .defaultValue(false)
64
        .build()
65
    );
66
67
    private final Setting<Boolean> showCount = sgOutput.add(new BoolSetting.Builder()
68
        .name("show-count")
69
        .description("Show how many times each packet type has been logged.")
70
        .defaultValue(true)
71
        .build()
72
    );
73
74
    private final Setting<Boolean> showSummary = sgOutput.add(new BoolSetting.Builder()
75
        .name("show-summary")
76
        .description("Show final packet count summary when module is deactivated.")
77
        .defaultValue(true)
78
        .build()
79
    );
80
81
    private final Setting<Boolean> logToChat = sgOutput.add(new BoolSetting.Builder()
82
        .name("log-to-chat")
83
        .description("Log packets to chat.")
84
        .defaultValue(true)
85
        .build()
86
    );
87
88
    // File logging settings
89
90
    private final Setting<Boolean> logToFile = sgOutput.add(new BoolSetting.Builder()
91
        .name("log-to-file")
92
        .description("Save packet logs to a file in the meteor-client folder.")
93
        .defaultValue(false)
94
        .build()
95
    );
96
97
    private final Setting<Integer> flushInterval = sgOutput.add(new IntSetting.Builder()
98
        .name("flush-interval")
99
        .description("How often to flush logs to disk (in seconds).")
100
        .defaultValue(1)
101
        .min(1)
102
        .sliderMax(10)
103
        .visible(logToFile::get)
104
        .build()
105
    );
106
107
    private final Setting<Integer> maxFileSizeMB = sgOutput.add(new IntSetting.Builder()
108
        .name("max-file-size-mb")
109
        .description("Maximum size per log file in MB. Creates new file when exceeded.")
110
        .defaultValue(10)
111
        .min(1)
112
        .sliderMax(100)
113
        .visible(logToFile::get)
114
        .build()
115
    );
116
117
    private final Setting<Integer> maxTotalLogsMB = sgOutput.add(new IntSetting.Builder()
118
        .name("max-total-logs-mb")
119
        .description("Maximum total disk space for all packet logs in MB. Deletes oldest when exceeded.")
120
        .defaultValue(50)
121
        .min(1)
122
        .sliderMax(500)
123
        .visible(logToFile::get)
124
        .build()
125
    );
126
127
    private static final Path PACKET_LOGS_DIR = MeteorClient.FOLDER.toPath().resolve("packet-logs");
128
    private static final int LINE_SEPARATOR_BYTES = System.lineSeparator().getBytes(StandardCharsets.UTF_8).length;
129
    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");
130
    private static final DateTimeFormatter FILE_NAME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss");
131
    private final Object2IntOpenHashMap<PacketType<? extends Packet<?>>> packetCounts = new Object2IntOpenHashMap<>();
132
    private @Nullable BufferedWriter fileWriter;
133
    private long lastFlushMs;
134
    private long currentFileSizeBytes;
135
    private int currentFileIndex;
136
    private @Nullable LocalDateTime sessionStartTime;
137
138
    public PacketLogger() {
139
        super(Categories.Misc, "packet-logger", "Allows you to log certain packets.");
140
        runInMainMenu = true;
141
    }
142
143
    @Override
144
    public void onActivate() {
145
        closeFileWriter();
146
147
        packetCounts.clear();
148
        lastFlushMs = System.currentTimeMillis();
149
        sessionStartTime = LocalDateTime.now();
150
        currentFileIndex = 0;
151
        currentFileSizeBytes = 0;
152
153
        if (logToFile.get()) {
154
            try {
155
                Files.createDirectories(PACKET_LOGS_DIR);
156
                cleanupOldLogs();
157
                openNewLogFile();
158
            } catch (IOException e) {
159
                error("Failed to initialize packet logging: %s", e.getMessage());
160
                fileWriter = null;
161
            }
162
        }
163
    }
164
165
    @Override
166
    public void onDeactivate() {
167
        if (showSummary.get() && !packetCounts.isEmpty()) {
168
            logSummary();
169
        }
170
        closeFileWriter();
171
    }
172
173
    private void logPacket(String direction, Packet<?> packet) {
174
        if (!logToChat.get() && !logToFile.get()) return;
175
176
        // Update count
177
        packetCounts.addTo(packet.type(), 1);
178
179
        // Build log message
180
        StringBuilder msg = new StringBuilder(128);
181
        if (showTimestamp.get()) msg.append("[").append(LocalDateTime.now().format(TIME_FORMATTER)).append("] ");
182
        msg.append(direction).append(" ").append(packet.type());
183
        if (showCount.get()) msg.append(" (#").append(packetCounts.getInt(packet.type())).append(")");
184
        if (showPacketData.get()) msg.append("\n  Data: ").append(packet);
185
186
        // Log to chat and/or file
187
        String line = msg.toString();
188
        if (logToChat.get()) info(line);
189
        if (logToFile.get()) writeLine(line);
190
    }
191
192
    private void logSummary() {
193
        int totalPackets = packetCounts.values().intStream().sum();
194
195
        List<String> lines = new ArrayList<>();
196
        lines.add("--- SUMMARY ---");
197
        lines.add("Final packet counts (total " + totalPackets + "):");
198
199
        packetCounts.object2IntEntrySet().stream()
200
            .sorted((a, b) -> Integer.compare(b.getIntValue(), a.getIntValue()))
201
            .forEach(e -> lines.add("  %s: %d".formatted(e.getKey().toString(), e.getIntValue())));
202
203
        for (String line : lines) {
204
            if (logToChat.get()) info(line);
205
            if (logToFile.get()) writeLine(line);
206
        }
207
    }
208
209
    private void writeLine(String line) {
210
        if (fileWriter == null) return;
211
212
        try {
213
            int lineBytes = line.getBytes(StandardCharsets.UTF_8).length + LINE_SEPARATOR_BYTES;
214
            if (currentFileSizeBytes + lineBytes > maxFileSizeMB.get() * 1024L * 1024L) openNewLogFile();
215
216
            fileWriter.write(line);
217
            fileWriter.newLine();
218
            currentFileSizeBytes += lineBytes;
219
220
            long now = System.currentTimeMillis();
221
            if (now - lastFlushMs >= flushInterval.get() * 1000L) {
222
                fileWriter.flush();
223
                lastFlushMs = now;
224
            }
225
        } catch (IOException e) {
226
            error("Failed to write to packet log file: %s. File logging disabled.", e.getMessage());
227
            closeFileWriter();
228
        }
229
    }
230
231
    private void openNewLogFile() throws IOException {
232
        if (fileWriter != null) fileWriter.close();
233
        if (sessionStartTime == null) sessionStartTime = LocalDateTime.now();
234
235
        String fileName = "packets-%s-%d.log".formatted(sessionStartTime.format(FILE_NAME_FORMATTER), currentFileIndex++);
236
        fileWriter = Files.newBufferedWriter(
237
            PACKET_LOGS_DIR.resolve(fileName),
238
            StandardCharsets.UTF_8,
239
            StandardOpenOption.CREATE,
240
            StandardOpenOption.WRITE
241
        );
242
        currentFileSizeBytes = 0;
243
        cleanupOldLogs();
244
    }
245
246
    private void closeFileWriter() {
247
        if (fileWriter != null) {
248
            try {
249
                fileWriter.flush();
250
                fileWriter.close();
251
            } catch (IOException _) {
252
                // Safe to ignore on close or rotation
253
            }
254
            fileWriter = null;
255
        }
256
    }
257
258
    /**
259
     * Cleans up old log files if total size exceeds the maximum limit.
260
     * Deletes oldest files first.
261
     */
262
    private void cleanupOldLogs() throws IOException {
263
        long maxBytes = maxTotalLogsMB.get() * 1024L * 1024L;
264
        List<LogFileEntry> logFiles = new ArrayList<>();
265
        try (var stream = Files.list(PACKET_LOGS_DIR)) {
266
            for (Path p : stream.toList()) {
267
                String name = p.getFileName().toString();
268
                if (!name.startsWith("packets-") || !name.endsWith(".log")) continue;
269
                try {
270
                    logFiles.add(new LogFileEntry(p, Files.size(p), Files.getLastModifiedTime(p).toMillis()));
271
                } catch (IOException _) {
272
                    // Skip files that can't be accessed
273
                }
274
            }
275
        }
276
277
        logFiles.sort(Comparator.comparingLong(LogFileEntry::lastModified));
278
        long totalSize = 0;
279
        for (LogFileEntry entry : logFiles) {
280
            totalSize += entry.size();
281
            if (totalSize > maxBytes) Files.deleteIfExists(entry.path());
282
        }
283
    }
284
285
    private record LogFileEntry(Path path, long size, long lastModified) {
286
    }
287
288
    @EventHandler(priority = EventPriority.HIGHEST + 1)
289
    private void onReceivePacket(PacketEvent.Receive event) {
290
        if (s2cPackets.get().contains(event.packet.type())) logPacket("<- S2C", event.packet);
291
    }
292
293
    @EventHandler(priority = EventPriority.HIGHEST + 1)
294
    private void onSendPacket(PacketEvent.Send event) {
295
        if (c2sPackets.get().contains(event.packet.type())) logPacket("-> C2S", event.packet);
296
    }
297
}
298