com/hypixel/hytale/server/core/io/NetworkSerializable.java
package com.hypixel.hytale.server.core.io;
public interface NetworkSerializable<Packet> {
Packet toPacket();
}
com/hypixel/hytale/server/core/io/NetworkSerializer.java
package com.hypixel.hytale.server.core.io;
@FunctionalInterface
public interface NetworkSerializer<Type, Packet> {
Packet toPacket(Type var1);
}
com/hypixel/hytale/server/core/io/NetworkSerializers.java
package com.hypixel.hytale.server.core.io;
import com.hypixel.hytale.math.shape.Box;
import com.hypixel.hytale.protocol.Hitbox;
public interface NetworkSerializers {
NetworkSerializer<Box, Hitbox> BOX = (t) -> {
Hitbox packet = new Hitbox();
packet.minX = (float)t.getMin().getX();
packet.minY = (float)t.getMin().getY();
packet.minZ = (float)t.getMin().getZ();
packet.maxX = (float)t.getMax().getX();
packet.maxY = (float)t.getMax().getY();
packet.maxZ = (float)t.getMax().getZ();
return packet;
};
}
com/hypixel/hytale/server/core/io/PacketHandler.java
package com.hypixel.hytale.server.core.io;
import com.google.common.flogger.LazyArgs;
import com.hypixel.hytale.codec.Codec;
import com.hypixel.hytale.codec.codecs.EnumCodec;
import com.hypixel.hytale.common.util.FormatUtil;
import com.hypixel.hytale.common.util.NetworkUtil;
import com.hypixel.hytale.logger.HytaleLogger;
import com.hypixel.hytale.metrics.MetricsRegistry;
import com.hypixel.hytale.metrics.metric.HistoricMetric;
import com.hypixel.hytale.metrics.metric.Metric;
import com.hypixel.hytale.protocol.CachedPacket;
import com.hypixel.hytale.protocol.Packet;
import com.hypixel.hytale.protocol.io.PacketStatsRecorder;
import com.hypixel.hytale.protocol.io.netty.ProtocolUtil;
import com.hypixel.hytale.protocol.packets.connection.Disconnect;
import com.hypixel.hytale.protocol.packets.connection.DisconnectType;
import com.hypixel.hytale.protocol.packets.connection.Ping;
import com.hypixel.hytale.protocol.packets.connection.Pong;
import com.hypixel.hytale.protocol.packets.connection.PongType;
import com.hypixel.hytale.server.core.HytaleServer;
import com.hypixel.hytale.server.core.auth.PlayerAuthentication;
import com.hypixel.hytale.server.core.io.adapter.PacketAdapters;
import com.hypixel.hytale.server.core.io.handlers.login.AuthenticationPacketHandler;
import com.hypixel.hytale.server.core.io.handlers.login.PasswordPacketHandler;
import com.hypixel.hytale.server.core.io.netty.NettyUtil;
import com.hypixel.hytale.server.core.modules.time.WorldTimeResource;
import com.hypixel.hytale.server.core.receiver.IPacketReceiver;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
io.netty.channel.local.LocalAddress;
io.netty.channel.unix.DomainSocketAddress;
io.netty.handler.codec.quic.QuicStreamChannel;
io.netty.util.Attribute;
io.netty.util.AttributeKey;
it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue;
it.unimi.dsi.fastutil.ints.IntPriorityQueue;
it.unimi.dsi.fastutil.longs.LongArrayFIFOQueue;
it.unimi.dsi.fastutil.longs.LongPriorityQueue;
java.net.InetAddress;
java.net.InetSocketAddress;
java.net.SocketAddress;
java.security.SecureRandom;
java.time.Duration;
java.time.Instant;
java.util.Map;
java.util.concurrent.CompletableFuture;
java.util.concurrent.ScheduledFuture;
java.util.concurrent.TimeUnit;
java.util.concurrent.atomic.AtomicInteger;
java.util.concurrent.locks.Lock;
java.util.concurrent.locks.ReentrantLock;
java.util.function.BooleanSupplier;
java.util.logging.Level;
javax.annotation.Nonnull;
javax.annotation.Nullable;
{
;
HytaleLogger.get();
AttributeKey<Long> LOGIN_START_ATTRIBUTE_KEY;
Channel channel;
ProtocolVersion protocolVersion;
PlayerAuthentication auth;
queuePackets;
();
();
PingInfo[] pingInfo;
pingTimer;
registered;
ScheduledFuture<?> timeoutTask;
Throwable clientReadyForChunksFutureStack;
CompletableFuture<Void> clientReadyForChunksFuture;
();
{
.channel = channel;
.protocolVersion = protocolVersion;
.pingInfo = [PongType.VALUES.length];
(PongType pingType : PongType.VALUES) {
.pingInfo[pingType.ordinal()] = (pingType);
}
}
Channel {
.channel;
}
{
HytaleLogger.getLogger().at(Level.INFO).log(.getIdentifier() + );
}
{
;
}
String ;
ProtocolVersion {
.protocolVersion;
}
{
.registered = ;
.registered0(oldHandler);
}
{
}
{
.registered = ;
.clearTimeout();
.unregistered0(newHandler);
}
{
}
{
.accept(packet);
}
;
{
HytaleLogger.getLogger().at(Level.INFO).log(, .getIdentifier());
}
{
.clearTimeout();
}
{
.queuePackets = queuePackets;
}
{
(.queuedPackets.getAndSet() > ) {
.channel.flush();
}
}
{
Packet[] cachedPackets = [packets.length];
.handleOutboundAndCachePackets(packets, cachedPackets);
(.queuePackets) {
.channel.write(cachedPackets, .channel.voidPromise());
.queuedPackets.getAndIncrement();
} {
.channel.writeAndFlush(cachedPackets, .channel.voidPromise());
}
}
{
Packet[] cachedPackets = [packets.length + ];
.handleOutboundAndCachePackets(packets, cachedPackets);
cachedPackets[cachedPackets.length - ] = .handleOutboundAndCachePacket(finalPacket);
(.queuePackets) {
.channel.write(cachedPackets, .channel.voidPromise());
.queuedPackets.getAndIncrement();
} {
.channel.writeAndFlush(cachedPackets, .channel.voidPromise());
}
}
{
.writePacket(packet, );
}
{
.writePacket(packet, );
}
{
(!PacketAdapters.__handleOutbound(, packet)) {
Packet toSend;
(cache) {
toSend = .handleOutboundAndCachePacket(packet);
} {
toSend = packet;
}
(.queuePackets) {
.channel.write(toSend, .channel.voidPromise());
.queuedPackets.getAndIncrement();
} {
.channel.writeAndFlush(toSend, .channel.voidPromise());
}
}
}
{
( ; i < packets.length; ++i) {
packets[i];
(!PacketAdapters.__handleOutbound(, packet)) {
cachedPackets[i] = .handleOutboundAndCachePacket(packet);
}
}
}
Packet {
(Packet)(packet CachedPacket ? packet : CachedPacket.cache(packet));
}
{
.disconnectReason.setServerDisconnectReason(message);
HytaleLogger.getLogger().at(Level.INFO).log(, NettyUtil.formatRemoteAddress(.channel), message);
.disconnect0(message);
}
{
.channel.writeAndFlush( (message, DisconnectType.Disconnect)).addListener(ProtocolUtil.CLOSE_ON_COMPLETE);
}
PacketStatsRecorder {
(PacketStatsRecorder).channel.attr(PacketStatsRecorder.CHANNEL_KEY).get();
}
PingInfo {
.pingInfo[pongType.ordinal()];
}
{
.getPingInfo(PongType.Tick).getPingMetricSet().getAverage();
PacketHandler.PingInfo.TIME_UNIT.toMillis(Math.round(average * )) + ;
}
{
.pingTimer -= dt;
(.pingTimer <= ) {
.pingTimer = ;
.sendPing();
}
}
{
.pingIdRandom.nextInt();
Instant.now();
System.nanoTime();
(PingInfo info : .pingInfo) {
info.recordSent(id, nowTimestamp);
}
.writeNoCache( (id, WorldTimeResource.instantToInstantData(nowInstant), ().getPingInfo(PongType.Raw).getPingMetricSet().getLastValue(), ().getPingInfo(PongType.Direct).getPingMetricSet().getLastValue(), ().getPingInfo(PongType.Tick).getPingMetricSet().getLastValue()));
}
{
.pingInfo[packet.type.ordinal()].handlePacket(packet);
}
{
(.timeoutTask != ) {
.timeoutTask.cancel();
}
( AuthenticationPacketHandler || !( PasswordPacketHandler) || .auth != ) {
logConnectionTimings(.channel, + stageId, Level.FINEST);
Map<String, Duration> timeouts = HytaleServer.get().getConfig().getConnectionTimeouts().getJoinTimeouts();
timeout;
(timeouts.containsKey(stageId)) {
timeout = ((Duration)timeouts.get(stageId)).toMillis();
} {
timeout = TimeUnit.MILLISECONDS.convert(def, timeUnit);
}
.timeoutTask = .channel.eventLoop().schedule(() -> {
(.channel.isOpen()) {
(!meets.getAsBoolean()) {
.disconnect();
HytaleLogger.getLogger().at(Level.WARNING).log(, FormatUtil.timeUnitToString(timeout, TimeUnit.MILLISECONDS), .getIdentifier(), stageId);
}
}
}, timeout, TimeUnit.MILLISECONDS);
}
}
{
(.timeoutTask != ) {
.timeoutTask.cancel();
}
(.clientReadyForChunksFuture != ) {
.clientReadyForChunksFuture.cancel();
.clientReadyForChunksFuture = ;
.clientReadyForChunksFutureStack = ;
}
}
PlayerAuthentication {
.auth;
}
{
.channel.isActive();
}
{
.queuedPackets.get();
}
{
.channel;
SocketAddress socketAddress;
(var3 QuicStreamChannel quicStreamChannel) {
socketAddress = quicStreamChannel.parent().remoteSocketAddress();
} {
socketAddress = .channel.remoteAddress();
}
(socketAddress InetSocketAddress) {
((InetSocketAddress)socketAddress).getAddress();
NetworkUtil.addressMatchesAny(address, NetworkUtil.AddressType.ANY_LOCAL, NetworkUtil.AddressType.LOOPBACK);
} {
socketAddress DomainSocketAddress || socketAddress LocalAddress;
}
}
{
.channel;
SocketAddress socketAddress;
(var3 QuicStreamChannel quicStreamChannel) {
socketAddress = quicStreamChannel.parent().remoteSocketAddress();
} {
socketAddress = .channel.remoteAddress();
}
(socketAddress InetSocketAddress) {
((InetSocketAddress)socketAddress).getAddress();
NetworkUtil.addressMatchesAny(address);
} {
socketAddress DomainSocketAddress || socketAddress LocalAddress;
}
}
DisconnectReason {
.disconnectReason;
}
{
(.clientReadyForChunksFuture != ) {
(, .clientReadyForChunksFutureStack);
} {
HytaleLogger.getLogger().at(Level.WARNING).log(, .getIdentifier());
.clientReadyForChunksFutureStack = ();
.clientReadyForChunksFuture = clientReadyFuture;
}
}
CompletableFuture<Void> {
.clientReadyForChunksFuture;
}
{
Attribute<Long> loginStartAttribute = channel.attr(LOGIN_START_ATTRIBUTE_KEY);
System.nanoTime();
loginStartAttribute.getAndSet(now);
(before == ) {
LOGIN_TIMING_LOGGER.at(level).log(message);
} {
LOGIN_TIMING_LOGGER.at(level).log(, message, LazyArgs.lazy(() -> FormatUtil.nanosToString(now - before)));
}
}
{
LOGIN_TIMING_LOGGER.setLevel(Level.ALL);
LOGIN_START_ATTRIBUTE_KEY = AttributeKey.<Long>newInstance();
}
{
MetricsRegistry<PingInfo> METRICS_REGISTRY;
TimeUnit TIME_UNIT;
;
;
;
;
;
TimeUnit PING_FREQUENCY_UNIT;
;
;
;
PongType pingType;
();
();
();
();
HistoricMetric pingMetricSet;
();
{
.pingType = pingType;
.pingMetricSet = HistoricMetric.builder(, TimeUnit.MILLISECONDS).addPeriod(, TimeUnit.SECONDS).addPeriod(, TimeUnit.MINUTES).addPeriod(, TimeUnit.MINUTES).build();
}
{
.queueLock.lock();
{
.pingIdQueue.enqueue(id);
.pingTimestampQueue.enqueue(timestamp);
} {
.queueLock.unlock();
}
}
{
(packet.type != .pingType) {
String.valueOf(packet.type);
( + var10002 + + String.valueOf(.pingType));
} {
.queueLock.lock();
nextIdToHandle;
sentTimestamp;
{
nextIdToHandle = .pingIdQueue.dequeueInt();
sentTimestamp = .pingTimestampQueue.dequeueLong();
} {
.queueLock.unlock();
}
(packet.id != nextIdToHandle) {
(String.valueOf(packet.id));
} {
System.nanoTime();
nanoTime - sentTimestamp;
(pingValue <= ) {
(String.format(, pingValue));
} {
.pingLock.lock();
{
.pingMetricSet.add(nanoTime, TIME_UNIT.convert(pingValue, TimeUnit.NANOSECONDS));
.packetQueueMetric.add(()packet.packetQueueSize);
} {
.pingLock.unlock();
}
}
}
}
}
PongType {
.pingType;
}
Metric {
.packetQueueMetric;
}
HistoricMetric {
.pingMetricSet;
}
{
.pingLock.lock();
{
.packetQueueMetric.clear();
.pingMetricSet.clear();
} {
.pingLock.unlock();
}
}
{
METRICS_REGISTRY = ( ()).register(, (pingInfo) -> pingInfo.pingType, (PongType.class)).register(, PingInfo::getPingMetricSet, HistoricMetric.METRICS_CODEC).register(, (pingInfo) -> pingInfo.packetQueueMetric.getMin(), Codec.LONG).register(, (pingInfo) -> pingInfo.packetQueueMetric.getAverage(), Codec.DOUBLE).register(, (pingInfo) -> pingInfo.packetQueueMetric.getMax(), Codec.LONG);
TIME_UNIT = TimeUnit.MICROSECONDS;
PING_FREQUENCY_UNIT = TimeUnit.SECONDS;
}
}
{
String serverDisconnectReason;
DisconnectType clientDisconnectType;
{
}
String {
.serverDisconnectReason;
}
{
.serverDisconnectReason = serverDisconnectReason;
.clientDisconnectType = ;
}
DisconnectType {
.clientDisconnectType;
}
{
.clientDisconnectType = clientDisconnectType;
.serverDisconnectReason = ;
}
String {
.serverDisconnectReason;
+ var10000 + + String.valueOf(.clientDisconnectType) + ;
}
}
}
com/hypixel/hytale/server/core/io/PacketStatsRecorderImpl.java
package com.hypixel.hytale.server.core.io;
import com.hypixel.hytale.codec.Codec;
import com.hypixel.hytale.codec.codecs.array.ArrayCodec;
import com.hypixel.hytale.metrics.MetricsRegistry;
import com.hypixel.hytale.metrics.metric.AverageCollector;
import com.hypixel.hytale.protocol.PacketRegistry;
import com.hypixel.hytale.protocol.io.PacketStatsRecorder;
import java.util.ArrayList;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class PacketStatsRecorderImpl implements PacketStatsRecorder {
public static final MetricsRegistry<PacketStatsRecorderImpl> METRICS_REGISTRY;
private final PacketStatsEntry[] entries = new PacketStatsEntry[512];
public PacketStatsRecorderImpl() {
for(int i = 0; i < this.entries.length; ++i) {
this.entries[i] = new PacketStatsEntry(i);
}
}
{
(packetId >= && packetId < .entries.length) {
.entries[packetId].recordSend(uncompressedSize, compressedSize);
}
}
{
(packetId >= && packetId < .entries.length) {
.entries[packetId].recordReceive(uncompressedSize, compressedSize);
}
}
PacketStatsEntry {
.entries[packetId];
}
{
METRICS_REGISTRY = ( ()).register(, (recorder) -> {
ArrayList<PacketStatsEntry> entries = ();
( ; i < ; ++i) {
recorder.entries[i];
(entry.hasData()) {
entries.add(entry);
}
}
(PacketStatsEntry[])entries.toArray((x$) -> [x$]);
}, (PacketStatsRecorderImpl.PacketStatsEntry.METRICS_REGISTRY, (x$) -> [x$]));
}
.PacketStatsEntry {
MetricsRegistry<PacketStatsEntry> METRICS_REGISTRY;
packetId;
();
();
();
();
();
();
();
();
();
Queue<SizeRecord> sentRecently = ();
();
();
();
();
();
();
();
();
();
Queue<SizeRecord> receivedRecently = ();
{
.packetId = packetId;
}
{
.sentCount.incrementAndGet();
.sentUncompressedTotal.addAndGet(()uncompressedSize);
.sentCompressedTotal.addAndGet(()compressedSize);
.sentUncompressedMin.accumulateAndGet(()uncompressedSize, Math::min);
.sentUncompressedMax.accumulateAndGet(()uncompressedSize, Math::max);
.sentCompressedMin.accumulateAndGet(()compressedSize, Math::min);
.sentCompressedMax.accumulateAndGet(()compressedSize, Math::max);
.sentUncompressedAvg.add(()uncompressedSize);
.sentCompressedAvg.add(()compressedSize);
System.nanoTime();
.sentRecently.add( (now, uncompressedSize, compressedSize));
.pruneOld(.sentRecently, now);
}
{
.receivedCount.incrementAndGet();
.receivedUncompressedTotal.addAndGet(()uncompressedSize);
.receivedCompressedTotal.addAndGet(()compressedSize);
.receivedUncompressedMin.accumulateAndGet(()uncompressedSize, Math::min);
.receivedUncompressedMax.accumulateAndGet(()uncompressedSize, Math::max);
.receivedCompressedMin.accumulateAndGet(()compressedSize, Math::min);
.receivedCompressedMax.accumulateAndGet(()compressedSize, Math::max);
.receivedUncompressedAvg.add(()uncompressedSize);
.receivedCompressedAvg.add(()compressedSize);
System.nanoTime();
.receivedRecently.add( (now, uncompressedSize, compressedSize));
.pruneOld(.receivedRecently, now);
}
{
now - TimeUnit.SECONDS.toNanos();
( (SizeRecord)queue.peek(); head != && head.nanos < cutoff; head = (SizeRecord)queue.peek()) {
queue.poll();
}
}
{
.sentCount.get() > || .receivedCount.get() > ;
}
{
.packetId;
}
String {
PacketRegistry. PacketRegistry.getById(.packetId);
info != ? info.name() : ;
}
{
.sentCount.get();
}
{
.sentUncompressedTotal.get();
}
{
.sentCompressedTotal.get();
}
{
.sentCount.get() > ? .sentUncompressedMin.get() : ;
}
{
.sentUncompressedMax.get();
}
{
.sentCount.get() > ? .sentCompressedMin.get() : ;
}
{
.sentCompressedMax.get();
}
{
.sentUncompressedAvg.get();
}
{
.sentCompressedAvg.get();
}
{
.receivedCount.get();
}
{
.receivedUncompressedTotal.get();
}
{
.receivedCompressedTotal.get();
}
{
.receivedCount.get() > ? .receivedUncompressedMin.get() : ;
}
{
.receivedUncompressedMax.get();
}
{
.receivedCount.get() > ? .receivedCompressedMin.get() : ;
}
{
.receivedCompressedMax.get();
}
{
.receivedUncompressedAvg.get();
}
{
.receivedCompressedAvg.get();
}
PacketStatsRecorder.RecentStats {
.computeRecentStats(.sentRecently);
}
PacketStatsRecorder.RecentStats {
.computeRecentStats(.receivedRecently);
}
PacketStatsRecorder.RecentStats {
;
;
;
;
;
;
;
(SizeRecord record : queue) {
++count;
uncompressedTotal += ()record.uncompressedSize;
compressedTotal += ()record.compressedSize;
uncompressedMin = Math.min(uncompressedMin, record.uncompressedSize);
uncompressedMax = Math.max(uncompressedMax, record.uncompressedSize);
compressedMin = Math.min(compressedMin, record.compressedSize);
compressedMax = Math.max(compressedMax, record.compressedSize);
}
count == ? PacketStatsRecorder.RecentStats.EMPTY : .RecentStats(count, uncompressedTotal, compressedTotal, uncompressedMin, uncompressedMax, compressedMin, compressedMax);
}
{
.sentCount.set();
.sentUncompressedTotal.set();
.sentCompressedTotal.set();
.sentUncompressedMin.set();
.sentUncompressedMax.set();
.sentCompressedMin.set();
.sentCompressedMax.set();
.sentUncompressedAvg.clear();
.sentCompressedAvg.clear();
.sentRecently.clear();
.receivedCount.set();
.receivedUncompressedTotal.set();
.receivedCompressedTotal.set();
.receivedUncompressedMin.set();
.receivedUncompressedMax.set();
.receivedCompressedMin.set();
.receivedCompressedMax.set();
.receivedUncompressedAvg.clear();
.receivedCompressedAvg.clear();
.receivedRecently.clear();
}
{
METRICS_REGISTRY = ( ()).register(, PacketStatsEntry::getPacketId, Codec.INTEGER).register(, PacketStatsEntry::getName, Codec.STRING).register(, PacketStatsEntry::getSentCount, Codec.INTEGER).register(, PacketStatsEntry::getSentUncompressedTotal, Codec.LONG).register(, PacketStatsEntry::getSentCompressedTotal, Codec.LONG).register(, PacketStatsEntry::getSentUncompressedMin, Codec.LONG).register(, PacketStatsEntry::getSentUncompressedMax, Codec.LONG).register(, PacketStatsEntry::getSentCompressedMin, Codec.LONG).register(, PacketStatsEntry::getSentCompressedMax, Codec.LONG).register(, PacketStatsEntry::getReceivedCount, Codec.INTEGER).register(, PacketStatsEntry::getReceivedUncompressedTotal, Codec.LONG).register(, PacketStatsEntry::getReceivedCompressedTotal, Codec.LONG).register(, PacketStatsEntry::getReceivedUncompressedMin, Codec.LONG).register(, PacketStatsEntry::getReceivedUncompressedMax, Codec.LONG).register(, PacketStatsEntry::getReceivedCompressedMin, Codec.LONG).register(, PacketStatsEntry::getReceivedCompressedMax, Codec.LONG);
}
{
}
}
}
com/hypixel/hytale/server/core/io/ProtocolVersion.java
package com.hypixel.hytale.server.core.io;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class ProtocolVersion {
private final String hash;
public ProtocolVersion(String hash) {
this.hash = hash;
}
public String getHash() {
return this.hash;
}
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
} else if (o != null && this.getClass() == o.getClass()) {
ProtocolVersion that = (ProtocolVersion)o;
return this.hash != null ? this.hash.equals(that.hash) : that.hash == null;
} else {
return false;
}
}
public int hashCode() {
int result = * (.hash != ? .hash.hashCode() : );
result;
}
String {
+ .hash + ;
}
}
com/hypixel/hytale/server/core/io/ServerManager.java
package com.hypixel.hytale.server.core.io;
import com.hypixel.hytale.common.plugin.PluginManifest;
import com.hypixel.hytale.common.util.CompletableFutureUtil;
import com.hypixel.hytale.common.util.FormatUtil;
import com.hypixel.hytale.common.util.NetworkUtil;
import com.hypixel.hytale.logger.HytaleLogger;
import com.hypixel.hytale.logger.sentry.SkipSentryException;
import com.hypixel.hytale.server.core.Constants;
import com.hypixel.hytale.server.core.HytaleServer;
import com.hypixel.hytale.server.core.Options;
import com.hypixel.hytale.server.core.event.events.ShutdownEvent;
import com.hypixel.hytale.server.core.io.commands.BindingsCommand;
import com.hypixel.hytale.server.core.io.handlers.IPacketHandler;
import com.hypixel.hytale.server.core.io.handlers.SubPacketHandler;
import com.hypixel.hytale.server.core.io.handlers.game.GamePacketHandler;
import com.hypixel.hytale.server.core.io.handlers.game.InventoryPacketHandler;
import com.hypixel.hytale.server.core.io.transport.QUICTransport;
import com.hypixel.hytale.server.core.io.transport.TCPTransport;
import com.hypixel.hytale.server.core.io.transport.Transport;
import com.hypixel.hytale.server.core.io.transport.TransportType;
import com.hypixel.hytale.server.core.plugin.JavaPlugin;
import com.hypixel.hytale.server.core.plugin.JavaPluginInit;
import com.hypixel.hytale.server.core.universe.Universe;
import com.hypixel.hytale.sneakythrow.SneakyThrow;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.net.InetAddress;
import java.net.InetSocketAddress;
java.net.SocketAddress;
java.net.SocketException;
java.net.UnknownHostException;
java.util.Collections;
java.util.List;
java.util.concurrent.CompletableFuture;
java.util.concurrent.CopyOnWriteArrayList;
java.util.concurrent.TimeUnit;
java.util.function.Function;
java.util.logging.Level;
javax.annotation.Nonnull;
javax.annotation.Nullable;
{
PluginManifest.corePlugin(ServerManager.class).build();
NetworkUtil.AddressType[] NON_PUBLIC_ADDRESS_TYPES;
ServerManager instance;
List<Channel> listeners = ();
List<Function<IPacketHandler, SubPacketHandler>> subPacketHandlers = <Function<IPacketHandler, SubPacketHandler>>();
Transport transport;
CompletableFuture<Void> registerFuture;
CompletableFuture<Void> bootFuture;
ServerManager {
instance;
}
{
(init);
instance = ;
(!Options.getOptionSet().has(Options.BARE)) {
.init();
}
}
{
.registerFuture = CompletableFutureUtil.<Void>_catch(CompletableFuture.runAsync(SneakyThrow.sneakyRunnable(() -> {
System.nanoTime();
Object var10001;
((TransportType)Options.getOptionSet().valuesOf(Options.TRANSPORT).getFirst()) {
TCP -> var10001 = ();
QUIC -> var10001 = ();
-> ((String), (Throwable));
}
.transport = (Transport)var10001;
.getLogger().at(Level.INFO).log(, FormatUtil.nanosToString(System.nanoTime() - start));
.registerFuture = ;
})));
}
{
.getEventRegistry().register(()-, ShutdownEvent.class, (event) -> .unbindAllListeners());
get().registerSubPacketHandlers(InventoryPacketHandler::);
.getCommandRegistry().registerCommand( ());
}
{
.bootFuture = CompletableFuture.runAsync(() -> {
CompletableFuture<Void> registerFuture = .registerFuture;
(registerFuture != ) {
registerFuture.getNow((Object));
}
(!HytaleServer.get().isShuttingDown()) {
(!Options.getOptionSet().has(Options.MIGRATIONS) && !Options.getOptionSet().has(Options.BARE)) {
(Constants.SINGLEPLAYER) {
{
InetAddress[] localhosts = InetAddress.getAllByName();
(InetAddress localhost : localhosts) {
.bind( (localhost, ((InetSocketAddress)Options.getOptionSet().valueOf(Options.BIND)).getPort()));
}
} (UnknownHostException e) {
SneakyThrow.sneakyThrow(e);
}
} {
(InetSocketAddress address : Options.getOptionSet().valuesOf(Options.BIND)) {
.bind(address);
}
(.listeners.isEmpty()) {
();
}
}
}
.bootFuture = ;
}
});
}
{
Universe.get().disconnectAllPLayers();
.unbindAllListeners();
.transport.shutdown();
.transport = ;
.getLogger().at(Level.INFO).log();
}
{
(Channel channel : .listeners) {
.unbind0(channel);
}
.listeners.clear();
}
List<Channel> {
Collections.unmodifiableList(.listeners);
}
{
(address.getAddress().isAnyLocalAddress() && .transport.getType() == TransportType.QUIC) {
.bind0( (NetworkUtil.ANY_IPV6_ADDRESS, address.getPort()));
(channelIpv6 != ) {
.listeners.add(channelIpv6);
}
.bind0( (NetworkUtil.ANY_IPV4_ADDRESS, address.getPort()));
(channelIpv4 != ) {
.listeners.add(channelIpv4);
}
.bind0( (NetworkUtil.LOOPBACK_IPV6_ADDRESS, address.getPort()));
(channelIpv6Localhost != ) {
.listeners.add(channelIpv6Localhost);
}
channelIpv4 != || channelIpv6 != ;
} {
.bind0(address);
(channel != ) {
.listeners.add(channel);
}
channel != ;
}
}
{
.unbind0(channel);
(success) {
.listeners.remove(channel);
}
success;
}
InetSocketAddress SocketException {
(Channel channel : .listeners) {
channel.localAddress();
(socketAddress InetSocketAddress inetSocketAddress) {
inetSocketAddress.getAddress();
(address.isLoopbackAddress()) {
inetSocketAddress;
}
(address.isAnyLocalAddress()) {
NetworkUtil.getFirstNonLoopbackAddress();
(anyNonLoopbackAddress == ) {
;
}
(anyNonLoopbackAddress, inetSocketAddress.getPort());
}
inetSocketAddress;
}
}
;
}
InetSocketAddress SocketException {
(Channel channel : .listeners) {
channel.localAddress();
(socketAddress InetSocketAddress inetSocketAddress) {
inetSocketAddress.getAddress();
(!address.isLoopbackAddress()) {
(address.isAnyLocalAddress()) {
NetworkUtil.getFirstNonLoopbackAddress();
(anyNonLoopbackAddress == ) {
;
}
(anyNonLoopbackAddress, inetSocketAddress.getPort());
}
inetSocketAddress;
}
}
}
;
}
InetSocketAddress SocketException {
(Channel channel : .listeners) {
channel.localAddress();
(socketAddress InetSocketAddress inetSocketAddress) {
inetSocketAddress.getAddress();
(!address.isLoopbackAddress() && !address.isSiteLocalAddress()) {
(address.isAnyLocalAddress()) {
NetworkUtil.getFirstAddressWithout(NON_PUBLIC_ADDRESS_TYPES);
(anyPublicAddress == ) {
;
}
(anyPublicAddress, inetSocketAddress.getPort());
}
inetSocketAddress;
}
}
}
;
}
{
CompletableFuture<Void> future = .bootFuture;
(future != ) {
future.getNow((Object));
}
}
{
.subPacketHandlers.add(supplier);
}
{
(Function<IPacketHandler, SubPacketHandler> subPacketHandler : .subPacketHandlers) {
packetHandler.registerSubPacketHandler((SubPacketHandler)subPacketHandler.apply(packetHandler));
}
}
Channel {
System.nanoTime();
.getLogger().at(Level.FINE).log(, address, .transport.getType());
{
.transport.bind(address).sync();
(f.isSuccess()) {
f.channel();
.getLogger().at(Level.INFO).log(, channel.localAddress(), FormatUtil.nanosToString(System.nanoTime() - start));
channel;
}
((HytaleLogger.Api).getLogger().at(Level.SEVERE).withCause( (f.cause()))).log(, address);
} (InterruptedException e) {
Thread.currentThread().interrupt();
( + String.valueOf(address), e);
} (Throwable t) {
((HytaleLogger.Api).getLogger().at(Level.SEVERE).withCause( (t))).log(, address);
}
;
}
{
System.nanoTime();
.getLogger().at(Level.FINE).log(, channel);
{
channel.close().await(, TimeUnit.SECONDS);
.getLogger().at(Level.INFO).log(, channel, FormatUtil.nanosToString(System.nanoTime() - start));
;
} (InterruptedException e) {
((HytaleLogger.Api).getLogger().at(Level.SEVERE).withCause(e)).log();
Thread.currentThread().interrupt();
;
}
}
{
NON_PUBLIC_ADDRESS_TYPES = .AddressType[]{NetworkUtil.AddressType.ANY_LOCAL, NetworkUtil.AddressType.LOOPBACK, NetworkUtil.AddressType.SITE_LOCAL, NetworkUtil.AddressType.LINK_LOCAL, NetworkUtil.AddressType.MULTICAST};
}
}
com/hypixel/hytale/server/core/io/adapter/PacketAdapters.java
package com.hypixel.hytale.server.core.io.adapter;
import com.hypixel.hytale.logger.HytaleLogger;
import com.hypixel.hytale.protocol.Packet;
import com.hypixel.hytale.server.core.io.PacketHandler;
import com.hypixel.hytale.server.core.io.handlers.game.GamePacketHandler;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import javax.annotation.Nonnull;
public class PacketAdapters {
private static final List<PacketFilter> inboundHandlers = new CopyOnWriteArrayList();
private static final List<PacketFilter> outboundHandlers = new CopyOnWriteArrayList();
public PacketAdapters() {
}
@Nonnull
public static PacketFilter registerInbound(@Nonnull PacketWatcher watcher) {
PacketFilter out = (packetListener, packet) -> {
watcher.accept(packetListener, packet);
return false;
};
registerInbound(out);
return out;
}
public static void registerInbound(PacketFilter predicate) {
inboundHandlers.add(predicate);
}
PacketFilter {
(packetListener, packet) -> {
watcher.accept(packetListener, packet);
;
};
registerOutbound(out);
out;
}
{
outboundHandlers.add(predicate);
}
PacketFilter {
(packetHandler, client) -> packetHandler GamePacketHandler && filter.test(((GamePacketHandler)packetHandler).getPlayerRef(), client);
registerInbound(out);
out;
}
PacketFilter {
(packetHandler, server) -> packetHandler GamePacketHandler && filter.test(((GamePacketHandler)packetHandler).getPlayerRef(), server);
registerOutbound(out);
out;
}
PacketFilter {
(packetHandler, client) -> {
(packetHandler GamePacketHandler) {
watcher.accept(((GamePacketHandler)packetHandler).getPlayerRef(), client);
}
;
};
registerInbound(out);
out;
}
PacketFilter {
(packetHandler, server) -> {
(packetHandler GamePacketHandler) {
watcher.accept(((GamePacketHandler)packetHandler).getPlayerRef(), server);
}
;
};
registerOutbound(out);
out;
}
{
(!inboundHandlers.remove(predicate)) {
();
}
}
{
(!outboundHandlers.remove(predicate)) {
();
}
}
{
handle(inboundHandlers, player, packet);
}
<T > {
( ; i < list.size(); ++i) {
{
(((PacketFilter)list.get(i)).test(player, packet)) {
;
}
} (Throwable t) {
((HytaleLogger.Api)HytaleLogger.getLogger().at(Level.SEVERE).withCause(t)).log(, packet, player);
}
}
;
}
{
handle(outboundHandlers, player, packet);
}
}
com/hypixel/hytale/server/core/io/adapter/PacketFilter.java
package com.hypixel.hytale.server.core.io.adapter;
import com.hypixel.hytale.protocol.Packet;
import com.hypixel.hytale.server.core.io.PacketHandler;
import java.util.function.BiPredicate;
public interface PacketFilter extends BiPredicate<PacketHandler, Packet> {
boolean test(PacketHandler var1, Packet var2);
}
com/hypixel/hytale/server/core/io/adapter/PacketWatcher.java
package com.hypixel.hytale.server.core.io.adapter;
import com.hypixel.hytale.protocol.Packet;
import com.hypixel.hytale.server.core.io.PacketHandler;
import java.util.function.BiConsumer;
@FunctionalInterface
public interface PacketWatcher extends BiConsumer<PacketHandler, Packet> {
void accept(PacketHandler var1, Packet var2);
}
com/hypixel/hytale/server/core/io/adapter/PlayerPacketFilter.java
package com.hypixel.hytale.server.core.io.adapter;
import com.hypixel.hytale.protocol.Packet;
import com.hypixel.hytale.server.core.universe.PlayerRef;
import java.util.function.BiPredicate;
public interface PlayerPacketFilter extends BiPredicate<PlayerRef, Packet> {
boolean test(PlayerRef var1, Packet var2);
}
com/hypixel/hytale/server/core/io/adapter/PlayerPacketWatcher.java
package com.hypixel.hytale.server.core.io.adapter;
import com.hypixel.hytale.protocol.Packet;
import com.hypixel.hytale.server.core.universe.PlayerRef;
import java.util.function.BiConsumer;
public interface PlayerPacketWatcher extends BiConsumer<PlayerRef, Packet> {
void accept(PlayerRef var1, Packet var2);
}
com/hypixel/hytale/server/core/io/commands/BindingsCommand.java
package com.hypixel.hytale.server.core.io.commands;
import com.hypixel.hytale.server.core.Message;
import com.hypixel.hytale.server.core.command.system.CommandContext;
import com.hypixel.hytale.server.core.command.system.basecommands.CommandBase;
import com.hypixel.hytale.server.core.io.ServerManager;
import com.hypixel.hytale.server.core.util.message.MessageFormat;
import io.netty.channel.Channel;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
public class BindingsCommand extends CommandBase {
@Nonnull
private static final Message MESSAGE_IO_SERVER_MANAGER_BINDINGS = Message.translation("server.io.servermanager.bindings");
public BindingsCommand() {
super("bindings", "server.io.servermanager.bindings");
}
protected void executeSync(@Nonnull CommandContext context) {
List<Channel> listeners = ServerManager.get().getListeners();
context.sendMessage(MessageFormat.list(MESSAGE_IO_SERVER_MANAGER_BINDINGS, (Collection)listeners.stream().map(Channel::toString).map(Message::raw).collect(Collectors.toSet())));
}
}
com/hypixel/hytale/server/core/io/handlers/GenericConnectionPacketHandler.java
package com.hypixel.hytale.server.core.io.handlers;
import com.hypixel.hytale.server.core.io.PacketHandler;
import com.hypixel.hytale.server.core.io.ProtocolVersion;
import io.netty.channel.Channel;
import javax.annotation.Nonnull;
public abstract class GenericConnectionPacketHandler extends PacketHandler {
protected final String language;
public GenericConnectionPacketHandler(@Nonnull Channel channel, @Nonnull ProtocolVersion protocolVersion, String language) {
super(channel, protocolVersion);
this.language = language;
}
}
com/hypixel/hytale/server/core/io/handlers/GenericPacketHandler.java
package com.hypixel.hytale.server.core.io.handlers;
import com.hypixel.hytale.protocol.Packet;
import com.hypixel.hytale.server.core.io.PacketHandler;
import com.hypixel.hytale.server.core.io.ProtocolVersion;
import io.netty.channel.Channel;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.util.List;
import java.util.function.Consumer;
import javax.annotation.Nonnull;
public abstract class GenericPacketHandler extends PacketHandler {
private static final Consumer<Packet> EMPTY_CONSUMER = (packet) -> {
};
@Nonnull
protected final List<SubPacketHandler> packetHandlers = new ObjectArrayList<SubPacketHandler>();
private Consumer<Packet>[] handlers = newHandlerArray(0);
@Nonnull
public static Consumer<Packet>[] newHandlerArray(int size) {
return new Consumer[size];
}
public GenericPacketHandler(@Nonnull Channel channel, @Nonnull ProtocolVersion protocolVersion) {
super(channel, protocolVersion);
}
public void registerSubPacketHandler {
.packetHandlers.add(subPacketHandler);
}
{
(packetId >= .handlers.length) {
Consumer<Packet>[] newHandlers = newHandlerArray(packetId + );
System.arraycopy(.handlers, , newHandlers, , .handlers.length);
.handlers = newHandlers;
}
.handlers[packetId] = handler;
}
{
( packetId : packetIds) {
.registerHandler(packetId, EMPTY_CONSUMER);
}
}
{
packet.getId();
Consumer<Packet> handler = .handlers.length > packetId ? .handlers[packetId] : ;
(handler != ) {
{
handler.accept(packet);
} (Throwable e) {
( + packetId + + String.valueOf(packet), e);
}
} {
( + packetId + + String.valueOf(packet));
}
}
}
com/hypixel/hytale/server/core/io/handlers/IPacketHandler.java
package com.hypixel.hytale.server.core.io.handlers;
import com.hypixel.hytale.protocol.Packet;
import com.hypixel.hytale.server.core.universe.PlayerRef;
import java.util.function.Consumer;
import javax.annotation.Nonnull;
public interface IPacketHandler {
void registerHandler(int var1, @Nonnull Consumer<Packet> var2);
void registerNoOpHandlers(int... var1);
@Nonnull
PlayerRef getPlayerRef();
@Nonnull
String getIdentifier();
}
com/hypixel/hytale/server/core/io/handlers/InitialPacketHandler.java
package com.hypixel.hytale.server.core.io.handlers;
import com.hypixel.hytale.logger.HytaleLogger;
import com.hypixel.hytale.protocol.Packet;
import com.hypixel.hytale.protocol.io.netty.ProtocolUtil;
import com.hypixel.hytale.protocol.packets.auth.ConnectAccept;
import com.hypixel.hytale.protocol.packets.connection.ClientType;
import com.hypixel.hytale.protocol.packets.connection.Connect;
import com.hypixel.hytale.protocol.packets.connection.Disconnect;
import com.hypixel.hytale.server.core.Constants;
import com.hypixel.hytale.server.core.HytaleServer;
import com.hypixel.hytale.server.core.Options;
import com.hypixel.hytale.server.core.auth.PlayerAuthentication;
import com.hypixel.hytale.server.core.io.PacketHandler;
import com.hypixel.hytale.server.core.io.ProtocolVersion;
import com.hypixel.hytale.server.core.io.handlers.login.AuthenticationPacketHandler;
import com.hypixel.hytale.server.core.io.handlers.login.PasswordPacketHandler;
import com.hypixel.hytale.server.core.io.netty.NettyUtil;
import com.hypixel.hytale.server.core.modules.singleplayer.SingleplayerModule;
import com.hypixel.hytale.server.core.plugin.PluginManager;
import io.netty.channel.Channel;
import io.netty.handler.codec.quic.QuicStreamChannel;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class InitialPacketHandler {
;
AuthenticationPacketHandler.AuthHandlerSupplier EDITOR_PACKET_HANDLER_SUPPLIER;
receivedConnect;
{
(channel, (ProtocolVersion));
}
String {
+ NettyUtil.formatRemoteAddress(.channel) + ;
}
{
HytaleServer.get().getConfig().getConnectionTimeouts().getInitialTimeout();
.setTimeout(, () -> !.registered, initialTimeout.toMillis(), TimeUnit.MILLISECONDS);
PacketHandler.logConnectionTimings(.channel, , Level.FINE);
}
{
(packet.getId() == ) {
.handle((Connect)packet);
} (packet.getId() == ) {
.handle((Disconnect)packet);
} {
.disconnect( + packet.getId());
}
}
{
(.receivedConnect) {
.disconnect(message);
} {
HytaleLogger.getLogger().at(Level.INFO).log(, NettyUtil.formatRemoteAddress(.channel));
ProtocolUtil.closeConnection(.channel);
}
}
{
.receivedConnect = ;
.clearTimeout();
PacketHandler.logConnectionTimings(.channel, , Level.FINE);
packet.protocolHash;
(clientProtocolHash.length() > ) {
.disconnect( + clientProtocolHash.length());
} {
;
(!clientProtocolHash.equals(expectedHash)) {
.disconnect( + expectedHash + + clientProtocolHash);
} (HytaleServer.get().isShuttingDown()) {
.disconnect();
} (!HytaleServer.get().isBooted()) {
.disconnect( + String.valueOf(PluginManager.get().getState()) + );
} {
(clientProtocolHash);
packet.language;
(language == ) {
language = ;
}
!(.channel QuicStreamChannel);
(isTcpConnection) {
HytaleLogger.getLogger().at(Level.INFO).log(, NettyUtil.formatRemoteAddress(.channel));
}
(packet.uuid == ) {
.disconnect();
} (packet.username != && !packet.username.isEmpty()) {
(packet.referralData != && packet.referralData.length > ) {
HytaleLogger.getLogger().at(Level.WARNING).log(, packet.username, packet.referralData.length, );
.disconnect();
} {
packet.identityToken != && !packet.identityToken.isEmpty();
packet.clientType == ClientType.Editor;
Options. (Options.AuthMode)Options.getOptionSet().valueOf(Options.AUTH_MODE);
(hasIdentityToken && authMode == Options.AuthMode.AUTHENTICATED) {
(isTcpConnection) {
HytaleLogger.getLogger().at(Level.WARNING).log(, NettyUtil.formatRemoteAddress(.channel));
.disconnect();
;
}
AuthenticationPacketHandler. isEditorClient ? EDITOR_PACKET_HANDLER_SUPPLIER : SetupPacketHandler::;
(isEditorClient && supplier == ) {
.disconnect();
;
}
HytaleLogger.getLogger().at(Level.INFO).log(, packet.username, packet.uuid, NettyUtil.formatRemoteAddress(.channel));
NettyUtil.setChannelHandler(.channel, (.channel, protocolVersion, language, supplier, packet.clientType, packet.identityToken, packet.uuid, packet.username, packet.referralData, packet.referralSource));
} {
(authMode == Options.AuthMode.AUTHENTICATED) {
HytaleLogger.getLogger().at(Level.WARNING).log(, NettyUtil.formatRemoteAddress(.channel), authMode);
.disconnect();
;
}
(authMode == Options.AuthMode.OFFLINE) {
(!Constants.SINGLEPLAYER) {
HytaleLogger.getLogger().at(Level.WARNING).log(, NettyUtil.formatRemoteAddress(.channel));
.disconnect();
;
}
(!SingleplayerModule.isOwner((PlayerAuthentication), packet.uuid)) {
HytaleLogger.getLogger().at(Level.WARNING).log(, packet.username, packet.uuid, SingleplayerModule.getUuid());
.disconnect();
;
}
}
HytaleLogger.getLogger().at(Level.INFO).log(, packet.username, packet.uuid, NettyUtil.formatRemoteAddress(.channel));
[] passwordChallenge = .generatePasswordChallengeIfNeeded(packet.uuid);
.write( (passwordChallenge));
PasswordPacketHandler. isEditorClient && EDITOR_PACKET_HANDLER_SUPPLIER != ? (ch, pv, lang, auth) -> EDITOR_PACKET_HANDLER_SUPPLIER.create(ch, pv, lang, auth) : SetupPacketHandler::;
NettyUtil.setChannelHandler(.channel, (.channel, protocolVersion, language, packet.uuid, packet.username, packet.referralData, packet.referralSource, passwordChallenge, setupSupplier));
}
}
} {
.disconnect();
}
}
}
}
[] generatePasswordChallengeIfNeeded(UUID playerUuid) {
HytaleServer.get().getConfig().getPassword();
(password != && !password.isEmpty()) {
(Constants.SINGLEPLAYER) {
SingleplayerModule.getUuid();
(ownerUuid != && ownerUuid.equals(playerUuid)) {
;
}
}
[] challenge = [];
( ()).nextBytes(challenge);
challenge;
} {
;
}
}
{
.disconnectReason.setClientDisconnectType(packet.type);
HytaleLogger.getLogger().at(Level.WARNING).log(, NettyUtil.formatRemoteAddress(.channel));
ProtocolUtil.closeApplicationConnection(.channel);
}
}
com/hypixel/hytale/server/core/io/handlers/SetupPacketHandler.java
package com.hypixel.hytale.server.core.io.handlers;
import com.hypixel.hytale.common.util.CompletableFutureUtil;
import com.hypixel.hytale.component.Ref;
import com.hypixel.hytale.event.IEventDispatcher;
import com.hypixel.hytale.logger.HytaleLogger;
import com.hypixel.hytale.math.util.MathUtil;
import com.hypixel.hytale.protocol.Asset;
import com.hypixel.hytale.protocol.HostAddress;
import com.hypixel.hytale.protocol.Packet;
import com.hypixel.hytale.protocol.io.netty.ProtocolUtil;
import com.hypixel.hytale.protocol.packets.auth.ClientReferral;
import com.hypixel.hytale.protocol.packets.connection.Disconnect;
import com.hypixel.hytale.protocol.packets.connection.DisconnectType;
import com.hypixel.hytale.protocol.packets.interface_.ServerInfo;
import com.hypixel.hytale.protocol.packets.setup.PlayerOptions;
import com.hypixel.hytale.protocol.packets.setup.RequestAssets;
import com.hypixel.hytale.protocol.packets.setup.ViewRadius;
import com.hypixel.hytale.protocol.packets.setup.WorldLoadFinished;
import com.hypixel.hytale.protocol.packets.setup.WorldLoadProgress;
import com.hypixel.hytale.protocol.packets.setup.WorldSettings;
import com.hypixel.hytale.server.core.Constants;
import com.hypixel.hytale.server.core.HytaleServer;
import com.hypixel.hytale.server.core.HytaleServerConfig;
import com.hypixel.hytale.server.core.Message;
import com.hypixel.hytale.server.core.asset.AssetRegistryLoader;
import com.hypixel.hytale.server.core.asset.common.CommonAssetModule;
import com.hypixel.hytale.server.core.asset.common.PlayerCommonAssets;
import com.hypixel.hytale.server.core.asset.common.events.SendCommonAssetsEvent;
com.hypixel.hytale.server.core.auth.PlayerAuthentication;
com.hypixel.hytale.server.core.cosmetics.CosmeticsModule;
com.hypixel.hytale.server.core.event.events.player.PlayerSetupConnectEvent;
com.hypixel.hytale.server.core.event.events.player.PlayerSetupDisconnectEvent;
com.hypixel.hytale.server.core.io.PacketHandler;
com.hypixel.hytale.server.core.io.ProtocolVersion;
com.hypixel.hytale.server.core.io.netty.NettyUtil;
com.hypixel.hytale.server.core.modules.i18n.I18nModule;
com.hypixel.hytale.server.core.modules.singleplayer.SingleplayerModule;
com.hypixel.hytale.server.core.universe.PlayerRef;
com.hypixel.hytale.server.core.universe.Universe;
com.hypixel.hytale.server.core.universe.world.World;
com.hypixel.hytale.server.core.universe.world.storage.EntityStore;
com.hypixel.hytale.server.core.util.DumpUtil;
io.netty.channel.Channel;
io.netty.channel.ChannelHandlerContext;
java.util.UUID;
java.util.concurrent.CompletableFuture;
java.util.concurrent.TimeUnit;
java.util.logging.Level;
javax.annotation.Nonnull;
{
UUID uuid;
String username;
[] referralData;
HostAddress referralSource;
PlayerCommonAssets assets;
receivedRequest;
clientViewRadiusChunks;
{
(channel, protocolVersion, language, uuid, username, ([]), (HostAddress));
}
{
(channel, protocolVersion, language);
.clientViewRadiusChunks = ;
.uuid = uuid;
.username = username;
.referralData = referralData;
.referralSource = referralSource;
.auth = ;
(referralData != && referralData.length > ) {
HytaleLogger.getLogger().at(Level.INFO).log(, username, referralData.length, referralSource != ? referralSource.host : , referralSource != ? referralSource.port : );
}
}
{
(channel, protocolVersion, language);
.clientViewRadiusChunks = ;
.uuid = auth.getUuid();
.username = auth.getUsername();
.auth = auth;
.referralData = auth.getReferralData();
.referralSource = auth.getReferralSource();
(.referralData != && .referralData.length > ) {
HytaleLogger.getLogger().at(Level.INFO).log(, .username, .referralData.length, .referralSource != ? .referralSource.host : , .referralSource != ? .referralSource.port : );
}
}
String {
NettyUtil.formatRemoteAddress(.channel);
+ var10000 + + .username + + String.valueOf(.uuid) + + (.auth != ? : ) + ;
}
{
.setTimeout(, () -> .assets != , , TimeUnit.SECONDS);
(PlayerSetupConnectEvent)HytaleServer.get().getEventBus().dispatchFor(PlayerSetupConnectEvent.class).dispatch( (, .username, .uuid, .auth, .referralData, .referralSource));
(event.isCancelled()) {
.disconnect(event.getReason());
} {
event.getClientReferral();
(clientReferral != ) {
.writeNoCache(clientReferral);
} {
Universe.get().getPlayer(.uuid);
(otherPlayer != ) {
HytaleLogger.getLogger().at(Level.INFO).log(, .uuid, otherPlayer.getUsername());
otherPlayer.getPacketHandler().getChannel();
(!NettyUtil.isFromSameOrigin(otherPlayerChannel, .channel)) {
.disconnect();
otherPlayer.sendMessage(Message.translation());
;
}
Ref<EntityStore> reference = otherPlayer.getReference();
(reference != ) {
((EntityStore)reference.getStore().getExternalData()).getWorld();
(world != ) {
CompletableFuture<Void> removalFuture = ();
world.execute(() -> {
otherPlayer.getPacketHandler().disconnect();
world.execute(() -> removalFuture.complete((Object)));
});
removalFuture.join();
} {
otherPlayer.getPacketHandler().disconnect();
}
}
}
PacketHandler.logConnectionTimings(.channel, , Level.FINE);
();
worldSettings.worldHeight = ;
Asset[] requiredAssets = CommonAssetModule.get().getRequiredAssets();
.assets = (requiredAssets);
worldSettings.requiredAssets = requiredAssets;
.write(worldSettings);
HytaleServer.get().getConfig();
.write( (HytaleServer.get().getServerName(), serverConfig.getMotd(), serverConfig.getMaxPlayers()));
.setTimeout(, () -> .receivedRequest, , TimeUnit.SECONDS);
}
}
}
{
(packet.getId()) {
-> .handle((Disconnect)packet);
-> .handle((RequestAssets)packet);
-> .handle((ViewRadius)packet);
-> .handle((PlayerOptions)packet);
-> .disconnect( + packet.getId());
}
}
{
.closed(ctx);
IEventDispatcher<PlayerSetupDisconnectEvent, PlayerSetupDisconnectEvent> dispatcher = HytaleServer.get().getEventBus().dispatchFor(PlayerSetupDisconnectEvent.class);
(dispatcher.hasListener()) {
dispatcher.dispatch( (.username, .uuid, .auth, .disconnectReason));
}
(Constants.SINGLEPLAYER) {
(Universe.get().getPlayerCount() == ) {
HytaleLogger.getLogger().at(Level.INFO).log();
HytaleServer.get().shutdownServer();
} (SingleplayerModule.isOwner(.auth, .uuid)) {
HytaleLogger.getLogger().at(Level.INFO).log();
Universe.get().getPlayers().forEach((p) -> p.getPacketHandler().disconnect(.username + ));
HytaleServer.get().shutdownServer();
}
}
}
{
.disconnectReason.setClientDisconnectType(packet.type);
HytaleLogger.getLogger().at(Level.INFO).log(, .uuid, .username, NettyUtil.formatRemoteAddress(.channel), packet.type.name(), packet.reason);
ProtocolUtil.closeApplicationConnection(.channel);
(packet.type == DisconnectType.Crash && Constants.SINGLEPLAYER && (Universe.get().getPlayerCount() == || SingleplayerModule.isOwner(.auth, .uuid))) {
DumpUtil.dump(, );
}
}
{
(.receivedRequest) {
();
} {
.receivedRequest = ;
PacketHandler.logConnectionTimings(.channel, , Level.FINE);
CompletableFuture<Void> future = CompletableFutureUtil.<Void>_catch(((CompletableFuture)HytaleServer.get().getEventBus().dispatchForAsync(SendCommonAssetsEvent.class).dispatch( (, packet.assets))).thenAccept((event) -> {
(.channel.isActive()) {
PacketHandler.logConnectionTimings(.channel, , Level.FINE);
.assets.sent(event.getRequestedAssets());
AssetRegistryLoader.sendAssets();
I18nModule.get().sendTranslations(, .language);
PacketHandler.logConnectionTimings(.channel, , Level.FINE);
.write( (, , ));
.write( ());
}
}).exceptionally((throwable) -> {
(!.channel.isActive()) {
;
} {
.disconnect();
(, throwable);
}
}));
.setTimeout(, () -> future.isDone() || !future.cancel(), , TimeUnit.SECONDS);
}
}
{
.clientViewRadiusChunks = MathUtil.ceil(()(()packet.value / ));
}
{
(!.receivedRequest) {
();
} {
PacketHandler.logConnectionTimings(.channel, , Level.FINE);
(.channel.isActive()) {
(packet.skin != ) {
{
CosmeticsModule.get().validateSkin(packet.skin);
} (CosmeticsModule.InvalidSkinException e) {
.disconnect( + e.getMessage());
;
}
}
CompletableFuture<Void> future = CompletableFutureUtil.<Void>_catch(Universe.get().addPlayer(.channel, .language, .protocolVersion, .uuid, .username, .auth, .clientViewRadiusChunks, packet.skin).thenAccept((player) -> {
(.channel.isActive()) {
PacketHandler.logConnectionTimings(.channel, , Level.FINE);
.clearTimeout();
}
}).exceptionally((throwable) -> {
(!.channel.isActive()) {
;
} {
.disconnect();
(, throwable);
}
}));
.setTimeout(, () -> future.isDone() || !future.cancel(), , TimeUnit.SECONDS);
}
}
}
}
com/hypixel/hytale/server/core/io/handlers/SubPacketHandler.java
package com.hypixel.hytale.server.core.io.handlers;
public interface SubPacketHandler {
void registerHandlers();
}
com/hypixel/hytale/server/core/io/handlers/game/GamePacketHandler.java
package com.hypixel.hytale.server.core.io.handlers.game;
import com.hypixel.hytale.component.ComponentType;
import com.hypixel.hytale.component.Ref;
import com.hypixel.hytale.component.Store;
import com.hypixel.hytale.logger.HytaleLogger;
import com.hypixel.hytale.math.util.ChunkUtil;
import com.hypixel.hytale.math.util.MathUtil;
import com.hypixel.hytale.math.vector.Transform;
import com.hypixel.hytale.math.vector.Vector3d;
import com.hypixel.hytale.math.vector.Vector3f;
import com.hypixel.hytale.math.vector.Vector3i;
import com.hypixel.hytale.protocol.BlockRotation;
import com.hypixel.hytale.protocol.GameMode;
import com.hypixel.hytale.protocol.HostAddress;
import com.hypixel.hytale.protocol.Packet;
import com.hypixel.hytale.protocol.io.netty.ProtocolUtil;
import com.hypixel.hytale.protocol.packets.camera.RequestFlyCameraMode;
import com.hypixel.hytale.protocol.packets.camera.SetFlyCameraMode;
import com.hypixel.hytale.protocol.packets.connection.Disconnect;
import com.hypixel.hytale.protocol.packets.connection.Pong;
import com.hypixel.hytale.protocol.packets.entities.MountMovement;
import com.hypixel.hytale.protocol.packets.interaction.SyncInteractionChain;
import com.hypixel.hytale.protocol.packets.interaction.SyncInteractionChains;
import com.hypixel.hytale.protocol.packets.interface_.ChatMessage;
import com.hypixel.hytale.protocol.packets.interface_.CustomPageEvent;
import com.hypixel.hytale.protocol.packets.interface_.Page;
import com.hypixel.hytale.protocol.packets.interface_.SetPage;
import com.hypixel.hytale.protocol.packets.interface_.UpdateLanguage;
import com.hypixel.hytale.protocol.packets.machinima.RequestMachinimaActorModel;
com.hypixel.hytale.protocol.packets.machinima.SetMachinimaActorModel;
com.hypixel.hytale.protocol.packets.machinima.UpdateMachinimaScene;
com.hypixel.hytale.protocol.packets.player.ClientMovement;
com.hypixel.hytale.protocol.packets.player.ClientPlaceBlock;
com.hypixel.hytale.protocol.packets.player.ClientReady;
com.hypixel.hytale.protocol.packets.player.MouseInteraction;
com.hypixel.hytale.protocol.packets.player.RemoveMapMarker;
com.hypixel.hytale.protocol.packets.player.SyncPlayerPreferences;
com.hypixel.hytale.protocol.packets.serveraccess.SetServerAccess;
com.hypixel.hytale.protocol.packets.serveraccess.UpdateServerAccess;
com.hypixel.hytale.protocol.packets.setup.RequestAssets;
com.hypixel.hytale.protocol.packets.setup.ViewRadius;
com.hypixel.hytale.protocol.packets.window.ClientOpenWindow;
com.hypixel.hytale.protocol.packets.window.CloseWindow;
com.hypixel.hytale.protocol.packets.window.SendWindowAction;
com.hypixel.hytale.protocol.packets.window.UpdateWindow;
com.hypixel.hytale.protocol.packets.world.SetPaused;
com.hypixel.hytale.protocol.packets.worldmap.MapMarker;
com.hypixel.hytale.protocol.packets.worldmap.TeleportToWorldMapMarker;
com.hypixel.hytale.protocol.packets.worldmap.TeleportToWorldMapPosition;
com.hypixel.hytale.protocol.packets.worldmap.UpdateWorldMapVisible;
com.hypixel.hytale.server.core.Constants;
com.hypixel.hytale.server.core.HytaleServer;
com.hypixel.hytale.server.core.HytaleServerConfig;
com.hypixel.hytale.server.core.Message;
com.hypixel.hytale.server.core.NameMatching;
com.hypixel.hytale.server.core.asset.common.CommonAssetModule;
com.hypixel.hytale.server.core.asset.type.blocktype.config.BlockType;
com.hypixel.hytale.server.core.asset.type.model.config.Model;
com.hypixel.hytale.server.core.asset.type.model.config.ModelAsset;
com.hypixel.hytale.server.core.auth.PlayerAuthentication;
com.hypixel.hytale.server.core.command.system.CommandManager;
com.hypixel.hytale.server.core.command.system.CommandSender;
com.hypixel.hytale.server.core.console.ConsoleModule;
com.hypixel.hytale.server.core.entity.entities.Player;
com.hypixel.hytale.server.core.entity.entities.player.data.PlayerWorldData;
com.hypixel.hytale.server.core.entity.entities.player.pages.PageManager;
com.hypixel.hytale.server.core.entity.entities.player.windows.ValidatedWindow;
com.hypixel.hytale.server.core.entity.entities.player.windows.Window;
com.hypixel.hytale.server.core.entity.movement.MovementStatesComponent;
com.hypixel.hytale.server.core.event.events.player.PlayerChatEvent;
com.hypixel.hytale.server.core.inventory.Inventory;
com.hypixel.hytale.server.core.inventory.ItemStack;
com.hypixel.hytale.server.core.io.ProtocolVersion;
com.hypixel.hytale.server.core.io.ServerManager;
com.hypixel.hytale.server.core.io.handlers.GenericPacketHandler;
com.hypixel.hytale.server.core.io.handlers.IPacketHandler;
com.hypixel.hytale.server.core.io.handlers.SubPacketHandler;
com.hypixel.hytale.server.core.io.netty.NettyUtil;
com.hypixel.hytale.server.core.modules.entity.EntityModule;
com.hypixel.hytale.server.core.modules.entity.component.TransformComponent;
com.hypixel.hytale.server.core.modules.entity.player.PlayerCreativeSettings;
com.hypixel.hytale.server.core.modules.entity.player.PlayerInput;
com.hypixel.hytale.server.core.modules.entity.player.PlayerSettings;
com.hypixel.hytale.server.core.modules.entity.teleport.PendingTeleport;
com.hypixel.hytale.server.core.modules.entity.teleport.Teleport;
com.hypixel.hytale.server.core.modules.entity.tracker.EntityTrackerSystems;
com.hypixel.hytale.server.core.modules.interaction.BlockPlaceUtils;
com.hypixel.hytale.server.core.modules.interaction.InteractionModule;
com.hypixel.hytale.server.core.modules.singleplayer.SingleplayerModule;
com.hypixel.hytale.server.core.universe.PlayerRef;
com.hypixel.hytale.server.core.universe.Universe;
com.hypixel.hytale.server.core.universe.world.World;
com.hypixel.hytale.server.core.universe.world.WorldMapTracker;
com.hypixel.hytale.server.core.universe.world.chunk.BlockChunk;
com.hypixel.hytale.server.core.universe.world.chunk.section.BlockSection;
com.hypixel.hytale.server.core.universe.world.storage.ChunkStore;
com.hypixel.hytale.server.core.universe.world.storage.EntityStore;
com.hypixel.hytale.server.core.util.MessageUtil;
com.hypixel.hytale.server.core.util.PositionUtil;
com.hypixel.hytale.server.core.util.ValidateUtil;
io.netty.channel.Channel;
io.netty.channel.ChannelHandlerContext;
it.unimi.dsi.fastutil.objects.ObjectArrayList;
java.net.InetSocketAddress;
java.util.Collections;
java.util.Deque;
java.util.List;
java.util.Objects;
java.util.UUID;
java.util.concurrent.CompletableFuture;
java.util.concurrent.ConcurrentLinkedDeque;
java.util.concurrent.CopyOnWriteArrayList;
java.util.function.Supplier;
java.util.logging.Level;
javax.annotation.Nonnull;
{
;
PlayerRef playerRef;
Player playerComponent;
Deque<SyncInteractionChain> interactionPacketQueue = ();
{
(channel, protocolVersion);
.auth = auth;
ServerManager.get().populateSubPacketHandlers();
.registerHandlers();
}
Deque<SyncInteractionChain> {
.interactionPacketQueue;
}
PlayerRef {
.playerRef;
}
{
.playerRef = playerRef;
.playerComponent = playerComponent;
}
String {
NettyUtil.formatRemoteAddress(.channel);
+ var10000 + + (.playerRef != ? String.valueOf(.playerRef.getUuid()) + + .playerRef.getUsername() : ) + ;
}
{
.registerHandler(, (p) -> .handle((Disconnect)p));
.registerHandler(, (p) -> .handlePong((Pong)p));
.registerHandler(, (p) -> .handle((ClientMovement)p));
.registerHandler(, (p) -> .handle((ChatMessage)p));
.registerHandler(, (p) -> .handle((RequestAssets)p));
.registerHandler(, (p) -> .handle((CustomPageEvent)p));
.registerHandler(, (p) -> .handle((ViewRadius)p));
.registerHandler(, (p) -> .handle((UpdateLanguage)p));
.registerHandler(, (p) -> .handle((MouseInteraction)p));
.registerHandler(, (p) -> .handle((UpdateServerAccess)p));
.registerHandler(, (p) -> .handle((SetServerAccess)p));
.registerHandler(, (p) -> .handle((ClientOpenWindow)p));
.registerHandler(, (p) -> .handle((SendWindowAction)p));
.registerHandler(, (p) -> .handle((CloseWindow)p));
.registerHandler(, (p) -> .handle((RequestMachinimaActorModel)p));
.registerHandler(, (p) -> .handle((UpdateMachinimaScene)p));
.registerHandler(, (p) -> .handle((ClientReady)p));
.registerHandler(, (p) -> .handle((MountMovement)p));
.registerHandler(, (p) -> .handle((SyncPlayerPreferences)p));
.registerHandler(, (p) -> .handle((ClientPlaceBlock)p));
.registerHandler(, (p) -> .handle((RemoveMapMarker)p));
.registerHandler(, (p) -> .handle((UpdateWorldMapVisible)p));
.registerHandler(, (p) -> .handle((TeleportToWorldMapMarker)p));
.registerHandler(, (p) -> .handle((TeleportToWorldMapPosition)p));
.registerHandler(, (p) -> .handle((SyncInteractionChains)p));
.registerHandler(, (p) -> .handle((SetPaused)p));
.registerHandler(, (p) -> .handle((RequestFlyCameraMode)p));
.packetHandlers.forEach(SubPacketHandler::registerHandlers);
}
{
.closed(ctx);
Universe.get().removePlayer(.playerRef);
}
{
.disconnectReason.setServerDisconnectReason(message);
(.playerRef != ) {
HytaleLogger.getLogger().at(Level.INFO).log(, .playerRef.getUsername(), NettyUtil.formatRemoteAddress(.channel), message);
.disconnect0(message);
Universe.get().removePlayer(.playerRef);
} {
.disconnect(message);
}
}
{
.disconnectReason.setClientDisconnectType(packet.type);
HytaleLogger.getLogger().at(Level.INFO).log(, .playerRef.getUuid(), .playerRef.getUsername(), NettyUtil.formatRemoteAddress(.channel), packet.type.name(), packet.reason);
ProtocolUtil.closeApplicationConnection(.channel);
}
{
Ref<EntityStore> ref = .playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
InteractionModule.get().doMouseInteraction(ref, store, packet, playerComponent, .playerRef);
});
}
}
{
(packet.absolutePosition != && !ValidateUtil.isSafePosition(packet.absolutePosition)) {
.disconnect();
} ((packet.bodyOrientation == || ValidateUtil.isSafeDirection(packet.bodyOrientation)) && (packet.lookOrientation == || ValidateUtil.isSafeDirection(packet.lookOrientation))) {
Ref<EntityStore> ref = .playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(ref.isValid()) {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
(!playerComponent.isWaitingForClientReady()) {
(PlayerInput)store.getComponent(ref, PlayerInput.getComponentType());
(playerInputComponent != ) {
(packet.movementStates != ) {
playerInputComponent.queue( .SetMovementStates(packet.movementStates));
}
(packet.velocity != ) {
playerInputComponent.queue( .SetClientVelocity(packet.velocity));
}
(PendingTeleport)store.getComponent(ref, PendingTeleport.getComponentType());
(pendingTeleport != ) {
(packet.teleportAck == ) {
;
}
(pendingTeleport.validate(packet.teleportAck.teleportId, packet.absolutePosition)) {
OK:
:
(!pendingTeleport.isEmpty()) {
;
}
store.removeComponent(ref, PendingTeleport.getComponentType());
;
INVALID_ID:
.disconnect();
;
INVALID_POSITION:
.disconnect();
;
}
}
(packet.mountedTo != ) {
(packet.mountedTo != playerInputComponent.getMountId()) {
;
}
(packet.riderMovementStates != ) {
playerInputComponent.queue( .SetRiderMovementStates(packet.riderMovementStates));
}
}
(packet.bodyOrientation != ) {
playerInputComponent.queue( .SetBody(packet.bodyOrientation));
}
(packet.lookOrientation != ) {
playerInputComponent.queue( .SetHead(packet.lookOrientation));
}
(packet.wishMovement != ) {
playerInputComponent.queue( .WishMovement(packet.wishMovement.x, packet.wishMovement.y, packet.wishMovement.z));
}
(packet.absolutePosition != ) {
playerInputComponent.queue( .AbsoluteMovement(packet.absolutePosition.x, packet.absolutePosition.y, packet.absolutePosition.z));
} (packet.relativePosition != && (packet.relativePosition.x != || packet.relativePosition.y != || packet.relativePosition.z != || packet.movementStates != )) {
playerInputComponent.queue( .RelativeMovement(()packet.relativePosition.x / , ()packet.relativePosition.y / , ()packet.relativePosition.z / ));
}
}
}
}
});
}
} {
.disconnect();
}
}
{
(packet.message != && !packet.message.isEmpty()) {
packet.message;
message.charAt();
(firstChar == ) {
CommandManager.get().handleCommand((CommandSender).playerComponent, message.substring());
} (firstChar == ) {
.playerRef.sendMessage(Message.translation().param(, message));
} {
Ref<EntityStore> ref = .playerRef.getReference();
(ref == || !ref.isValid()) {
;
}
.playerRef.getUuid();
List<PlayerRef> targetPlayerRefs = <PlayerRef>(Universe.get().getPlayers());
targetPlayerRefs.removeIf((targetPlayerRef) -> targetPlayerRef.getHiddenPlayersManager().isPlayerHidden(playerUUID));
((CompletableFuture)HytaleServer.get().getEventBus().dispatchForAsync(PlayerChatEvent.class).dispatch( (.playerRef, targetPlayerRefs, message))).whenComplete((playerChatEvent, throwable) -> {
(throwable != ) {
((HytaleLogger.Api)HytaleLogger.getLogger().at(Level.SEVERE).withCause(throwable)).log(, .playerRef.getUsername());
} (!playerChatEvent.isCancelled()) {
playerChatEvent.getFormatter().format(.playerRef, playerChatEvent.getContent());
HytaleLogger.getLogger().at(Level.INFO).log(MessageUtil.toAnsiString(sentMessage).toAnsi(ConsoleModule.get().getTerminal()));
(PlayerRef targetPlayerRef : playerChatEvent.getTargets()) {
targetPlayerRef.sendMessage(sentMessage);
}
}
});
}
} {
.disconnect();
}
}
{
CommonAssetModule.get().sendAssetsToPlayer(, packet.assets, );
}
{
Ref<EntityStore> ref = .playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
playerComponent.getPageManager();
pageManager.handleEvent(ref, store, packet);
});
} {
.playerRef.getPacketHandler().writeNoCache( (Page.None, ));
}
}
{
Ref<EntityStore> ref = .playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
EntityTrackerSystems. (EntityTrackerSystems.EntityViewer)store.getComponent(ref, EntityTrackerSystems.EntityViewer.getComponentType());
entityViewerComponent != ;
MathUtil.ceil(()(()packet.value / ));
playerComponent.setClientViewRadius(viewRadiusChunks);
entityViewerComponent.viewRadiusBlocks = playerComponent.getViewRadius() * ;
});
}
}
{
Ref<EntityStore> ref = .playerRef.getReference();
(ref != && ref.isValid()) {
.playerRef.setLanguage(packet.language);
}
}
{
Ref<EntityStore> ref = .playerRef.getReference();
(ref != && ref.isValid()) {
Supplier<? > supplier = (Supplier)Window.CLIENT_REQUESTABLE_WINDOW_TYPES.get(packet.type);
(supplier == ) {
();
} {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
playerComponent.getWindowManager().clientOpenWindow((Window)supplier.get());
(updateWindowPacket != ) {
.writeNoCache(updateWindowPacket);
}
});
}
}
}
{
Ref<EntityStore> ref = .playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
playerComponent.getWindowManager().getWindow(packet.id);
(window != ) {
(window ValidatedWindow && !((ValidatedWindow)window).validate()) {
window.close();
} {
window.handleAction(.playerRef.getReference(), store, packet.action);
}
}
});
}
}
{
Ref<EntityStore> ref = .playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
ComponentType<EntityStore, PlayerSettings> componentType = EntityModule.get().getPlayerSettingsComponentType();
store.putComponent(ref, componentType, (packet.showEntityMarkers, packet.armorItemsPreferredPickupLocation, packet.weaponAndToolItemsPreferredPickupLocation, packet.usableItemsItemsPreferredPickupLocation, packet.solidBlockItemsPreferredPickupLocation, packet.miscItemsPreferredPickupLocation, (packet.allowNPCDetection, packet.respondToHit)));
});
}
}
{
Ref<EntityStore> ref = .playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
playerComponent.getInventory();
(packet.position.x, packet.position.y, packet.position.z);
(packet.rotation.rotationYaw, packet.rotation.rotationPitch, packet.rotation.rotationRoll);
(TransformComponent)store.getComponent(ref, TransformComponent.getComponentType());
(transformComponent != && playerComponent.getGameMode() != GameMode.Creative) {
transformComponent.getPosition();
(()targetBlock.x + , ()targetBlock.y + , ()targetBlock.z + );
(position.distanceSquaredTo(blockCenter) > ) {
;
}
}
Store<ChunkStore> chunkStore = world.getChunkStore().getStore();
ChunkUtil.indexChunkFromBlock(targetBlock.x, targetBlock.z);
Ref<ChunkStore> chunkReference = ((ChunkStore)chunkStore.getExternalData()).getChunkReference(chunkIndex);
(chunkReference != ) {
(BlockChunk)chunkStore.getComponent(chunkReference, BlockChunk.getComponentType());
(blockChunk != ) {
blockChunk.getSectionAtBlockY(targetBlock.y);
(section != ) {
playerComponent.getInventory().getItemInHand();
(itemInHand == ) {
section.invalidateBlock(targetBlock.x, targetBlock.y, targetBlock.z);
} {
itemInHand.getBlockKey();
(heldBlockKey == ) {
section.invalidateBlock(targetBlock.x, targetBlock.y, targetBlock.z);
} {
(packet.placedBlockId != -) {
((BlockType)BlockType.getAssetMap().getAsset(packet.placedBlockId)).getId();
(BlockType)BlockType.getAssetMap().getAsset(heldBlockKey);
(heldBlockType != && BlockPlaceUtils.canPlaceBlock(heldBlockType, clientPlacedBlockTypeKey)) {
heldBlockKey = clientPlacedBlockTypeKey;
}
}
BlockPlaceUtils.placeBlock(ref, itemInHand, heldBlockKey, inventory.getHotbar(), Vector3i.ZERO, targetBlock, blockRotation, inventory, inventory.getActiveHotbarSlot(), playerComponent.getGameMode() != GameMode.Creative, chunkReference, chunkStore, store);
}
}
}
}
}
});
}
}
{
Ref<EntityStore> ref = .playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
playerComponent.getPlayerConfigData().getPerWorldData(world.getName());
perWorldData.removeLastDeath(packet.markerId);
});
}
}
{
Ref<EntityStore> ref = .playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
playerComponent.getWindowManager().closeWindow(packet.id);
});
}
}
{
(!Constants.SINGLEPLAYER) {
();
} (!SingleplayerModule.isOwner(.playerRef)) {
();
} {
List<InetSocketAddress> publicAddresses = ();
(HostAddress host : packet.hosts) {
publicAddresses.add(InetSocketAddress.createUnresolved(host.host, host.port & ));
}
SingleplayerModule.get();
singleplayerModule.setPublicAddresses(publicAddresses);
singleplayerModule.updateAccess(packet.access);
}
}
{
(!Constants.SINGLEPLAYER) {
();
} (!SingleplayerModule.isOwner(.playerRef)) {
();
} {
HytaleServer.get().getConfig();
(config != ) {
config.setPassword(packet.password != ? packet.password : );
HytaleServerConfig.save(config);
}
SingleplayerModule.get().requestServerAccess(packet.access);
}
}
{
(ModelAsset)ModelAsset.getAssetMap().getAsset(packet.modelId);
.writeNoCache( (Model.createUnitScaleModel(modelAsset).toPacket(), packet.sceneName, packet.actorName));
}
{
Ref<EntityStore> ref = .playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(.playerRef.getUsername(), packet.sceneName, packet.frame, packet.updateType, packet.scene);
(.equals(packet.player)) {
(PlayerRef otherPlayerRef : world.getPlayerRefs()) {
(!Objects.equals(otherPlayerRef, .playerRef)) {
otherPlayerRef.getPacketHandler().writeNoCache(updatePacket);
}
}
.playerRef.sendMessage(Message.translation());
} {
(PlayerRef)NameMatching.DEFAULT.find(Universe.get().getPlayers(), packet.player, PlayerRef::getUsername);
(target != && ((EntityStore)target.getReference().getStore().getExternalData()).getWorld() == world) {
target.getPacketHandler().write((Packet)updatePacket);
.playerRef.sendMessage(Message.translation().param(, target.getUsername()));
} {
.playerRef.sendMessage(Message.translation().param(, packet.player));
}
}
});
}
}
{
HytaleLogger.getLogger().at(Level.WARNING).log(, .getIdentifier(), packet);
CompletableFuture<Void> future = .clientReadyForChunksFuture;
(packet.readyForChunks && !packet.readyForGameplay && future != ) {
.clientReadyForChunksFutureStack = ;
.clientReadyForChunksFuture = ;
future.completeAsync(() -> );
}
(packet.readyForGameplay) {
Ref<EntityStore> ref = .playerRef.getReference();
(ref == || !ref.isValid()) {
;
}
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
playerComponent.handleClientReady();
});
}
}
{
Ref<EntityStore> ref = .playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
playerComponent.getWorldMapTracker().setClientHasWorldMapVisible(packet.visible);
});
}
}
{
Ref<EntityStore> ref = .playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
playerComponent.getWorldMapTracker();
(!worldMapTracker.isAllowTeleportToMarkers()) {
.disconnect();
} {
(MapMarker)worldMapTracker.getSentMarkers().get(packet.id);
(marker != ) {
PositionUtil.toTransform(marker.transform);
Teleport.createForPlayer(transform);
world.getEntityStore().getStore().addComponent(.playerRef.getReference(), Teleport.getComponentType(), teleportComponent);
}
}
});
}
}
{
Ref<EntityStore> ref = .playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
playerComponent.getWorldMapTracker();
(!worldMapTracker.isAllowTeleportToCoordinates()) {
.disconnect();
} {
world.getChunkStore().getChunkReferenceAsync(ChunkUtil.indexChunkFromBlock(packet.x, packet.y)).thenAcceptAsync((chunkRef) -> {
(BlockChunk)world.getChunkStore().getStore().getComponent(chunkRef, BlockChunk.getComponentType());
blockChunkComponent != ;
(()packet.x, ()(blockChunkComponent.getHeight(packet.x, packet.y) + ), ()packet.y);
Teleport.createForPlayer((World), position, (, , ));
world.getEntityStore().getStore().addComponent(.playerRef.getReference(), Teleport.getComponentType(), teleportComponent);
}, world);
}
});
}
}
{
Collections.addAll(.interactionPacketQueue, packet.updates);
}
{
Ref<EntityStore> ref = .playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
Ref<EntityStore> entityReference = world.getEntityStore().getRefFromNetworkId(playerComponent.getMountEntityId());
(entityReference != && entityReference.isValid()) {
(TransformComponent)store.getComponent(entityReference, TransformComponent.getComponentType());
transformComponent != ;
transformComponent.setPosition(PositionUtil.toVector3d(packet.absolutePosition));
transformComponent.setRotation(PositionUtil.toRotation(packet.bodyOrientation));
(MovementStatesComponent)store.getComponent(entityReference, MovementStatesComponent.getComponentType());
movementStatesComponent != ;
movementStatesComponent.setMovementStates(packet.movementStates);
}
});
}
}
{
Ref<EntityStore> ref = .playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(world.getPlayerCount() == && Constants.SINGLEPLAYER) {
world.setPaused(packet.paused);
}
});
}
}
{
Ref<EntityStore> ref = .playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
(playerComponent.hasPermission()) {
.writeNoCache( (packet.entering));
(packet.entering) {
.playerRef.sendMessage(Message.translation());
} {
.playerRef.sendMessage(Message.translation());
}
} {
.playerRef.sendMessage(Message.translation());
}
});
}
}
}
com/hypixel/hytale/server/core/io/handlers/game/InventoryPacketHandler.java
package com.hypixel.hytale.server.core.io.handlers.game;
import com.hypixel.hytale.component.Ref;
import com.hypixel.hytale.component.Store;
import com.hypixel.hytale.logger.HytaleLogger;
import com.hypixel.hytale.protocol.GameMode;
import com.hypixel.hytale.protocol.ItemSoundEvent;
import com.hypixel.hytale.protocol.SoundCategory;
import com.hypixel.hytale.protocol.packets.inventory.DropCreativeItem;
import com.hypixel.hytale.protocol.packets.inventory.DropItemStack;
import com.hypixel.hytale.protocol.packets.inventory.InventoryAction;
import com.hypixel.hytale.protocol.packets.inventory.MoveItemStack;
import com.hypixel.hytale.protocol.packets.inventory.SetActiveSlot;
import com.hypixel.hytale.protocol.packets.inventory.SetCreativeItem;
import com.hypixel.hytale.protocol.packets.inventory.SmartGiveCreativeItem;
import com.hypixel.hytale.protocol.packets.inventory.SmartMoveItemStack;
import com.hypixel.hytale.protocol.packets.inventory.SwitchHotbarBlockSet;
import com.hypixel.hytale.server.core.Message;
import com.hypixel.hytale.server.core.asset.type.item.config.BlockGroup;
import com.hypixel.hytale.server.core.asset.type.item.config.BlockSelectorToolData;
import com.hypixel.hytale.server.core.asset.type.item.config.Item;
import com.hypixel.hytale.server.core.asset.type.item.config.ItemArmor;
import com.hypixel.hytale.server.core.asset.type.itemsound.config.ItemSoundSet;
import com.hypixel.hytale.server.core.asset.type.soundevent.config.SoundEvent;
import com.hypixel.hytale.server.core.entity.ItemUtils;
import com.hypixel.hytale.server.core.entity.entities.Player;
import com.hypixel.hytale.server.core.entity.entities.player.windows.ItemContainerWindow;
import com.hypixel.hytale.server.core.entity.entities.player.windows.Window;
com.hypixel.hytale.server.core.event.events.ecs.DropItemEvent;
com.hypixel.hytale.server.core.event.events.ecs.SwitchActiveSlotEvent;
com.hypixel.hytale.server.core.inventory.Inventory;
com.hypixel.hytale.server.core.inventory.ItemStack;
com.hypixel.hytale.server.core.inventory.container.CombinedItemContainer;
com.hypixel.hytale.server.core.inventory.container.ItemContainer;
com.hypixel.hytale.server.core.inventory.container.SortType;
com.hypixel.hytale.server.core.inventory.transaction.ItemStackSlotTransaction;
com.hypixel.hytale.server.core.inventory.transaction.ItemStackTransaction;
com.hypixel.hytale.server.core.io.PacketHandler;
com.hypixel.hytale.server.core.io.handlers.IPacketHandler;
com.hypixel.hytale.server.core.io.handlers.SubPacketHandler;
com.hypixel.hytale.server.core.modules.item.ItemModule;
com.hypixel.hytale.server.core.universe.PlayerRef;
com.hypixel.hytale.server.core.universe.world.SoundUtil;
com.hypixel.hytale.server.core.universe.world.World;
com.hypixel.hytale.server.core.universe.world.storage.EntityStore;
com.hypixel.hytale.server.core.util.NotificationUtil;
com.hypixel.hytale.server.core.util.TempAssetIdUtil;
java.util.logging.Level;
javax.annotation.Nonnull;
{
IPacketHandler packetHandler;
{
.packetHandler = packetHandler;
}
{
.packetHandler.registerHandler(, (p) -> .handle((SetCreativeItem)p));
.packetHandler.registerHandler(, (p) -> .handle((DropCreativeItem)p));
.packetHandler.registerHandler(, (p) -> .handle((SmartGiveCreativeItem)p));
.packetHandler.registerHandler(, (p) -> .handle((DropItemStack)p));
.packetHandler.registerHandler(, (p) -> .handle((MoveItemStack)p));
.packetHandler.registerHandler(, (p) -> .handle((SmartMoveItemStack)p));
.packetHandler.registerHandler(, (p) -> .handle((SetActiveSlot)p));
.packetHandler.registerHandler(, (p) -> .handle((SwitchHotbarBlockSet)p));
.packetHandler.registerHandler(, (p) -> .handle((InventoryAction)p));
}
{
.packetHandler.getPlayerRef();
Ref<EntityStore> ref = playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
(PlayerRef)store.getComponent(ref, PlayerRef.getComponentType());
playerRefComponent != ;
(playerComponent.getGameMode() != GameMode.Creative) {
NotificationUtil.sendNotification(playerRefComponent.getPacketHandler(), Message.translation());
} {
playerComponent.getInventory();
packet.item.quantity;
(quantity > ) {
ItemStack.fromPacket(packet.item);
(packet.slotId < ) {
inventory.getCombinedHotbarFirst().addItemStack(itemStack);
transaction.getRemainder();
(remainder != && !remainder.isEmpty()) {
ItemUtils.dropItem(ref, remainder, store);
}
} {
inventory.getSectionById(packet.inventorySectionId);
(packet.override) {
sectionById.setItemStackForSlot(()packet.slotId, itemStack);
} {
sectionById.getItemStack(()packet.slotId);
(existing != && !existing.isEmpty() && existing.isStackableWith(itemStack)) {
sectionById.addItemStackToSlot(()packet.slotId, itemStack);
} {
sectionById.setItemStackForSlot(()packet.slotId, itemStack);
}
}
}
} (packet.override) {
inventory.getSectionById(packet.inventorySectionId).setItemStackForSlot(()packet.slotId, (ItemStack));
}
}
});
}
}
{
.packetHandler.getPlayerRef();
Ref<EntityStore> ref = playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
ItemStack.fromPacket(packet.item);
(itemStack != ) {
itemStack.getItem();
(item != Item.UNKNOWN) {
itemStack = itemStack.withQuantity(Math.min(itemStack.getQuantity(), item.getMaxStack()));
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
(PlayerRef)store.getComponent(ref, PlayerRef.getComponentType());
playerRefComponent != ;
(playerComponent.getGameMode() != GameMode.Creative) {
NotificationUtil.sendNotification(playerRefComponent.getPacketHandler(), Message.translation());
} {
ItemUtils.dropItem(ref, itemStack, store);
}
});
}
}
}
}
{
.packetHandler.getPlayerRef();
Ref<EntityStore> ref = playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
playerComponent.getInventory();
inventory.getActiveHotbarSlot();
(slot != -) {
inventory.getHotbar();
hotbar.getItemStack(()slot);
(stack != && !stack.isEmpty()) {
BlockGroup.findItemGroup(stack.getItem());
(set != ) {
(Item)Item.getAssetMap().getAsset(packet.itemId);
(desiredItem != ) {
set.getIndex(stack.getItem());
(currentIndex != -) {
set.getIndex(desiredItem);
(desiredIndex != - && desiredIndex != currentIndex) {
;
-;
inventory.getCombinedArmorHotbarUtilityStorage();
( ; i < combinedInventory.getCapacity(); ++i) {
combinedInventory.getItemStack(i);
(!ItemStack.isEmpty(potentialSelector)) {
potentialSelector.getItem();
item.getBlockSelectorToolData();
(selectorTool != && (maxSelectorTool == || maxSelectorTool.getDurability() < potentialSelector.getDurability())) {
maxSelectorTool = potentialSelector;
maxSlot = i;
}
}
}
(maxSelectorTool != ) {
maxSelectorTool.getItem().getBlockSelectorToolData();
(playerComponent.canDecreaseItemStackDurability(ref, store) && !maxSelectorTool.isUnbreakable()) {
playerComponent.updateItemStackDurability(ref, maxSelectorTool, combinedInventory, maxSlot, -toolData.getDurabilityLossOnUse(), store);
}
(set.get(desiredIndex), stack.getQuantity());
hotbar.setItemStackForSlot(()slot, replacement);
(ItemSoundSet)ItemSoundSet.getAssetMap().getAsset(desiredItem.getItemSoundSetIndex());
(soundSet != ) {
(String)soundSet.getSoundEventIds().get(ItemSoundEvent.Drop);
(dragSound != ) {
SoundEvent.getAssetMap().getIndex(dragSound);
(dragSoundIndex != ) {
SoundUtil.playSoundEvent2d(ref, dragSoundIndex, SoundCategory.UI, store);
}
}
}
}
}
}
}
}
}
}
});
}
}
{
.packetHandler.getPlayerRef();
Ref<EntityStore> ref = playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
(PlayerRef)store.getComponent(ref, PlayerRef.getComponentType());
playerRefComponent != ;
(playerComponent.getGameMode() != GameMode.Creative) {
NotificationUtil.sendNotification(playerRefComponent.getPacketHandler(), Message.translation());
} {
playerComponent.getInventory();
ItemStack.fromPacket(packet.item);
(packet.moveType) {
EquipOrMergeStack:
itemStack.getItem();
item.getArmor();
(itemArmor != ) {
inventory.getArmor().setItemStackForSlot(()itemArmor.getArmorSlot().ordinal(), itemStack);
;
}
itemStack.getQuantity();
(item.getUtility().isUsable()) {
inventory.getUtility().addItemStack(itemStack);
transaction.getRemainder();
(ItemStack.isEmpty(remainder) || remainder.getQuantity() != quantity) {
(ItemStackSlotTransaction slotTransaction : transaction.getSlotTransactions()) {
(slotTransaction.succeeded()) {
inventory.setActiveUtilitySlot(()slotTransaction.getSlot());
}
}
}
;
}
;
PutInHotbarOrWindow:
inventory.getCombinedHotbarFirst().addItemStack(itemStack);
}
}
});
}
}
{
.packetHandler.getPlayerRef();
Ref<EntityStore> ref = playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
DropItemEvent. .PlayerRequest(packet.inventorySectionId, ()packet.slotId);
store.invoke(ref, event);
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
playerComponent.getInventory();
(!event.isCancelled()) {
inventory.getSectionById(event.getInventorySectionId()).removeItemStackFromSlot(event.getSlotId(), packet.quantity);
transaction.getOutput();
(item == || item.isEmpty()) {
HytaleLogger.getLogger().at(Level.WARNING).log(, playerRef.getUsername());
;
}
item.getItemId();
(!ItemModule.exists(itemId)) {
HytaleLogger.getLogger().at(Level.WARNING).log(, playerRef.getUsername(), itemId);
;
}
ItemUtils.throwItem(ref, item, , store);
SoundUtil.playSoundEvent2d(ref, TempAssetIdUtil.getSoundEventIndex(), SoundCategory.UI, store);
} {
playerComponent.sendInventory();
}
});
}
}
{
.packetHandler.getPlayerRef();
Ref<EntityStore> ref = playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
playerComponent.getInventory();
inventory.moveItem(packet.fromSectionId, packet.fromSlotId, packet.quantity, packet.toSectionId, packet.toSlotId);
(packet.toSectionId != packet.fromSectionId && packet.toSectionId == -) {
()packet.toSlotId;
packet.toSectionId;
inventory.getActiveSlot(inventorySectionId);
(currentSlot == newSlot) {
;
}
(inventorySectionId, currentSlot, newSlot, );
store.invoke(ref, event);
(event.isCancelled() || event.getNewSlot() == currentSlot) {
;
}
newSlot = event.getNewSlot();
inventory.setActiveSlot(inventorySectionId, newSlot);
playerRef.getPacketHandler().writeNoCache( (inventorySectionId, newSlot));
}
});
}
}
{
.packetHandler.getPlayerRef();
Ref<EntityStore> ref = playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
playerComponent.getInventory();
inventory.smartMoveItem(packet.fromSectionId, packet.fromSlotId, packet.quantity, packet.moveType);
});
}
}
{
.packetHandler.getPlayerRef();
Ref<EntityStore> ref = playerRef.getReference();
(ref != && ref.isValid()) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
playerComponent.getInventory();
playerRef.getPacketHandler();
(packet.inventorySectionId == -) {
packetHandler.disconnect();
} (packet.activeSlot >= - && packet.activeSlot < inventory.getSectionById(packet.inventorySectionId).getCapacity()) {
(packet.activeSlot == inventory.getActiveSlot(packet.inventorySectionId)) {
packetHandler.disconnect();
} {
inventory.getActiveSlot(packet.inventorySectionId);
()packet.activeSlot;
(packet.inventorySectionId, previousSlot, targetSlot, );
store.invoke(ref, event);
(event.isCancelled()) {
targetSlot = previousSlot;
} (targetSlot != event.getNewSlot()) {
targetSlot = event.getNewSlot();
}
(targetSlot != packet.activeSlot) {
packetHandler.writeNoCache( (packet.inventorySectionId, targetSlot));
}
(targetSlot != previousSlot) {
inventory.setActiveSlot(packet.inventorySectionId, targetSlot);
}
}
} {
packetHandler.disconnect( + packet.inventorySectionId + );
}
});
}
}
{
.packetHandler.getPlayerRef();
Ref<EntityStore> ref = playerRef.getReference();
(ref != && ref.isValid()) {
(packet.inventorySectionId >= || packet.inventorySectionId == -) {
Store<EntityStore> store = ref.getStore();
((EntityStore)store.getExternalData()).getWorld();
world.execute(() -> {
(Player)store.getComponent(ref, Player.getComponentType());
playerComponent != ;
playerComponent.getInventory();
(packet.inventoryActionType) {
TakeAll:
(packet.inventorySectionId == -) {
inventory.takeAll(packet.inventorySectionId);
;
}
playerComponent.getWindowManager().getWindow(packet.inventorySectionId);
(window ItemContainerWindow) {
inventory.takeAll(packet.inventorySectionId);
}
;
PutAll:
(packet.inventorySectionId == -) {
inventory.putAll(packet.inventorySectionId);
;
}
playerComponent.getWindowManager().getWindow(packet.inventorySectionId);
(window ItemContainerWindow) {
inventory.putAll(packet.inventorySectionId);
}
;
QuickStack:
(packet.inventorySectionId == -) {
inventory.quickStack(packet.inventorySectionId);
;
}
playerComponent.getWindowManager().getWindow(packet.inventorySectionId);
(window ItemContainerWindow) {
inventory.quickStack(packet.inventorySectionId);
}
;
Sort:
SortType.VALUES[packet.actionData];
(packet.inventorySectionId == ) {
inventory.sortStorage(sortType);
} {
(packet.inventorySectionId == - && inventory.getBackpack() != ) {
inventory.getBackpack().sortItems(sortType);
;
}
playerComponent.getWindowManager().getWindow(packet.inventorySectionId);
(window ItemContainerWindow) {
(ItemContainerWindow)window;
itemContainerWindow.getItemContainer().sortItems(sortType);
}
}
}
});
}
}
}
}
com/hypixel/hytale/server/core/io/handlers/login/AuthenticationPacketHandler.java
package com.hypixel.hytale.server.core.io.handlers.login;
import com.hypixel.hytale.protocol.HostAddress;
import com.hypixel.hytale.protocol.packets.connection.ClientType;
import com.hypixel.hytale.server.core.HytaleServer;
import com.hypixel.hytale.server.core.auth.PlayerAuthentication;
import com.hypixel.hytale.server.core.io.PacketHandler;
import com.hypixel.hytale.server.core.io.ProtocolVersion;
import com.hypixel.hytale.server.core.io.netty.NettyUtil;
import com.hypixel.hytale.server.core.universe.Universe;
import io.netty.channel.Channel;
import java.util.UUID;
import java.util.logging.Level;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class AuthenticationPacketHandler extends HandshakeHandler {
private final AuthHandlerSupplier authHandlerSupplier;
public AuthenticationPacketHandler(@Nonnull Channel channel, @Nonnull ProtocolVersion protocolVersion, @Nonnull String language, @Nonnull AuthHandlerSupplier authHandlerSupplier, @Nonnull ClientType clientType, @Nonnull String identityToken, @Nonnull UUID uuid, @Nonnull String username, @Nullable byte[] referralData, @Nullable HostAddress referralSource) {
super(channel, protocolVersion, language, clientType, identityToken, uuid, username, referralData, referralSource);
.authHandlerSupplier = authHandlerSupplier;
}
String {
NettyUtil.formatRemoteAddress(.channel);
+ var10000 + + String.valueOf(.authHandlerSupplier) + ;
}
{
HytaleServer.get().getConfig().getMaxPlayers();
(maxPlayers > && Universe.get().getPlayerCount() >= maxPlayers) {
.disconnect();
} {
.registered0(oldHandler);
}
}
{
PacketHandler.logConnectionTimings(.channel, , Level.FINE);
NettyUtil.setChannelHandler(.channel, (.channel, .protocolVersion, .language, .auth.getUuid(), .auth.getUsername(), .auth.getReferralData(), .auth.getReferralSource(), passwordChallenge, (ch, pv, lang, a) -> .authHandlerSupplier.create(ch, pv, lang, a)));
}
{
PacketHandler ;
}
}
com/hypixel/hytale/server/core/io/handlers/login/HandshakeHandler.java
package com.hypixel.hytale.server.core.io.handlers.login;
import com.hypixel.hytale.logger.HytaleLogger;
import com.hypixel.hytale.protocol.HostAddress;
import com.hypixel.hytale.protocol.Packet;
import com.hypixel.hytale.protocol.io.netty.ProtocolUtil;
import com.hypixel.hytale.protocol.packets.auth.AuthGrant;
import com.hypixel.hytale.protocol.packets.auth.AuthToken;
import com.hypixel.hytale.protocol.packets.auth.ServerAuthToken;
import com.hypixel.hytale.protocol.packets.connection.ClientType;
import com.hypixel.hytale.protocol.packets.connection.Disconnect;
import com.hypixel.hytale.server.core.Constants;
import com.hypixel.hytale.server.core.HytaleServer;
import com.hypixel.hytale.server.core.auth.AuthConfig;
import com.hypixel.hytale.server.core.auth.JWTValidator;
import com.hypixel.hytale.server.core.auth.PlayerAuthentication;
import com.hypixel.hytale.server.core.auth.ServerAuthManager;
import com.hypixel.hytale.server.core.auth.SessionServiceClient;
import com.hypixel.hytale.server.core.io.PacketHandler;
import com.hypixel.hytale.server.core.io.ProtocolVersion;
import com.hypixel.hytale.server.core.io.handlers.GenericConnectionPacketHandler;
import com.hypixel.hytale.server.core.io.netty.NettyUtil;
import com.hypixel.hytale.server.core.io.transport.QUICTransport;
import com.hypixel.hytale.server.core.modules.singleplayer.SingleplayerModule;
import io.netty.channel.Channel;
import io.netty.handler.timeout.ReadTimeoutHandler;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.UUID;
java.util.concurrent.TimeUnit;
java.util.logging.Level;
javax.annotation.Nonnull;
javax.annotation.Nullable;
{
HytaleLogger.forEnclosingClass();
SessionServiceClient sessionServiceClient;
JWTValidator jwtValidator;
AuthState authState;
authTokenPacketReceived;
String authenticatedUsername;
;
;
;
ClientType clientType;
String identityToken;
UUID playerUuid;
String username;
[] referralData;
HostAddress referralSource;
{
(channel, protocolVersion, language);
.authState = HandshakeHandler.AuthState.REQUESTING_AUTH_GRANT;
.authTokenPacketReceived = ;
.clientType = clientType;
.identityToken = identityToken;
.playerUuid = playerUuid;
.username = username;
.referralData = referralData;
.referralSource = referralSource;
}
SessionServiceClient {
(sessionServiceClient == ) {
(HandshakeHandler.class) {
(sessionServiceClient == ) {
sessionServiceClient = ();
}
}
}
sessionServiceClient;
}
JWTValidator {
(jwtValidator == ) {
(HandshakeHandler.class) {
(jwtValidator == ) {
jwtValidator = (getSessionServiceClient(), , AuthConfig.getServerAudience());
}
}
}
jwtValidator;
}
{
(packet.getId()) {
-> .handle((Disconnect)packet);
-> .handle((AuthToken)packet);
-> .disconnect( + packet.getId());
}
}
{
HytaleServer.get().getConfig().getConnectionTimeouts().getAuthTimeout();
.channel.pipeline().replace((String), , (authTimeout.toMillis(), TimeUnit.MILLISECONDS));
JWTValidator. getJwtValidator().validateIdentityToken(.identityToken);
(identityClaims == ) {
LOGGER.at(Level.WARNING).log(, .username, NettyUtil.formatRemoteAddress(.channel));
.disconnect();
} {
identityClaims.getSubjectAsUUID();
(tokenUuid != && tokenUuid.equals(.playerUuid)) {
.clientType == ClientType.Editor ? : ;
(!identityClaims.hasScope(requiredScope)) {
LOGGER.at(Level.WARNING).log(, .username, NettyUtil.formatRemoteAddress(.channel), .clientType, requiredScope, identityClaims.scope);
.disconnect( + requiredScope + );
} {
LOGGER.at(Level.INFO).log(, .username, .playerUuid, identityClaims.scope, NettyUtil.formatRemoteAddress(.channel));
.setTimeout(, () -> .authState != HandshakeHandler.AuthState.REQUESTING_AUTH_GRANT, , TimeUnit.SECONDS);
.requestAuthGrant();
}
} {
LOGGER.at(Level.WARNING).log(, .username, NettyUtil.formatRemoteAddress(.channel), .playerUuid, tokenUuid);
.disconnect();
}
}
}
{
ServerAuthManager.getInstance().getSessionToken();
(serverSessionToken != && !serverSessionToken.isEmpty()) {
getSessionServiceClient().requestAuthorizationGrantAsync(.identityToken, AuthConfig.getServerAudience(), serverSessionToken).thenAccept((authGrant) -> {
(.channel.isActive()) {
(authGrant == ) {
.channel.eventLoop().execute(() -> .disconnect());
} {
ServerAuthManager.getInstance().getIdentityToken();
(serverIdentityToken != && !serverIdentityToken.isEmpty()) {
.channel.eventLoop().execute(() -> {
(.channel.isActive()) {
(.authState != HandshakeHandler.AuthState.REQUESTING_AUTH_GRANT) {
LOGGER.at(Level.WARNING).log(, .authState);
} {
.clearTimeout();
LOGGER.at(Level.INFO).log(, NettyUtil.formatRemoteAddress(.channel), !serverIdentityToken.isEmpty());
.write( (authGrant, serverIdentityToken));
.authState = HandshakeHandler.AuthState.AWAITING_AUTH_TOKEN;
.setTimeout(, () -> .authState != HandshakeHandler.AuthState.AWAITING_AUTH_TOKEN, , TimeUnit.SECONDS);
}
}
});
} {
LOGGER.at(Level.SEVERE).log();
.channel.eventLoop().execute(() -> .disconnect());
}
}
}
}).exceptionally((ex) -> {
((HytaleLogger.Api)LOGGER.at(Level.WARNING).withCause(ex)).log();
.channel.eventLoop().execute(() -> .disconnect( + ex.getMessage()));
;
});
} {
LOGGER.at(Level.SEVERE).log();
.disconnect();
}
}
{
.disconnectReason.setClientDisconnectType(packet.type);
LOGGER.at(Level.INFO).log(, .playerUuid, .username, NettyUtil.formatRemoteAddress(.channel), packet.type.name(), packet.reason);
ProtocolUtil.closeApplicationConnection(.channel);
}
{
(.authState != HandshakeHandler.AuthState.AWAITING_AUTH_TOKEN) {
LOGGER.at(Level.WARNING).log(, .authState, NettyUtil.formatRemoteAddress(.channel));
.disconnect();
} (.authTokenPacketReceived) {
LOGGER.at(Level.WARNING).log(, NettyUtil.formatRemoteAddress(.channel));
.disconnect();
} {
.authTokenPacketReceived = ;
.authState = HandshakeHandler.AuthState.PROCESSING_AUTH_TOKEN;
.clearTimeout();
packet.accessToken;
(accessToken != && !accessToken.isEmpty()) {
packet.serverAuthorizationGrant;
(X509Certificate).channel.attr(QUICTransport.CLIENT_CERTIFICATE_ATTR).get();
LOGGER.at(Level.INFO).log(, NettyUtil.formatRemoteAddress(.channel), clientCert != , serverAuthGrant != && !serverAuthGrant.isEmpty());
JWTValidator. getJwtValidator().validateToken(accessToken, clientCert);
(claims == ) {
LOGGER.at(Level.WARNING).log(, NettyUtil.formatRemoteAddress(.channel));
.disconnect();
} {
claims.getSubjectAsUUID();
claims.username;
(tokenUuid != && tokenUuid.equals(.playerUuid)) {
(tokenUsername != && !tokenUsername.isEmpty()) {
(!tokenUsername.equals(.username)) {
LOGGER.at(Level.WARNING).log(, NettyUtil.formatRemoteAddress(.channel), .username, tokenUsername);
.disconnect();
} {
.authenticatedUsername = tokenUsername;
(serverAuthGrant != && !serverAuthGrant.isEmpty()) {
.authState = HandshakeHandler.AuthState.EXCHANGING_SERVER_TOKEN;
.setTimeout(, () -> .authState != HandshakeHandler.AuthState.EXCHANGING_SERVER_TOKEN, , TimeUnit.SECONDS);
.exchangeServerAuthGrant(serverAuthGrant);
} {
LOGGER.at(Level.WARNING).log();
.disconnect();
}
}
} {
LOGGER.at(Level.WARNING).log(, NettyUtil.formatRemoteAddress(.channel));
.disconnect();
}
} {
LOGGER.at(Level.WARNING).log(, NettyUtil.formatRemoteAddress(.channel), .playerUuid, tokenUuid);
.disconnect();
}
}
} {
LOGGER.at(Level.WARNING).log(, NettyUtil.formatRemoteAddress(.channel));
.disconnect();
}
}
}
{
ServerAuthManager.getInstance();
serverAuthManager.getServerCertificateFingerprint();
(serverCertFingerprint == ) {
LOGGER.at(Level.SEVERE).log();
.disconnect();
} {
serverAuthManager.getSessionToken();
LOGGER.at(Level.FINE).log(, serverSessionToken != , serverAuthManager.getIdentityToken() != );
(serverSessionToken == ) {
LOGGER.at(Level.SEVERE).log();
LOGGER.at(Level.FINE).log(, serverAuthManager.getAuthStatus(), serverAuthManager.hasSessionToken(), serverAuthManager.hasIdentityToken());
.disconnect();
} {
LOGGER.at(Level.FINE).log(, serverSessionToken.length() > ? serverSessionToken.substring(, ) : serverSessionToken);
getSessionServiceClient().exchangeAuthGrantForTokenAsync(serverAuthGrant, serverCertFingerprint, serverSessionToken).thenAccept((serverAccessToken) -> {
(.channel.isActive()) {
.channel.eventLoop().execute(() -> {
(.channel.isActive()) {
(.authState != HandshakeHandler.AuthState.EXCHANGING_SERVER_TOKEN) {
LOGGER.at(Level.WARNING).log(, .authState);
} (serverAccessToken == ) {
LOGGER.at(Level.SEVERE).log();
.disconnect();
} {
[] passwordChallenge = .generatePasswordChallengeIfNeeded();
LOGGER.at(Level.INFO).log(, NettyUtil.formatRemoteAddress(.channel), passwordChallenge != );
.write( (serverAccessToken, passwordChallenge));
.completeAuthentication(passwordChallenge);
}
}
});
}
}).exceptionally((ex) -> {
((HytaleLogger.Api)LOGGER.at(Level.WARNING).withCause(ex)).log();
.channel.eventLoop().execute(() -> {
(.authState == HandshakeHandler.AuthState.EXCHANGING_SERVER_TOKEN) {
.disconnect();
}
});
;
});
}
}
}
[] generatePasswordChallengeIfNeeded() {
HytaleServer.get().getConfig().getPassword();
(password != && !password.isEmpty()) {
(Constants.SINGLEPLAYER) {
SingleplayerModule.getUuid();
(ownerUuid != && ownerUuid.equals(.playerUuid)) {
;
}
}
[] challenge = [];
( ()).nextBytes(challenge);
challenge;
} {
;
}
}
{
.auth = (.playerUuid, .authenticatedUsername);
(.referralData != ) {
.auth.setReferralData(.referralData);
}
(.referralSource != ) {
.auth.setReferralSource(.referralSource);
}
.authState = HandshakeHandler.AuthState.AUTHENTICATED;
.clearTimeout();
LOGGER.at(Level.INFO).log(, .authenticatedUsername, .playerUuid, NettyUtil.formatRemoteAddress(.channel));
.onAuthenticated(passwordChallenge);
}
;
{
REQUESTING_AUTH_GRANT,
AWAITING_AUTH_TOKEN,
PROCESSING_AUTH_TOKEN,
EXCHANGING_SERVER_TOKEN,
AUTHENTICATED;
{
}
}
}
com/hypixel/hytale/server/core/io/handlers/login/PasswordPacketHandler.java
package com.hypixel.hytale.server.core.io.handlers.login;
import com.hypixel.hytale.logger.HytaleLogger;
import com.hypixel.hytale.protocol.HostAddress;
import com.hypixel.hytale.protocol.Packet;
import com.hypixel.hytale.protocol.io.netty.ProtocolUtil;
import com.hypixel.hytale.protocol.packets.auth.PasswordAccepted;
import com.hypixel.hytale.protocol.packets.auth.PasswordRejected;
import com.hypixel.hytale.protocol.packets.auth.PasswordResponse;
import com.hypixel.hytale.protocol.packets.connection.Disconnect;
import com.hypixel.hytale.server.core.HytaleServer;
import com.hypixel.hytale.server.core.auth.PlayerAuthentication;
import com.hypixel.hytale.server.core.io.PacketHandler;
import com.hypixel.hytale.server.core.io.ProtocolVersion;
import com.hypixel.hytale.server.core.io.handlers.GenericConnectionPacketHandler;
import com.hypixel.hytale.server.core.io.netty.NettyUtil;
import io.netty.channel.Channel;
import io.netty.handler.timeout.ReadTimeoutHandler;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class PasswordPacketHandler extends GenericConnectionPacketHandler {
private HytaleLogger.forEnclosingClass();
;
;
;
UUID playerUuid;
String username;
[] referralData;
HostAddress referralSource;
[] passwordChallenge;
SetupHandlerSupplier setupHandlerSupplier;
;
{
(channel, protocolVersion, language);
.playerUuid = playerUuid;
.username = username;
.referralData = referralData;
.referralSource = referralSource;
.passwordChallenge = passwordChallenge;
.setupHandlerSupplier = setupHandlerSupplier;
}
String {
NettyUtil.formatRemoteAddress(.channel);
+ var10000 + + .username + ;
}
{
HytaleServer.get().getConfig().getConnectionTimeouts().getPlayTimeout();
.channel.pipeline().replace((String), , (playTimeout.toMillis(), TimeUnit.MILLISECONDS));
(.passwordChallenge != && .passwordChallenge.length != ) {
LOGGER.at(Level.FINE).log(, .username);
.setTimeout(, () -> !.registered, , TimeUnit.SECONDS);
} {
LOGGER.at(Level.FINE).log(, .username);
.proceedToSetup();
}
}
{
(packet.getId()) {
-> .handle((Disconnect)packet);
-> .handle((PasswordResponse)packet);
-> .disconnect( + packet.getId());
}
}
{
.disconnectReason.setClientDisconnectType(packet.type);
LOGGER.at(Level.INFO).log(, .playerUuid, .username, NettyUtil.formatRemoteAddress(.channel), packet.type.name(), packet.reason);
ProtocolUtil.closeApplicationConnection(.channel);
}
{
.clearTimeout();
(.passwordChallenge != && .passwordChallenge.length != ) {
[] clientHash = packet.hash;
(clientHash != && clientHash.length != ) {
HytaleServer.get().getConfig().getPassword();
(password != && !password.isEmpty()) {
[] expectedHash = computePasswordHash(.passwordChallenge, password);
(expectedHash == ) {
LOGGER.at(Level.SEVERE).log();
.disconnect();
} (!MessageDigest.isEqual(expectedHash, clientHash)) {
--.attemptsRemaining;
LOGGER.at(Level.WARNING).log(, .username, NettyUtil.formatRemoteAddress(.channel), .attemptsRemaining);
(.attemptsRemaining <= ) {
.disconnect();
} {
.passwordChallenge = generateChallenge();
.write( (.passwordChallenge, .attemptsRemaining));
.setTimeout(, () -> !.registered, , TimeUnit.SECONDS);
}
} {
LOGGER.at(Level.INFO).log(, .username, .playerUuid);
.write( ());
.proceedToSetup();
}
} {
LOGGER.at(Level.SEVERE).log();
.disconnect();
}
} {
LOGGER.at(Level.WARNING).log(, NettyUtil.formatRemoteAddress(.channel));
.disconnect();
}
} {
LOGGER.at(Level.WARNING).log(, NettyUtil.formatRemoteAddress(.channel));
.disconnect();
}
}
[] generateChallenge() {
[] challenge = [];
( ()).nextBytes(challenge);
challenge;
}
{
.auth = (.playerUuid, .username);
(.referralData != ) {
.auth.setReferralData(.referralData);
}
(.referralSource != ) {
.auth.setReferralSource(.referralSource);
}
LOGGER.at(Level.INFO).log(, .username, .playerUuid);
NettyUtil.setChannelHandler(.channel, .setupHandlerSupplier.create(.channel, .protocolVersion, .language, .auth));
}
[] computePasswordHash([] challenge, String password) {
{
MessageDigest.getInstance();
digest.update(challenge);
digest.update(password.getBytes(StandardCharsets.UTF_8));
digest.digest();
} (NoSuchAlgorithmException var3) {
;
}
}
{
PacketHandler ;
}
}
com/hypixel/hytale/server/core/io/netty/HytaleChannelInitializer.java
package com.hypixel.hytale.server.core.io.netty;
import com.hypixel.hytale.logger.HytaleLogger;
import com.hypixel.hytale.protocol.io.PacketStatsRecorder;
import com.hypixel.hytale.protocol.io.netty.PacketDecoder;
import com.hypixel.hytale.protocol.io.netty.PacketEncoder;
import com.hypixel.hytale.protocol.io.netty.ProtocolUtil;
import com.hypixel.hytale.protocol.packets.connection.Disconnect;
import com.hypixel.hytale.protocol.packets.connection.DisconnectType;
import com.hypixel.hytale.server.core.HytaleServer;
import com.hypixel.hytale.server.core.HytaleServerConfig;
import com.hypixel.hytale.server.core.io.PacketHandler;
import com.hypixel.hytale.server.core.io.PacketStatsRecorderImpl;
import com.hypixel.hytale.server.core.io.handlers.InitialPacketHandler;
import com.hypixel.hytale.server.core.io.transport.QUICTransport;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.quic.QuicChannel;
import io.netty.handler.codec.quic.QuicStreamChannel;
import io.netty.handler.timeout.ReadTimeoutException;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.TimeoutException;
import io.netty.handler.timeout.WriteTimeoutException;
import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
java.util.concurrent.atomic.AtomicBoolean;
java.util.logging.Level;
javax.annotation.Nonnull;
<Channel> {
{
}
{
(channel QuicStreamChannel quicStreamChannel) {
HytaleLogger.getLogger().at(Level.INFO).log(, NettyUtil.formatRemoteAddress(channel), NettyUtil.formatLocalAddress(channel));
quicStreamChannel.parent();
(X509Certificate)parentChannel.attr(QUICTransport.CLIENT_CERTIFICATE_ATTR).get();
(clientCert != ) {
channel.attr(QUICTransport.CLIENT_CERTIFICATE_ATTR).set(clientCert);
HytaleLogger.getLogger().at(Level.FINE).log(, clientCert.getSubjectX500Principal().getName());
}
} {
HytaleLogger.getLogger().at(Level.INFO).log(, NettyUtil.formatRemoteAddress(channel), NettyUtil.formatLocalAddress(channel));
}
();
channel.attr(PacketStatsRecorder.CHANNEL_KEY).set(statsRecorder);
HytaleServer.get().getConfig().getConnectionTimeouts().getInitialTimeout();
channel.pipeline().addLast((String), (ChannelHandler)( (initialTimeout.toMillis(), TimeUnit.MILLISECONDS)));
channel.pipeline().addLast((String), (ChannelHandler)( ()));
HytaleServerConfig. HytaleServer.get().getConfig().getRateLimitConfig();
(rateLimitConfig.isEnabled()) {
channel.pipeline().addLast((String), (ChannelHandler)( (rateLimitConfig.getBurstCapacity(), rateLimitConfig.getPacketsPerSecond())));
}
channel.pipeline().addLast((String), (ChannelHandler)( ()));
channel.pipeline().addLast((String), (ChannelHandler)NettyUtil.PACKET_ARRAY_ENCODER_INSTANCE);
(NettyUtil.PACKET_LOGGER.getLevel() != Level.OFF) {
channel.pipeline().addLast((String), (ChannelHandler)NettyUtil.LOGGER);
}
(channel);
channel.pipeline().addLast((String), (ChannelHandler)( (playerConnection)));
channel.pipeline().addLast( ());
playerConnection.registered((PacketHandler));
}
{
((HytaleLogger.Api)HytaleLogger.getLogger().at(Level.WARNING).withCause(cause)).log();
(ctx.channel().isWritable()) {
ctx.channel().writeAndFlush( (, DisconnectType.Crash)).addListener(ProtocolUtil.CLOSE_ON_COMPLETE);
} {
ProtocolUtil.closeApplicationConnection(ctx.channel());
}
}
Exception {
ProtocolUtil.closeApplicationConnection(ctx.channel());
.channelInactive(ctx);
}
{
();
{
}
{
(!(cause ClosedChannelException)) {
ctx.pipeline().get();
String identifier;
(handler PlayerChannelHandler) {
identifier = ((PlayerChannelHandler)handler).getHandler().getIdentifier();
} {
identifier = NettyUtil.formatRemoteAddress(ctx.channel());
}
(.handled.getAndSet()) {
(cause IOException && cause.getMessage() != ) {
(cause.getMessage()) {
:
:
:
;
}
}
((HytaleLogger.Api)HytaleLogger.getLogger().at(Level.WARNING).withCause(cause)).log();
} (cause TimeoutException) {
cause ReadTimeoutException;
cause WriteTimeoutException;
readTimeout ? : (writeTimeout ? : );
HytaleLogger.getLogger().at(Level.INFO).log(msg, identifier);
((HytaleLogger.Api)NettyUtil.CONNECTION_EXCEPTION_LOGGER.at(Level.FINE).withCause(cause)).log(msg, identifier);
(ctx.channel().isWritable()) {
ctx.channel().writeAndFlush( (readTimeout ? : (writeTimeout ? : ), DisconnectType.Crash)).addListener(ProtocolUtil.CLOSE_ON_COMPLETE);
} {
ProtocolUtil.closeApplicationConnection(ctx.channel());
}
} {
((HytaleLogger.Api)HytaleLogger.getLogger().at(Level.SEVERE).withCause(cause)).log(, cause.getMessage());
(ctx.channel().isWritable()) {
ctx.channel().writeAndFlush( (, DisconnectType.Crash)).addListener(ProtocolUtil.CLOSE_ON_COMPLETE);
} {
ProtocolUtil.closeApplicationConnection(ctx.channel());
}
}
}
}
}
}
com/hypixel/hytale/server/core/io/netty/LatencySimulationHandler.java
package com.hypixel.hytale.server.core.io.netty;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.util.Comparator;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nonnull;
public class LatencySimulationHandler extends ChannelDuplexHandler {
public static final String PIPELINE_KEY = "latencySimulator";
private static final AtomicInteger counter = new AtomicInteger();
private final DelayQueue<DelayedHandler> delayedQueue = new DelayQueue();
@Nonnull
private final Thread taskThread;
private final long delayNanos;
public {
.delayNanos = unit.toNanos(delay);
.taskThread = (() -> {
{
(!Thread.interrupted()) {
(DelayedHandler).delayedQueue.take();
handler.ctx.executor().execute(handler);
}
} (InterruptedException var2) {
Thread.currentThread().interrupt();
}
}, + counter.getAndIncrement());
.taskThread.setDaemon();
.taskThread.start();
}
Exception {
.delayedQueue.offer( (ctx, System.nanoTime() + .delayNanos));
}
Exception {
.delayedQueue.offer( (ctx, System.nanoTime() + .delayNanos, msg, promise));
}
{
.delayedQueue.offer( (ctx, System.nanoTime() + .delayNanos));
}
Exception {
.handlerRemoved(ctx);
.taskThread.interrupt();
ObjectArrayList<DelayedHandler> list = <DelayedHandler>(.delayedQueue);
list.sort(Comparator.comparingLong((value) -> value.executeAtNanos));
(DelayedHandler handler : list) {
handler.run();
}
}
Exception {
.close(ctx, promise);
.taskThread.interrupt();
}
{
channel.pipeline();
(pipeline.get() == ) {
(delay > ) {
pipeline.addAfter(, , (delay, unit));
}
} (delay <= ) {
pipeline.remove();
} {
pipeline.replace((String), , (delay, unit));
}
}
, Runnable {
ChannelHandlerContext ctx;
executeAtNanos;
{
.ctx = ctx;
.executeAtNanos = executeAtNanos;
}
{
unit.convert(.executeAtNanos - System.nanoTime(), TimeUnit.NANOSECONDS);
}
{
Long.compare(.executeAtNanos, ((DelayedHandler)o).executeAtNanos);
}
}
{
{
(ctx, executeAtNanos);
}
{
.ctx.read();
}
}
{
Object msg;
ChannelPromise promise;
{
(ctx, executeAtNanos);
.msg = msg;
.promise = promise;
}
{
.ctx.write(.msg, .promise);
}
}
{
{
(ctx, executeAtNanos);
}
{
.ctx.flush();
}
}
}
com/hypixel/hytale/server/core/io/netty/NettyUtil.java
package com.hypixel.hytale.server.core.io.netty;
import com.hypixel.hytale.logger.HytaleLogger;
import com.hypixel.hytale.logger.backend.HytaleLoggerBackend;
import com.hypixel.hytale.server.core.io.PacketHandler;
import com.hypixel.hytale.server.core.universe.PlayerRef;
import com.hypixel.hytale.server.core.universe.Universe;
import com.hypixel.hytale.server.core.util.concurrent.ThreadUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.ServerChannel;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollDatagramChannel;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.kqueue.KQueue;
import io.netty.channel.kqueue.KQueueDatagramChannel;
import io.netty.channel.kqueue.KQueueEventLoopGroup;
import io.netty.channel.kqueue.KQueueServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.SocketProtocolFamily;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.quic.QuicChannel;
import io.netty.handler.codec.quic.QuicStreamChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.internal.ObjectUtil;
io.netty.util.internal.StringUtil;
io.netty.util.internal.SystemPropertyUtil;
java.lang.reflect.Constructor;
java.net.InetSocketAddress;
java.net.SocketAddress;
java.util.Objects;
java.util.concurrent.ThreadFactory;
java.util.logging.Level;
javax.annotation.Nonnull;
javax.annotation.Nullable;
{
HytaleLogger.get();
HytaleLogger.get();
;
;
PacketArrayEncoder PACKET_ARRAY_ENCODER_INSTANCE;
;
;
LoggingHandler LOGGER;
;
;
;
{
}
{
}
{
(channel.pipeline().get() == ) {
channel.pipeline().addAfter(, , LOGGER);
}
}
{
channel.pipeline().remove();
}
{
channel.pipeline().replace((String), , (packetHandler));
;
(oldHandler PlayerChannelHandler) {
oldPlayerConnection = ((PlayerChannelHandler)oldHandler).getHandler();
oldPlayerConnection.unregistered(packetHandler);
}
packetHandler.registered(oldPlayerConnection);
}
EventLoopGroup {
getEventLoopGroup(, name);
}
EventLoopGroup {
(nThreads == ) {
nThreads = Math.max(, SystemPropertyUtil.getInt(, Runtime.getRuntime().availableProcessors() * ));
}
ThreadUtil.daemonCounted(name + );
(Epoll.isAvailable()) {
(nThreads, factory);
} {
(EventLoopGroup)(KQueue.isAvailable() ? (nThreads, factory) : (nThreads, factory));
}
}
Class<? > getServerChannel() {
(Epoll.isAvailable()) {
EpollServerSocketChannel.class;
} {
KQueue.isAvailable() ? KQueueServerSocketChannel.class : NioServerSocketChannel.class;
}
}
ReflectiveChannelFactory<? > getDatagramChannelFactory(SocketProtocolFamily family) {
(Epoll.isAvailable()) {
<DatagramChannel>(EpollDatagramChannel.class, family);
} {
KQueue.isAvailable() ? (KQueueDatagramChannel.class, family) : (NioDatagramChannel.class, family);
}
}
String {
(channel QuicChannel quicChannel) {
String.valueOf(quicChannel.remoteAddress());
var3 + + String.valueOf(quicChannel.remoteSocketAddress()) + ;
} (channel QuicStreamChannel quicStreamChannel) {
String.valueOf(quicStreamChannel.parent().localAddress());
var10000 + + String.valueOf(quicStreamChannel.parent().remoteSocketAddress()) + + quicStreamChannel.remoteAddress().streamId() + ;
} {
channel.remoteAddress().toString();
}
}
String {
(channel QuicChannel quicChannel) {
String.valueOf(quicChannel.localAddress());
var3 + + String.valueOf(quicChannel.localSocketAddress()) + ;
} (channel QuicStreamChannel quicStreamChannel) {
String.valueOf(quicStreamChannel.parent().localAddress());
var10000 + + String.valueOf(quicStreamChannel.parent().localSocketAddress()) + + quicStreamChannel.localAddress().streamId() + ;
} {
channel.localAddress().toString();
}
}
SocketAddress {
(channel QuicChannel quicChannel) {
quicChannel.remoteSocketAddress();
} (channel QuicStreamChannel quicStreamChannel) {
quicStreamChannel.parent().remoteSocketAddress();
} {
channel.remoteAddress();
}
}
{
getRemoteSocketAddress(channel1);
getRemoteSocketAddress(channel2);
(remoteSocketAddress1 != && remoteSocketAddress2 != ) {
(Objects.equals(remoteSocketAddress1, remoteSocketAddress2)) {
;
} (!remoteSocketAddress1.getClass().equals(remoteSocketAddress2.getClass())) {
;
} {
(remoteSocketAddress1 InetSocketAddress) {
(InetSocketAddress)remoteSocketAddress1;
(remoteSocketAddress2 InetSocketAddress) {
(InetSocketAddress)remoteSocketAddress2;
(remoteInetSocketAddress1.getAddress().isLoopbackAddress() && remoteInetSocketAddress2.getAddress().isLoopbackAddress()) {
;
}
remoteInetSocketAddress1.getAddress().equals(remoteInetSocketAddress2.getAddress());
}
}
;
}
} {
;
}
}
{
HytaleLoggerBackend.getLogger(PACKET_LOGGER.getName());
loggerBackend.setOnLevelChange((oldLevel, newLevel) -> {
Universe.get();
(universe != ) {
(newLevel == Level.OFF) {
(PlayerRef p : universe.getPlayers()) {
uninjectLogger(p.getPacketHandler().getChannel());
}
} {
(PlayerRef p : universe.getPlayers()) {
injectLogger(p.getPacketHandler().getChannel());
}
}
}
});
PACKET_LOGGER.setLevel(Level.OFF);
loggerBackend.loadLogLevel();
CONNECTION_EXCEPTION_LOGGER.setLevel(Level.ALL);
PACKET_ARRAY_ENCODER_INSTANCE = ();
LOGGER = (, LogLevel.INFO);
}
<T > <T> {
Constructor<? > constructor;
SocketProtocolFamily family;
{
ObjectUtil.checkNotNull(clazz, );
{
.constructor = clazz.getConstructor(SocketProtocolFamily.class);
.family = family;
} (NoSuchMethodException e) {
( + StringUtil.simpleClassName(clazz) + , e);
}
}
T {
{
(T)(.constructor.newInstance(.family));
} (Throwable t) {
( + String.valueOf(.constructor.getDeclaringClass()), t);
}
}
String {
StringUtil.simpleClassName(.constructor.getDeclaringClass());
var10000 + + String.valueOf(.family) + ;
}
String {
StringUtil.simpleClassName(io.netty.channel.ReflectiveChannelFactory.class);
var10000 + + StringUtil.simpleClassName(.constructor.getDeclaringClass()) + + String.valueOf(.family) + ;
}
}
}
com/hypixel/hytale/server/core/io/netty/PacketArrayEncoder.java
package com.hypixel.hytale.server.core.io.netty;
import com.hypixel.hytale.protocol.Packet;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import java.util.List;
import javax.annotation.Nonnull;
@ChannelHandler.Sharable
public class PacketArrayEncoder extends MessageToMessageEncoder<Packet[]> {
public PacketArrayEncoder() {
}
protected void encode(ChannelHandlerContext ctx, @Nonnull Packet[] packets, @Nonnull List<Object> out) {
for(Packet packet : packets) {
if (packet != null) {
out.add(packet);
}
}
}
}
com/hypixel/hytale/server/core/io/netty/PlayerChannelHandler.java
package com.hypixel.hytale.server.core.io.netty;
import com.hypixel.hytale.protocol.Packet;
import com.hypixel.hytale.server.core.io.PacketHandler;
import com.hypixel.hytale.server.core.io.adapter.PacketAdapters;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class PlayerChannelHandler extends ChannelInboundHandlerAdapter {
private final PacketHandler handler;
public PlayerChannelHandler(PacketHandler handler) {
this.handler = handler;
}
public PacketHandler getHandler() {
return this.handler;
}
public void channelInactive(ChannelHandlerContext ctx) {
this.handler.logCloseMessage();
this.handler.closed(ctx);
}
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (ctx.channel().isActive()) {
Packet packet = (Packet)msg;
if (!PacketAdapters.__handleInbound(this.handler, packet)) {
this.handler.handle(packet);
}
}
}
}
com/hypixel/hytale/server/core/io/netty/RateLimitHandler.java
package com.hypixel.hytale.server.core.io.netty;
import com.hypixel.hytale.logger.HytaleLogger;
import com.hypixel.hytale.protocol.io.netty.ProtocolUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.util.logging.Level;
public class RateLimitHandler extends ChannelInboundHandlerAdapter {
private static final HytaleLogger LOGGER = HytaleLogger.forEnclosingClass();
private final int maxTokens;
private final int refillRate;
private int tokens;
private long lastRefillTime;
public RateLimitHandler(int maxTokens, int refillRate) {
this.maxTokens = maxTokens;
this.refillRate = refillRate;
this.tokens = maxTokens;
this.lastRefillTime = System.nanoTime();
}
private void refillTokens() {
long now = System.nanoTime();
long elapsedNanos now - .lastRefillTime;
elapsedNanos * ().refillRate / ;
(tokensToAdd > ) {
.tokens = ()Math.min(().maxTokens, ().tokens + tokensToAdd);
.lastRefillTime = now;
}
}
{
.refillTokens();
(.tokens > ) {
--.tokens;
ctx.fireChannelRead(msg);
} {
LOGGER.at(Level.WARNING).log(, NettyUtil.formatRemoteAddress(ctx.channel()));
ProtocolUtil.closeApplicationConnection(ctx.channel(), );
}
}
}
com/hypixel/hytale/server/core/io/transport/QUICTransport.java
package com.hypixel.hytale.server.core.io.transport;
import com.hypixel.hytale.logger.HytaleLogger;
import com.hypixel.hytale.protocol.io.netty.ProtocolUtil;
import com.hypixel.hytale.protocol.packets.connection.Disconnect;
import com.hypixel.hytale.protocol.packets.connection.DisconnectType;
import com.hypixel.hytale.server.core.HytaleServer;
import com.hypixel.hytale.server.core.auth.CertificateUtil;
import com.hypixel.hytale.server.core.auth.ServerAuthManager;
import com.hypixel.hytale.server.core.io.netty.HytaleChannelInitializer;
import com.hypixel.hytale.server.core.io.netty.NettyUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.SocketProtocolFamily;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.handler.codec.quic.InsecureQuicTokenHandler;
import io.netty.handler.codec.quic.QuicChannel;
import io.netty.handler.codec.quic.QuicCongestionControlAlgorithm;
import io.netty.handler.codec.quic.QuicServerCodecBuilder;
import io.netty.handler.codec.quic.QuicSslContext;
import io.netty.handler.codec.quic.QuicSslContextBuilder;
import io.netty.handler.ssl.ClientAuth;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate;
io.netty.util.AttributeKey;
java.net.Inet4Address;
java.net.Inet6Address;
java.net.InetSocketAddress;
java.security.PrivateKey;
java.security.cert.Certificate;
java.security.cert.CertificateException;
java.security.cert.X509Certificate;
java.time.Duration;
java.util.concurrent.TimeUnit;
java.util.logging.Level;
javax.annotation.Nonnull;
javax.annotation.Nullable;
javax.net.ssl.SSLEngine;
jdk.net.ExtendedSocketOptions;
{
HytaleLogger.forEnclosingClass();
AttributeKey<X509Certificate> CLIENT_CERTIFICATE_ATTR = AttributeKey.<X509Certificate>valueOf();
NettyUtil.getEventLoopGroup();
Bootstrap bootstrapIpv4;
Bootstrap bootstrapIpv6;
InterruptedException {
;
{
ssc = ();
} (CertificateException e) {
(e);
}
ServerAuthManager.getInstance().setServerCertificate(ssc.cert());
LOGGER.at(Level.INFO).log(, CertificateUtil.computeCertificateFingerprint(ssc.cert()));
QuicSslContextBuilder.forServer((PrivateKey)ssc.key(), (String), (X509Certificate[])(ssc.cert())).applicationProtocols().earlyData().clientAuth(ClientAuth.REQUIRE).trustManager(InsecureTrustManagerFactory.INSTANCE).build();
NettyUtil.ReflectiveChannelFactory<? > channelFactoryIpv4 = NettyUtil.getDatagramChannelFactory(SocketProtocolFamily.INET);
LOGGER.at(Level.INFO).log(, channelFactoryIpv4.getSimpleName());
.bootstrapIpv4 = ((Bootstrap)((Bootstrap)((Bootstrap)((Bootstrap)((Bootstrap)( ()).group(.workerGroup)).channelFactory(channelFactoryIpv4)).option(ChannelOption.SO_REUSEADDR, )).option(NioChannelOption.of(ExtendedSocketOptions.IP_DONTFRAGMENT), )).handler( (sslContext))).validate();
NettyUtil.ReflectiveChannelFactory<? > channelFactoryIpv6 = NettyUtil.getDatagramChannelFactory(SocketProtocolFamily.INET6);
LOGGER.at(Level.INFO).log(, channelFactoryIpv6.getSimpleName());
.bootstrapIpv6 = ((Bootstrap)((Bootstrap)((Bootstrap)((Bootstrap)((Bootstrap)( ()).group(.workerGroup)).channelFactory(channelFactoryIpv6)).option(ChannelOption.SO_REUSEADDR, )).option(NioChannelOption.of(ExtendedSocketOptions.IP_DONTFRAGMENT), )).handler( (sslContext))).validate();
.bootstrapIpv4.register().sync();
.bootstrapIpv6.register().sync();
}
TransportType {
TransportType.QUIC;
}
ChannelFuture InterruptedException {
(address.getAddress() Inet4Address) {
.bootstrapIpv4.bind(address).sync();
} (address.getAddress() Inet6Address) {
.bootstrapIpv6.bind(address).sync();
} {
( + String.valueOf(address.getAddress().getClass()));
}
}
{
LOGGER.at(Level.INFO).log();
{
.workerGroup.shutdownGracefully(, , TimeUnit.SECONDS).await(, TimeUnit.SECONDS);
} (InterruptedException e) {
((HytaleLogger.Api)LOGGER.at(Level.SEVERE).withCause(e)).log();
Thread.currentThread().interrupt();
}
}
{
QuicSslContext sslContext;
{
.sslContext = sslContext;
}
{
;
}
Exception {
HytaleServer.get().getConfig().getConnectionTimeouts().getPlayTimeout();
((QuicServerCodecBuilder)((QuicServerCodecBuilder)((QuicServerCodecBuilder)((QuicServerCodecBuilder)((QuicServerCodecBuilder)((QuicServerCodecBuilder)((QuicServerCodecBuilder)((QuicServerCodecBuilder)((QuicServerCodecBuilder)((QuicServerCodecBuilder)((QuicServerCodecBuilder)( ()).sslContext(.sslContext)).tokenHandler(InsecureQuicTokenHandler.INSTANCE).maxIdleTimeout(playTimeout.toMillis(), TimeUnit.MILLISECONDS)).ackDelayExponent()).initialMaxData()).initialMaxStreamDataUnidirectional()).initialMaxStreamsUnidirectional()).initialMaxStreamDataBidirectionalLocal()).initialMaxStreamDataBidirectionalRemote()).initialMaxStreamsBidirectional()).discoverPmtu()).congestionControlAlgorithm(QuicCongestionControlAlgorithm.BBR)).handler( () {
{
;
}
Exception {
(QuicChannel)ctx.channel();
QUICTransport.LOGGER.at(Level.INFO).log(, NettyUtil.formatRemoteAddress(channel), NettyUtil.formatLocalAddress(channel));
QuicChannelInboundHandlerAdapter..extractClientCertificate(channel);
(clientCert == ) {
QUICTransport.LOGGER.at(Level.WARNING).log(, NettyUtil.formatRemoteAddress(channel));
ProtocolUtil.closeConnection(channel);
} {
channel.attr(QUICTransport.CLIENT_CERTIFICATE_ATTR).set(clientCert);
QUICTransport.LOGGER.at(Level.FINE).log(, clientCert.getSubjectX500Principal().getName());
}
}
{
((QuicChannel)ctx.channel()).collectStats().addListener((f) -> {
(f.isSuccess()) {
QUICTransport.LOGGER.at(Level.INFO).log(, f.getNow());
}
});
}
{
((HytaleLogger.Api)QUICTransport.LOGGER.at(Level.WARNING).withCause(cause)).log();
ctx.channel();
(channel.isWritable()) {
channel.writeAndFlush( (, DisconnectType.Crash)).addListener(ProtocolUtil.CLOSE_ON_COMPLETE);
} {
ProtocolUtil.closeApplicationConnection(channel);
}
}
}).streamHandler( ()).build();
ctx.channel().pipeline().addLast(quicHandler);
}
X509Certificate {
{
channel.sslEngine();
(sslEngine == ) {
;
}
Certificate[] peerCerts = sslEngine.getSession().getPeerCertificates();
(peerCerts != && peerCerts.length > && peerCerts[] X509Certificate) {
(X509Certificate)peerCerts[];
}
} (Exception e) {
QUICTransport.LOGGER.at(Level.FINEST).log(, e.getMessage());
}
;
}
}
}
com/hypixel/hytale/server/core/io/transport/TCPTransport.java
package com.hypixel.hytale.server.core.io.transport;
import com.hypixel.hytale.logger.HytaleLogger;
import com.hypixel.hytale.server.core.io.netty.HytaleChannelInitializer;
import com.hypixel.hytale.server.core.io.netty.NettyUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.ServerChannel;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import javax.annotation.Nonnull;
public class TCPTransport implements Transport {
private static final HytaleLogger LOGGER = HytaleLogger.forEnclosingClass();
@Nonnull
private final EventLoopGroup bossGroup = NettyUtil.getEventLoopGroup(1, "ServerBossGroup");
@Nonnull
private final EventLoopGroup workerGroup = NettyUtil.getEventLoopGroup("ServerWorkerGroup");
private final ServerBootstrap bootstrap;
public InterruptedException {
Class<? > serverChannel = NettyUtil.getServerChannel();
LOGGER.at(Level.INFO).log(, serverChannel.getSimpleName());
.bootstrap = ((ServerBootstrap)((ServerBootstrap)((ServerBootstrap)( ()).group(.bossGroup, .workerGroup).channel(serverChannel)).option(ChannelOption.SO_BACKLOG, )).option(ChannelOption.SO_REUSEADDR, )).childHandler( ()).validate();
.bootstrap.register().sync();
}
TransportType {
TransportType.TCP;
}
ChannelFuture InterruptedException {
.bootstrap.bind(address).sync();
}
{
LOGGER.at(Level.INFO).log();
{
.bossGroup.shutdownGracefully(, , TimeUnit.SECONDS).await(, TimeUnit.SECONDS);
} (InterruptedException e) {
((HytaleLogger.Api)LOGGER.at(Level.SEVERE).withCause(e)).log();
Thread.currentThread().interrupt();
}
LOGGER.at(Level.INFO).log();
{
.workerGroup.shutdownGracefully(, , TimeUnit.SECONDS).await(, TimeUnit.SECONDS);
} (InterruptedException e) {
((HytaleLogger.Api)LOGGER.at(Level.SEVERE).withCause(e)).log();
Thread.currentThread().interrupt();
}
}
}
com/hypixel/hytale/server/core/io/transport/Transport.java
package com.hypixel.hytale.server.core.io.transport;
import io.netty.channel.ChannelFuture;
import java.net.InetSocketAddress;
public interface Transport {
TransportType getType();
ChannelFuture bind(InetSocketAddress var1) throws InterruptedException;
void shutdown();
}
com/hypixel/hytale/server/core/io/transport/TransportType.java
package com.hypixel.hytale.server.core.io.transport;
public enum TransportType {
TCP,
QUIC;
private TransportType() {
}
}