| 1 | package net.minecraft.network;
|
| 2 |
|
| 3 | import com.google.common.collect.Queues;
|
| 4 | import com.mojang.logging.LogUtils;
|
| 5 | import io.netty.bootstrap.Bootstrap;
|
| 6 | import io.netty.channel.Channel;
|
| 7 | import io.netty.channel.ChannelException;
|
| 8 | import io.netty.channel.ChannelFuture;
|
| 9 | import io.netty.channel.ChannelFutureListener;
|
| 10 | import io.netty.channel.ChannelHandlerContext;
|
| 11 | import io.netty.channel.ChannelInboundHandler;
|
| 12 | import io.netty.channel.ChannelInitializer;
|
| 13 | import io.netty.channel.ChannelOption;
|
| 14 | import io.netty.channel.ChannelOutboundHandler;
|
| 15 | import io.netty.channel.ChannelOutboundHandlerAdapter;
|
| 16 | import io.netty.channel.ChannelPipeline;
|
| 17 | import io.netty.channel.ChannelPromise;
|
| 18 | import io.netty.channel.SimpleChannelInboundHandler;
|
| 19 | import io.netty.channel.local.LocalChannel;
|
| 20 | import io.netty.channel.local.LocalServerChannel;
|
| 21 | import io.netty.handler.flow.FlowControlHandler;
|
| 22 | import io.netty.handler.timeout.ReadTimeoutHandler;
|
| 23 | import io.netty.handler.timeout.TimeoutException;
|
| 24 | import java.net.InetSocketAddress;
|
| 25 | import java.net.SocketAddress;
|
| 26 | import java.nio.channels.ClosedChannelException;
|
| 27 | import java.util.Objects;
|
| 28 | import java.util.Queue;
|
| 29 | import java.util.concurrent.RejectedExecutionException;
|
| 30 | import java.util.function.Consumer;
|
| 31 | import javax.crypto.Cipher;
|
| 32 | import net.fabricmc.fabric.api.networking.v1.context.PacketContextProvider;
|
| 33 | import net.minecraft.SharedConstants;
|
| 34 | import net.minecraft.network.chat.Component;
|
| 35 | import net.minecraft.network.protocol.BundlerInfo;
|
| 36 | import net.minecraft.network.protocol.Packet;
|
| 37 | import net.minecraft.network.protocol.PacketFlow;
|
| 38 | import net.minecraft.network.protocol.common.ClientboundDisconnectPacket;
|
| 39 | import net.minecraft.network.protocol.handshake.ClientIntent;
|
| 40 | import net.minecraft.network.protocol.handshake.ClientIntentionPacket;
|
| 41 | import net.minecraft.network.protocol.handshake.HandshakeProtocols;
|
| 42 | import net.minecraft.network.protocol.handshake.ServerHandshakePacketListener;
|
| 43 | import net.minecraft.network.protocol.login.ClientLoginPacketListener;
|
| 44 | import net.minecraft.network.protocol.login.ClientboundLoginDisconnectPacket;
|
| 45 | import net.minecraft.network.protocol.login.LoginProtocols;
|
| 46 | import net.minecraft.network.protocol.status.ClientStatusPacketListener;
|
| 47 | import net.minecraft.network.protocol.status.StatusProtocols;
|
| 48 | import net.minecraft.server.RunningOnDifferentThreadException;
|
| 49 | import net.minecraft.server.network.EventLoopGroupHolder;
|
| 50 | import net.minecraft.util.Mth;
|
| 51 | import net.minecraft.util.Util;
|
| 52 | import net.minecraft.util.debugchart.LocalSampleLogger;
|
| 53 | import org.jspecify.annotations.Nullable;
|
| 54 | import org.slf4j.Logger;
|
| 55 | import org.slf4j.Marker;
|
| 56 | import org.slf4j.MarkerFactory;
|
| 57 |
|
| 58 | public class Connection extends SimpleChannelInboundHandler<Packet<?>> implements PacketContextProvider {
|
| 59 | private static final float AVERAGE_PACKETS_SMOOTHING = 0.75F;
|
| 60 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 61 | public static final Marker ROOT_MARKER = MarkerFactory.getMarker("NETWORK");
|
| 62 | public static final Marker PACKET_MARKER = Util.make(MarkerFactory.getMarker("NETWORK_PACKETS"), m -> m.add(ROOT_MARKER));
|
| 63 | public static final Marker PACKET_RECEIVED_MARKER = Util.make(MarkerFactory.getMarker("PACKET_RECEIVED"), m -> m.add(PACKET_MARKER));
|
| 64 | public static final Marker PACKET_SENT_MARKER = Util.make(MarkerFactory.getMarker("PACKET_SENT"), m -> m.add(PACKET_MARKER));
|
| 65 | private static final ProtocolInfo<ServerHandshakePacketListener> INITIAL_PROTOCOL = HandshakeProtocols.SERVERBOUND;
|
| 66 | private final PacketFlow receiving;
|
| 67 | private volatile boolean sendLoginDisconnect = true;
|
| 68 | private final Queue<Consumer<Connection>> pendingActions = Queues.newConcurrentLinkedQueue();
|
| 69 | private Channel channel;
|
| 70 | private SocketAddress address;
|
| 71 | private volatile @Nullable PacketListener disconnectListener;
|
| 72 | private volatile @Nullable PacketListener packetListener;
|
| 73 | private @Nullable DisconnectionDetails disconnectionDetails;
|
| 74 | private boolean disconnectionHandled;
|
| 75 | private int receivedPackets;
|
| 76 | private int sentPackets;
|
| 77 | private float averageReceivedPackets;
|
| 78 | private float averageSentPackets;
|
| 79 | private int tickCount;
|
| 80 | private boolean handlingFault;
|
| 81 | private volatile @Nullable DisconnectionDetails delayedDisconnect;
|
| 82 | private @Nullable BandwidthDebugMonitor bandwidthDebugMonitor;
|
| 83 |
|
| 84 | public Connection(final PacketFlow receiving) {
|
| 85 | this.receiving = receiving;
|
| 86 | }
|
| 87 |
|
| 88 | @Override
|
| 89 | public void channelActive(final ChannelHandlerContext ctx) throws Exception {
|
| 90 | super.channelActive(ctx);
|
| 91 | this.channel = ctx.channel();
|
| 92 | this.address = this.channel.remoteAddress();
|
| 93 | if (this.delayedDisconnect != null) {
|
| 94 | this.disconnect(this.delayedDisconnect);
|
| 95 | }
|
| 96 | }
|
| 97 |
|
| 98 | @Override
|
| 99 | public void channelInactive(final ChannelHandlerContext ctx) {
|
| 100 | this.disconnect(Component.translatable("disconnect.endOfStream"));
|
| 101 | }
|
| 102 |
|
| 103 | @Override
|
| 104 | public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
|
| 105 | if (cause instanceof SkipPacketException) {
|
| 106 | LOGGER.debug("Skipping packet due to errors", cause.getCause());
|
| 107 | } else {
|
| 108 | boolean isFirstFault = !this.handlingFault;
|
| 109 | this.handlingFault = true;
|
| 110 | if (this.channel.isOpen()) {
|
| 111 | if (cause instanceof TimeoutException) {
|
| 112 | LOGGER.debug("Timeout", cause);
|
| 113 | this.disconnect(Component.translatable("disconnect.timeout"));
|
| 114 | } else {
|
| 115 | Component reason = Component.translatable("disconnect.genericReason", "Internal Exception: " + cause);
|
| 116 | PacketListener listener = this.packetListener;
|
| 117 | DisconnectionDetails details;
|
| 118 | if (listener != null) {
|
| 119 | details = listener.createDisconnectionInfo(reason, cause);
|
| 120 | } else {
|
| 121 | details = new DisconnectionDetails(reason);
|
| 122 | }
|
| 123 |
|
| 124 | if (isFirstFault) {
|
| 125 | LOGGER.debug("Failed to sent packet", cause);
|
| 126 | if (this.getSending() == PacketFlow.CLIENTBOUND) {
|
| 127 | Packet<?> packet = this.sendLoginDisconnect ? new ClientboundLoginDisconnectPacket(reason) : new ClientboundDisconnectPacket(reason);
|
| 128 | this.send(packet, PacketSendListener.thenRun(() -> this.disconnect(details)));
|
| 129 | } else {
|
| 130 | this.disconnect(details);
|
| 131 | }
|
| 132 |
|
| 133 | this.setReadOnly();
|
| 134 | } else {
|
| 135 | LOGGER.debug("Double fault", cause);
|
| 136 | this.disconnect(details);
|
| 137 | }
|
| 138 | }
|
| 139 | }
|
| 140 | }
|
| 141 | }
|
| 142 |
|
| 143 | protected void channelRead0(final ChannelHandlerContext ctx, final Packet<?> packet) {
|
| 144 | if (this.channel.isOpen()) {
|
| 145 | PacketListener packetListener = this.packetListener;
|
| 146 | if (packetListener == null) {
|
| 147 | throw new IllegalStateException("Received a packet before the packet listener was initialized");
|
| 148 | }
|
| 149 |
|
| 150 | if (packetListener.shouldHandleMessage(packet)) {
|
| 151 | try {
|
| 152 | genericsFtw(packet, packetListener);
|
| 153 | } catch (RunningOnDifferentThreadException var5) {
|
| 154 | } catch (RejectedExecutionException ignored) {
|
| 155 | this.disconnect(Component.translatable("multiplayer.disconnect.server_shutdown"));
|
| 156 | } catch (ClassCastException exception) {
|
| 157 | LOGGER.error("Received {} that couldn't be processed", packet.getClass(), exception);
|
| 158 | this.disconnect(Component.translatable("multiplayer.disconnect.invalid_packet"));
|
| 159 | }
|
| 160 |
|
| 161 | this.receivedPackets++;
|
| 162 | }
|
| 163 | }
|
| 164 | }
|
| 165 |
|
| 166 | private static <T extends PacketListener> void genericsFtw(final Packet<T> packet, final PacketListener listener) {
|
| 167 | packet.handle((T)listener);
|
| 168 | }
|
| 169 |
|
| 170 | private void validateListener(final ProtocolInfo<?> protocol, final PacketListener packetListener) {
|
| 171 | Objects.requireNonNull(packetListener, "packetListener");
|
| 172 | PacketFlow listenerFlow = packetListener.flow();
|
| 173 | if (listenerFlow != this.receiving) {
|
| 174 | throw new IllegalStateException("Trying to set listener for wrong side: connection is " + this.receiving + ", but listener is " + listenerFlow);
|
| 175 | }
|
| 176 |
|
| 177 | ConnectionProtocol listenerProtocol = packetListener.protocol();
|
| 178 | if (protocol.id() != listenerProtocol) {
|
| 179 | throw new IllegalStateException("Listener protocol (" + listenerProtocol + ") does not match requested one " + protocol);
|
| 180 | }
|
| 181 | }
|
| 182 |
|
| 183 | private static void syncAfterConfigurationChange(final ChannelFuture future) {
|
| 184 | try {
|
| 185 | future.syncUninterruptibly();
|
| 186 | } catch (Exception e) {
|
| 187 | if (e instanceof ClosedChannelException) {
|
| 188 | LOGGER.info("Connection closed during protocol change");
|
| 189 | } else {
|
| 190 | throw e;
|
| 191 | }
|
| 192 | }
|
| 193 | }
|
| 194 |
|
| 195 | public <T extends PacketListener> void setupInboundProtocol(final ProtocolInfo<T> protocol, final T packetListener) {
|
| 196 | this.validateListener(protocol, packetListener);
|
| 197 | if (protocol.flow() != this.getReceiving()) {
|
| 198 | throw new IllegalStateException("Invalid inbound protocol: " + protocol.id());
|
| 199 | }
|
| 200 |
|
| 201 | this.packetListener = packetListener;
|
| 202 | this.disconnectListener = null;
|
| 203 | UnconfiguredPipelineHandler.InboundConfigurationTask configMessage = UnconfiguredPipelineHandler.setupInboundProtocol(protocol);
|
| 204 | BundlerInfo bundlerInfo = protocol.bundlerInfo();
|
| 205 | if (bundlerInfo != null) {
|
| 206 | PacketBundlePacker newBundler = new PacketBundlePacker(bundlerInfo);
|
| 207 | configMessage = configMessage.andThen(ctx -> ctx.pipeline().addAfter("decoder", "bundler", newBundler));
|
| 208 | }
|
| 209 |
|
| 210 | syncAfterConfigurationChange(this.channel.writeAndFlush(configMessage));
|
| 211 | }
|
| 212 |
|
| 213 | public void setupOutboundProtocol(final ProtocolInfo<?> protocol) {
|
| 214 | if (protocol.flow() != this.getSending()) {
|
| 215 | throw new IllegalStateException("Invalid outbound protocol: " + protocol.id());
|
| 216 | }
|
| 217 |
|
| 218 | UnconfiguredPipelineHandler.OutboundConfigurationTask configMessage = UnconfiguredPipelineHandler.setupOutboundProtocol(protocol);
|
| 219 | BundlerInfo bundlerInfo = protocol.bundlerInfo();
|
| 220 | if (bundlerInfo != null) {
|
| 221 | PacketBundleUnpacker newUnbundler = new PacketBundleUnpacker(bundlerInfo);
|
| 222 | configMessage = configMessage.andThen(ctx -> ctx.pipeline().addAfter("encoder", "unbundler", newUnbundler));
|
| 223 | }
|
| 224 |
|
| 225 | boolean isLoginProtocol = protocol.id() == ConnectionProtocol.LOGIN;
|
| 226 | syncAfterConfigurationChange(this.channel.writeAndFlush(configMessage.andThen(ctx -> this.sendLoginDisconnect = isLoginProtocol)));
|
| 227 | }
|
| 228 |
|
| 229 | public void setListenerForServerboundHandshake(final PacketListener packetListener) {
|
| 230 | if (this.packetListener != null) {
|
| 231 | throw new IllegalStateException("Listener already set");
|
| 232 | }
|
| 233 |
|
| 234 | if (this.receiving == PacketFlow.SERVERBOUND && packetListener.flow() == PacketFlow.SERVERBOUND && packetListener.protocol() == INITIAL_PROTOCOL.id()) {
|
| 235 | this.packetListener = packetListener;
|
| 236 | } else {
|
| 237 | throw new IllegalStateException("Invalid initial listener");
|
| 238 | }
|
| 239 | }
|
| 240 |
|
| 241 | public void initiateServerboundStatusConnection(final String hostName, final int port, final ClientStatusPacketListener listener) {
|
| 242 | this.initiateServerboundConnection(hostName, port, StatusProtocols.SERVERBOUND, StatusProtocols.CLIENTBOUND, listener, ClientIntent.STATUS);
|
| 243 | }
|
| 244 |
|
| 245 | public void initiateServerboundPlayConnection(final String hostName, final int port, final ClientLoginPacketListener listener) {
|
| 246 | this.initiateServerboundConnection(hostName, port, LoginProtocols.SERVERBOUND, LoginProtocols.CLIENTBOUND, listener, ClientIntent.LOGIN);
|
| 247 | }
|
| 248 |
|
| 249 | public <S extends ServerboundPacketListener, C extends ClientboundPacketListener> void initiateServerboundPlayConnection(
|
| 250 | final String hostName, final int port, final ProtocolInfo<S> outbound, final ProtocolInfo<C> inbound, final C listener, final boolean transfer
|
| 251 | ) {
|
| 252 | this.initiateServerboundConnection(hostName, port, outbound, inbound, listener, transfer ? ClientIntent.TRANSFER : ClientIntent.LOGIN);
|
| 253 | }
|
| 254 |
|
| 255 | private <S extends ServerboundPacketListener, C extends ClientboundPacketListener> void initiateServerboundConnection(
|
| 256 | final String hostName, final int port, final ProtocolInfo<S> outbound, final ProtocolInfo<C> inbound, final C listener, final ClientIntent intent
|
| 257 | ) {
|
| 258 | if (outbound.id() != inbound.id()) {
|
| 259 | throw new IllegalStateException("Mismatched initial protocols");
|
| 260 | }
|
| 261 |
|
| 262 | this.disconnectListener = listener;
|
| 263 | this.runOnceConnected(connection -> {
|
| 264 | this.setupInboundProtocol(inbound, listener);
|
| 265 | connection.sendPacket(new ClientIntentionPacket(SharedConstants.getCurrentVersion().protocolVersion(), hostName, port, intent), null, true);
|
| 266 | this.setupOutboundProtocol(outbound);
|
| 267 | });
|
| 268 | }
|
| 269 |
|
| 270 | public void send(final Packet<?> packet) {
|
| 271 | this.send(packet, null);
|
| 272 | }
|
| 273 |
|
| 274 | public void send(final Packet<?> packet, final @Nullable ChannelFutureListener listener) {
|
| 275 | this.send(packet, listener, true);
|
| 276 | }
|
| 277 |
|
| 278 | public void send(final Packet<?> packet, final @Nullable ChannelFutureListener listener, final boolean flush) {
|
| 279 | if (this.isConnected()) {
|
| 280 | this.flushQueue();
|
| 281 | this.sendPacket(packet, listener, flush);
|
| 282 | } else {
|
| 283 | this.pendingActions.add(connection -> connection.sendPacket(packet, listener, flush));
|
| 284 | }
|
| 285 | }
|
| 286 |
|
| 287 | public void runOnceConnected(final Consumer<Connection> action) {
|
| 288 | if (this.isConnected()) {
|
| 289 | this.flushQueue();
|
| 290 | action.accept(this);
|
| 291 | } else {
|
| 292 | this.pendingActions.add(action);
|
| 293 | }
|
| 294 | }
|
| 295 |
|
| 296 | private void sendPacket(final Packet<?> packet, final @Nullable ChannelFutureListener listener, final boolean flush) {
|
| 297 | this.sentPackets++;
|
| 298 | if (this.channel.eventLoop().inEventLoop()) {
|
| 299 | this.doSendPacket(packet, listener, flush);
|
| 300 | } else {
|
| 301 | this.channel.eventLoop().execute(() -> this.doSendPacket(packet, listener, flush));
|
| 302 | }
|
| 303 | }
|
| 304 |
|
| 305 | private void doSendPacket(final Packet<?> packet, final @Nullable ChannelFutureListener listener, final boolean flush) {
|
| 306 | if (listener != null) {
|
| 307 | ChannelFuture future = flush ? this.channel.writeAndFlush(packet) : this.channel.write(packet);
|
| 308 | future.addListener(listener);
|
| 309 | } else if (flush) {
|
| 310 | this.channel.writeAndFlush(packet, this.channel.voidPromise());
|
| 311 | } else {
|
| 312 | this.channel.write(packet, this.channel.voidPromise());
|
| 313 | }
|
| 314 | }
|
| 315 |
|
| 316 | public void flushChannel() {
|
| 317 | if (this.isConnected()) {
|
| 318 | this.flush();
|
| 319 | } else {
|
| 320 | this.pendingActions.add(Connection::flush);
|
| 321 | }
|
| 322 | }
|
| 323 |
|
| 324 | private void flush() {
|
| 325 | if (this.channel.eventLoop().inEventLoop()) {
|
| 326 | this.channel.flush();
|
| 327 | } else {
|
| 328 | this.channel.eventLoop().execute(() -> this.channel.flush());
|
| 329 | }
|
| 330 | }
|
| 331 |
|
| 332 | private void flushQueue() {
|
| 333 | if (this.channel != null && this.channel.isOpen()) {
|
| 334 | synchronized (this.pendingActions) {
|
| 335 | Consumer<Connection> pendingAction;
|
| 336 | while ((pendingAction = this.pendingActions.poll()) != null) {
|
| 337 | pendingAction.accept(this);
|
| 338 | }
|
| 339 | }
|
| 340 | }
|
| 341 | }
|
| 342 |
|
| 343 | public void tick() {
|
| 344 | this.flushQueue();
|
| 345 | if (this.packetListener instanceof TickablePacketListener tickable) {
|
| 346 | tickable.tick();
|
| 347 | }
|
| 348 |
|
| 349 | if (!this.isConnected() && !this.disconnectionHandled) {
|
| 350 | this.handleDisconnection();
|
| 351 | }
|
| 352 |
|
| 353 | if (this.channel != null) {
|
| 354 | this.channel.flush();
|
| 355 | }
|
| 356 |
|
| 357 | if (this.tickCount++ % 20 == 0) {
|
| 358 | this.tickSecond();
|
| 359 | }
|
| 360 |
|
| 361 | if (this.bandwidthDebugMonitor != null) {
|
| 362 | this.bandwidthDebugMonitor.tick();
|
| 363 | }
|
| 364 | }
|
| 365 |
|
| 366 | protected void tickSecond() {
|
| 367 | this.averageSentPackets = Mth.lerp(0.75F, this.sentPackets, this.averageSentPackets);
|
| 368 | this.averageReceivedPackets = Mth.lerp(0.75F, this.receivedPackets, this.averageReceivedPackets);
|
| 369 | this.sentPackets = 0;
|
| 370 | this.receivedPackets = 0;
|
| 371 | }
|
| 372 |
|
| 373 | public SocketAddress getRemoteAddress() {
|
| 374 | return this.address;
|
| 375 | }
|
| 376 |
|
| 377 | public String getLoggableAddress(final boolean logIPs) {
|
| 378 | if (this.address == null) {
|
| 379 | return "local";
|
| 380 | } else {
|
| 381 | return logIPs ? this.address.toString() : "IP hidden";
|
| 382 | }
|
| 383 | }
|
| 384 |
|
| 385 | public void disconnect(final Component reason) {
|
| 386 | this.disconnect(new DisconnectionDetails(reason));
|
| 387 | }
|
| 388 |
|
| 389 | public void disconnect(final DisconnectionDetails details) {
|
| 390 | if (this.channel == null) {
|
| 391 | this.delayedDisconnect = details;
|
| 392 | }
|
| 393 |
|
| 394 | if (this.isConnected()) {
|
| 395 | this.channel.close().awaitUninterruptibly();
|
| 396 | this.disconnectionDetails = details;
|
| 397 | }
|
| 398 | }
|
| 399 |
|
| 400 | public boolean isMemoryConnection() {
|
| 401 | return this.channel instanceof LocalChannel || this.channel instanceof LocalServerChannel;
|
| 402 | }
|
| 403 |
|
| 404 | public PacketFlow getReceiving() {
|
| 405 | return this.receiving;
|
| 406 | }
|
| 407 |
|
| 408 | public PacketFlow getSending() {
|
| 409 | return this.receiving.getOpposite();
|
| 410 | }
|
| 411 |
|
| 412 | public static Connection connectToServer(
|
| 413 | final InetSocketAddress address, final EventLoopGroupHolder eventLoopGroupHolder, final @Nullable LocalSampleLogger bandwidthLogger
|
| 414 | ) {
|
| 415 | Connection connection = new Connection(PacketFlow.CLIENTBOUND);
|
| 416 | if (bandwidthLogger != null) {
|
| 417 | connection.setBandwidthLogger(bandwidthLogger);
|
| 418 | }
|
| 419 |
|
| 420 | ChannelFuture connect = connect(address, eventLoopGroupHolder, connection);
|
| 421 | connect.syncUninterruptibly();
|
| 422 | return connection;
|
| 423 | }
|
| 424 |
|
| 425 | public static ChannelFuture connect(final InetSocketAddress address, final EventLoopGroupHolder eventLoopGroupHolder, final Connection connection) {
|
| 426 | return new Bootstrap().group(eventLoopGroupHolder.eventLoopGroup()).handler(new ChannelInitializer<Channel>() {
|
| 427 | @Override
|
| 428 | protected void initChannel(final Channel channel) {
|
| 429 | try {
|
| 430 | channel.config().setOption(ChannelOption.TCP_NODELAY, true);
|
| 431 | } catch (ChannelException var3) {
|
| 432 | }
|
| 433 |
|
| 434 | ChannelPipeline pipeline = channel.pipeline().addLast("timeout", new ReadTimeoutHandler(30));
|
| 435 | Connection.configureSerialization(pipeline, PacketFlow.CLIENTBOUND, false, connection.bandwidthDebugMonitor);
|
| 436 | connection.configurePacketHandler(pipeline);
|
| 437 | }
|
| 438 | }).channel(eventLoopGroupHolder.channelCls()).connect(address.getAddress(), address.getPort());
|
| 439 | }
|
| 440 |
|
| 441 | private static String outboundHandlerName(final boolean configureOutbound) {
|
| 442 | return configureOutbound ? "encoder" : "outbound_config";
|
| 443 | }
|
| 444 |
|
| 445 | private static String inboundHandlerName(final boolean configureInbound) {
|
| 446 | return configureInbound ? "decoder" : "inbound_config";
|
| 447 | }
|
| 448 |
|
| 449 | public void configurePacketHandler(final ChannelPipeline pipeline) {
|
| 450 | pipeline.addLast("hackfix", new ChannelOutboundHandlerAdapter() {
|
| 451 | @Override
|
| 452 | public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception {
|
| 453 | super.write(ctx, msg, promise);
|
| 454 | }
|
| 455 | }).addLast("packet_handler", this);
|
| 456 | }
|
| 457 |
|
| 458 | public static void configureSerialization(
|
| 459 | final ChannelPipeline pipeline, final PacketFlow inboundDirection, final boolean local, final @Nullable BandwidthDebugMonitor monitor
|
| 460 | ) {
|
| 461 | PacketFlow outboundDirection = inboundDirection.getOpposite();
|
| 462 | boolean configureInbound = inboundDirection == PacketFlow.SERVERBOUND;
|
| 463 | boolean configureOutbound = outboundDirection == PacketFlow.SERVERBOUND;
|
| 464 | pipeline.addLast("splitter", createFrameDecoder(monitor, local))
|
| 465 | .addLast(new FlowControlHandler())
|
| 466 | .addLast(inboundHandlerName(configureInbound), configureInbound ? new PacketDecoder<>(INITIAL_PROTOCOL) : new UnconfiguredPipelineHandler.Inbound())
|
| 467 | .addLast("prepender", createFrameEncoder(local))
|
| 468 | .addLast(outboundHandlerName(configureOutbound), configureOutbound ? new PacketEncoder<>(INITIAL_PROTOCOL) : new UnconfiguredPipelineHandler.Outbound());
|
| 469 | }
|
| 470 |
|
| 471 | private static ChannelOutboundHandler createFrameEncoder(final boolean local) {
|
| 472 | return local ? new LocalFrameEncoder() : new Varint21LengthFieldPrepender();
|
| 473 | }
|
| 474 |
|
| 475 | private static ChannelInboundHandler createFrameDecoder(final @Nullable BandwidthDebugMonitor monitor, final boolean local) {
|
| 476 | if (!local) {
|
| 477 | return new Varint21FrameDecoder(monitor);
|
| 478 | } else {
|
| 479 | return monitor != null ? new MonitoredLocalFrameDecoder(monitor) : new LocalFrameDecoder();
|
| 480 | }
|
| 481 | }
|
| 482 |
|
| 483 | public static void configureInMemoryPipeline(final ChannelPipeline pipeline, final PacketFlow packetFlow) {
|
| 484 | configureSerialization(pipeline, packetFlow, true, null);
|
| 485 | }
|
| 486 |
|
| 487 | public static Connection connectToLocalServer(final SocketAddress address) {
|
| 488 | final Connection connection = new Connection(PacketFlow.CLIENTBOUND);
|
| 489 | new Bootstrap().group(EventLoopGroupHolder.local().eventLoopGroup()).handler(new ChannelInitializer<Channel>() {
|
| 490 | @Override
|
| 491 | protected void initChannel(final Channel channel) {
|
| 492 | ChannelPipeline pipeline = channel.pipeline();
|
| 493 | Connection.configureInMemoryPipeline(pipeline, PacketFlow.CLIENTBOUND);
|
| 494 | connection.configurePacketHandler(pipeline);
|
| 495 | }
|
| 496 | }).channel(EventLoopGroupHolder.local().channelCls()).connect(address).syncUninterruptibly();
|
| 497 | return connection;
|
| 498 | }
|
| 499 |
|
| 500 | public static Connection fromChannel(final Channel channel, final PacketFlow flow, final @Nullable LocalSampleLogger bandwidthLogger) {
|
| 501 | Connection connection = new Connection(flow);
|
| 502 | if (bandwidthLogger != null) {
|
| 503 | connection.setBandwidthLogger(bandwidthLogger);
|
| 504 | }
|
| 505 |
|
| 506 | ChannelPipeline pipeline = channel.pipeline().addLast("timeout", new ReadTimeoutHandler(30));
|
| 507 | configureSerialization(pipeline, flow, false, connection.bandwidthDebugMonitor);
|
| 508 | connection.configurePacketHandler(pipeline);
|
| 509 | EventLoopGroupHolder.local().eventLoopGroup().register(channel).syncUninterruptibly();
|
| 510 | return connection;
|
| 511 | }
|
| 512 |
|
| 513 | public void setEncryptionKey(final Cipher decryptCipher, final Cipher encryptCipher) {
|
| 514 | this.channel.pipeline().addBefore("splitter", "decrypt", new CipherDecoder(decryptCipher));
|
| 515 | this.channel.pipeline().addBefore("prepender", "encrypt", new CipherEncoder(encryptCipher));
|
| 516 | }
|
| 517 |
|
| 518 | public boolean isConnected() {
|
| 519 | return this.channel != null && this.channel.isOpen();
|
| 520 | }
|
| 521 |
|
| 522 | public boolean isConnecting() {
|
| 523 | return this.channel == null;
|
| 524 | }
|
| 525 |
|
| 526 | public @Nullable PacketListener getPacketListener() {
|
| 527 | return this.packetListener;
|
| 528 | }
|
| 529 |
|
| 530 | public @Nullable DisconnectionDetails getDisconnectionDetails() {
|
| 531 | return this.disconnectionDetails;
|
| 532 | }
|
| 533 |
|
| 534 | public void setReadOnly() {
|
| 535 | if (this.channel != null) {
|
| 536 | this.channel.config().setAutoRead(false);
|
| 537 | }
|
| 538 | }
|
| 539 |
|
| 540 | public void setupCompression(final int threshold, final boolean validateDecompressed) {
|
| 541 | if (threshold >= 0) {
|
| 542 | if (this.channel.pipeline().get("decompress") instanceof CompressionDecoder compressionDecoder) {
|
| 543 | compressionDecoder.setThreshold(threshold, validateDecompressed);
|
| 544 | } else {
|
| 545 | this.channel.pipeline().addAfter("splitter", "decompress", new CompressionDecoder(threshold, validateDecompressed));
|
| 546 | }
|
| 547 |
|
| 548 | if (this.channel.pipeline().get("compress") instanceof CompressionEncoder compressionEncoder) {
|
| 549 | compressionEncoder.setThreshold(threshold);
|
| 550 | } else {
|
| 551 | this.channel.pipeline().addAfter("prepender", "compress", new CompressionEncoder(threshold));
|
| 552 | }
|
| 553 | } else {
|
| 554 | if (this.channel.pipeline().get("decompress") instanceof CompressionDecoder) {
|
| 555 | this.channel.pipeline().remove("decompress");
|
| 556 | }
|
| 557 |
|
| 558 | if (this.channel.pipeline().get("compress") instanceof CompressionEncoder) {
|
| 559 | this.channel.pipeline().remove("compress");
|
| 560 | }
|
| 561 | }
|
| 562 | }
|
| 563 |
|
| 564 | public void handleDisconnection() {
|
| 565 | if (this.channel != null && !this.channel.isOpen()) {
|
| 566 | if (this.disconnectionHandled) {
|
| 567 | LOGGER.warn("handleDisconnection() called twice");
|
| 568 | } else {
|
| 569 | this.disconnectionHandled = true;
|
| 570 | PacketListener packetListener = this.getPacketListener();
|
| 571 | PacketListener disconnectListener = packetListener != null ? packetListener : this.disconnectListener;
|
| 572 | if (disconnectListener != null) {
|
| 573 | DisconnectionDetails details = Objects.requireNonNullElseGet(
|
| 574 | this.getDisconnectionDetails(), () -> new DisconnectionDetails(Component.translatable("multiplayer.disconnect.generic"))
|
| 575 | );
|
| 576 | disconnectListener.onDisconnect(details);
|
| 577 | }
|
| 578 | }
|
| 579 | }
|
| 580 | }
|
| 581 |
|
| 582 | public float getAverageReceivedPackets() {
|
| 583 | return this.averageReceivedPackets;
|
| 584 | }
|
| 585 |
|
| 586 | public float getAverageSentPackets() {
|
| 587 | return this.averageSentPackets;
|
| 588 | }
|
| 589 |
|
| 590 | public void setBandwidthLogger(final LocalSampleLogger bandwidthLogger) {
|
| 591 | this.bandwidthDebugMonitor = new BandwidthDebugMonitor(bandwidthLogger);
|
| 592 | }
|
| 593 | }
|
| 594 |
|