Search in sources :

Example 41 with PacketWrapper

use of com.viaversion.viaversion.api.protocol.packet.PacketWrapper in project ViaVersion by ViaVersion.

the class MetadataRewriter1_11To1_10 method handleMetadata.

@Override
protected void handleMetadata(int entityId, com.viaversion.viaversion.api.minecraft.entities.EntityType type, Metadata metadata, List<Metadata> metadatas, UserConnection connection) {
    if (metadata.getValue() instanceof DataItem) {
        // Apply rewrite
        EntityIdRewriter.toClientItem((Item) metadata.getValue());
    }
    if (type == null)
        return;
    if (type.is(EntityType.ELDER_GUARDIAN) || type.is(EntityType.GUARDIAN)) {
        // Guardians
        int oldid = metadata.id();
        if (oldid == 12) {
            boolean val = (((byte) metadata.getValue()) & 0x02) == 0x02;
            metadata.setTypeAndValue(MetaType1_9.Boolean, val);
        }
    }
    if (type.isOrHasParent(EntityType.ABSTRACT_SKELETON)) {
        // Skeletons
        int oldid = metadata.id();
        if (oldid == 12) {
            metadatas.remove(metadata);
        }
        if (oldid == 13) {
            metadata.setId(12);
        }
    }
    if (type.isOrHasParent(EntityType.ZOMBIE)) {
        // Zombie | Zombie Villager | Husk
        if (type.is(EntityType.ZOMBIE, EntityType.HUSK) && metadata.id() == 14) {
            metadatas.remove(metadata);
        } else {
            if (metadata.id() == 15) {
                metadata.setId(14);
            } else {
                if (metadata.id() == 14) {
                    metadata.setId(15);
                }
            }
        }
    }
    if (type.isOrHasParent(EntityType.ABSTRACT_HORSE)) {
        // Horses
        // Remap metadata id
        int oldid = metadata.id();
        if (oldid == 14) {
            // Type
            metadatas.remove(metadata);
        }
        if (oldid == 16) {
            // Owner
            metadata.setId(14);
        }
        if (oldid == 17) {
            // Armor
            metadata.setId(16);
        }
        // Process per type
        if (type.is(EntityType.HORSE)) {
        // Normal Horse
        } else {
            // Remove 15, 16
            if (metadata.id() == 15 || metadata.id() == 16) {
                metadatas.remove(metadata);
            }
        }
        if (type.is(EntityType.DONKEY, EntityType.MULE)) {
            // Chested Horse
            if (metadata.id() == 13) {
                if ((((byte) metadata.getValue()) & 0x08) == 0x08) {
                    metadatas.add(new Metadata(15, MetaType1_9.Boolean, true));
                } else {
                    metadatas.add(new Metadata(15, MetaType1_9.Boolean, false));
                }
            }
        }
    }
    if (type.is(EntityType.ARMOR_STAND) && Via.getConfig().isHologramPatch()) {
        Metadata flags = metaByIndex(11, metadatas);
        Metadata customName = metaByIndex(2, metadatas);
        Metadata customNameVisible = metaByIndex(3, metadatas);
        if (metadata.id() == 0 && flags != null && customName != null && customNameVisible != null) {
            byte data = (byte) metadata.getValue();
            // Check invisible | Check small | Check if custom name is empty | Check if custom name visible is true
            if ((data & 0x20) == 0x20 && ((byte) flags.getValue() & 0x01) == 0x01 && !((String) customName.getValue()).isEmpty() && (boolean) customNameVisible.getValue()) {
                EntityTracker1_11 tracker = tracker(connection);
                if (tracker.addHologram(entityId)) {
                    try {
                        // Send movement
                        PacketWrapper wrapper = PacketWrapper.create(ClientboundPackets1_9_3.ENTITY_POSITION, null, connection);
                        wrapper.write(Type.VAR_INT, entityId);
                        wrapper.write(Type.SHORT, (short) 0);
                        wrapper.write(Type.SHORT, (short) (128D * (-Via.getConfig().getHologramYOffset() * 32D)));
                        wrapper.write(Type.SHORT, (short) 0);
                        wrapper.write(Type.BOOLEAN, true);
                        wrapper.send(Protocol1_11To1_10.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
Also used : EntityTracker1_11(com.viaversion.viaversion.protocols.protocol1_11to1_10.storage.EntityTracker1_11) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) DataItem(com.viaversion.viaversion.api.minecraft.item.DataItem) Metadata(com.viaversion.viaversion.api.minecraft.metadata.Metadata)

Example 42 with PacketWrapper

use of com.viaversion.viaversion.api.protocol.packet.PacketWrapper in project ViaVersion by ViaVersion.

the class InventoryPackets method registerPackets.

@Override
public void registerPackets() {
    registerSetSlot(ClientboundPackets1_9_3.SET_SLOT, Type.ITEM);
    registerWindowItems(ClientboundPackets1_9_3.WINDOW_ITEMS, Type.ITEM_ARRAY);
    registerEntityEquipment(ClientboundPackets1_9_3.ENTITY_EQUIPMENT, Type.ITEM);
    // Plugin message Packet -> Trading
    protocol.registerClientbound(ClientboundPackets1_9_3.PLUGIN_MESSAGE, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Channel
            map(Type.STRING);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    if (wrapper.get(Type.STRING, 0).equalsIgnoreCase("MC|TrList")) {
                        // Passthrough Window ID
                        wrapper.passthrough(Type.INT);
                        int size = wrapper.passthrough(Type.UNSIGNED_BYTE);
                        for (int i = 0; i < size; i++) {
                            // Input Item
                            EntityIdRewriter.toClientItem(wrapper.passthrough(Type.ITEM));
                            // Output Item
                            EntityIdRewriter.toClientItem(wrapper.passthrough(Type.ITEM));
                            // Has second item
                            boolean secondItem = wrapper.passthrough(Type.BOOLEAN);
                            if (secondItem)
                                // Second Item
                                EntityIdRewriter.toClientItem(wrapper.passthrough(Type.ITEM));
                            // Trade disabled
                            wrapper.passthrough(Type.BOOLEAN);
                            // Number of tools uses
                            wrapper.passthrough(Type.INT);
                            // Maximum number of trade uses
                            wrapper.passthrough(Type.INT);
                        }
                    }
                }
            });
        }
    });
    registerClickWindow(ServerboundPackets1_9_3.CLICK_WINDOW, Type.ITEM);
    registerCreativeInvAction(ServerboundPackets1_9_3.CREATIVE_INVENTORY_ACTION, Type.ITEM);
}
Also used : PacketHandler(com.viaversion.viaversion.api.protocol.remapper.PacketHandler) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) PacketRemapper(com.viaversion.viaversion.api.protocol.remapper.PacketRemapper)

