Minestom/src/main/java/net/minestom/server/utils/PacketUtils.java

295 lines
13 KiB
Java
Raw Normal View History

2020-04-24 03:25:58 +02:00
package net.minestom.server.utils;
2019-08-22 14:52:32 +02:00
2021-03-28 20:40:27 +02:00
import com.velocitypowered.natives.compression.VelocityCompressor;
import com.velocitypowered.natives.util.Natives;
2020-04-17 01:16:02 +02:00
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import net.minestom.server.MinecraftServer;
import net.minestom.server.adventure.AdventureSerializer;
import net.minestom.server.adventure.audience.PacketGroupingAudience;
import net.minestom.server.entity.Player;
import net.minestom.server.listener.manager.PacketListenerManager;
import net.minestom.server.network.netty.packet.FramedPacket;
2021-03-12 16:33:19 +01:00
import net.minestom.server.network.packet.server.ComponentHoldingServerPacket;
2020-04-24 03:25:58 +02:00
import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.network.player.NettyPlayerConnection;
import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.utils.binary.BinaryWriter;
import net.minestom.server.utils.callback.validator.PlayerValidator;
2020-11-05 22:20:51 +01:00
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
2019-08-22 14:52:32 +02:00
import java.util.Collection;
2021-03-28 20:40:27 +02:00
import java.util.zip.DataFormatException;
2020-08-15 04:05:15 +02:00
/**
2020-11-13 09:17:53 +01:00
* Utils class for packets. Including writing a {@link ServerPacket} into a {@link ByteBuf}
* for network processing.
2020-08-15 04:05:15 +02:00
*/
public final class PacketUtils {
private static final PacketListenerManager PACKET_LISTENER_MANAGER = MinecraftServer.getPacketListenerManager();
2021-03-28 20:40:27 +02:00
private static final ThreadLocal<VelocityCompressor> COMPRESSOR = ThreadLocal.withInitial(() -> Natives.compress.get().create(4));
private PacketUtils() {
}
2019-08-22 14:52:32 +02:00
/**
* Sends a packet to an audience. This method performs the following steps in the
* following order:
* <ol>
* <li>If {@code audience} is a {@link Player}, send the packet to them.</li>
* <li>Otherwise, if {@code audience} is a {@link PacketGroupingAudience}, call
* {@link #sendGroupedPacket(Collection, ServerPacket)} on the players that the
* grouping audience contains.</li>
* <li>Otherwise, if {@code audience} is a {@link ForwardingAudience.Single},
* call this method on the single audience inside the forwarding audience.</li>
* <li>Otherwise, if {@code audience} is a {@link ForwardingAudience}, call this
* method for each audience member of the forwarding audience.</li>
* <li>Otherwise, do nothing.</li>
* </ol>
*
* @param audience the audience
* @param packet the packet
*/
@SuppressWarnings("OverrideOnly") // we need to access the audiences inside ForwardingAudience
public static void sendPacket(@NotNull Audience audience, @NotNull ServerPacket packet) {
if (audience instanceof Player) {
((Player) audience).getPlayerConnection().sendPacket(packet);
} else if (audience instanceof PacketGroupingAudience) {
PacketUtils.sendGroupedPacket(((PacketGroupingAudience) audience).getPlayers(), packet);
} else if (audience instanceof ForwardingAudience.Single) {
PacketUtils.sendPacket(((ForwardingAudience.Single) audience).audience(), packet);
} else if (audience instanceof ForwardingAudience) {
for (Audience member : ((ForwardingAudience) audience).audiences()) {
PacketUtils.sendPacket(member, packet);
}
}
}
2020-11-13 09:17:53 +01:00
/**
* Sends a {@link ServerPacket} to multiple players.
2020-11-13 09:17:53 +01:00
* <p>
* Can drastically improve performance since the packet will not have to be processed as much.
2020-11-13 09:17:53 +01:00
*
* @param players the players to send the packet to
* @param packet the packet to send to the players
* @param playerValidator optional callback to check if a specify player of {@code players} should receive the packet
2020-11-13 09:17:53 +01:00
*/
public static void sendGroupedPacket(@NotNull Collection<Player> players, @NotNull ServerPacket packet,
@Nullable PlayerValidator playerValidator) {
2020-11-20 14:14:55 +01:00
if (players.isEmpty())
return;
2021-03-12 16:33:19 +01:00
// work out if the packet needs to be sent individually due to server-side translating
boolean needsTranslating = false;
if (AdventureSerializer.AUTOMATIC_COMPONENT_TRANSLATION && packet instanceof ComponentHoldingServerPacket) {
needsTranslating = AdventureSerializer.areAnyTranslatable(((ComponentHoldingServerPacket) packet).components());
2021-03-12 16:33:19 +01:00
}
if (MinecraftServer.hasGroupedPacket() && !needsTranslating) {
// Send grouped packet...
final boolean success = PACKET_LISTENER_MANAGER.processServerPacket(packet, players);
if (success) {
2021-03-20 11:59:02 +01:00
final ByteBuf finalBuffer = createFramedPacket(packet, true);
final FramedPacket framedPacket = new FramedPacket(finalBuffer);
2020-11-20 04:48:33 +01:00
// Send packet to all players
for (Player player : players) {
if (!player.isOnline())
continue;
// Verify if the player should receive the packet
if (playerValidator != null && !playerValidator.isValid(player))
continue;
2021-03-20 11:59:02 +01:00
finalBuffer.retain();
final PlayerConnection playerConnection = player.getPlayerConnection();
if (playerConnection instanceof NettyPlayerConnection) {
final NettyPlayerConnection nettyPlayerConnection = (NettyPlayerConnection) playerConnection;
2021-03-15 15:19:43 +01:00
nettyPlayerConnection.write(framedPacket, true);
} else {
playerConnection.sendPacket(packet);
}
2021-03-20 11:59:02 +01:00
finalBuffer.release();
}
2021-03-20 11:59:02 +01:00
finalBuffer.release(); // Release last reference
}
} else {
// Write the same packet for each individual players
for (Player player : players) {
// Verify if the player should receive the packet
if (playerValidator != null && !playerValidator.isValid(player))
continue;
final PlayerConnection playerConnection = player.getPlayerConnection();
2021-03-15 15:19:43 +01:00
playerConnection.sendPacket(packet, false);
}
}
}
/**
* Same as {@link #sendGroupedPacket(Collection, ServerPacket, PlayerValidator)}
* but with the player validator sets to null.
*
* @see #sendGroupedPacket(Collection, ServerPacket, PlayerValidator)
*/
public static void sendGroupedPacket(@NotNull Collection<Player> players, @NotNull ServerPacket packet) {
sendGroupedPacket(players, packet, null);
}
2020-08-15 04:05:15 +02:00
/**
2020-10-15 21:16:31 +02:00
* Writes a {@link ServerPacket} into a {@link ByteBuf}.
2020-08-15 04:05:15 +02:00
*
* @param buf the recipient of {@code packet}
* @param packet the packet to write into {@code buf}
*/
2020-11-05 22:20:51 +01:00
public static void writePacket(@NotNull ByteBuf buf, @NotNull ServerPacket packet) {
2021-03-22 14:31:38 +01:00
Utils.writeVarIntBuf(buf, packet.getId());
writePacketPayload(buf, packet);
}
2020-04-17 01:16:02 +02:00
2020-08-15 04:05:15 +02:00
/**
2021-03-22 14:31:38 +01:00
* Writes a packet payload.
2020-08-15 04:05:15 +02:00
*
* @param packet the packet to write
*/
2021-03-22 14:31:38 +01:00
private static void writePacketPayload(@NotNull ByteBuf buffer, @NotNull ServerPacket packet) {
BinaryWriter writer = new BinaryWriter(buffer);
2020-11-19 02:28:56 +01:00
try {
packet.write(writer);
} catch (Exception e) {
MinecraftServer.getExceptionManager().handleException(e);
2020-11-19 02:28:56 +01:00
}
}
2020-11-20 14:05:22 +01:00
/**
* Frames a buffer for it to be understood by a Minecraft client.
* <p>
* The content of {@code packetBuffer} can be either a compressed or uncompressed packet buffer,
* it depends of it the client did receive a {@link net.minestom.server.network.packet.server.login.SetCompressionPacket} packet before.
*
* @param packetBuffer the buffer containing compressed or uncompressed packet data
* @param frameTarget the buffer which will receive the framed version of {@code from}
*/
public static void frameBuffer(@NotNull ByteBuf packetBuffer, @NotNull ByteBuf frameTarget) {
final int packetSize = packetBuffer.readableBytes();
final int headerSize = Utils.getVarIntSize(packetSize);
if (headerSize > 3) {
throw new IllegalStateException("Unable to fit " + headerSize + " into 3");
}
2020-11-20 14:05:22 +01:00
frameTarget.ensureWritable(packetSize + headerSize);
2020-11-20 14:05:22 +01:00
Utils.writeVarIntBuf(frameTarget, packetSize);
frameTarget.writeBytes(packetBuffer, packetBuffer.readerIndex(), packetSize);
}
2020-11-20 14:05:22 +01:00
/**
* Compress using zlib the content of a packet.
* <p>
* {@code packetBuffer} needs to be the packet content without any header (if you want to use it to write a Minecraft packet).
*
2021-03-28 20:40:27 +02:00
* @param compressor the deflater for zlib compression
2020-11-20 14:05:22 +01:00
* @param packetBuffer the buffer containing all the packet fields
* @param compressionTarget the buffer which will receive the compressed version of {@code packetBuffer}
*/
2021-03-28 20:40:27 +02:00
public static void compressBuffer(@NotNull VelocityCompressor compressor, @NotNull ByteBuf packetBuffer, @NotNull ByteBuf compressionTarget) {
2020-11-20 14:05:22 +01:00
final int packetLength = packetBuffer.readableBytes();
2021-03-22 14:31:38 +01:00
final boolean compression = packetLength > MinecraftServer.getCompressionThreshold();
Utils.writeVarIntBuf(compressionTarget, compression ? packetLength : 0);
if (compression) {
2021-03-28 20:40:27 +02:00
compress(compressor, packetBuffer, compressionTarget);
} else {
2021-03-22 14:31:38 +01:00
compressionTarget.writeBytes(packetBuffer);
}
}
2021-03-28 20:40:27 +02:00
private static void compress(@NotNull VelocityCompressor compressor, @NotNull ByteBuf uncompressed, @NotNull ByteBuf compressed) {
try {
compressor.deflate(uncompressed, compressed);
} catch (DataFormatException e) {
e.printStackTrace();
}
}
2021-03-26 13:08:05 +01:00
public static void writeFramedPacket(@NotNull ByteBuf buffer,
@NotNull ServerPacket serverPacket) {
2021-03-22 14:31:38 +01:00
final int compressionThreshold = MinecraftServer.getCompressionThreshold();
final boolean compression = compressionThreshold > 0;
2021-03-22 14:31:38 +01:00
if (compression) {
2021-04-10 02:02:59 +02:00
// Dummy var-int
2021-03-28 19:34:38 +02:00
final int packetLengthIndex = Utils.writeEmptyVarIntHeader(buffer);
final int dataLengthIndex = Utils.writeEmptyVarIntHeader(buffer);
// Write packet
final int contentIndex = buffer.writerIndex();
writePacket(buffer, serverPacket);
final int afterIndex = buffer.writerIndex();
2021-03-28 19:34:38 +02:00
final int packetSize = (afterIndex - dataLengthIndex) - Utils.VARINT_HEADER_SIZE;
if (packetSize >= compressionThreshold) {
// Packet large enough
2021-03-28 20:40:27 +02:00
final VelocityCompressor compressor = COMPRESSOR.get();
// Compress id + payload
ByteBuf uncompressedCopy = buffer.copy(contentIndex, packetSize);
buffer.writerIndex(contentIndex);
2021-03-28 20:40:27 +02:00
compress(compressor, uncompressedCopy, buffer);
uncompressedCopy.release();
2021-03-28 19:34:38 +02:00
final int totalPacketLength = buffer.writerIndex() - contentIndex + Utils.VARINT_HEADER_SIZE;
2021-03-26 13:08:05 +01:00
2021-03-26 16:43:25 +01:00
// Update header values
2021-03-28 19:34:38 +02:00
Utils.overrideVarIntHeader(buffer, packetLengthIndex, totalPacketLength);
Utils.overrideVarIntHeader(buffer, dataLengthIndex, packetSize);
} else {
// Packet too small, just override header values
2021-03-28 19:34:38 +02:00
final int totalPacketLength = packetSize + Utils.VARINT_HEADER_SIZE;
Utils.overrideVarIntHeader(buffer, packetLengthIndex, totalPacketLength);
Utils.overrideVarIntHeader(buffer, dataLengthIndex, 0); // -> Uncompressed
2021-03-26 13:08:05 +01:00
}
} else {
2021-03-26 13:08:05 +01:00
// No compression
2021-04-10 02:02:59 +02:00
// Write dummy var-int
2021-03-28 19:34:38 +02:00
final int index = Utils.writeEmptyVarIntHeader(buffer);
2021-03-26 13:08:05 +01:00
// Write packet id + payload
writePacket(buffer, serverPacket);
2021-04-10 02:02:59 +02:00
// Rewrite dummy var-int to packet length
final int afterIndex = buffer.writerIndex();
2021-03-28 19:34:38 +02:00
final int packetSize = (afterIndex - index) - Utils.VARINT_HEADER_SIZE;
Utils.overrideVarIntHeader(buffer, index, packetSize);
2021-03-26 13:08:05 +01:00
}
}
2021-03-22 14:31:38 +01:00
2021-03-26 13:08:05 +01:00
/**
* Creates a "framed packet" (packet which can be send and understood by a Minecraft client)
* from a server packet, directly into an output buffer.
* <p>
* Can be used if you want to store a raw buffer and send it later without the additional writing cost.
* Compression is applied if {@link MinecraftServer#getCompressionThreshold()} is greater than 0.
*
* @param serverPacket the server packet to write
*/
@NotNull
public static ByteBuf createFramedPacket(@NotNull ServerPacket serverPacket, boolean directBuffer) {
2021-05-08 00:52:46 +02:00
ByteBuf packetBuf = directBuffer ? BufUtils.direct() : Unpooled.buffer();
writeFramedPacket(packetBuf, serverPacket);
2021-03-26 13:08:05 +01:00
return packetBuf;
}
2019-08-22 14:52:32 +02:00
}