net.minecraft.util.PacketByteBuf Java Examples

The following examples show how to use net.minecraft.util.PacketByteBuf. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FMLPlayMessages.java    From patchwork-api with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void encode(SpawnEntity msg, PacketByteBuf buf) {
	buf.writeVarInt(msg.typeId);
	buf.writeInt(msg.entityId);
	buf.writeUuid(msg.uuid);
	buf.writeDouble(msg.posX);
	buf.writeDouble(msg.posY);
	buf.writeDouble(msg.posZ);
	buf.writeByte(msg.pitch);
	buf.writeByte(msg.yaw);
	buf.writeByte(msg.headYaw);
	buf.writeShort(msg.velX);
	buf.writeShort(msg.velY);
	buf.writeShort(msg.velZ);

	if (msg.entity instanceof IEntityAdditionalSpawnData) {
		((IEntityAdditionalSpawnData) msg.entity).writeSpawnData(buf);
	}
}
 
Example #2
Source File: FMLPlayMessages.java    From patchwork-api with GNU Lesser General Public License v2.1 6 votes vote down vote up
private SpawnEntity(PacketByteBuf buf) {
	this.entity = null;

	this.typeId = buf.readVarInt();
	this.entityId = buf.readInt();
	this.uuid = buf.readUuid();
	this.posX = buf.readDouble();
	this.posY = buf.readDouble();
	this.posZ = buf.readDouble();
	this.pitch = buf.readByte();
	this.yaw = buf.readByte();
	this.headYaw = buf.readByte();
	this.velX = buf.readShort();
	this.velY = buf.readShort();
	this.velZ = buf.readShort();

	this.buf = buf;
}
 
Example #3
Source File: VelocityUtil.java    From Sandbox with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static boolean checkIntegrity(final PacketByteBuf buf) {
    final byte[] signature = new byte[32];
    buf.readBytes(signature);

    final byte[] data = new byte[buf.readableBytes()];
    buf.getBytes(buf.readerIndex(), data);

    try {
        final Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(SandboxConfig.velocityKey.get().getBytes(), "HmacSHA256"));
        final byte[] mySignature = mac.doFinal(data);
        if (!MessageDigest.isEqual(signature, mySignature)) {
            return false;
        }
    } catch (final InvalidKeyException | NoSuchAlgorithmException e) {
        throw new AssertionError(e);
    }

    int version = buf.readVarInt();
    if (version != 1) {
        throw new IllegalStateException("Unsupported forwarding version " + version + ", wanted " + 1);
    }

    return true;
}
 
Example #4
Source File: ClientNetworkHandler.java    From fabric-carpet with MIT License 6 votes vote down vote up
private static void onHi(PacketByteBuf data)
{
    synchronized (CarpetClient.sync)
    {
        CarpetClient.setCarpet();
        CarpetClient.serverCarpetVersion = data.readString(64);
        if (CarpetSettings.carpetVersion.equals(CarpetClient.serverCarpetVersion))
        {
            CarpetSettings.LOG.info("Joined carpet server with matching carpet version");
        }
        else
        {
            CarpetSettings.LOG.warn("Joined carpet server with another carpet version: "+CarpetClient.serverCarpetVersion);
        }
        if (CarpetClient.getPlayer() != null)
            respondHello();

    }
}
 