Example 43 with PacketWrapper

use of com.viaversion.viaversion.api.protocol.packet.PacketWrapper in project ViaVersion by ViaVersion.

the class VersionedPacketTransformerImpl method createAndTransform.

@Nullable
private PacketWrapper createAndTransform(UserConnection connection, PacketType packetType, Consumer<PacketWrapper> packetWriter) throws Exception {
    PacketWrapper packet = PacketWrapper.create(packetType, connection);
    packetWriter.accept(packet);
    return transform(packet);
}
Also used : PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) Nullable(org.checkerframework.checker.nullness.qual.Nullable)

Example 44 with PacketWrapper

use of com.viaversion.viaversion.api.protocol.packet.PacketWrapper in project ViaVersion by ViaVersion.

the class BaseProtocol1_7 method registerPackets.

@Override
protected void registerPackets() {
    /* Outgoing Packets */
    // Status Response Packet
    registerClientbound(ClientboundStatusPackets.STATUS_RESPONSE, new // Status Response Packet
    PacketRemapper() {

        @Override
        public void registerMap() {
            map(Type.STRING);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    ProtocolInfo info = wrapper.user().getProtocolInfo();
                    String originalStatus = wrapper.get(Type.STRING, 0);
                    try {
                        JsonElement json = GsonUtil.getGson().fromJson(originalStatus, JsonElement.class);
                        JsonObject version;
                        // Unknown!
                        int protocolVersion = 0;
                        if (json.isJsonObject()) {
                            if (json.getAsJsonObject().has("version")) {
                                version = json.getAsJsonObject().get("version").getAsJsonObject();
                                if (version.has("protocol")) {
                                    protocolVersion = ((Long) version.get("protocol").getAsLong()).intValue();
                                }
                            } else {
                                json.getAsJsonObject().add("version", version = new JsonObject());
                            }
                        } else {
                            // Format properly
                            json = new JsonObject();
                            json.getAsJsonObject().add("version", version = new JsonObject());
                        }
                        if (Via.getConfig().isSendSupportedVersions()) {
                            // Send supported versions
                            version.add("supportedVersions", GsonUtil.getGson().toJsonTree(Via.getAPI().getSupportedVersions()));
                        }
                        if (!Via.getAPI().getServerVersion().isKnown()) {
                            // Set the Server protocol if the detection on startup failed
                            ProtocolManagerImpl protocolManager = (ProtocolManagerImpl) Via.getManager().getProtocolManager();
                            protocolManager.setServerProtocol(new ServerProtocolVersionSingleton(ProtocolVersion.getProtocol(protocolVersion).getVersion()));
                        }
                        // Ensure the server has a version provider
                        VersionProvider versionProvider = Via.getManager().getProviders().get(VersionProvider.class);
                        if (versionProvider == null) {
                            wrapper.user().setActive(false);
                            return;
                        }
                        int closestServerProtocol = versionProvider.getClosestServerProtocol(wrapper.user());
                        List<ProtocolPathEntry> protocols = null;
                        if (info.getProtocolVersion() >= closestServerProtocol || Via.getPlatform().isOldClientsAllowed()) {
                            protocols = Via.getManager().getProtocolManager().getProtocolPath(info.getProtocolVersion(), closestServerProtocol);
                        }
                        if (protocols != null) {
                            if (protocolVersion == closestServerProtocol || protocolVersion == 0) {
                                // Fix ServerListPlus
                                ProtocolVersion prot = ProtocolVersion.getProtocol(info.getProtocolVersion());
                                version.addProperty("protocol", prot.getOriginalVersion());
                            }
                        } else {
                            // not compatible :(, *plays very sad violin*
                            wrapper.user().setActive(false);
                        }
                        if (Via.getConfig().blockedProtocolVersions().contains(info.getProtocolVersion())) {
                            // Show blocked versions as outdated
                            version.addProperty("protocol", -1);
                        }
                        // Update value
                        wrapper.set(Type.STRING, 0, GsonUtil.getGson().toJson(json));
                    } catch (JsonParseException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    });
    // Login Success Packet
    registerClientbound(ClientboundLoginPackets.GAME_PROFILE, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    ProtocolInfo info = wrapper.user().getProtocolInfo();
                    info.setState(State.PLAY);
                    UUID uuid = passthroughLoginUUID(wrapper);
                    info.setUuid(uuid);
                    String username = wrapper.passthrough(Type.STRING);
                    info.setUsername(username);
                    // Add to ported clients
                    Via.getManager().getConnectionManager().onLoginSuccess(wrapper.user());
                    if (!info.getPipeline().hasNonBaseProtocols()) {
                        // Only base protocol
                        wrapper.user().setActive(false);
                    }
                    if (Via.getManager().isDebug()) {
                        // Print out the route to console
                        Via.getPlatform().getLogger().log(Level.INFO, "{0} logged in with protocol {1}, Route: {2}", new Object[] { username, info.getProtocolVersion(), Joiner.on(", ").join(info.getPipeline().pipes(), ", ") });
                    }
                }
            });
        }
    });
    /* Incoming Packets */
    // Login Start Packet
    registerServerbound(ServerboundLoginPackets.HELLO, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(new PacketHandler() {

                @Override
                public void handle(final PacketWrapper wrapper) throws Exception {
                    int protocol = wrapper.user().getProtocolInfo().getProtocolVersion();
                    if (Via.getConfig().blockedProtocolVersions().contains(protocol)) {
                        if (!wrapper.user().getChannel().isOpen())
                            return;
                        if (!wrapper.user().shouldApplyBlockProtocol())
                            return;
                        // Disconnect Packet
                        PacketWrapper disconnectPacket = PacketWrapper.create(ClientboundLoginPackets.LOGIN_DISCONNECT, wrapper.user());
                        Protocol1_9To1_8.FIX_JSON.write(disconnectPacket, ChatColorUtil.translateAlternateColorCodes(Via.getConfig().getBlockedDisconnectMsg()));
                        // cancel current
                        wrapper.cancel();
                        // Send and close
                        ChannelFuture future = disconnectPacket.sendFuture(BaseProtocol.class);
                        future.addListener(f -> wrapper.user().getChannel().close());
                    }
                }
            });
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ProtocolPathEntry(com.viaversion.viaversion.api.protocol.ProtocolPathEntry) PacketRemapper(com.viaversion.viaversion.api.protocol.remapper.PacketRemapper) JsonObject(com.google.gson.JsonObject) ProtocolVersion(com.viaversion.viaversion.api.protocol.version.ProtocolVersion) JsonParseException(com.google.gson.JsonParseException) VersionProvider(com.viaversion.viaversion.api.protocol.version.VersionProvider) ProtocolManagerImpl(com.viaversion.viaversion.protocol.ProtocolManagerImpl) PacketHandler(com.viaversion.viaversion.api.protocol.remapper.PacketHandler) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) JsonElement(com.google.gson.JsonElement) ProtocolInfo(com.viaversion.viaversion.api.connection.ProtocolInfo) UUID(java.util.UUID) ServerProtocolVersionSingleton(com.viaversion.viaversion.protocol.ServerProtocolVersionSingleton)

