ViaVersion/common/src/main/java/com/viaversion/viaversion/connection/UserConnectionImpl.java

424 lines
14 KiB
Java
Raw Normal View History

2021-04-26 22:54:43 +02:00
/*
* This file is part of ViaVersion - https://github.com/ViaVersion/ViaVersion
2024-01-01 12:39:45 +01:00
* Copyright (C) 2016-2024 ViaVersion and contributors
2021-04-26 22:54:43 +02:00
*
2021-04-30 19:05:07 +02:00
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
2021-04-26 22:54:43 +02:00
*
2021-04-30 19:05:07 +02:00
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
2021-04-26 22:54:43 +02:00
*
2021-04-30 19:05:07 +02:00
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
2021-04-26 22:54:43 +02:00
*/
package com.viaversion.viaversion.connection;
import com.google.common.cache.CacheBuilder;
import com.viaversion.viaversion.api.Via;
import com.viaversion.viaversion.api.connection.ProtocolInfo;
import com.viaversion.viaversion.api.connection.StorableObject;
2021-04-26 22:54:43 +02:00
import com.viaversion.viaversion.api.connection.UserConnection;
Refactor entity tracking and meta handling This essentially merges the two approaches to the metadata handling from ViaVersion and ViaBackwards and improves on both designs. ViaVersion did not track every single entity, but only those needed (at least in theory) and can work with untracked entities' metadata. It had a very simple method overridden by metadata rewriter implementations, directly operating on the full metadata list and manually handling meta index changes as well as item/block/particle id changes. ViaBackwards on the other hand had to track *every single* entity and threw warnings otherwise - while less prone to errors due to giving obvious warnings in the console, it unnecessarily tracks a lot of entities, and those warnings also annoys users when encountering virtual entity plugins (operating asynchronously and sending update packets while already untracked or not yet tracked). Dedicated MetaHandlers made id changes and filtering a lot easier to read and write. However, the actual metadata list handling and its distribution to handlers was not very well implemented and required a lot of list copying and creation as well as exception throws to cancel individual metadata entries. This version has MetaFilters built with a Builder containing multiple helper functions, and the entity tracking is properly given its own map, hashed by a Protocol's class, to be easily and generically accessible from anywhere with only a Protocol class from the UserConnection, along with more optimized metadata list iteration. The entity tracking is largely unchanged, keeping ViaVersion's approach to not having to track *all* entities (and being able to handle null types in meta handlers). All of this is by no means absolutely perfect, but is much less prone to errors than both previous systems and takes a lot less effort to actually write. A last possible change would be to use a primitive int to object map that is built to be concurrency save for the EntityTracker, tho that would have to be chosen carefully.
2021-05-24 23:24:50 +02:00
import com.viaversion.viaversion.api.data.entity.EntityTracker;
import com.viaversion.viaversion.api.protocol.Protocol;
2021-04-26 22:54:43 +02:00
import com.viaversion.viaversion.api.protocol.packet.Direction;
import com.viaversion.viaversion.api.protocol.packet.PacketTracker;
import com.viaversion.viaversion.api.protocol.packet.PacketWrapper;
import com.viaversion.viaversion.api.protocol.packet.State;
2021-04-26 22:54:43 +02:00
import com.viaversion.viaversion.api.type.Type;
import com.viaversion.viaversion.exception.CancelException;
import com.viaversion.viaversion.protocol.packet.PacketWrapperImpl;
2021-04-26 22:54:43 +02:00
import com.viaversion.viaversion.util.ChatColorUtil;
import com.viaversion.viaversion.util.PipelineUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
Refactor entity tracking and meta handling This essentially merges the two approaches to the metadata handling from ViaVersion and ViaBackwards and improves on both designs. ViaVersion did not track every single entity, but only those needed (at least in theory) and can work with untracked entities' metadata. It had a very simple method overridden by metadata rewriter implementations, directly operating on the full metadata list and manually handling meta index changes as well as item/block/particle id changes. ViaBackwards on the other hand had to track *every single* entity and threw warnings otherwise - while less prone to errors due to giving obvious warnings in the console, it unnecessarily tracks a lot of entities, and those warnings also annoys users when encountering virtual entity plugins (operating asynchronously and sending update packets while already untracked or not yet tracked). Dedicated MetaHandlers made id changes and filtering a lot easier to read and write. However, the actual metadata list handling and its distribution to handlers was not very well implemented and required a lot of list copying and creation as well as exception throws to cancel individual metadata entries. This version has MetaFilters built with a Builder containing multiple helper functions, and the entity tracking is properly given its own map, hashed by a Protocol's class, to be easily and generically accessible from anywhere with only a Protocol class from the UserConnection, along with more optimized metadata list iteration. The entity tracking is largely unchanged, keeping ViaVersion's approach to not having to track *all* entities (and being able to handle null types in meta handlers). All of this is by no means absolutely perfect, but is much less prone to errors than both previous systems and takes a lot less effort to actually write. A last possible change would be to use a primitive int to object map that is built to be concurrency save for the EntityTracker, tho that would have to be chosen carefully.
2021-05-24 23:24:50 +02:00
import java.util.Collection;
2021-04-26 22:54:43 +02:00
import java.util.Collections;
Refactor entity tracking and meta handling This essentially merges the two approaches to the metadata handling from ViaVersion and ViaBackwards and improves on both designs. ViaVersion did not track every single entity, but only those needed (at least in theory) and can work with untracked entities' metadata. It had a very simple method overridden by metadata rewriter implementations, directly operating on the full metadata list and manually handling meta index changes as well as item/block/particle id changes. ViaBackwards on the other hand had to track *every single* entity and threw warnings otherwise - while less prone to errors due to giving obvious warnings in the console, it unnecessarily tracks a lot of entities, and those warnings also annoys users when encountering virtual entity plugins (operating asynchronously and sending update packets while already untracked or not yet tracked). Dedicated MetaHandlers made id changes and filtering a lot easier to read and write. However, the actual metadata list handling and its distribution to handlers was not very well implemented and required a lot of list copying and creation as well as exception throws to cancel individual metadata entries. This version has MetaFilters built with a Builder containing multiple helper functions, and the entity tracking is properly given its own map, hashed by a Protocol's class, to be easily and generically accessible from anywhere with only a Protocol class from the UserConnection, along with more optimized metadata list iteration. The entity tracking is largely unchanged, keeping ViaVersion's approach to not having to track *all* entities (and being able to handle null types in meta handlers). All of this is by no means absolutely perfect, but is much less prone to errors than both previous systems and takes a lot less effort to actually write. A last possible change would be to use a primitive int to object map that is built to be concurrency save for the EntityTracker, tho that would have to be chosen carefully.
2021-05-24 23:24:50 +02:00
import java.util.HashMap;
2021-04-26 22:54:43 +02:00
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import org.checkerframework.checker.nullness.qual.Nullable;
2021-04-26 22:54:43 +02:00
public class UserConnectionImpl implements UserConnection {
private static final AtomicLong IDS = new AtomicLong();
private final long id = IDS.incrementAndGet();
private final Map<Class<?>, StorableObject> storedObjects = new ConcurrentHashMap<>();
Refactor entity tracking and meta handling This essentially merges the two approaches to the metadata handling from ViaVersion and ViaBackwards and improves on both designs. ViaVersion did not track every single entity, but only those needed (at least in theory) and can work with untracked entities' metadata. It had a very simple method overridden by metadata rewriter implementations, directly operating on the full metadata list and manually handling meta index changes as well as item/block/particle id changes. ViaBackwards on the other hand had to track *every single* entity and threw warnings otherwise - while less prone to errors due to giving obvious warnings in the console, it unnecessarily tracks a lot of entities, and those warnings also annoys users when encountering virtual entity plugins (operating asynchronously and sending update packets while already untracked or not yet tracked). Dedicated MetaHandlers made id changes and filtering a lot easier to read and write. However, the actual metadata list handling and its distribution to handlers was not very well implemented and required a lot of list copying and creation as well as exception throws to cancel individual metadata entries. This version has MetaFilters built with a Builder containing multiple helper functions, and the entity tracking is properly given its own map, hashed by a Protocol's class, to be easily and generically accessible from anywhere with only a Protocol class from the UserConnection, along with more optimized metadata list iteration. The entity tracking is largely unchanged, keeping ViaVersion's approach to not having to track *all* entities (and being able to handle null types in meta handlers). All of this is by no means absolutely perfect, but is much less prone to errors than both previous systems and takes a lot less effort to actually write. A last possible change would be to use a primitive int to object map that is built to be concurrency save for the EntityTracker, tho that would have to be chosen carefully.
2021-05-24 23:24:50 +02:00
private final Map<Class<? extends Protocol>, EntityTracker> entityTrackers = new HashMap<>();
2021-04-26 22:54:43 +02:00
private final PacketTracker packetTracker = new PacketTracker(this);
private final Set<UUID> passthroughTokens = Collections.newSetFromMap(CacheBuilder.newBuilder()
.expireAfterWrite(10, TimeUnit.SECONDS)
.<UUID, Boolean>build().asMap());
private final ProtocolInfo protocolInfo = new ProtocolInfoImpl(this);
2021-04-26 22:54:43 +02:00
private final Channel channel;
private final boolean clientSide;
private boolean active = true;
private boolean pendingDisconnect;
private boolean packetLimiterEnabled = true;
2021-04-26 22:54:43 +02:00
/**
* Creates an UserConnection. When it's a client-side connection, some method behaviors are modified.
*
* @param channel netty channel.
* @param clientSide true if it's a client-side connection
*/
public UserConnectionImpl(@Nullable Channel channel, boolean clientSide) {
this.channel = channel;
this.clientSide = clientSide;
}
/**
* @see #UserConnectionImpl(Channel, boolean)
*/
public UserConnectionImpl(@Nullable Channel channel) {
this(channel, false);
}
@Override
public @Nullable <T extends StorableObject> T get(Class<T> objectClass) {
2021-04-26 22:54:43 +02:00
return (T) storedObjects.get(objectClass);
}
@Override
public boolean has(Class<? extends StorableObject> objectClass) {
2021-04-26 22:54:43 +02:00
return storedObjects.containsKey(objectClass);
}
2022-04-27 21:06:34 +02:00
@Override
public <T extends StorableObject> @Nullable T remove(Class<T> objectClass) {
final StorableObject object = storedObjects.remove(objectClass);
if (object != null) {
object.onRemove();
}
return (T) object;
2022-04-27 21:06:34 +02:00
}
2021-04-26 22:54:43 +02:00
@Override
public void put(StorableObject object) {
final StorableObject previousObject = storedObjects.put(object.getClass(), object);
if (previousObject != null) {
previousObject.onRemove();
}
2021-04-26 22:54:43 +02:00
}
Refactor entity tracking and meta handling This essentially merges the two approaches to the metadata handling from ViaVersion and ViaBackwards and improves on both designs. ViaVersion did not track every single entity, but only those needed (at least in theory) and can work with untracked entities' metadata. It had a very simple method overridden by metadata rewriter implementations, directly operating on the full metadata list and manually handling meta index changes as well as item/block/particle id changes. ViaBackwards on the other hand had to track *every single* entity and threw warnings otherwise - while less prone to errors due to giving obvious warnings in the console, it unnecessarily tracks a lot of entities, and those warnings also annoys users when encountering virtual entity plugins (operating asynchronously and sending update packets while already untracked or not yet tracked). Dedicated MetaHandlers made id changes and filtering a lot easier to read and write. However, the actual metadata list handling and its distribution to handlers was not very well implemented and required a lot of list copying and creation as well as exception throws to cancel individual metadata entries. This version has MetaFilters built with a Builder containing multiple helper functions, and the entity tracking is properly given its own map, hashed by a Protocol's class, to be easily and generically accessible from anywhere with only a Protocol class from the UserConnection, along with more optimized metadata list iteration. The entity tracking is largely unchanged, keeping ViaVersion's approach to not having to track *all* entities (and being able to handle null types in meta handlers). All of this is by no means absolutely perfect, but is much less prone to errors than both previous systems and takes a lot less effort to actually write. A last possible change would be to use a primitive int to object map that is built to be concurrency save for the EntityTracker, tho that would have to be chosen carefully.
2021-05-24 23:24:50 +02:00
@Override
public Collection<EntityTracker> getEntityTrackers() {
return entityTrackers.values();
}
@Override
public @Nullable <T extends EntityTracker> T getEntityTracker(Class<? extends Protocol> protocolClass) {
return (T) entityTrackers.get(protocolClass);
}
@Override
public void addEntityTracker(Class<? extends Protocol> protocolClass, EntityTracker tracker) {
if (!entityTrackers.containsKey(protocolClass)) {
entityTrackers.put(protocolClass, tracker);
}
Refactor entity tracking and meta handling This essentially merges the two approaches to the metadata handling from ViaVersion and ViaBackwards and improves on both designs. ViaVersion did not track every single entity, but only those needed (at least in theory) and can work with untracked entities' metadata. It had a very simple method overridden by metadata rewriter implementations, directly operating on the full metadata list and manually handling meta index changes as well as item/block/particle id changes. ViaBackwards on the other hand had to track *every single* entity and threw warnings otherwise - while less prone to errors due to giving obvious warnings in the console, it unnecessarily tracks a lot of entities, and those warnings also annoys users when encountering virtual entity plugins (operating asynchronously and sending update packets while already untracked or not yet tracked). Dedicated MetaHandlers made id changes and filtering a lot easier to read and write. However, the actual metadata list handling and its distribution to handlers was not very well implemented and required a lot of list copying and creation as well as exception throws to cancel individual metadata entries. This version has MetaFilters built with a Builder containing multiple helper functions, and the entity tracking is properly given its own map, hashed by a Protocol's class, to be easily and generically accessible from anywhere with only a Protocol class from the UserConnection, along with more optimized metadata list iteration. The entity tracking is largely unchanged, keeping ViaVersion's approach to not having to track *all* entities (and being able to handle null types in meta handlers). All of this is by no means absolutely perfect, but is much less prone to errors than both previous systems and takes a lot less effort to actually write. A last possible change would be to use a primitive int to object map that is built to be concurrency save for the EntityTracker, tho that would have to be chosen carefully.
2021-05-24 23:24:50 +02:00
}
2021-04-26 22:54:43 +02:00
@Override
public void clearStoredObjects(boolean isServerSwitch) {
if (isServerSwitch) {
storedObjects.values().removeIf(storableObject -> {
if (storableObject.clearOnServerSwitch()) {
storableObject.onRemove();
return true;
}
return false;
});
for (EntityTracker tracker : entityTrackers.values()) {
tracker.clearEntities();
tracker.trackClientEntity();
}
} else {
for (StorableObject object : storedObjects.values()) {
object.onRemove();
}
storedObjects.clear();
entityTrackers.clear();
}
2021-04-26 22:54:43 +02:00
}
@Override
public void sendRawPacket(ByteBuf packet) {
sendRawPacket(packet, true);
}
@Override
public void scheduleSendRawPacket(ByteBuf packet) {
sendRawPacket(packet, false);
}
private void sendRawPacket(final ByteBuf packet, boolean currentThread) {
2021-04-26 22:54:43 +02:00
Runnable act;
if (clientSide) {
// We'll just assume that Via decoder isn't wrapping the original decoder
act = () -> getChannel().pipeline()
.context(Via.getManager().getInjector().getDecoderName()).fireChannelRead(packet);
} else {
act = () -> channel.pipeline().context(Via.getManager().getInjector().getEncoderName()).writeAndFlush(packet);
}
if (currentThread) {
act.run();
} else {
try {
channel.eventLoop().submit(act);
} catch (Throwable e) {
packet.release(); // Couldn't schedule
e.printStackTrace();
}
}
}
@Override
public ChannelFuture sendRawPacketFuture(final ByteBuf packet) {
if (clientSide) {
// Assume that decoder isn't wrapping
getChannel().pipeline().context(Via.getManager().getInjector().getDecoderName()).fireChannelRead(packet);
return getChannel().newSucceededFuture();
2021-04-26 22:54:43 +02:00
} else {
return channel.pipeline().context(Via.getManager().getInjector().getEncoderName()).writeAndFlush(packet);
2021-04-26 22:54:43 +02:00
}
}
@Override
public PacketTracker getPacketTracker() {
return packetTracker;
}
@Override
public void disconnect(String reason) {
if (!channel.isOpen() || pendingDisconnect) return;
pendingDisconnect = true;
Via.getPlatform().runSync(() -> {
if (!Via.getPlatform().disconnect(this, ChatColorUtil.translateAlternateColorCodes(reason))) {
channel.close(); // =)
}
});
}
@Override
public void sendRawPacketToServer(ByteBuf packet) {
if (clientSide) {
sendRawPacketToServerClientSide(packet, true);
} else {
sendRawPacketToServerServerSide(packet, true);
}
}
@Override
public void scheduleSendRawPacketToServer(ByteBuf packet) {
2021-04-26 22:54:43 +02:00
if (clientSide) {
sendRawPacketToServerClientSide(packet, false);
2021-04-26 22:54:43 +02:00
} else {
sendRawPacketToServerServerSide(packet, false);
2021-04-26 22:54:43 +02:00
}
}
private void sendRawPacketToServerServerSide(final ByteBuf packet, boolean currentThread) {
final ByteBuf buf = packet.alloc().buffer();
try {
// We'll use passing through because there are some encoder wrappers
ChannelHandlerContext context = PipelineUtil
.getPreviousContext(Via.getManager().getInjector().getDecoderName(), channel.pipeline());
if (shouldTransformPacket()) {
// Bypass serverbound packet decoder transforming
try {
Type.VAR_INT.writePrimitive(buf, PacketWrapper.PASSTHROUGH_ID);
Type.UUID.write(buf, generatePassthroughToken());
} catch (Exception shouldNotHappen) {
throw new RuntimeException(shouldNotHappen);
}
2021-04-26 22:54:43 +02:00
}
2021-04-26 22:54:43 +02:00
buf.writeBytes(packet);
Runnable act = () -> {
if (context != null) {
context.fireChannelRead(buf);
} else {
channel.pipeline().fireChannelRead(buf);
}
};
if (currentThread) {
act.run();
} else {
try {
channel.eventLoop().submit(act);
} catch (Throwable t) {
// Couldn't schedule
buf.release();
throw t;
}
}
} finally {
packet.release();
}
}
private void sendRawPacketToServerClientSide(final ByteBuf packet, boolean currentThread) {
Runnable act = () -> getChannel().pipeline()
.context(Via.getManager().getInjector().getEncoderName()).writeAndFlush(packet);
if (currentThread) {
act.run();
} else {
try {
getChannel().eventLoop().submit(act);
} catch (Throwable e) {
e.printStackTrace();
packet.release(); // Couldn't schedule
}
}
}
@Override
public boolean checkServerboundPacket() {
2021-09-02 17:33:09 +02:00
if (pendingDisconnect) {
return false;
}
2021-04-26 22:54:43 +02:00
// Increment received + Check PPS
2021-09-02 17:33:09 +02:00
return !packetLimiterEnabled || !packetTracker.incrementReceived() || !packetTracker.exceedsMaxPPS();
2021-04-26 22:54:43 +02:00
}
@Override
public boolean checkClientboundPacket() {
packetTracker.incrementSent();
return true;
2021-04-26 22:54:43 +02:00
}
@Override
public boolean shouldTransformPacket() {
return active;
}
@Override
public void transformClientbound(ByteBuf buf, Function<Throwable, Exception> cancelSupplier) throws Exception {
transform(buf, Direction.CLIENTBOUND, cancelSupplier);
2021-04-26 22:54:43 +02:00
}
@Override
public void transformServerbound(ByteBuf buf, Function<Throwable, Exception> cancelSupplier) throws Exception {
transform(buf, Direction.SERVERBOUND, cancelSupplier);
2021-04-26 22:54:43 +02:00
}
private void transform(ByteBuf buf, Direction direction, Function<Throwable, Exception> cancelSupplier) throws Exception {
if (!buf.isReadable()) return;
2021-04-26 22:54:43 +02:00
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);
State state = protocolInfo.getState(direction);
2021-04-26 22:54:43 +02:00
try {
protocolInfo.getPipeline().transform(direction, state, wrapper);
2021-04-26 22:54:43 +02:00
} catch (CancelException ex) {
throw cancelSupplier.apply(ex);
}
ByteBuf transformed = buf.alloc().buffer();
try {
wrapper.writeToBuffer(transformed);
buf.clear().writeBytes(transformed);
} finally {
transformed.release();
}
}
@Override
public long getId() {
return id;
}
@Override
public @Nullable Channel getChannel() {
return channel;
}
@Override
public ProtocolInfo getProtocolInfo() {
2021-04-26 22:54:43 +02:00
return protocolInfo;
}
@Override
public Map<Class<?>, StorableObject> getStoredObjects() {
2021-04-26 22:54:43 +02:00
return storedObjects;
}
@Override
public boolean isActive() {
return active;
}
@Override
public void setActive(boolean active) {
this.active = active;
}
@Override
public boolean isPendingDisconnect() {
return pendingDisconnect;
}
@Override
public void setPendingDisconnect(boolean pendingDisconnect) {
this.pendingDisconnect = pendingDisconnect;
}
@Override
public boolean isClientSide() {
return clientSide;
}
@Override
public boolean shouldApplyBlockProtocol() {
return !clientSide; // Don't apply protocol blocking on client-side
}
@Override
public boolean isPacketLimiterEnabled() {
return packetLimiterEnabled;
}
@Override
public void setPacketLimiterEnabled(boolean packetLimiterEnabled) {
this.packetLimiterEnabled = packetLimiterEnabled;
}
2021-04-26 22:54:43 +02:00
@Override
public UUID generatePassthroughToken() {
UUID token = UUID.randomUUID();
passthroughTokens.add(token);
return token;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserConnectionImpl that = (UserConnectionImpl) o;
return id == that.id;
}
@Override
public int hashCode() {
return Long.hashCode(id);
}
}