| 1 | package net.minecraft.client.multiplayer;
|
| 2 |
|
| 3 | import com.google.common.collect.Lists;
|
| 4 | import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
| 5 | import com.mojang.logging.LogUtils;
|
| 6 | import io.netty.bootstrap.Bootstrap;
|
| 7 | import io.netty.channel.Channel;
|
| 8 | import io.netty.channel.ChannelException;
|
| 9 | import io.netty.channel.ChannelInitializer;
|
| 10 | import io.netty.channel.ChannelOption;
|
| 11 | import java.net.InetSocketAddress;
|
| 12 | import java.net.UnknownHostException;
|
| 13 | import java.util.ArrayList;
|
| 14 | import java.util.Arrays;
|
| 15 | import java.util.Collections;
|
| 16 | import java.util.Iterator;
|
| 17 | import java.util.List;
|
| 18 | import java.util.Optional;
|
| 19 | import net.fabricmc.api.EnvType;
|
| 20 | import net.fabricmc.api.Environment;
|
| 21 | import net.minecraft.ChatFormatting;
|
| 22 | import net.minecraft.client.gui.screens.ConnectScreen;
|
| 23 | import net.minecraft.client.multiplayer.resolver.ResolvedServerAddress;
|
| 24 | import net.minecraft.client.multiplayer.resolver.ServerAddress;
|
| 25 | import net.minecraft.client.multiplayer.resolver.ServerNameResolver;
|
| 26 | import net.minecraft.network.Connection;
|
| 27 | import net.minecraft.network.DisconnectionDetails;
|
| 28 | import net.minecraft.network.chat.CommonComponents;
|
| 29 | import net.minecraft.network.chat.Component;
|
| 30 | import net.minecraft.network.chat.ComponentUtils;
|
| 31 | import net.minecraft.network.chat.ResolutionContext;
|
| 32 | import net.minecraft.network.chat.ResolutionContext.LimitBehavior;
|
| 33 | import net.minecraft.network.chat.contents.objects.PlayerSprite;
|
| 34 | import net.minecraft.network.protocol.ping.ClientboundPongResponsePacket;
|
| 35 | import net.minecraft.network.protocol.ping.ServerboundPingRequestPacket;
|
| 36 | import net.minecraft.network.protocol.status.ClientStatusPacketListener;
|
| 37 | import net.minecraft.network.protocol.status.ClientboundStatusResponsePacket;
|
| 38 | import net.minecraft.network.protocol.status.ServerStatus;
|
| 39 | import net.minecraft.network.protocol.status.ServerboundStatusRequestPacket;
|
| 40 | import net.minecraft.network.protocol.status.ServerStatus.Players;
|
| 41 | import net.minecraft.server.MinecraftServer;
|
| 42 | import net.minecraft.server.network.EventLoopGroupHolder;
|
| 43 | import net.minecraft.server.players.NameAndId;
|
| 44 | import net.minecraft.util.Util;
|
| 45 | import org.slf4j.Logger;
|
| 46 |
|
| 47 | @Environment(EnvType.CLIENT)
|
| 48 | public class ServerStatusPinger {
|
| 49 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 50 | private static final Component CANT_CONNECT_MESSAGE = Component.translatable("multiplayer.status.cannot_connect").withColor(-65536);
|
| 51 | private static final ResolutionContext DESCRIPTION_SANITIZE_CONTEXT = ResolutionContext.builder()
|
| 52 | .withObjectInfoValidator(description -> !(description instanceof PlayerSprite))
|
| 53 | .setDepthLimit(16)
|
| 54 | .setDepthLimitBehavior(LimitBehavior.DISCARD_REMAINING)
|
| 55 | .build();
|
| 56 | private final List<Connection> connections = Collections.synchronizedList(Lists.newArrayList());
|
| 57 |
|
| 58 | public void pingServer(
|
| 59 | final ServerData data, final Runnable onPersistentDataChange, final Runnable onPongResponse, final EventLoopGroupHolder eventLoopGroupHolder
|
| 60 | ) throws UnknownHostException {
|
| 61 | final ServerAddress rawAddress = ServerAddress.parseString(data.ip);
|
| 62 | Optional<InetSocketAddress> resolvedAddress = ServerNameResolver.DEFAULT.resolveAddress(rawAddress).map(ResolvedServerAddress::asInetSocketAddress);
|
| 63 | if (resolvedAddress.isEmpty()) {
|
| 64 | this.onPingFailed(ConnectScreen.UNKNOWN_HOST_MESSAGE, data);
|
| 65 | } else {
|
| 66 | final InetSocketAddress address = resolvedAddress.get();
|
| 67 | final Connection connection = Connection.connectToServer(address, eventLoopGroupHolder, null);
|
| 68 | this.connections.add(connection);
|
| 69 | data.motd = Component.translatable("multiplayer.status.pinging");
|
| 70 | data.playerList = Collections.emptyList();
|
| 71 | ClientStatusPacketListener listener = new ClientStatusPacketListener() {
|
| 72 | private boolean success;
|
| 73 | private boolean receivedPing;
|
| 74 | private long pingStart;
|
| 75 |
|
| 76 | @Override
|
| 77 | public void handleStatusResponse(final ClientboundStatusResponsePacket packet) {
|
| 78 | if (this.receivedPing) {
|
| 79 | connection.disconnect(Component.translatable("multiplayer.status.unrequested"));
|
| 80 | } else {
|
| 81 | this.receivedPing = true;
|
| 82 | ServerStatus status = packet.status();
|
| 83 | data.motd = sanitizeDescription(status.description());
|
| 84 | status.version().ifPresentOrElse(version -> {
|
| 85 | data.version = Component.literal(version.name());
|
| 86 | data.protocol = version.protocol();
|
| 87 | }, () -> {
|
| 88 | data.version = Component.translatable("multiplayer.status.old");
|
| 89 | data.protocol = 0;
|
| 90 | });
|
| 91 | status.players().ifPresentOrElse(players -> {
|
| 92 | data.status = ServerStatusPinger.formatPlayerCount(players.online(), players.max());
|
| 93 | data.players = players;
|
| 94 | if (!players.sample().isEmpty()) {
|
| 95 | List<Component> playerNames = new ArrayList<>(players.sample().size());
|
| 96 |
|
| 97 | for (NameAndId profile : players.sample()) {
|
| 98 | Component playerName;
|
| 99 | if (profile.equals(MinecraftServer.ANONYMOUS_PLAYER_PROFILE)) {
|
| 100 | playerName = Component.translatable("multiplayer.status.anonymous_player");
|
| 101 | } else {
|
| 102 | playerName = Component.literal(profile.name());
|
| 103 | }
|
| 104 |
|
| 105 | playerNames.add(playerName);
|
| 106 | }
|
| 107 |
|
| 108 | if (players.sample().size() < players.online()) {
|
| 109 | playerNames.add(Component.translatable("multiplayer.status.and_more", players.online() - players.sample().size()));
|
| 110 | }
|
| 111 |
|
| 112 | data.playerList = playerNames;
|
| 113 | } else {
|
| 114 | data.playerList = List.of();
|
| 115 | }
|
| 116 | }, () -> data.status = Component.translatable("multiplayer.status.unknown").withStyle(ChatFormatting.DARK_GRAY));
|
| 117 | status.favicon().ifPresent(newIcon -> {
|
| 118 | if (!Arrays.equals(newIcon.iconBytes(), data.getIconBytes())) {
|
| 119 | data.setIconBytes(ServerData.validateIcon(newIcon.iconBytes()));
|
| 120 | onPersistentDataChange.run();
|
| 121 | }
|
| 122 | });
|
| 123 | this.pingStart = Util.getMillis();
|
| 124 | connection.send(new ServerboundPingRequestPacket(this.pingStart));
|
| 125 | this.success = true;
|
| 126 | }
|
| 127 | }
|
| 128 |
|
| 129 | private static Component sanitizeDescription(final Component original) {
|
| 130 | try {
|
| 131 | return ComponentUtils.resolve(ServerStatusPinger.DESCRIPTION_SANITIZE_CONTEXT, original);
|
| 132 | } catch (CommandSyntaxException e) {
|
| 133 | ServerStatusPinger.LOGGER.warn("Failed to sanitize status {}", original, e);
|
| 134 | return Component.empty();
|
| 135 | }
|
| 136 | }
|
| 137 |
|
| 138 | @Override
|
| 139 | public void handlePongResponse(final ClientboundPongResponsePacket packet) {
|
| 140 | long then = this.pingStart;
|
| 141 | long now = Util.getMillis();
|
| 142 | data.ping = now - then;
|
| 143 | connection.disconnect(Component.translatable("multiplayer.status.finished"));
|
| 144 | onPongResponse.run();
|
| 145 | }
|
| 146 |
|
| 147 | @Override
|
| 148 | public void onDisconnect(final DisconnectionDetails details) {
|
| 149 | if (!this.success) {
|
| 150 | ServerStatusPinger.this.onPingFailed(details.reason(), data);
|
| 151 | ServerStatusPinger.this.pingLegacyServer(address, rawAddress, data, eventLoopGroupHolder);
|
| 152 | }
|
| 153 | }
|
| 154 |
|
| 155 | @Override
|
| 156 | public boolean isAcceptingMessages() {
|
| 157 | return connection.isConnected();
|
| 158 | }
|
| 159 | };
|
| 160 |
|
| 161 | try {
|
| 162 | connection.initiateServerboundStatusConnection(rawAddress.getHost(), rawAddress.getPort(), listener);
|
| 163 | connection.send(ServerboundStatusRequestPacket.INSTANCE);
|
| 164 | } catch (Throwable t) {
|
| 165 | LOGGER.error("Failed to ping server {}", rawAddress, t);
|
| 166 | }
|
| 167 | }
|
| 168 | }
|
| 169 |
|
| 170 | private void onPingFailed(final Component reason, final ServerData data) {
|
| 171 | LOGGER.error("Can't ping {}: {}", data.ip, reason.getString());
|
| 172 | data.motd = CANT_CONNECT_MESSAGE;
|
| 173 | data.status = CommonComponents.EMPTY;
|
| 174 | }
|
| 175 |
|
| 176 | private void pingLegacyServer(
|
| 177 | final InetSocketAddress resolvedAddress, final ServerAddress rawAddress, final ServerData data, final EventLoopGroupHolder eventLoopGroupHolder
|
| 178 | ) {
|
| 179 | new Bootstrap().group(eventLoopGroupHolder.eventLoopGroup()).handler(new ChannelInitializer<Channel>() {
|
| 180 | @Override
|
| 181 | protected void initChannel(final Channel channel) {
|
| 182 | try {
|
| 183 | channel.config().setOption(ChannelOption.TCP_NODELAY, true);
|
| 184 | } catch (ChannelException var3) {
|
| 185 | }
|
| 186 |
|
| 187 | channel.pipeline().addLast(new LegacyServerPinger(rawAddress, (protocolVersion, gameVersion, motd, players, maxPlayers) -> {
|
| 188 | data.setState(ServerData.State.INCOMPATIBLE);
|
| 189 | data.version = Component.literal(gameVersion);
|
| 190 | data.motd = Component.literal(motd);
|
| 191 | data.status = ServerStatusPinger.formatPlayerCount(players, maxPlayers);
|
| 192 | data.players = new Players(maxPlayers, players, List.of());
|
| 193 | }));
|
| 194 | }
|
| 195 | }).channel(eventLoopGroupHolder.channelCls()).connect(resolvedAddress.getAddress(), resolvedAddress.getPort());
|
| 196 | }
|
| 197 |
|
| 198 | public static Component formatPlayerCount(final int curPlayers, final int maxPlayers) {
|
| 199 | Component current = Component.literal(Integer.toString(curPlayers)).withStyle(ChatFormatting.GRAY);
|
| 200 | Component max = Component.literal(Integer.toString(maxPlayers)).withStyle(ChatFormatting.GRAY);
|
| 201 | return Component.translatable("multiplayer.status.player_count", current, max).withStyle(ChatFormatting.DARK_GRAY);
|
| 202 | }
|
| 203 |
|
| 204 | public void tick() {
|
| 205 | synchronized (this.connections) {
|
| 206 | Iterator<Connection> iterator = this.connections.iterator();
|
| 207 |
|
| 208 | while (iterator.hasNext()) {
|
| 209 | Connection connection = iterator.next();
|
| 210 | if (connection.isConnected()) {
|
| 211 | connection.tick();
|
| 212 | } else {
|
| 213 | iterator.remove();
|
| 214 | connection.handleDisconnection();
|
| 215 | }
|
| 216 | }
|
| 217 | }
|
| 218 | }
|
| 219 |
|
| 220 | public void removeAll() {
|
| 221 | synchronized (this.connections) {
|
| 222 | Iterator<Connection> iterator = this.connections.iterator();
|
| 223 |
|
| 224 | while (iterator.hasNext()) {
|
| 225 | Connection connection = iterator.next();
|
| 226 | if (connection.isConnected()) {
|
| 227 | iterator.remove();
|
| 228 | connection.disconnect(Component.translatable("multiplayer.status.cancelled"));
|
| 229 | }
|
| 230 | }
|
| 231 | }
|
| 232 | }
|
| 233 | }
|
| 234 |
|