PacketLogger module

PacketLogger: Minecraft 26.3 cheat module, full source for every implementation (2 clients: OfflineClient, LiquidBounce (Kotlin)).

2 implementationsMISC

Full module source: 2 implementations

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

OfflineClientMISCsrc/main/java/com/jellypudding/offlineclient/modules/misc/PacketLogger.javaJava · 281 lines · 10.3 KB

Writes the packets you pick to chat or to a file.

SettingsIncomingOutgoingTimestampShow dataShow countShow summaryLog to chatLog to fileFlush intervalMax file sizeMax total size
PacketLogger.javaJava · Minecraft 26.2 · 281 lines · 10.3 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.misc;
2
3
import com.jellypudding.offlineclient.OfflineClient;
4
import com.jellypudding.offlineclient.event.Subscribe;
5
import com.jellypudding.offlineclient.event.events.ClientTickEvent;
6
import com.jellypudding.offlineclient.event.events.PacketReceiveEvent;
7
import com.jellypudding.offlineclient.event.events.PacketSendEvent;
8
import com.jellypudding.offlineclient.module.Category;
9
import com.jellypudding.offlineclient.module.Module;
10
import com.jellypudding.offlineclient.setting.BoolSetting;
11
import com.jellypudding.offlineclient.setting.ChoiceListSetting;
12
import com.jellypudding.offlineclient.setting.NumberSetting;
13
import com.jellypudding.offlineclient.util.ChatUtil;
14
import com.jellypudding.offlineclient.util.PacketNames;
15
import net.minecraft.ChatFormatting;
16
import net.minecraft.network.chat.ClickEvent;
17
import net.minecraft.network.chat.Component;
18
import net.minecraft.network.protocol.Packet;
19
20
import java.io.IOException;
21
import java.io.UncheckedIOException;
22
import java.nio.file.Files;
23
import java.nio.file.Path;
24
import java.nio.file.StandardOpenOption;
25
import java.time.LocalDate;
26
import java.time.LocalTime;
27
import java.time.format.DateTimeFormatter;
28
import java.util.ArrayList;
29
import java.util.Comparator;
30
import java.util.List;
31
import java.util.Map;
32
import java.util.concurrent.ConcurrentHashMap;
33
import java.util.concurrent.ConcurrentLinkedQueue;
34
import java.util.concurrent.atomic.AtomicInteger;
35
import java.util.stream.Stream;
36
37
// Prints or files every packet of the kinds you pick.
38
public final class PacketLogger extends Module {
39
40
    private static final DateTimeFormatter CLOCK = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");
41
42
    private static final int MEGABYTE = 1024 * 1024;
43
44
    // Lines held whilst the game thread is busy. Anything past this is dropped.
45
    private static final int MAX_PENDING = 8192;
46
47
    private final ChoiceListSetting incoming = new ChoiceListSetting("Incoming",
48
        "Kinds of packet from the server to log. Click to pick them.", PacketNames::incoming);
49
    private final ChoiceListSetting outgoing = new ChoiceListSetting("Outgoing",
50
        "Kinds of packet to the server to log. Click to pick them.", PacketNames::outgoing);
51
    private final BoolSetting timestamp = new BoolSetting("Timestamp",
52
        "Puts the time in front of every line.", true);
53
    private final BoolSetting showData = new BoolSetting("Show data",
54
        "Adds the contents of the packet to the line.", false);
55
    private final BoolSetting showCount = new BoolSetting("Show count",
56
        "Adds the running count for that kind to the line.", true);
57
    private final BoolSetting showSummary = new BoolSetting("Show summary",
58
        "Prints a count for every kind when the module is switched off.", true);
59
    private final BoolSetting toChat = new BoolSetting("Log to chat",
60
        "Prints each line into your chat.", true);
61
    private final BoolSetting toFile = new BoolSetting("Log to file",
62
        "Writes each line into offlineclient/packet-logs inside your game folder.", false);
63
    private final NumberSetting flushSeconds = new NumberSetting("Flush interval",
64
        "Seconds between one write to the file and the next.", 1, 1, 10, 1, "s").min(1).max(60)
65
        .under(toFile);
66
    private final NumberSetting maxFileSize = new NumberSetting("Max file size",
67
        "A new file is started once this one gets bigger.", 10, 1, 100, 1, " MB").min(1).max(1000)
68
        .under(toFile);
69
    private final NumberSetting maxTotalSize = new NumberSetting("Max total size",
70
        "The oldest files are deleted once the folder gets bigger.", 50, 1, 500, 1, " MB")
71
        .min(1).max(10000)
72
        .under(toFile);
73
74
    // Filled from the netty thread and drained on the main thread.
75
    private final ConcurrentLinkedQueue<String> pending = new ConcurrentLinkedQueue<>();
76
    private final AtomicInteger held = new AtomicInteger();
77
    private final Map<String, AtomicInteger> counts = new ConcurrentHashMap<>();
78
79
    private final List<String> buffer = new ArrayList<>();
80
    private Path file;
81
    private long written;
82
    private int flushTimer;
83
84
    public PacketLogger() {
85
        super("PacketLogger", "Writes the packets you pick to chat or to a file.", Category.MISC);
86
        addSettings(incoming, outgoing, timestamp, showData, showCount, showSummary, toChat,
87
            toFile, flushSeconds, maxFileSize, maxTotalSize);
88
        searchTags("packet log", "network log", "sniffer");
89
    }
90
91
    @Override
92
    public String getSuffix() {
93
        int total = 0;
94
        for (AtomicInteger count : counts.values()) {
95
            total += count.get();
96
        }
97
        return count(total);
98
    }
99
100
    @Override
101
    protected void onEnable() {
102
        pending.clear();
103
        held.set(0);
104
        counts.clear();
105
        buffer.clear();
106
        file = null;
107
        written = 0;
108
        flushTimer = 0;
109
    }
110
111
    @Override
112
    protected void onDisable() {
113
        drain();
114
        flush();
115
        if (showSummary.isOn()) {
116
            summarise();
117
        }
118
        pending.clear();
119
        held.set(0);
120
        counts.clear();
121
        buffer.clear();
122
        file = null;
123
    }
124
125
    private void summarise() {
126
        List<Map.Entry<String, AtomicInteger>> rows = new ArrayList<>(counts.entrySet());
127
        rows.sort(Comparator.comparingInt((Map.Entry<String, AtomicInteger> row)
128
            -> row.getValue().get()).reversed());
129
        for (Map.Entry<String, AtomicInteger> row : rows) {
130
            ChatUtil.message("§b" + row.getValue().get() + " §7" + row.getKey());
131
        }
132
    }
133
134
    @Subscribe
135
    private void onPacketReceive(PacketReceiveEvent event) {
136
        record(event.getPacket(), incoming, "in");
137
    }
138
139
    @Subscribe
140
    private void onPacketSend(PacketSendEvent event) {
141
        record(event.getPacket(), outgoing, "out");
142
    }
143
144
    // Fired on the netty thread. Only the line is built here.
145
    private void record(Packet<?> packet, ChoiceListSetting picked, String direction) {
146
        String name = packet.type().id().toString();
147
        if (!picked.contains(name)) {
148
            return;
149
        }
150
        int count = counts.computeIfAbsent(direction + " " + name, key -> new AtomicInteger())
151
            .incrementAndGet();
152
        StringBuilder line = new StringBuilder();
153
        if (timestamp.isOn()) {
154
            line.append('[').append(LocalTime.now().format(CLOCK)).append("] ");
155
        }
156
        line.append(direction).append(' ').append(name);
157
        if (showCount.isOn()) {
158
            line.append(" x").append(count);
159
        }
160
        if (showData.isOn()) {
161
            line.append(' ').append(packet);
162
        }
163
        if (held.incrementAndGet() > MAX_PENDING) {
164
            held.decrementAndGet();
165
            return;
166
        }
167
        pending.add(line.toString());
168
    }
169
170
    @Subscribe
171
    private void onClientTick(ClientTickEvent event) {
172
        drain();
173
    }
174
175
    private void drain() {
176
        String line;
177
        while ((line = pending.poll()) != null) {
178
            held.decrementAndGet();
179
            if (toChat.isOn()) {
180
                ChatUtil.message("§7" + line);
181
            }
182
            if (toFile.isOn()) {
183
                buffer.add(line);
184
            }
185
        }
186
        if (buffer.isEmpty()) {
187
            flushTimer = 0;
188
            return;
189
        }
190
        if (++flushTimer < flushSeconds.getInt() * 20) {
191
            return;
192
        }
193
        flush();
194
    }
195
196
    private void flush() {
197
        flushTimer = 0;
198
        if (buffer.isEmpty()) {
199
            return;
200
        }
201
        write(buffer);
202
        buffer.clear();
203
    }
204
205
    private void write(List<String> lines) {
206
        StringBuilder text = new StringBuilder();
207
        for (String line : lines) {
208
            text.append(line).append(System.lineSeparator());
209
        }
210
        try {
211
            Path folder = folder();
212
            Files.createDirectories(folder);
213
            if (file == null || written > maxFileSize.getInt() * (long) MEGABYTE) {
214
                file = nextFile(folder);
215
                written = 0;
216
                announce(file);
217
            }
218
            byte[] bytes = text.toString().getBytes(java.nio.charset.StandardCharsets.UTF_8);
219
            Files.write(file, bytes, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
220
            written += bytes.length;
221
            prune(folder);
222
        } catch (IOException | UncheckedIOException error) {
223
            OfflineClient.LOG.error("Failed to write the packet log", error);
224
        }
225
    }
226
227
    // Says which file is being written. Clicking the line opens the folder.
228
    private static void announce(Path file) {
229
        Path game = OfflineClient.MC.gameDirectory.toPath();
230
        Component where = Component.literal(game.relativize(file).toString().replace('\\', '/'))
231
            .withStyle(style -> style.withColor(ChatFormatting.WHITE)
232
                .withClickEvent(new ClickEvent.OpenFile(file.getParent())));
233
        ChatUtil.component(Component.literal("§bPacketLogger §7is writing to ").append(where));
234
    }
235
236
    private static Path folder() {
237
        return OfflineClient.MC.gameDirectory.toPath().resolve("offlineclient")
238
            .resolve("packet-logs");
239
    }
240
241
    private static Path nextFile(Path folder) throws IOException {
242
        String stem = "packets-" + LocalDate.now();
243
        for (int i = 1; ; i++) {
244
            Path candidate = folder.resolve(stem + "-" + i + ".log");
245
            if (!Files.exists(candidate)) {
246
                return candidate;
247
            }
248
        }
249
    }
250
251
    // The oldest files go once the folder outgrows the allowance.
252
    private void prune(Path folder) throws IOException {
253
        long allowance = maxTotalSize.getInt() * (long) MEGABYTE;
254
        List<Path> files = new ArrayList<>();
255
        try (Stream<Path> stream = Files.list(folder)) {
256
            stream.filter(Files::isRegularFile).forEach(files::add);
257
        }
258
        long total = 0;
259
        for (Path each : files) {
260
            total += Files.size(each);
261
        }
262
        if (total <= allowance) {
263
            return;
264
        }
265
        files.sort(Comparator.comparing(each -> {
266
            try {
267
                return Files.getLastModifiedTime(each);
268
            } catch (IOException error) {
269
                throw new UncheckedIOException(error);
270
            }
271
        }));
272
        for (Path each : files) {
273
            if (total <= allowance || each.equals(file)) {
274
                continue;
275
            }
276
            total -= Files.size(each);
277
            Files.deleteIfExists(each);
278
        }
279
    }
280
}
281
LiquidBounce (Kotlin)MISCsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/misc/ModulePacketLogger.ktKotlin · 271 lines · 10.0 KB

Prints all packets and their fields.

SettingsFilterC2SPacketsS2CPacketsShowFieldTypeOutputTarget
ModulePacketLogger.ktKotlin · Minecraft 26.2 · 271 lines · 10.0 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of LiquidBounce (https://github.com/CCBlueX/LiquidBounce)
3
 *
4
 * Copyright (c) 2015 - 2026 CCBlueX
5
 *
6
 * LiquidBounce is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * LiquidBounce is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with LiquidBounce. If not, see <https://www.gnu.org/licenses/>.
18
 */
19
package net.ccbluex.liquidbounce.features.module.modules.misc
20
21
import kotlinx.atomicfu.atomic
22
import net.ccbluex.fastutil.mapToArray
23
import net.ccbluex.liquidbounce.config.ConfigSystem
24
import net.ccbluex.liquidbounce.config.gson.adapter.toUnderlinedString
25
import net.ccbluex.liquidbounce.config.types.list.Tagged
26
import net.ccbluex.liquidbounce.event.events.PacketEvent
27
import net.ccbluex.liquidbounce.event.events.TransferOrigin
28
import net.ccbluex.liquidbounce.event.handler
29
import net.ccbluex.liquidbounce.features.misc.SelfDestruct.isDestructed
30
import net.ccbluex.liquidbounce.features.module.ClientModule
31
import net.ccbluex.liquidbounce.features.module.ModuleCategories
32
import net.ccbluex.liquidbounce.utils.client.MessageMetadata
33
import net.ccbluex.liquidbounce.utils.text.asPlainText
34
import net.ccbluex.liquidbounce.utils.text.asText
35
import net.ccbluex.liquidbounce.utils.client.bold
36
import net.ccbluex.liquidbounce.utils.client.chat
37
import net.ccbluex.liquidbounce.utils.client.copyable
38
import net.ccbluex.liquidbounce.utils.client.highlight
39
import net.ccbluex.liquidbounce.utils.client.regular
40
import net.ccbluex.liquidbounce.utils.client.toName
41
import net.ccbluex.liquidbounce.utils.client.variable
42
import net.ccbluex.liquidbounce.utils.collection.Filter
43
import net.ccbluex.liquidbounce.utils.kotlin.EventPriorityConvention
44
import net.ccbluex.liquidbounce.utils.kotlin.isNotRoot
45
import net.ccbluex.liquidbounce.utils.kotlin.toFullString
46
import net.ccbluex.liquidbounce.utils.text.PlainText
47
import net.ccbluex.liquidbounce.utils.text.buildText
48
import net.minecraft.ChatFormatting
49
import net.minecraft.network.chat.MutableComponent
50
import net.minecraft.network.protocol.Packet
51
import net.minecraft.resources.Identifier
52
import okio.appendingSink
53
import okio.buffer
54
import java.io.File
55
import java.lang.reflect.Field
56
import java.lang.reflect.Modifier
57
import java.lang.reflect.Type
58
import java.time.LocalDateTime
59
import java.util.concurrent.ConcurrentHashMap
60
61
/**
62
 * Module PacketLogger
63
 *
64
 * Prints all packets and their fields.
65
 *
66
 * @author ccetl
67
 */
68
object ModulePacketLogger : ClientModule("PacketLogger", ModuleCategories.MISC) {
69
70
    private val filter by enumChoice("Filter", Filter.BLACKLIST)
71
    private val clientPackets by c2sPackets("C2SPackets", sortedSetOf())
72
    private val serverPackets by s2cPackets("S2CPackets", sortedSetOf())
73
    private val showFieldType by boolean("ShowFieldType", true)
74
75
    private val outputTarget by multiEnumChoice("OutputTarget", OutputTarget.CHAT, canBeNone = false).onChanged {
76
        if (OutputTarget.FILE in it) {
77
            createFileIfNeeded()
78
        }
79
    }
80
81
    private val outputDir = ConfigSystem.rootFolder.resolve("packet-logger").apply { mkdirs() }
82
83
    private val classNames = ConcurrentHashMap<Class<out Packet<*>>, String>()
84
    private val fieldNames = ConcurrentHashMap<Field, String>()
85
86
    init {
87
        // Do not include this module in the auto config, as this is for debugging purposes only.
88
        doNotIncludeAlways()
89
    }
90
91
    private val outputFile = atomic<File?>(null)
92
93
    private fun createFileIfNeeded() {
94
        outputFile.compareAndSet(
95
            expect = null,
96
            update = outputDir.resolve("${LocalDateTime.now().toUnderlinedString()}.csv"),
97
        )
98
    }
99
100
    override fun onEnabled() {
101
        createFileIfNeeded()
102
        super.onEnabled()
103
    }
104
105
    override fun onDisabled() {
106
        outputFile.value = null
107
        classNames.clear()
108
        fieldNames.clear()
109
    }
110
111
    @Suppress("unused")
112
    private val packetHandler = handler<PacketEvent>(priority = EventPriorityConvention.READ_FINAL_STATE) { event ->
113
        onPacket(event.origin, event.packet, event.isCancelled)
114
    }
115
116
    fun onPacket(origin: TransferOrigin, packet: Packet<*>, canceled: Boolean = false) {
117
        if (!running) {
118
            return
119
        }
120
121
        val packetId = packet.type().id
122
        if (!filter(packetId, if (origin == TransferOrigin.INCOMING) serverPackets else clientPackets)) {
123
            return
124
        }
125
126
        outputTarget.forEach {
127
            it.handle(origin, packet, canceled, packetId)
128
        }
129
    }
130
131
    private enum class OutputTarget(override val tag: String) : Tagged {
132
        CHAT("Chat") {
133
            override fun handle(origin: TransferOrigin, packet: Packet<*>, canceled: Boolean, packetId: Identifier) {
134
                val clazz = packet.javaClass
135
136
                val packetClassName = clazz.name.substringAfterLast('.')
137
138
                val text = "".asText()
139
                if (origin == TransferOrigin.INCOMING) {
140
                    text.append(message("receive").withStyle(ChatFormatting.BLUE).bold(true))
141
                } else {
142
                    text.append(message("send").withStyle(ChatFormatting.GRAY).bold(true))
143
                }
144
145
                text.append(" ")
146
147
                text.append(highlight(packetClassName).copyable(copyContent = packetClassName))
148
149
                val packetName = packetId.toName()
150
151
                text.append(regular(" (ID: "))
152
                text.append(variable(packetName).copyable(copyContent = packetName))
153
                text.append(regular(")"))
154
155
                if (clazz.isRecord) {
156
                    text.append(" (Record)".asPlainText(ChatFormatting.DARK_GRAY))
157
                }
158
159
                if (canceled) {
160
                    text.append(" (".asPlainText(ChatFormatting.RED))
161
                    text.append(message("canceled").withStyle(ChatFormatting.RED))
162
                    text.append(")".asPlainText(ChatFormatting.RED))
163
                }
164
165
                text.appendFields(clazz, packet)
166
167
                chat(text, metadata = MessageMetadata(prefix = false))
168
            }
169
        },
170
171
        FILE("File") {
172
            override fun handle(origin: TransferOrigin, packet: Packet<*>, canceled: Boolean, packetId: Identifier) {
173
                val file = outputFile.value ?: return
174
175
                val clazz = packet.javaClass
176
177
                val packetClassName = clazz.name.substringAfterLast('.')
178
179
                file.appendingSink().buffer().use {
180
                    it.writeUtf8(System.currentTimeMillis().toString())
181
                        .writeByte(','.code)
182
                        .writeUtf8(origin.tag)
183
                        .writeByte(','.code)
184
                        .writeUtf8(packetClassName)
185
                        .writeByte(','.code)
186
                        .writeUtf8(packetId.toString())
187
                        .writeByte(','.code)
188
                        .writeUtf8(canceled.toString())
189
                        .writeByte(','.code)
190
                        .writeByte('"'.code)
191
192
                    collectFields(clazz, packet).forEach { (name, type, value) ->
193
                        it.writeUtf8(name)
194
                            .writeByte(':'.code)
195
                            .writeUtf8(type.toFullString())
196
                            .writeByte('='.code)
197
                            .writeUtf8(value.toString())
198
                            .writeByte(';'.code)
199
                    }
200
201
                    it.writeByte('"'.code).writeByte('\n'.code)
202
                }
203
            }
204
        };
205
206
        abstract fun handle(origin: TransferOrigin, packet: Packet<*>, canceled: Boolean, packetId: Identifier)
207
    }
208
209
    @JvmRecord
210
    private data class PacketField(val name: String, val type: Type, val value: Any?)
211
212
    private fun collectFields(clazz: Class<out Packet<*>>, packet: Packet<*>): List<PacketField> {
213
        val fields = mutableListOf<PacketField>()
214
215
        var currentClass: Class<*>? = clazz
216
217
        while (currentClass.isNotRoot()) {
218
            currentClass.declaredFields.forEach { field ->
219
                if (Modifier.isStatic(field.modifiers)) {
220
                    return@forEach
221
                }
222
223
                field.isAccessible = true
224
225
                val name = field.name
226
227
                val value = try {
228
                    field.get(packet)?.toString()
229
                } catch (@Suppress("SwallowedException") _: IllegalAccessException) {
230
                    "null"
231
                }
232
233
                fields += PacketField(name, field.genericType, value)
234
            }
235
236
            currentClass = currentClass.superclass
237
        }
238
239
        return fields
240
    }
241
242
    private fun MutableComponent.appendFields(clazz: Class<out Packet<*>>, packet: Packet<*>) {
243
        val fieldTexts = collectFields(clazz, packet).mapToArray { (name, type, value) ->
244
            buildText {
245
                add("- ".asPlainText(ChatFormatting.GRAY))
246
                add(name.asText().withStyle(ChatFormatting.AQUA).copyable(copyContent = name))
247
                if (showFieldType) {
248
                    add(": ".asPlainText(ChatFormatting.GRAY))
249
                    val typeString = type.toFullString()
250
                    add(typeString.asText().withStyle(ChatFormatting.YELLOW).copyable(copyContent = typeString))
251
                }
252
                add(" = ".asPlainText(ChatFormatting.GRAY))
253
                val valueString = value.toString()
254
                add(valueString.asText().withStyle(ChatFormatting.WHITE).copyable(copyContent = valueString))
255
            }
256
        }
257
258
        if (fieldTexts.isNotEmpty()) {
259
            append(":")
260
            fieldTexts.forEach {
261
                append(PlainText.NEW_LINE)
262
                append(it)
263
            }
264
        }
265
    }
266
267
    override val running: Boolean
268
        get() = !isDestructed && enabled
269
270
}
271