Example 45 with PacketWrapper

use of com.viaversion.viaversion.api.protocol.packet.PacketWrapper in project ViaVersion by ViaVersion.

the class UserConnectionImpl method transform.

private void transform(ByteBuf buf, Direction direction, Function<Throwable, Exception> cancelSupplier) throws Exception {
    if (!buf.isReadable())
        return;
    int id = Type.VAR_INT.readPrimitive(buf);
    if (id == PacketWrapper.PASSTHROUGH_ID) {
        if (!passthroughTokens.remove(Type.UUID.read(buf))) {
            throw new IllegalArgumentException("Invalid token");
        }
        return;
    }
    PacketWrapper wrapper = new PacketWrapperImpl(id, buf, this);
    try {
        protocolInfo.getPipeline().transform(direction, protocolInfo.getState(), wrapper);
    } catch (CancelException ex) {
        throw cancelSupplier.apply(ex);
    }
    ByteBuf transformed = buf.alloc().buffer();
    try {
        wrapper.writeToBuffer(transformed);
        buf.clear().writeBytes(transformed);
    } finally {
        transformed.release();
    }
}
Also used : PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) PacketWrapperImpl(com.viaversion.viaversion.protocol.packet.PacketWrapperImpl) CancelException(com.viaversion.viaversion.exception.CancelException) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

