Rewrite networking.

This commit is contained in:
LexManos committed 2023-09-10 20:27:15 -07:00
1 parent 3edefbe33e
commit 4649f7af36
103 files changed
+4399 -5303

No files matched your search

@@ -20,8 +20,13 @@ import net.minecraft.core.Holder;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.registries.Registries;
import net.minecraft.gametest.framework.GameTestServer;
import net.minecraft.network.Connection;
import net.minecraft.network.ConnectionProtocol;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.protocol.handshake.ClientIntent;
import net.minecraft.network.protocol.handshake.ClientIntentionPacket;
import net.minecraft.network.protocol.login.ClientboundLoginDisconnectPacket;
import net.minecraft.server.packs.PackResources;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.repository.PackSource;
@@ -35,11 +40,10 @@ import net.minecraftforge.common.world.BiomeModifier;
import net.minecraftforge.fml.ModLoader;
import net.minecraftforge.fml.ModLoadingStage;
import net.minecraftforge.fml.ModLoadingWarning;
import net.minecraftforge.network.ConnectionType;
import net.minecraftforge.network.NetworkConstants;
import net.minecraftforge.network.NetworkHooks;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.forgespi.locating.IModFile;
import net.minecraftforge.network.ConnectionType;
import net.minecraftforge.network.NetworkContext;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.registries.ForgeRegistries.Keys;
import net.minecraftforge.resource.PathPackResources;
import net.minecraftforge.server.permission.PermissionAPI;
@@ -48,10 +52,6 @@ import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import net.minecraft.network.Connection;
import net.minecraft.network.ConnectionProtocol;
import net.minecraft.network.protocol.handshake.ClientIntentionPacket;
import net.minecraft.network.protocol.login.ClientboundLoginDisconnectPacket;
import net.minecraft.server.packs.repository.Pack;
import net.minecraft.server.packs.repository.Pack.Info;
import net.minecraft.server.MinecraftServer;
@@ -69,16 +69,17 @@ import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.GameData;
import org.jetbrains.annotations.ApiStatus;
public class ServerLifecycleHooks
{
@SuppressWarnings("deprecation")
@ApiStatus.Internal
public class ServerLifecycleHooks {
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker SERVERHOOKS = MarkerManager.getMarker("SERVERHOOKS");
private static final LevelResource SERVERCONFIG = new LevelResource("serverconfig");
private static final AtomicBoolean allowLogins = new AtomicBoolean(false);
private static volatile CountDownLatch exitLatch = null;
private static MinecraftServer currentServer;
private static Path getServerConfigPath(final MinecraftServer server)
{
private static Path getServerConfigPath(final MinecraftServer server) {
final Path serverConfig = server.getWorldPath(SERVERCONFIG);
if (!Files.isDirectory(serverConfig)) {
try {
@@ -90,8 +91,7 @@ public class ServerLifecycleHooks
return serverConfig;
}
public static boolean handleServerAboutToStart(final MinecraftServer server)
{
public static boolean handleServerAboutToStart(final MinecraftServer server) {
currentServer = server;
// on the dedi server we need to force the stuff to setup properly
LogicalSidedProvider.setServer(()->server);
@@ -100,8 +100,7 @@ public class ServerLifecycleHooks
return !MinecraftForge.EVENT_BUS.post(new ServerAboutToStartEvent(server));
}
public static boolean handleServerStarting(final MinecraftServer server)
{
public static boolean handleServerStarting(final MinecraftServer server) {
DistExecutor.runWhenOn(Dist.DEDICATED_SERVER, ()->()->{
LanguageHook.loadLanguagesOnServer(server);
// GameTestServer requires the gametests to be registered earlier, so it is done in main and should not be done twice.
@@ -112,90 +111,28 @@ public class ServerLifecycleHooks
return !MinecraftForge.EVENT_BUS.post(new ServerStartingEvent(server));
}
public static void handleServerStarted(final MinecraftServer server)
{
MinecraftForge.EVENT_BUS.post(new ServerStartedEvent(server));
allowLogins.set(true);
}
public static void handleServerStopping(final MinecraftServer server)
{
allowLogins.set(false);
MinecraftForge.EVENT_BUS.post(new ServerStoppingEvent(server));
}
public static void expectServerStopped()
{
public static void expectServerStopped() {
exitLatch = new CountDownLatch(1);
}
public static void handleServerStopped(final MinecraftServer server)
{
public static void handleServerStopped(final MinecraftServer server) {
if (!server.isDedicatedServer()) GameData.revertToFrozen();
MinecraftForge.EVENT_BUS.post(new ServerStoppedEvent(server));
currentServer = null;
LogicalSidedProvider.setServer(null);
CountDownLatch latch = exitLatch;
if (latch != null)
{
if (latch != null) {
latch.countDown();
exitLatch = null;
}
ConfigTracker.INSTANCE.unloadConfigs(ModConfig.Type.SERVER, getServerConfigPath(server));
}
public static MinecraftServer getCurrentServer()
{
public static MinecraftServer getCurrentServer() {
return currentServer;
}
private static AtomicBoolean allowLogins = new AtomicBoolean(false);
public static boolean handleServerLogin(final ClientIntentionPacket packet, final Connection manager) {
if (!allowLogins.get())
{
MutableComponent text = Component.literal("Server is still starting! Please wait before reconnecting.");
LOGGER.info(SERVERHOOKS,"Disconnecting Player (server is still starting): {}", text.getContents());
manager.send(new ClientboundLoginDisconnectPacket(text));
manager.disconnect(text);
return false;
}
if (packet.nextProtocol() == ConnectionProtocol.LOGIN) {
var fmlVersion = NetworkHooks.getFMLVersion(packet.hostName());
final ConnectionType connectionType = ConnectionType.forVersionFlag(fmlVersion);
final int versionNumber = connectionType.getFMLVersionNumber(fmlVersion);
if (connectionType == ConnectionType.MODDED && versionNumber != NetworkConstants.FMLNETVERSION) {
rejectConnection(manager, connectionType, "This modded server is not impl compatible with your modded client. Please verify your Forge version closely matches the server. Got net version " + versionNumber + " this server is net version " + NetworkConstants.FMLNETVERSION);
return false;
}
if (connectionType == ConnectionType.VANILLA && !NetworkRegistry.acceptsVanillaClientConnections()) {
rejectConnection(manager, connectionType, "This server has mods that require Forge to be installed on the client. Contact your server admin for more details.");
return false;
}
}
if (packet.nextProtocol() == ConnectionProtocol.STATUS) return true;
NetworkHooks.registerServerLoginChannel(manager, packet);
return true;
}
private static void rejectConnection(final Connection manager, ConnectionType type, String message) {
//manager.setProtocol(ConnectionProtocol.LOGIN); Pretty sure things auto swap in ProtocolSwapHandler
LOGGER.info(SERVERHOOKS, "[{}] Disconnecting {} connection attempt: {}", manager.getLoggableAddress(true), type, message); // TODO: Respect logIP setting
MutableComponent text = Component.literal(message);
manager.send(new ClientboundLoginDisconnectPacket(text));
manager.disconnect(text);
}
public static void handleExit(int retVal)
{
System.exit(retVal);
}
@ApiStatus.Internal
public static RepositorySource buildPackFinder(Map<IModFile, ? extends PathPackResources> modResourcePacks) {
@@ -203,8 +140,7 @@ public class ServerLifecycleHooks
}
private static void serverPackFinder(Map<IModFile, ? extends PathPackResources> modResourcePacks, Consumer<Pack> packAcceptor) {
for (Entry<IModFile, ? extends PathPackResources> e : modResourcePacks.entrySet())
{
for (Entry<IModFile, ? extends PathPackResources> e : modResourcePacks.entrySet()) {
IModInfo mod = e.getKey().getModInfos().get(0);
if (Objects.equals(mod.getModId(), "minecraft")) continue; // skip the minecraft "mod"
final String name = "mod:" + mod.getModId();
@@ -233,8 +169,7 @@ public class ServerLifecycleHooks
}
}
private static void runModifiers(final MinecraftServer server)
{
private static void runModifiers(final MinecraftServer server) {
final RegistryAccess registries = server.registryAccess();
// The order of holders() is the order modifiers were loaded in.
@@ -249,13 +184,57 @@ public class ServerLifecycleHooks
// Apply sorted biome modifiers to each biome.
registries.registryOrThrow(Registries.BIOME).holders().forEach(biomeHolder ->
{
biomeHolder.value().modifiableBiomeInfo().applyBiomeModifiers(biomeHolder, biomeModifiers);
});
biomeHolder.value().modifiableBiomeInfo().applyBiomeModifiers(biomeHolder, biomeModifiers)
);
// Apply sorted structure modifiers to each structure.
registries.registryOrThrow(Registries.STRUCTURE).holders().forEach(structureHolder ->
{
structureHolder.value().modifiableStructureInfo().applyStructureModifiers(structureHolder, structureModifiers);
});
structureHolder.value().modifiableStructureInfo().applyStructureModifiers(structureHolder, structureModifiers)
);
}
//==================================================================================================================================================================================
//==================================================================================================================================================================================
//==================================================================================================================================================================================
//==================================================================================================================================================================================
//==================================================================================================================================================================================
//==================================================================================================================================================================================
public static void handleServerStarted(final MinecraftServer server) {
MinecraftForge.EVENT_BUS.post(new ServerStartedEvent(server));
allowLogins.set(true);
}
public static void handleServerStopping(final MinecraftServer server) {
allowLogins.set(false);
MinecraftForge.EVENT_BUS.post(new ServerStoppingEvent(server));
}
public static boolean handleServerLogin(final ClientIntentionPacket packet, final Connection connection) {
var ctx = NetworkContext.get(connection);
ctx.processIntention(packet.hostName());
if (!allowLogins.get())
return rejectConnection(connection, ctx.getType(), "Server is still starting! Please wait before reconnecting.");
if (packet.nextProtocol() != ConnectionProtocol.LOGIN)
return true;
if (ctx.getType() == ConnectionType.MODDED && ctx.getNetVersion() != NetworkContext.NET_VERSION)
return rejectConnection(connection, ctx.getType(), "This modded server is not impl compatible with your modded client. Please verify your Forge version closely matches the server. Got net version " + ctx.getNetVersion() + " this server is net version " + NetworkContext.NET_VERSION);
if (ctx.getType() == ConnectionType.VANILLA && !NetworkRegistry.acceptsVanillaClientConnections())
return rejectConnection(connection, ctx.getType(), "This server has mods that require Forge to be installed on the client. Contact your server admin for more details.");
NetworkRegistry.onConnectionStart(connection);
return true;
}
private static boolean rejectConnection(final Connection connection, ConnectionType type, String message) {
connection.setClientboundProtocolAfterHandshake(ClientIntent.LOGIN);
LOGGER.info(SERVERHOOKS, "[{}] Disconnecting {} connection attempt: {}", connection.getLoggableAddress(true), type, message); // TODO: Respect logIP setting
var text = Component.literal(message);
connection.send(new ClientboundLoginDisconnectPacket(text));
connection.disconnect(text);
return false;
}
}