Skip to content

Commit

Permalink
Fix long NBT tag encoding for >32768 bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
eigenraven committed Jan 2, 2024
1 parent 618ab88 commit e1f0a71
Showing 1 changed file with 54 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -1,20 +1,67 @@
package com.mitchej123.hodgepodge.mixins.early.minecraft;

import java.io.IOException;

import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTSizeTracker;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.PacketBuffer;

import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.ModifyArg;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Unique;

import com.mitchej123.hodgepodge.Common;

@Mixin(PacketBuffer.class)
public class MixinPacketBuffer {

@ModifyArg(
method = "Lnet/minecraft/network/PacketBuffer;readNBTTagCompoundFromBuffer()Lnet/minecraft/nbt/NBTTagCompound;",
at = @At(value = "INVOKE", target = "Lnet/minecraft/nbt/NBTSizeTracker;<init>(J)V"))
private long hodgepodge$modifyMaxNetworkNBTSizeLimit(long original) {
return Common.config.maxNetworkNbtSizeLimit;
// A magic value that means the real length of the packet is encoded in a following int.
@Unique
private static final short MAGIC_LENGTH_IS_INT = Short.MAX_VALUE;

/**
* @author eigenraven
* @reason Change the length encoding to support values longer than a short, requires changing of local variable
* types.
*/
@Overwrite
public NBTTagCompound readNBTTagCompoundFromBuffer() throws IOException {
final PacketBuffer self = (PacketBuffer) (Object) this;
short shortLength = self.readShort();
final int realLength;
if (shortLength < 0) {
return null;
} else if (shortLength == MAGIC_LENGTH_IS_INT) {
realLength = self.readInt();
} else {
realLength = shortLength;
}
byte[] buffer = new byte[shortLength];
self.readBytes(buffer);
return CompressedStreamTools.func_152457_a(buffer, new NBTSizeTracker(Common.config.maxNetworkNbtSizeLimit));
}

/**
* @author eigenraven
* @reason Change the length encoding to support values longer than a short, requires changing of local variable
* types.
*/
@Overwrite
public void writeNBTTagCompoundToBuffer(NBTTagCompound nbt) throws IOException {
final PacketBuffer self = (PacketBuffer) (Object) this;
if (nbt == null) {
self.writeShort(-1);
} else {
byte[] buffer = CompressedStreamTools.compress(nbt);
if (buffer.length >= MAGIC_LENGTH_IS_INT) {
self.writeShort(MAGIC_LENGTH_IS_INT);
self.writeInt(buffer.length);
} else {
self.writeShort(buffer.length);
}
self.writeBytes(buffer);
}
}

}

0 comments on commit e1f0a71

Please sign in to comment.