PacketWrapper (com.viaversion.viaversion.api.protocol.packet.PacketWrapper)107 PacketRemapper (com.viaversion.viaversion.api.protocol.remapper.PacketRemapper)76 PacketHandler (com.viaversion.viaversion.api.protocol.remapper.PacketHandler)63 Type (com.viaversion.viaversion.api.type.Type)38 Item (com.viaversion.viaversion.api.minecraft.item.Item)32 Chunk (com.viaversion.viaversion.api.minecraft.chunks.Chunk)22 Metadata (com.viaversion.viaversion.api.minecraft.metadata.Metadata)22 ClientWorld (com.viaversion.viaversion.protocols.protocol1_9_3to1_9_1_2.storage.ClientWorld)22 ChunkSection (com.viaversion.viaversion.api.minecraft.chunks.ChunkSection)18 ArrayList (java.util.ArrayList)17 UserConnection (com.viaversion.viaversion.api.connection.UserConnection)16 Position (com.viaversion.viaversion.api.minecraft.Position)16 List (java.util.List)14 ClientboundPackets1_13 (com.viaversion.viaversion.protocols.protocol1_13to1_12_2.ClientboundPackets1_13)13 CompoundTag (com.github.steveice10.opennbt.tag.builtin.CompoundTag)11 EntityType (com.viaversion.viaversion.api.minecraft.entities.EntityType)11 ViaBackwards (com.viaversion.viabackwards.ViaBackwards)10 Via (com.viaversion.viaversion.api.Via)9 BlockChangeRecord (com.viaversion.viaversion.api.minecraft.BlockChangeRecord)9 ClientboundPackets1_14 (com.viaversion.viaversion.protocols.protocol1_14to1_13_2.ClientboundPackets1_14)9