ViaVersion/bungee/src/main/java/com/viaversion/viaversion/bungee/handlers/BungeeServerHandler.java

294 lines
13 KiB
Java
Raw Normal View History

/*
* 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
*
* 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.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.viaversion.viaversion.bungee.handlers;
import com.viaversion.viaversion.api.Via;
2021-04-26 22:54:43 +02:00
import com.viaversion.viaversion.api.connection.ProtocolInfo;
import com.viaversion.viaversion.api.connection.StorableObject;
2021-04-26 21:35:29 +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.ClientEntityIdChangeListener;
import com.viaversion.viaversion.api.data.entity.EntityTracker;
import com.viaversion.viaversion.api.protocol.Protocol;
import com.viaversion.viaversion.api.protocol.ProtocolPathEntry;
import com.viaversion.viaversion.api.protocol.ProtocolPipeline;
2021-04-26 22:54:43 +02:00
import com.viaversion.viaversion.api.protocol.packet.PacketWrapper;
2021-04-26 21:16:10 +02:00
import com.viaversion.viaversion.api.protocol.version.ProtocolVersion;
import com.viaversion.viaversion.api.type.Type;
import com.viaversion.viaversion.bungee.storage.BungeeStorage;
import com.viaversion.viaversion.protocols.protocol1_13to1_12_2.packets.InventoryPackets;
2021-06-01 23:27:33 +02:00
import com.viaversion.viaversion.protocols.protocol1_9to1_8.ClientboundPackets1_9;
import com.viaversion.viaversion.protocols.protocol1_9to1_8.Protocol1_9To1_8;
import com.viaversion.viaversion.protocols.protocol1_9to1_8.providers.EntityIdProvider;
import com.viaversion.viaversion.protocols.protocol1_9to1_8.storage.EntityTracker1_9;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.connection.Server;
import net.md_5.bungee.api.event.ServerConnectEvent;
import net.md_5.bungee.api.event.ServerConnectedEvent;
import net.md_5.bungee.api.event.ServerSwitchEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.score.Team;
import net.md_5.bungee.event.EventHandler;
import net.md_5.bungee.protocol.packet.PluginMessage;
// All of this is madness
public class BungeeServerHandler implements Listener {
private static final Method getHandshake;
private static final Method getRegisteredChannels;
private static final Method getBrandMessage;
private static final Method setProtocol;
private static final Method getEntityMap;
private static final Method setVersion;
private static final Field entityRewrite;
private static final Field channelWrapper;
static {
try {
getHandshake = Class.forName("net.md_5.bungee.connection.InitialHandler").getDeclaredMethod("getHandshake");
getRegisteredChannels = Class.forName("net.md_5.bungee.connection.InitialHandler").getDeclaredMethod("getRegisteredChannels");
getBrandMessage = Class.forName("net.md_5.bungee.connection.InitialHandler").getDeclaredMethod("getBrandMessage");
setProtocol = Class.forName("net.md_5.bungee.protocol.packet.Handshake").getDeclaredMethod("setProtocolVersion", int.class);
getEntityMap = Class.forName("net.md_5.bungee.entitymap.EntityMap").getDeclaredMethod("getEntityMap", int.class);
setVersion = Class.forName("net.md_5.bungee.netty.ChannelWrapper").getDeclaredMethod("setVersion", int.class);
channelWrapper = Class.forName("net.md_5.bungee.UserConnection").getDeclaredField("ch");
channelWrapper.setAccessible(true);
entityRewrite = Class.forName("net.md_5.bungee.UserConnection").getDeclaredField("entityRewrite");
entityRewrite.setAccessible(true);
} catch (ReflectiveOperationException e) {
2021-11-15 11:00:18 +01:00
Via.getPlatform().getLogger().severe("Error initializing BungeeServerHandler, try updating BungeeCord or ViaVersion!");
throw new RuntimeException(e);
}
}
// Set the handshake version every time someone connects to any server
2020-06-30 13:51:06 +02:00
@EventHandler(priority = 120)
public void onServerConnect(ServerConnectEvent event) {
if (event.isCancelled()) {
return;
}
UserConnection user = Via.getManager().getConnectionManager().getConnectedClient(event.getPlayer().getUniqueId());
if (user == null) {
2019-09-19 11:22:06 +02:00
return;
}
if (!user.has(BungeeStorage.class)) {
user.put(new BungeeStorage(event.getPlayer()));
}
int serverProtocolVersion = Via.proxyPlatform().protocolDetectorService().serverProtocolVersion(event.getTarget().getName());
int clientProtocolVersion = user.getProtocolInfo().getProtocolVersion();
List<ProtocolPathEntry> protocols = Via.getManager().getProtocolManager().getProtocolPath(clientProtocolVersion, serverProtocolVersion);
// Check if ViaVersion can support that version
try {
Object handshake = getHandshake.invoke(event.getPlayer().getPendingConnection());
setProtocol.invoke(handshake, protocols == null ? clientProtocolVersion : serverProtocolVersion);
} catch (InvocationTargetException | IllegalAccessException e) {
Via.getPlatform().getLogger().log(Level.SEVERE, "Error setting handshake version", e);
}
}
2020-06-30 13:51:06 +02:00
@EventHandler(priority = -120)
public void onServerConnected(ServerConnectedEvent event) {
try {
checkServerChange(event, Via.getManager().getConnectionManager().getConnectedClient(event.getPlayer().getUniqueId()));
} catch (Exception e) {
Via.getPlatform().getLogger().log(Level.SEVERE, "Failed to handle server switch", e);
}
}
2020-06-30 13:51:06 +02:00
@EventHandler(priority = -120)
public void onServerSwitch(ServerSwitchEvent event) {
// Update entity id
UserConnection userConnection = Via.getManager().getConnectionManager().getConnectedClient(event.getPlayer().getUniqueId());
if (userConnection == null) {
return;
}
int playerId;
try {
playerId = Via.getManager().getProviders().get(EntityIdProvider.class).getEntityId(userConnection);
2023-10-11 15:14:41 +02:00
} catch (Exception ignored) {
return;
}
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
for (EntityTracker tracker : userConnection.getEntityTrackers()) {
tracker.setClientEntityId(playerId);
}
// For ViaRewind
for (StorableObject object : userConnection.getStoredObjects().values()) {
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
if (object instanceof ClientEntityIdChangeListener) {
((ClientEntityIdChangeListener) object).setClientEntityId(playerId);
}
}
}
public void checkServerChange(ServerConnectedEvent event, UserConnection user) throws Exception {
if (user == null) {
return;
}
BungeeStorage storage = user.get(BungeeStorage.class);
if (storage == null) {
return;
}
Server server = event.getServer();
if (server == null || server.getInfo().getName().equals(storage.getCurrentServer())) {
return;
}
// Clear auto-team
EntityTracker1_9 oldEntityTracker = user.getEntityTracker(Protocol1_9To1_8.class);
2023-10-11 15:14:41 +02:00
if (oldEntityTracker != null && oldEntityTracker.isAutoTeam() && oldEntityTracker.isTeamExists()) {
oldEntityTracker.sendTeamPacket(false, true);
}
2023-10-11 15:14:41 +02:00
String serverName = server.getInfo().getName();
storage.setCurrentServer(serverName);
int serverProtocolVersion = Via.proxyPlatform().protocolDetectorService().serverProtocolVersion(serverName);
if (serverProtocolVersion <= ProtocolVersion.v1_8.getVersion() && storage.getBossbar() != null) { // 1.8 doesn't have BossBar packet
// This ensures we can encode it properly as only the 1.9 protocol is currently implemented.
if (user.getProtocolInfo().getPipeline().contains(Protocol1_9To1_8.class)) {
for (UUID uuid : storage.getBossbar()) {
PacketWrapper wrapper = PacketWrapper.create(ClientboundPackets1_9.BOSSBAR, null, user);
wrapper.write(Type.UUID, uuid);
wrapper.write(Type.VAR_INT, 1); // remove
wrapper.send(Protocol1_9To1_8.class);
}
}
storage.getBossbar().clear();
}
ProtocolInfo info = user.getProtocolInfo();
int previousServerProtocol = info.getServerProtocolVersion();
2018-08-04 12:37:33 +02:00
// Refresh the pipes
List<ProtocolPathEntry> protocolPath = Via.getManager().getProtocolManager().getProtocolPath(info.getProtocolVersion(), serverProtocolVersion);
ProtocolPipeline pipeline = user.getProtocolInfo().getPipeline();
user.clearStoredObjects(true);
pipeline.cleanPipes();
if (protocolPath == null) {
// TODO Check Bungee Supported Protocols? *shrugs*
serverProtocolVersion = info.getProtocolVersion();
} else {
List<Protocol> protocols = new ArrayList<>(protocolPath.size());
for (ProtocolPathEntry entry : protocolPath) {
protocols.add(entry.protocol());
}
pipeline.add(protocols);
}
info.setServerProtocolVersion(serverProtocolVersion);
// Add version-specific base Protocol
pipeline.add(Via.getManager().getProtocolManager().getBaseProtocol(serverProtocolVersion));
// Workaround 1.13 server change
int id1_13 = ProtocolVersion.v1_13.getVersion();
boolean toNewId = previousServerProtocol < id1_13 && serverProtocolVersion >= id1_13;
boolean toOldId = previousServerProtocol >= id1_13 && serverProtocolVersion < id1_13;
if (previousServerProtocol != -1 && (toNewId || toOldId)) {
Collection<String> registeredChannels = (Collection<String>) getRegisteredChannels.invoke(event.getPlayer().getPendingConnection());
if (!registeredChannels.isEmpty()) {
Collection<String> newChannels = new HashSet<>();
for (Iterator<String> iterator = registeredChannels.iterator(); iterator.hasNext(); ) {
String channel = iterator.next();
String oldChannel = channel;
if (toNewId) {
channel = InventoryPackets.getNewPluginChannelId(channel);
} else {
channel = InventoryPackets.getOldPluginChannelId(channel);
2018-08-04 12:37:33 +02:00
}
if (channel == null) {
iterator.remove();
continue;
}
if (!oldChannel.equals(channel)) {
iterator.remove();
newChannels.add(channel);
}
}
registeredChannels.addAll(newChannels);
}
PluginMessage brandMessage = (PluginMessage) getBrandMessage.invoke(event.getPlayer().getPendingConnection());
if (brandMessage != null) {
String channel = brandMessage.getTag();
if (toNewId) {
channel = InventoryPackets.getNewPluginChannelId(channel);
} else {
channel = InventoryPackets.getOldPluginChannelId(channel);
}
if (channel != null) {
brandMessage.setTag(channel);
}
}
}
user.put(storage);
user.setActive(protocolPath != null);
// Init all protocols TODO check if this can get moved up to the previous for loop, and doesn't require the pipeline to already exist.
for (Protocol protocol : pipeline.pipes()) {
protocol.init(user);
}
ProxiedPlayer player = storage.getPlayer();
EntityTracker1_9 newTracker = user.getEntityTracker(Protocol1_9To1_8.class);
if (newTracker != null && Via.getConfig().isAutoTeam()) {
String currentTeam = null;
for (Team team : player.getScoreboard().getTeams()) {
if (team.getPlayers().contains(info.getUsername())) {
currentTeam = team.getName();
}
}
// Reinitialize auto-team
newTracker.setAutoTeam(true);
if (currentTeam == null) {
// Send auto-team as it was cleared above
newTracker.sendTeamPacket(true, true);
newTracker.setCurrentTeam("viaversion");
} else {
// Auto-team will be sent when bungee send remove packet
newTracker.setAutoTeam(Via.getConfig().isAutoTeam());
newTracker.setCurrentTeam(currentTeam);
}
}
Object wrapper = channelWrapper.get(player);
setVersion.invoke(wrapper, serverProtocolVersion);
Object entityMap = getEntityMap.invoke(null, serverProtocolVersion);
entityRewrite.set(player, entityMap);
}
}