Example #5
Source File: MixinClientPlayNetworkHandler.java    From Sandbox with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Inject(method = "onCustomPayload", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/NetworkThreadUtils;forceMainThread(Lnet/minecraft/network/Packet;Lnet/minecraft/network/listener/PacketListener;Lnet/minecraft/util/thread/ThreadExecutor;)V", shift = At.Shift.AFTER, remap = false), cancellable = true)
public void onCustomPayload(CustomPayloadS2CPacket s2c, CallbackInfo info) {
    CustomPayloadPacket customPayloadPacket = (CustomPayloadPacket) s2c;
    PacketByteBuf data = null;
    try {
        Identifier channel = customPayloadPacket.channel();
        if (!channel.getNamespace().equals("minecraft")) { //Override non-vanilla packets
            Class<? extends Packet> packetClass = NetworkManager.get(channel);
            if (packetClass != null) {
                data = customPayloadPacket.data();
                Packet packet = packetClass.getConstructor().newInstance();
                packet.read(data);
                packet.apply();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (data != null) {
            data.release();
            info.cancel();
        }
    }
}
 
Example #6
Source File: IndexedMessageCodec.java    From patchwork-api with GNU Lesser General Public License v2.1 6 votes vote down vote up
void consume(PacketByteBuf payload, int payloadIndex, NetworkEvent.Context context) {
	if (payload == null) {
		LOGGER.error(SIMPLENET, "Received empty payload on channel {}", channelName);
		return;
	}

	short discriminator = payload.readUnsignedByte();
	final MessageHandler<?> messageHandler = indices.get(discriminator);

	if (messageHandler == null) {
		LOGGER.error(SIMPLENET, "Received invalid discriminator byte {} on channel {}", discriminator, channelName);
		return;
	}

	tryDecode(payload, context, payloadIndex, messageHandler);
}
 
Example #7
Source File: MixinServerLoginNetworkHandler.java    From Sandbox with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Inject(method = "onQueryResponse", at = @At("HEAD"), cancellable = true)
public void onQueryResponse(LoginQueryResponseC2SPacket packet, CallbackInfo info) {
    if (SandboxConfig.velocity.get() && velocityId == ((CustomPayloadPacket.LoginQueryPacket) packet).getQueryId()) {
        PacketByteBuf buf = ((CustomPayloadPacket.LoginQueryPacket) packet).getBuffer();
        if (buf == null) {
            this.disconnect(new LiteralText("This server requires you to log in through a proxy"));
            info.cancel();
            return;
        }
        if (!VelocityUtil.checkIntegrity(buf)) {
            this.disconnect(new LiteralText("Unable to verify player details"));
            info.cancel();
            return;
        }

        ((ClientConnectionInternal) this.client).setSocketAddress(new InetSocketAddress(VelocityUtil.readAddress(buf), ((InetSocketAddress) this.client.getAddress()).getPort()));
        this.profile = VelocityUtil.createProfile(buf);
        velocityConn = true;
        acceptPlayer();
        info.cancel();
    }
}
 
Example #8
Source File: FluidRecipeSerializer.java    From the-hallow with MIT License 5 votes vote down vote up
@Override
public FluidRecipe read(Identifier id, PacketByteBuf buf) {
	int size = buf.readInt();

	ArrayList<Ingredient> ingredients = new ArrayList<>();
	for(int i = 0; i < size; i++) {
		ingredients.add(Ingredient.fromPacket(buf));
	}

	return new FluidRecipe(ingredients, buf.readItemStack(), id, type, this);
}
 
Example #9
Source File: MixinPacketInflater.java    From bleachhack-1.14 with GNU General Public License v3.0 5 votes vote down vote up
@Inject(at = @At("HEAD"), method = "decode(Lio/netty/channel/ChannelHandlerContext;Lio/netty/buffer/ByteBuf;Ljava/util/List;)V", cancellable = true)
protected void decode(ChannelHandlerContext channelHandlerContext_1, ByteBuf byteBuf_1, List<Object> list_1, CallbackInfo info) throws Exception {
	
	if (!ModuleManager.getModule(AntiChunkBan.class).isToggled()) return;
	
	info.cancel();
	
	if (byteBuf_1.readableBytes() != 0) {
         PacketByteBuf packetByteBuf_1 = new PacketByteBuf(byteBuf_1);
         int int_1 = packetByteBuf_1.readVarInt();
         if (int_1 == 0) {
            list_1.add(packetByteBuf_1.readBytes(packetByteBuf_1.readableBytes()));
         } else {
            if (int_1 > 51200000) {
               throw new DecoderException("Badly compressed packet - size of " + (int_1 / 1000000) + "MB is larger than protocol maximum of 50 MB");
            }

            byte[] bytes_1 = new byte[packetByteBuf_1.readableBytes()];
            packetByteBuf_1.readBytes(bytes_1);
            this.inflater.setInput(bytes_1);
            byte[] bytes_2 = new byte[int_1];
            this.inflater.inflate(bytes_2);
            list_1.add(Unpooled.wrappedBuffer(bytes_2));
            this.inflater.reset();
         }

      }
}
 
Example #10
Source File: ClientNetworkHandler.java    From fabric-carpet with MIT License 5 votes vote down vote up
private static void onSyncData(PacketByteBuf data, ClientPlayerEntity player)
{
    CompoundTag compound = data.readCompoundTag();
    if (compound == null) return;
    for (String key: compound.getKeys())
    {
        if (dataHandlers.containsKey(key))
            dataHandlers.get(key).accept(player, compound.get(key));
        else
            CarpetSettings.LOG.error("Unknown carpet data: "+key);
    }
}
 
Example #11
Source File: IndexedMessageCodec.java    From patchwork-api with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static <M> int tryEncode(PacketByteBuf target, M message, MessageHandler<M> codec) {
	if (codec.encoder != null) {
		target.writeByte(codec.index & 0xff);
		codec.encoder.accept(message, target);
	}

	if (codec.loginIndexGetter != null) {
		return codec.loginIndexGetter.apply(message);
	} else {
		return Integer.MIN_VALUE;
	}
}
 
Example #12
Source File: ClientNetworkHandler.java    From fabric-carpet with MIT License 5 votes vote down vote up
public static void respondHello()
{
    CarpetClient.getPlayer().networkHandler.sendPacket(new CustomPayloadC2SPacket(
            CarpetClient.CARPET_CHANNEL,
            (new PacketByteBuf(Unpooled.buffer())).writeVarInt(CarpetClient.HELLO).writeString(CarpetSettings.carpetVersion)
    ));
}
 
Example #13
Source File: MixinPacketInflater.java    From bleachhack-1.14 with GNU General Public License v3.0 5 votes vote down vote up
@Inject(at = @At("HEAD"), method = "decode(Lio/netty/channel/ChannelHandlerContext;Lio/netty/buffer/ByteBuf;Ljava/util/List;)V", cancellable = true)
protected void decode(ChannelHandlerContext channelHandlerContext_1, ByteBuf byteBuf_1, List<Object> list_1, CallbackInfo info) throws Exception {
	
	if (!ModuleManager.getModule(AntiChunkBan.class).isToggled()) return;
	
	info.cancel();
	
	if (byteBuf_1.readableBytes() != 0) {
         PacketByteBuf packetByteBuf_1 = new PacketByteBuf(byteBuf_1);
         int int_1 = packetByteBuf_1.readVarInt();
         if (int_1 == 0) {
            list_1.add(packetByteBuf_1.readBytes(packetByteBuf_1.readableBytes()));
         } else {
            if (int_1 > 51200000) {
               throw new DecoderException("Badly compressed packet - size of " + (int_1 / 1000000) + "MB is larger than protocol maximum of 50 MB");
            }

            byte[] bytes_1 = new byte[packetByteBuf_1.readableBytes()];
            packetByteBuf_1.readBytes(bytes_1);
            this.inflater.setInput(bytes_1);
            byte[] bytes_2 = new byte[int_1];
            this.inflater.inflate(bytes_2);
            list_1.add(Unpooled.wrappedBuffer(bytes_2));
            this.inflater.reset();
         }

      }
}
 
Example #14
Source File: ServerNetworkHandler.java    From fabric-carpet with MIT License 5 votes vote down vote up
public static void handleData(PacketByteBuf data, ServerPlayerEntity player)
{
    if (data != null)
    {
        int id = data.readVarInt();
        if (id == CarpetClient.HELLO)
            onHello(player, data);
        if (id == CarpetClient.DATA)
            onClientData(player, data);
    }
}
 
Example #15
Source File: ServerNetworkHandler.java    From fabric-carpet with MIT License 5 votes vote down vote up
public static void onPlayerJoin(ServerPlayerEntity playerEntity)
{
    if (!playerEntity.networkHandler.connection.isLocal())
    {
        playerEntity.networkHandler.sendPacket(new CustomPayloadS2CPacket(
                CarpetClient.CARPET_CHANNEL,
                (new PacketByteBuf(Unpooled.buffer())).writeVarInt(CarpetClient.HI).writeString(CarpetSettings.carpetVersion)
        ));
    }
    else
    {
        validCarpetPlayers.add(playerEntity);
    }

}
 
Example #16
Source File: ServerNetworkHandler.java    From fabric-carpet with MIT License 5 votes vote down vote up
public static void onHello(ServerPlayerEntity playerEntity, PacketByteBuf packetData)
{

    validCarpetPlayers.add(playerEntity);
    String clientVersion = packetData.readString(64);
    remoteCarpetPlayers.put(playerEntity, clientVersion);
    if (clientVersion.equals(CarpetSettings.carpetVersion))
        CarpetSettings.LOG.info("Player "+playerEntity.getName().getString()+" joined with a matching carpet client");
    else
        CarpetSettings.LOG.warn("Player "+playerEntity.getName().getString()+" joined with another carpet version: "+clientVersion);
    DataBuilder data = DataBuilder.create().withTickRate();
    CarpetServer.settingsManager.getRules().forEach(data::withRule);
    playerEntity.networkHandler.sendPacket(new CustomPayloadS2CPacket(CarpetClient.CARPET_CHANNEL, data.build() ));
}
 
Example #17
Source File: ServerNetworkHandler.java    From fabric-carpet with MIT License 5 votes vote down vote up
private static void onClientData(ServerPlayerEntity player, PacketByteBuf data)
{
    CompoundTag compound = data.readCompoundTag();
    if (compound == null) return;
    for (String key: compound.getKeys())
    {
        if (dataHandlers.containsKey(key))
            dataHandlers.get(key).accept(player, compound.get(key));
        else
            CarpetSettings.LOG.warn("Unknown carpet client data: "+key);
    }
}
 
Example #18
Source File: HallowedTreasureChestEntity.java    From the-hallow with MIT License 5 votes vote down vote up
@Override
public Packet<?> createSpawnPacket() {
	PacketByteBuf packet = new PacketByteBuf(Unpooled.buffer());
	
	packet.writeDouble(getX());
	packet.writeDouble(getY());
	packet.writeDouble(getZ());
	
	packet.writeBoolean(shouldReplace);
	packet.writeFloat(rotation);
	
	packet.writeInt(getEntityId());
	
	return ServerSidePacketRegistry.INSTANCE.toPacket(ENTITY_ID, packet);
}
 
Example #19
Source File: IndexedMessageCodec.java    From patchwork-api with GNU Lesser General Public License v2.1 5 votes vote down vote up
public <M> int build(M message, PacketByteBuf target) {
	MessageHandler<M> codec = findMessageType(message);

	if (codec == null) {
		LOGGER.error(SIMPLENET, "Received invalid message {} on channel {}", message.getClass().getName(), channelName);
		throw new IllegalArgumentException("Invalid message " + message.getClass().getName());
	}

	return tryEncode(target, message, codec);
}
 
Example #20
Source File: IndexedMessageCodec.java    From patchwork-api with GNU Lesser General Public License v2.1 5 votes vote down vote up
MessageHandler(int index, Class<M> messageType, BiConsumer<M, PacketByteBuf> encoder, Function<PacketByteBuf, M> decoder, BiConsumer<M, Supplier<NetworkEvent.Context>> messageConsumer) {
	this.index = index;
	this.messageType = messageType;
	this.encoder = encoder;
	this.decoder = decoder;
	this.messageConsumer = messageConsumer;
	this.loginIndexGetter = null;
	this.loginIndexSetter = null;
	indices.put((short) (index & 0xff), this);
	types.put(messageType, this);
}
 
Example #21
Source File: VelocityUtil.java    From Sandbox with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static LoginQueryRequestS2CPacket create(int id) {
    LoginQueryRequestS2CPacket packet = new LoginQueryRequestS2CPacket();
    try {
        ReflectionHelper.setPrivateField(LoginQueryRequestS2CPacket.class, packet, "queryId", id);
        ReflectionHelper.setPrivateField(LoginQueryRequestS2CPacket.class, packet, "channel", PLAYER_INFO_CHANNEL);
        ReflectionHelper.setPrivateField(LoginQueryRequestS2CPacket.class, packet, "payload", new PacketByteBuf(Unpooled.buffer()));
    } catch (IllegalAccessException | NoSuchFieldException e) {
        e.printStackTrace();
    }
    return packet;
}
 
Example #22
Source File: VelocityUtil.java    From Sandbox with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void readProperties(final PacketByteBuf buf, final GameProfile profile) {
    if (buf.readableBytes() < 4)
        return;
    final int properties = buf.readInt();
    for (int i1 = 0; i1 < properties; i1++) {
        final String name = buf.readString(32767);
        final String value = buf.readString(32767);
        final String signature = buf.readBoolean() ? buf.readString(32767) : null;
        profile.getProperties().put(name, new Property(name, value, signature));
    }
}
 
Example #23
Source File: ClientNetworkHandler.java    From fabric-carpet with MIT License 5 votes vote down vote up
public static void handleData(PacketByteBuf data, ClientPlayerEntity player)
{
    if (data != null)
    {
        int id = data.readVarInt();
        if (id == CarpetClient.HI)
            onHi(data);
        if (id == CarpetClient.DATA)
            onSyncData(data, player);
    }
}
 
Example #24
Source File: AddonS2CPacket.java    From Sandbox with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void read(PacketByteBuf var1) {
    count = var1.readInt();
    prefix = var1.readString(Short.MAX_VALUE);
    if (count > 0) {
        addons = new ArrayList<>();
    } else {
        addons = Collections.emptyList();
    }
    for (int i = 0; i < count; i++) {
        String suffix = var1.readString(Short.MAX_VALUE);
        String hash = var1.readString(Short.MAX_VALUE);
        addons.add(new Pair<>(suffix, hash));
    }
}
 
Example #25
Source File: PatchworkPlayNetworkingMessages.java    From patchwork-api with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static Packet<?> getOpenContainerPacket(FMLPlayMessages.OpenContainer message) {
	PacketByteBuf buf = new PacketByteBuf(Unpooled.buffer());

	buf.writeByte(OPEN_CONTAINER);
	FMLPlayMessages.OpenContainer.encode(message, buf);

	return ServerSidePacketRegistry.INSTANCE.toPacket(IDENTIFIER, buf);
}
 
Example #26
Source File: FMLPlayMessages.java    From patchwork-api with GNU Lesser General Public License v2.1 4 votes vote down vote up
public PacketByteBuf getAdditionalData() {
	return additionalData;
}
 
Example #27
Source File: FMLPlayMessages.java    From patchwork-api with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static void encode(OpenContainer msg, PacketByteBuf buf) {
	buf.writeVarInt(msg.id);
	buf.writeVarInt(msg.windowId);
	buf.writeText(msg.name);
	buf.writeByteArray(msg.additionalData.readByteArray());
}
 
Example #28
Source File: PatchworkPlayNetworkingMessages.java    From patchwork-api with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void sendContainerOpenPacket(ServerPlayerEntity player, NameableContainerFactory factory, Consumer<PacketByteBuf> extraDataWriter) {
	if (player.world.isClient) {
		return;
	}

	player.method_14247();

	ContainerSyncAccess access = (ContainerSyncAccess) player;
	int openContainerId = access.patchwork$getNewContainerSyncId();

	PacketByteBuf extraData = new PacketByteBuf(Unpooled.buffer());
	extraDataWriter.accept(extraData);

	// reset to beginning in case modders read for whatever reason
	extraData.readerIndex(0);

	PacketByteBuf output = new PacketByteBuf(Unpooled.buffer());
	output.writeVarInt(extraData.readableBytes());
	output.writeBytes(extraData);

	if (output.readableBytes() > 32600 || output.readableBytes() < 1) {
		throw new IllegalArgumentException("Invalid PacketByteBuf for openGui, found " + output.readableBytes() + " bytes");
	}

	Container c = factory.createMenu(openContainerId, player.inventory, player);
	ContainerType<?> type = c.getType();

	FMLPlayMessages.OpenContainer msg = new FMLPlayMessages.OpenContainer(type, openContainerId, factory.getDisplayName(), output);
	Packet<?> packet = PatchworkPlayNetworkingMessages.getOpenContainerPacket(msg);

	player.networkHandler.sendPacket(packet);
	player.container = c;
	player.container.addListener(player);

	// TODO MinecraftForge.EVENT_BUS.post(new PlayerContainerEvent.Open(player, c));
}
 
Example #29
Source File: FMLPlayMessages.java    From patchwork-api with GNU Lesser General Public License v2.1 4 votes vote down vote up
private OpenContainer(int id, int windowId, Text name, PacketByteBuf additionalData) {
	this.id = id;
	this.windowId = windowId;
	this.name = name;
	this.additionalData = additionalData;
}
 
Example #30
Source File: FluidRecipeSerializer.java    From the-hallow with MIT License 4 votes vote down vote up
@Override
public void write(PacketByteBuf buf, FluidRecipe recipe) {
	buf.writeInt(recipe.getIngredients().size());
	recipe.getIngredients().forEach(ingredient -> ingredient.write(buf));
	buf.writeItemStack(recipe.getOutput());
}