| 1 | package net.minecraft.server.players;
|
| 2 |
|
| 3 | import com.google.common.collect.Lists;
|
| 4 | import com.google.common.collect.Maps;
|
| 5 | import com.google.common.collect.Sets;
|
| 6 | import com.mojang.authlib.GameProfile;
|
| 7 | import com.mojang.logging.LogUtils;
|
| 8 | import java.io.File;
|
| 9 | import java.io.IOException;
|
| 10 | import java.net.SocketAddress;
|
| 11 | import java.nio.file.Files;
|
| 12 | import java.nio.file.Path;
|
| 13 | import java.text.SimpleDateFormat;
|
| 14 | import java.time.Instant;
|
| 15 | import java.util.EnumSet;
|
| 16 | import java.util.List;
|
| 17 | import java.util.Locale;
|
| 18 | import java.util.Map;
|
| 19 | import java.util.Optional;
|
| 20 | import java.util.Set;
|
| 21 | import java.util.UUID;
|
| 22 | import java.util.function.Function;
|
| 23 | import java.util.function.Predicate;
|
| 24 | import net.minecraft.ChatFormatting;
|
| 25 | import net.minecraft.commands.CommandSourceStack;
|
| 26 | import net.minecraft.core.BlockPos;
|
| 27 | import net.minecraft.core.LayeredRegistryAccess;
|
| 28 | import net.minecraft.nbt.CompoundTag;
|
| 29 | import net.minecraft.network.Connection;
|
| 30 | import net.minecraft.network.RegistryFriendlyByteBuf;
|
| 31 | import net.minecraft.network.chat.ChatType;
|
| 32 | import net.minecraft.network.chat.Component;
|
| 33 | import net.minecraft.network.chat.MutableComponent;
|
| 34 | import net.minecraft.network.chat.OutgoingChatMessage;
|
| 35 | import net.minecraft.network.chat.PlayerChatMessage;
|
| 36 | import net.minecraft.network.protocol.Packet;
|
| 37 | import net.minecraft.network.protocol.common.ClientboundUpdateTagsPacket;
|
| 38 | import net.minecraft.network.protocol.game.ClientboundChangeDifficultyPacket;
|
| 39 | import net.minecraft.network.protocol.game.ClientboundEntityEventPacket;
|
| 40 | import net.minecraft.network.protocol.game.ClientboundGameEventPacket;
|
| 41 | import net.minecraft.network.protocol.game.ClientboundInitializeBorderPacket;
|
| 42 | import net.minecraft.network.protocol.game.ClientboundLoginPacket;
|
| 43 | import net.minecraft.network.protocol.game.ClientboundPlayerAbilitiesPacket;
|
| 44 | import net.minecraft.network.protocol.game.ClientboundPlayerInfoRemovePacket;
|
| 45 | import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket;
|
| 46 | import net.minecraft.network.protocol.game.ClientboundRespawnPacket;
|
| 47 | import net.minecraft.network.protocol.game.ClientboundSetBorderCenterPacket;
|
| 48 | import net.minecraft.network.protocol.game.ClientboundSetBorderLerpSizePacket;
|
| 49 | import net.minecraft.network.protocol.game.ClientboundSetBorderSizePacket;
|
| 50 | import net.minecraft.network.protocol.game.ClientboundSetBorderWarningDelayPacket;
|
| 51 | import net.minecraft.network.protocol.game.ClientboundSetBorderWarningDistancePacket;
|
| 52 | import net.minecraft.network.protocol.game.ClientboundSetChunkCacheRadiusPacket;
|
| 53 | import net.minecraft.network.protocol.game.ClientboundSetDefaultSpawnPositionPacket;
|
| 54 | import net.minecraft.network.protocol.game.ClientboundSetExperiencePacket;
|
| 55 | import net.minecraft.network.protocol.game.ClientboundSetHeldSlotPacket;
|
| 56 | import net.minecraft.network.protocol.game.ClientboundSetPlayerTeamPacket;
|
| 57 | import net.minecraft.network.protocol.game.ClientboundSetSimulationDistancePacket;
|
| 58 | import net.minecraft.network.protocol.game.ClientboundSoundPacket;
|
| 59 | import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket;
|
| 60 | import net.minecraft.network.protocol.game.ClientboundUpdateRecipesPacket;
|
| 61 | import net.minecraft.network.protocol.game.GameProtocols;
|
| 62 | import net.minecraft.network.protocol.status.ServerStatus;
|
| 63 | import net.minecraft.resources.Identifier;
|
| 64 | import net.minecraft.resources.ResourceKey;
|
| 65 | import net.minecraft.server.MinecraftServer;
|
| 66 | import net.minecraft.server.PlayerAdvancements;
|
| 67 | import net.minecraft.server.RegistryLayer;
|
| 68 | import net.minecraft.server.ServerScoreboard;
|
| 69 | import net.minecraft.server.level.ServerLevel;
|
| 70 | import net.minecraft.server.level.ServerPlayer;
|
| 71 | import net.minecraft.server.network.CommonListenerCookie;
|
| 72 | import net.minecraft.server.network.ServerGamePacketListenerImpl;
|
| 73 | import net.minecraft.server.notifications.NotificationService;
|
| 74 | import net.minecraft.server.permissions.LevelBasedPermissionSet;
|
| 75 | import net.minecraft.server.permissions.PermissionLevel;
|
| 76 | import net.minecraft.sounds.SoundEvents;
|
| 77 | import net.minecraft.sounds.SoundSource;
|
| 78 | import net.minecraft.stats.ServerStatsCounter;
|
| 79 | import net.minecraft.stats.Stats;
|
| 80 | import net.minecraft.tags.TagNetworkSerialization;
|
| 81 | import net.minecraft.util.FileUtil;
|
| 82 | import net.minecraft.world.effect.MobEffectInstance;
|
| 83 | import net.minecraft.world.entity.Entity;
|
| 84 | import net.minecraft.world.entity.LivingEntity;
|
| 85 | import net.minecraft.world.entity.player.Player;
|
| 86 | import net.minecraft.world.entity.projectile.throwableitemprojectile.ThrownEnderpearl;
|
| 87 | import net.minecraft.world.item.crafting.RecipeManager;
|
| 88 | import net.minecraft.world.level.Level;
|
| 89 | import net.minecraft.world.level.block.Blocks;
|
| 90 | import net.minecraft.world.level.block.state.BlockState;
|
| 91 | import net.minecraft.world.level.border.BorderChangeListener;
|
| 92 | import net.minecraft.world.level.border.WorldBorder;
|
| 93 | import net.minecraft.world.level.gamerules.GameRules;
|
| 94 | import net.minecraft.world.level.portal.TeleportTransition;
|
| 95 | import net.minecraft.world.level.storage.LevelData;
|
| 96 | import net.minecraft.world.level.storage.LevelResource;
|
| 97 | import net.minecraft.world.level.storage.PlayerDataStorage;
|
| 98 | import net.minecraft.world.phys.Vec3;
|
| 99 | import net.minecraft.world.scores.DisplaySlot;
|
| 100 | import net.minecraft.world.scores.Objective;
|
| 101 | import net.minecraft.world.scores.PlayerTeam;
|
| 102 | import net.minecraft.world.scores.Team;
|
| 103 | import org.jspecify.annotations.Nullable;
|
| 104 | import org.slf4j.Logger;
|
| 105 |
|
| 106 | public abstract class PlayerList {
|
| 107 | public static final File USERBANLIST_FILE = new File("banned-players.json");
|
| 108 | public static final File IPBANLIST_FILE = new File("banned-ips.json");
|
| 109 | public static final File OPLIST_FILE = new File("ops.json");
|
| 110 | public static final File WHITELIST_FILE = new File("whitelist.json");
|
| 111 | public static final Component CHAT_FILTERED_FULL = Component.translatable("chat.filtered_full");
|
| 112 | public static final Component DUPLICATE_LOGIN_DISCONNECT_MESSAGE = Component.translatable("multiplayer.disconnect.duplicate_login");
|
| 113 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 114 | private static final int SEND_PLAYER_INFO_INTERVAL = 600;
|
| 115 | private static final SimpleDateFormat BAN_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z", Locale.ROOT);
|
| 116 | private final MinecraftServer server;
|
| 117 | private final List<ServerPlayer> players = Lists.newArrayList();
|
| 118 | private final Map<UUID, ServerPlayer> playersByUUID = Maps.newHashMap();
|
| 119 | private final Map<NameAndId, PermissionLevel> playerPermissions = Maps.newHashMap();
|
| 120 | private final UserBanList bans;
|
| 121 | private final IpBanList ipBans;
|
| 122 | private final ServerOpList ops;
|
| 123 | private final UserWhiteList whitelist;
|
| 124 | private final Map<UUID, ServerStatsCounter> stats = Maps.newHashMap();
|
| 125 | private final Map<UUID, PlayerAdvancements> advancements = Maps.newHashMap();
|
| 126 | private final PlayerDataStorage playerIo;
|
| 127 | private final LayeredRegistryAccess<RegistryLayer> registries;
|
| 128 | private int viewDistance;
|
| 129 | private int simulationDistance;
|
| 130 | private int sendAllPlayerInfoIn;
|
| 131 |
|
| 132 | public PlayerList(
|
| 133 | final MinecraftServer server,
|
| 134 | final LayeredRegistryAccess<RegistryLayer> registries,
|
| 135 | final PlayerDataStorage playerIo,
|
| 136 | final NotificationService notificationService
|
| 137 | ) {
|
| 138 | this.server = server;
|
| 139 | this.registries = registries;
|
| 140 | this.playerIo = playerIo;
|
| 141 | this.whitelist = new UserWhiteList(WHITELIST_FILE, notificationService);
|
| 142 | this.ops = new ServerOpList(OPLIST_FILE, notificationService);
|
| 143 | this.bans = new UserBanList(USERBANLIST_FILE, notificationService);
|
| 144 | this.ipBans = new IpBanList(IPBANLIST_FILE, notificationService);
|
| 145 | }
|
| 146 |
|
| 147 | public void placeNewPlayer(final Connection connection, final ServerPlayer player, final CommonListenerCookie cookie) {
|
| 148 | NameAndId gameProfile = player.nameAndId();
|
| 149 | UserNameToIdResolver profileCache = this.server.services().nameToIdCache();
|
| 150 | Optional<NameAndId> oldProfile = profileCache.get(gameProfile.id());
|
| 151 | String oldName = oldProfile.map(NameAndId::name).orElse(gameProfile.name());
|
| 152 | profileCache.add(gameProfile);
|
| 153 | ServerLevel level = player.level();
|
| 154 | String address = connection.getLoggableAddress(this.server.logIPs());
|
| 155 | LOGGER.info(
|
| 156 | "{}[{}] logged in with entity id {} at ({}, {}, {})", player.getPlainTextName(), address, player.getId(), player.getX(), player.getY(), player.getZ()
|
| 157 | );
|
| 158 | LevelData levelData = level.getLevelData();
|
| 159 | ServerGamePacketListenerImpl playerConnection = new ServerGamePacketListenerImpl(this.server, connection, player, cookie);
|
| 160 | connection.setupInboundProtocol(
|
| 161 | GameProtocols.SERVERBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(this.server.registryAccess()), playerConnection), playerConnection
|
| 162 | );
|
| 163 | playerConnection.suspendFlushing();
|
| 164 | GameRules gameRules = level.getGameRules();
|
| 165 | boolean immediateRespawn = gameRules.get(GameRules.IMMEDIATE_RESPAWN);
|
| 166 | boolean reducedDebugInfo = gameRules.get(GameRules.REDUCED_DEBUG_INFO);
|
| 167 | boolean doLimitedCrafting = gameRules.get(GameRules.LIMITED_CRAFTING);
|
| 168 | playerConnection.send(
|
| 169 | new ClientboundLoginPacket(
|
| 170 | player.getId(),
|
| 171 | levelData.isHardcore(),
|
| 172 | this.server.levelKeys(),
|
| 173 | this.getMaxPlayers(),
|
| 174 | this.getViewDistance(),
|
| 175 | this.getSimulationDistance(),
|
| 176 | reducedDebugInfo,
|
| 177 | !immediateRespawn,
|
| 178 | doLimitedCrafting,
|
| 179 | player.createCommonSpawnInfo(level),
|
| 180 | this.server.usesAuthentication(),
|
| 181 | this.server.enforceSecureProfile()
|
| 182 | )
|
| 183 | );
|
| 184 | playerConnection.send(new ClientboundChangeDifficultyPacket(levelData.getDifficulty(), levelData.isDifficultyLocked()));
|
| 185 | playerConnection.send(new ClientboundPlayerAbilitiesPacket(player.getAbilities()));
|
| 186 | playerConnection.send(new ClientboundSetHeldSlotPacket(player.getInventory().getSelectedSlot()));
|
| 187 | RecipeManager recipeManager = this.server.getRecipeManager();
|
| 188 | playerConnection.send(new ClientboundUpdateRecipesPacket(recipeManager.getSynchronizedItemProperties(), recipeManager.getSynchronizedStonecutterRecipes()));
|
| 189 | this.sendPlayerPermissionLevel(player);
|
| 190 | player.getStats().markAllDirty();
|
| 191 | player.getRecipeBook().sendInitialRecipeBook(player);
|
| 192 | this.updateEntireScoreboard(level.getScoreboard(), player);
|
| 193 | this.server.invalidateStatus();
|
| 194 | MutableComponent component;
|
| 195 | if (player.getGameProfile().name().equalsIgnoreCase(oldName)) {
|
| 196 | component = Component.translatable("multiplayer.player.joined", player.getDisplayName());
|
| 197 | } else {
|
| 198 | component = Component.translatable("multiplayer.player.joined.renamed", player.getDisplayName(), oldName);
|
| 199 | }
|
| 200 |
|
| 201 | this.broadcastSystemMessage(component.withStyle(ChatFormatting.YELLOW), false);
|
| 202 | playerConnection.teleport(player.getX(), player.getY(), player.getZ(), player.getYRot(), player.getXRot());
|
| 203 | ServerStatus status = this.server.getStatus();
|
| 204 | if (status != null && !cookie.transferred()) {
|
| 205 | player.sendServerStatus(status);
|
| 206 | }
|
| 207 |
|
| 208 | player.connection.send(ClientboundPlayerInfoUpdatePacket.createPlayerInitializing(this.players));
|
| 209 | this.players.add(player);
|
| 210 | this.playersByUUID.put(player.getUUID(), player);
|
| 211 | this.broadcastAll(ClientboundPlayerInfoUpdatePacket.createPlayerInitializing(List.of(player)));
|
| 212 | this.sendLevelInfo(player, level);
|
| 213 | level.addNewPlayer(player);
|
| 214 | this.server.getCustomBossEvents().onPlayerConnect(player);
|
| 215 | this.sendActivePlayerEffects(player);
|
| 216 | player.sendPostEffects();
|
| 217 | player.initInventoryMenu();
|
| 218 | this.server.notificationManager().playerJoined(player);
|
| 219 | playerConnection.resumeFlushing();
|
| 220 | }
|
| 221 |
|
| 222 | protected void updateEntireScoreboard(final ServerScoreboard scoreboard, final ServerPlayer player) {
|
| 223 | Set<Objective> objectives = Sets.newHashSet();
|
| 224 |
|
| 225 | for (PlayerTeam team : scoreboard.getPlayerTeams()) {
|
| 226 | player.connection.send(ClientboundSetPlayerTeamPacket.createAddOrModifyPacket(team, true));
|
| 227 | }
|
| 228 |
|
| 229 | for (DisplaySlot slot : DisplaySlot.values()) {
|
| 230 | Objective objective = scoreboard.getDisplayObjective(slot);
|
| 231 | if (objective != null && !objectives.contains(objective)) {
|
| 232 | for (Packet<?> packet : scoreboard.getStartTrackingPackets(objective)) {
|
| 233 | player.connection.send(packet);
|
| 234 | }
|
| 235 |
|
| 236 | objectives.add(objective);
|
| 237 | }
|
| 238 | }
|
| 239 | }
|
| 240 |
|
| 241 | public void addWorldborderListener(final ServerLevel level) {
|
| 242 | level.getWorldBorder().addListener(new BorderChangeListener() {
|
| 243 | @Override
|
| 244 | public void onSetSize(final WorldBorder border, final double newSize) {
|
| 245 | PlayerList.this.broadcastAll(new ClientboundSetBorderSizePacket(border), level.dimension());
|
| 246 | }
|
| 247 |
|
| 248 | @Override
|
| 249 | public void onLerpSize(final WorldBorder border, final double fromSize, final double targetSize, final long ticks, final long gameTime) {
|
| 250 | PlayerList.this.broadcastAll(new ClientboundSetBorderLerpSizePacket(border), level.dimension());
|
| 251 | }
|
| 252 |
|
| 253 | @Override
|
| 254 | public void onSetCenter(final WorldBorder border, final double x, final double z) {
|
| 255 | PlayerList.this.broadcastAll(new ClientboundSetBorderCenterPacket(border), level.dimension());
|
| 256 | }
|
| 257 |
|
| 258 | @Override
|
| 259 | public void onSetWarningTime(final WorldBorder border, final int time) {
|
| 260 | PlayerList.this.broadcastAll(new ClientboundSetBorderWarningDelayPacket(border), level.dimension());
|
| 261 | }
|
| 262 |
|
| 263 | @Override
|
| 264 | public void onSetWarningBlocks(final WorldBorder border, final int blocks) {
|
| 265 | PlayerList.this.broadcastAll(new ClientboundSetBorderWarningDistancePacket(border), level.dimension());
|
| 266 | }
|
| 267 |
|
| 268 | @Override
|
| 269 | public void onSetDamagePerBlock(final WorldBorder border, final double damagePerBlock) {
|
| 270 | }
|
| 271 |
|
| 272 | @Override
|
| 273 | public void onSetSafeZone(final WorldBorder border, final double safeZone) {
|
| 274 | }
|
| 275 | });
|
| 276 | }
|
| 277 |
|
| 278 | public Optional<CompoundTag> loadPlayerData(final NameAndId nameAndId) {
|
| 279 | UUID lastSingleplayerOwnerUUID = this.server.getWorldData().getSinglePlayerUUID();
|
| 280 | if (this.server.isSingleplayerOwner(nameAndId) && lastSingleplayerOwnerUUID != null) {
|
| 281 | LOGGER.debug("loading single player");
|
| 282 | return this.playerIo.load(new NameAndId(lastSingleplayerOwnerUUID, "<singleplayer owner>"));
|
| 283 | } else {
|
| 284 | return this.playerIo.load(nameAndId);
|
| 285 | }
|
| 286 | }
|
| 287 |
|
| 288 | protected void save(final ServerPlayer player) {
|
| 289 | this.playerIo.save(player);
|
| 290 | ServerStatsCounter stats = this.stats.get(player.getUUID());
|
| 291 | if (stats != null) {
|
| 292 | stats.save();
|
| 293 | }
|
| 294 |
|
| 295 | PlayerAdvancements advancements = this.advancements.get(player.getUUID());
|
| 296 | if (advancements != null) {
|
| 297 | advancements.save();
|
| 298 | }
|
| 299 | }
|
| 300 |
|
| 301 | public void remove(final ServerPlayer player) {
|
| 302 | ServerLevel level = player.level();
|
| 303 | player.awardStat(Stats.LEAVE_GAME);
|
| 304 | this.save(player);
|
| 305 | if (player.isPassenger()) {
|
| 306 | Entity vehicle = player.getRootVehicle();
|
| 307 | if (vehicle.hasExactlyOnePlayerPassenger()) {
|
| 308 | LOGGER.debug("Removing player mount");
|
| 309 | player.stopRiding();
|
| 310 | vehicle.getPassengersAndSelf().forEach(e -> e.setRemoved(Entity.RemovalReason.UNLOADED_WITH_PLAYER));
|
| 311 | }
|
| 312 | }
|
| 313 |
|
| 314 | player.unRide();
|
| 315 |
|
| 316 | for (ThrownEnderpearl enderpearl : player.getEnderPearls()) {
|
| 317 | enderpearl.setRemoved(Entity.RemovalReason.UNLOADED_WITH_PLAYER);
|
| 318 | }
|
| 319 |
|
| 320 | level.removePlayerImmediately(player, Entity.RemovalReason.UNLOADED_WITH_PLAYER);
|
| 321 | player.getAdvancements().clearTriggers();
|
| 322 | this.players.remove(player);
|
| 323 | this.server.getCustomBossEvents().onPlayerDisconnect(player);
|
| 324 | UUID uuid = player.getUUID();
|
| 325 | ServerPlayer serverPlayer = this.playersByUUID.get(uuid);
|
| 326 | if (serverPlayer == player) {
|
| 327 | this.playersByUUID.remove(uuid);
|
| 328 | this.stats.remove(uuid);
|
| 329 | this.advancements.remove(uuid);
|
| 330 | this.server.notificationManager().playerLeft(player);
|
| 331 | }
|
| 332 |
|
| 333 | this.broadcastAll(new ClientboundPlayerInfoRemovePacket(List.of(player.getUUID())));
|
| 334 | }
|
| 335 |
|
| 336 | public @Nullable Component canPlayerLogin(final SocketAddress address, final NameAndId nameAndId) {
|
| 337 | if (this.bans.isBanned(nameAndId)) {
|
| 338 | UserBanListEntry ban = this.bans.get(nameAndId);
|
| 339 | MutableComponent reason = Component.translatable("multiplayer.disconnect.banned.reason", ban.getReasonMessage());
|
| 340 | if (ban.getExpires() != null) {
|
| 341 | reason.append(Component.translatable("multiplayer.disconnect.banned.expiration", BAN_DATE_FORMAT.format(ban.getExpires())));
|
| 342 | }
|
| 343 |
|
| 344 | return reason;
|
| 345 | } else {
|
| 346 | if (!this.isWhiteListed(nameAndId)) {
|
| 347 | return Component.translatable("multiplayer.disconnect.not_whitelisted");
|
| 348 | }
|
| 349 |
|
| 350 | if (this.ipBans.isBanned(address)) {
|
| 351 | IpBanListEntry ban = this.ipBans.get(address);
|
| 352 | MutableComponent reason = Component.translatable("multiplayer.disconnect.banned_ip.reason", ban.getReasonMessage());
|
| 353 | if (ban.getExpires() != null) {
|
| 354 | reason.append(Component.translatable("multiplayer.disconnect.banned_ip.expiration", BAN_DATE_FORMAT.format(ban.getExpires())));
|
| 355 | }
|
| 356 |
|
| 357 | return reason;
|
| 358 | } else {
|
| 359 | return this.players.size() >= this.getMaxPlayers() && !this.canBypassPlayerLimit(nameAndId)
|
| 360 | ? Component.translatable("multiplayer.disconnect.server_full")
|
| 361 | : null;
|
| 362 | }
|
| 363 | }
|
| 364 | }
|
| 365 |
|
| 366 | public boolean disconnectAllPlayersWithProfile(final UUID playerId) {
|
| 367 | Set<ServerPlayer> dupes = Sets.newIdentityHashSet();
|
| 368 |
|
| 369 | for (ServerPlayer player : this.players) {
|
| 370 | if (player.getUUID().equals(playerId)) {
|
| 371 | dupes.add(player);
|
| 372 | }
|
| 373 | }
|
| 374 |
|
| 375 | ServerPlayer serverPlayer = this.playersByUUID.get(playerId);
|
| 376 | if (serverPlayer != null) {
|
| 377 | dupes.add(serverPlayer);
|
| 378 | }
|
| 379 |
|
| 380 | for (ServerPlayer player : dupes) {
|
| 381 | player.connection.disconnect(DUPLICATE_LOGIN_DISCONNECT_MESSAGE);
|
| 382 | }
|
| 383 |
|
| 384 | return !dupes.isEmpty();
|
| 385 | }
|
| 386 |
|
| 387 | public ServerPlayer respawn(final ServerPlayer serverPlayer, final boolean keepAllPlayerData, final Entity.RemovalReason removalReason) {
|
| 388 | TeleportTransition respawnInfo = serverPlayer.findRespawnPositionAndUseSpawnBlock(!keepAllPlayerData, TeleportTransition.DO_NOTHING);
|
| 389 | this.players.remove(serverPlayer);
|
| 390 | serverPlayer.level().removePlayerImmediately(serverPlayer, removalReason);
|
| 391 | ServerLevel level = respawnInfo.newLevel();
|
| 392 | ServerPlayer player = new ServerPlayer(this.server, level, serverPlayer.getGameProfile(), serverPlayer.clientInformation());
|
| 393 | player.connection = serverPlayer.connection;
|
| 394 | player.restoreFrom(serverPlayer, keepAllPlayerData);
|
| 395 | player.setId(serverPlayer.getId());
|
| 396 | player.setMainArm(serverPlayer.getMainArm());
|
| 397 | if (!respawnInfo.missingRespawnBlock()) {
|
| 398 | player.copyRespawnPosition(serverPlayer);
|
| 399 | }
|
| 400 |
|
| 401 | for (String tag : serverPlayer.entityTags()) {
|
| 402 | player.addTag(tag);
|
| 403 | }
|
| 404 |
|
| 405 | for (Identifier postEffect : serverPlayer.getPostEffects()) {
|
| 406 | player.addPostEffect(postEffect);
|
| 407 | }
|
| 408 |
|
| 409 | Vec3 pos = respawnInfo.position();
|
| 410 | player.snapTo(pos.x, pos.y, pos.z, respawnInfo.yRot(), respawnInfo.xRot());
|
| 411 | if (respawnInfo.missingRespawnBlock()) {
|
| 412 | player.connection.send(new ClientboundGameEventPacket(ClientboundGameEventPacket.NO_RESPAWN_BLOCK_AVAILABLE, 0.0F));
|
| 413 | }
|
| 414 |
|
| 415 | byte dataToKeep = (byte)(keepAllPlayerData ? 1 : 0);
|
| 416 | ServerLevel playerLevel = player.level();
|
| 417 | LevelData levelData = playerLevel.getLevelData();
|
| 418 | player.connection.send(new ClientboundRespawnPacket(player.createCommonSpawnInfo(playerLevel), dataToKeep));
|
| 419 | player.connection.teleport(player.getX(), player.getY(), player.getZ(), player.getYRot(), player.getXRot());
|
| 420 | player.connection.send(new ClientboundSetDefaultSpawnPositionPacket(level.getRespawnData()));
|
| 421 | player.connection.send(new ClientboundChangeDifficultyPacket(levelData.getDifficulty(), levelData.isDifficultyLocked()));
|
| 422 | player.connection.send(new ClientboundSetExperiencePacket(player.experienceProgress, player.totalExperience, player.experienceLevel));
|
| 423 | this.sendActivePlayerEffects(player);
|
| 424 | player.sendPostEffects();
|
| 425 | this.sendLevelInfo(player, level);
|
| 426 | this.sendPlayerPermissionLevel(player);
|
| 427 | level.addRespawnedPlayer(player);
|
| 428 | this.players.add(player);
|
| 429 | this.playersByUUID.put(player.getUUID(), player);
|
| 430 | player.initInventoryMenu();
|
| 431 | player.setHealth(player.getHealth());
|
| 432 | ServerPlayer.RespawnConfig respawnConfig = player.getRespawnConfig();
|
| 433 | if (!keepAllPlayerData && respawnConfig != null) {
|
| 434 | LevelData.RespawnData respawnData = respawnConfig.respawnData();
|
| 435 | ServerLevel respawnLevel = this.server.getLevel(respawnData.dimension());
|
| 436 | if (respawnLevel != null) {
|
| 437 | BlockPos respawnPosition = respawnData.pos();
|
| 438 | BlockState blockState = respawnLevel.getBlockState(respawnPosition);
|
| 439 | if (blockState.is(Blocks.RESPAWN_ANCHOR)) {
|
| 440 | player.connection
|
| 441 | .send(
|
| 442 | new ClientboundSoundPacket(
|
| 443 | SoundEvents.RESPAWN_ANCHOR_DEPLETE,
|
| 444 | SoundSource.BLOCKS,
|
| 445 | respawnPosition.getX(),
|
| 446 | respawnPosition.getY(),
|
| 447 | respawnPosition.getZ(),
|
| 448 | 1.0F,
|
| 449 | 1.0F,
|
| 450 | level.getRandom().nextLong()
|
| 451 | )
|
| 452 | );
|
| 453 | }
|
| 454 | }
|
| 455 | }
|
| 456 |
|
| 457 | return player;
|
| 458 | }
|
| 459 |
|
| 460 | public void sendActivePlayerEffects(final ServerPlayer player) {
|
| 461 | this.sendActiveEffects(player, player.connection);
|
| 462 | }
|
| 463 |
|
| 464 | public void sendActiveEffects(final LivingEntity livingEntity, final ServerGamePacketListenerImpl connection) {
|
| 465 | for (MobEffectInstance effect : livingEntity.getActiveEffects()) {
|
| 466 | connection.send(new ClientboundUpdateMobEffectPacket(livingEntity.getId(), effect, false));
|
| 467 | }
|
| 468 | }
|
| 469 |
|
| 470 | public void sendPlayerPermissionLevel(final ServerPlayer player) {
|
| 471 | LevelBasedPermissionSet permissions = this.server.getProfilePermissions(player.nameAndId());
|
| 472 | this.sendPlayerPermissionLevel(player, permissions);
|
| 473 | }
|
| 474 |
|
| 475 | public void tick() {
|
| 476 | if (++this.sendAllPlayerInfoIn > 600) {
|
| 477 | this.broadcastAll(new ClientboundPlayerInfoUpdatePacket(EnumSet.of(ClientboundPlayerInfoUpdatePacket.Action.UPDATE_LATENCY), this.players));
|
| 478 | this.sendAllPlayerInfoIn = 0;
|
| 479 | }
|
| 480 | }
|
| 481 |
|
| 482 | public void broadcastAll(final Packet<?> packet) {
|
| 483 | for (ServerPlayer player : this.players) {
|
| 484 | player.connection.send(packet);
|
| 485 | }
|
| 486 | }
|
| 487 |
|
| 488 | public void broadcastAll(final Packet<?> packet, final ResourceKey<Level> dimension) {
|
| 489 | for (ServerPlayer player : this.players) {
|
| 490 | if (player.level().dimension() == dimension) {
|
| 491 | player.connection.send(packet);
|
| 492 | }
|
| 493 | }
|
| 494 | }
|
| 495 |
|
| 496 | public void broadcastSystemToTeam(final Player player, final Component message) {
|
| 497 | Team team = player.getTeam();
|
| 498 | if (team != null) {
|
| 499 | for (String name : team.getPlayers()) {
|
| 500 | ServerPlayer teamPlayer = this.getPlayerByName(name);
|
| 501 | if (teamPlayer != null && teamPlayer != player) {
|
| 502 | teamPlayer.sendSystemMessage(message);
|
| 503 | }
|
| 504 | }
|
| 505 | }
|
| 506 | }
|
| 507 |
|
| 508 | public void broadcastSystemToAllExceptTeam(final Player player, final Component message) {
|
| 509 | Team team = player.getTeam();
|
| 510 | if (team == null) {
|
| 511 | this.broadcastSystemMessage(message, false);
|
| 512 | } else {
|
| 513 | for (int i = 0; i < this.players.size(); i++) {
|
| 514 | ServerPlayer targetPlayer = this.players.get(i);
|
| 515 | if (targetPlayer.getTeam() != team) {
|
| 516 | targetPlayer.sendSystemMessage(message);
|
| 517 | }
|
| 518 | }
|
| 519 | }
|
| 520 | }
|
| 521 |
|
| 522 | public String[] getPlayerNamesArray() {
|
| 523 | String[] names = new String[this.players.size()];
|
| 524 |
|
| 525 | for (int i = 0; i < this.players.size(); i++) {
|
| 526 | names[i] = this.players.get(i).getGameProfile().name();
|
| 527 | }
|
| 528 |
|
| 529 | return names;
|
| 530 | }
|
| 531 |
|
| 532 | public UserBanList getBans() {
|
| 533 | return this.bans;
|
| 534 | }
|
| 535 |
|
| 536 | public IpBanList getIpBans() {
|
| 537 | return this.ipBans;
|
| 538 | }
|
| 539 |
|
| 540 | public void op(final NameAndId nameAndId) {
|
| 541 | this.op(nameAndId, Optional.empty(), Optional.empty());
|
| 542 | }
|
| 543 |
|
| 544 | public void op(final NameAndId nameAndId, final Optional<LevelBasedPermissionSet> permissions, final Optional<Boolean> canBypassPlayerLimit) {
|
| 545 | this.ops
|
| 546 | .add(
|
| 547 | new ServerOpListEntry(
|
| 548 | nameAndId, permissions.orElse(this.server.operatorUserPermissions()), canBypassPlayerLimit.orElse(this.ops.canBypassPlayerLimit(nameAndId))
|
| 549 | )
|
| 550 | );
|
| 551 | ServerPlayer player = this.getPlayer(nameAndId.id());
|
| 552 | if (player != null) {
|
| 553 | this.sendPlayerPermissionLevel(player);
|
| 554 | }
|
| 555 | }
|
| 556 |
|
| 557 | public void deop(final NameAndId nameAndId) {
|
| 558 | if (this.ops.remove(nameAndId)) {
|
| 559 | ServerPlayer player = this.getPlayer(nameAndId.id());
|
| 560 | if (player != null) {
|
| 561 | this.sendPlayerPermissionLevel(player);
|
| 562 | }
|
| 563 | }
|
| 564 | }
|
| 565 |
|
| 566 | private void sendPlayerPermissionLevel(final ServerPlayer player, final LevelBasedPermissionSet permissions) {
|
| 567 | if (player.connection != null) {
|
| 568 | byte eventId = switch (permissions.level()) {
|
| 569 | case ALL -> 24;
|
| 570 | case MODERATORS -> 25;
|
| 571 | case GAMEMASTERS -> 26;
|
| 572 | case ADMINS -> 27;
|
| 573 | case OWNERS -> 28;
|
| 574 | };
|
| 575 | player.connection.send(new ClientboundEntityEventPacket(player, eventId));
|
| 576 | }
|
| 577 |
|
| 578 | this.server.getCommands().sendCommands(player);
|
| 579 | }
|
| 580 |
|
| 581 | public boolean isWhiteListed(final NameAndId nameAndId) {
|
| 582 | return !this.isUsingWhitelist() || this.ops.contains(nameAndId) || this.whitelist.contains(nameAndId);
|
| 583 | }
|
| 584 |
|
| 585 | public boolean isOp(final NameAndId nameAndId) {
|
| 586 | if (this.ops.contains(nameAndId)) {
|
| 587 | return true;
|
| 588 | } else {
|
| 589 | return this.server.isSingleplayerOwner(nameAndId) ? this.server.getWorldData().isAllowCommands() : false;
|
| 590 | }
|
| 591 | }
|
| 592 |
|
| 593 | public @Nullable ServerPlayer getPlayerByName(final String name) {
|
| 594 | int size = this.players.size();
|
| 595 |
|
| 596 | for (int i = 0; i < size; i++) {
|
| 597 | ServerPlayer player = this.players.get(i);
|
| 598 | if (player.getGameProfile().name().equalsIgnoreCase(name)) {
|
| 599 | return player;
|
| 600 | }
|
| 601 | }
|
| 602 |
|
| 603 | return null;
|
| 604 | }
|
| 605 |
|
| 606 | public void broadcast(
|
| 607 | final @Nullable Player except, final double x, final double y, final double z, final double range, final ResourceKey<Level> dimension, final Packet<?> packet
|
| 608 | ) {
|
| 609 | for (int i = 0; i < this.players.size(); i++) {
|
| 610 | ServerPlayer player = this.players.get(i);
|
| 611 | if (player != except && player.level().dimension() == dimension) {
|
| 612 | double xd = x - player.getX();
|
| 613 | double yd = y - player.getY();
|
| 614 | double zd = z - player.getZ();
|
| 615 | if (xd * xd + yd * yd + zd * zd < range * range) {
|
| 616 | player.connection.send(packet);
|
| 617 | }
|
| 618 | }
|
| 619 | }
|
| 620 | }
|
| 621 |
|
| 622 | public void saveAll() {
|
| 623 | for (int i = 0; i < this.players.size(); i++) {
|
| 624 | this.save(this.players.get(i));
|
| 625 | }
|
| 626 | }
|
| 627 |
|
| 628 | public UserWhiteList getWhiteList() {
|
| 629 | return this.whitelist;
|
| 630 | }
|
| 631 |
|
| 632 | public String[] getWhiteListNames() {
|
| 633 | return this.whitelist.getUserList();
|
| 634 | }
|
| 635 |
|
| 636 | public ServerOpList getOps() {
|
| 637 | return this.ops;
|
| 638 | }
|
| 639 |
|
| 640 | public String[] getOpNames() {
|
| 641 | return this.ops.getUserList();
|
| 642 | }
|
| 643 |
|
| 644 | public void reloadWhiteList() {
|
| 645 | }
|
| 646 |
|
| 647 | public void sendLevelInfo(final ServerPlayer player, final ServerLevel level) {
|
| 648 | WorldBorder worldBorder = level.getWorldBorder();
|
| 649 | player.connection.send(new ClientboundInitializeBorderPacket(worldBorder));
|
| 650 | player.connection.send(this.server.clockManager().createFullSyncPacket());
|
| 651 | player.connection.send(new ClientboundSetDefaultSpawnPositionPacket(level.getRespawnData()));
|
| 652 | if (level.isRaining()) {
|
| 653 | player.connection.send(new ClientboundGameEventPacket(ClientboundGameEventPacket.START_RAINING, 0.0F));
|
| 654 | player.connection.send(new ClientboundGameEventPacket(ClientboundGameEventPacket.RAIN_LEVEL_CHANGE, level.getRainLevel(1.0F)));
|
| 655 | player.connection.send(new ClientboundGameEventPacket(ClientboundGameEventPacket.THUNDER_LEVEL_CHANGE, level.getThunderLevel(1.0F)));
|
| 656 | }
|
| 657 |
|
| 658 | player.connection.send(new ClientboundGameEventPacket(ClientboundGameEventPacket.LEVEL_CHUNKS_LOAD_START, 0.0F));
|
| 659 | this.server.tickRateManager().updateJoiningPlayer(player);
|
| 660 | }
|
| 661 |
|
| 662 | public void sendAllPlayerInfo(final ServerPlayer player) {
|
| 663 | player.inventoryMenu.sendAllDataToRemote();
|
| 664 | player.resetSentInfo();
|
| 665 | player.connection.send(new ClientboundSetHeldSlotPacket(player.getInventory().getSelectedSlot()));
|
| 666 | }
|
| 667 |
|
| 668 | public int getPlayerCount() {
|
| 669 | return this.players.size();
|
| 670 | }
|
| 671 |
|
| 672 | public int getMaxPlayers() {
|
| 673 | return this.server.getMaxPlayers();
|
| 674 | }
|
| 675 |
|
| 676 | public boolean isUsingWhitelist() {
|
| 677 | return this.server.isUsingWhitelist();
|
| 678 | }
|
| 679 |
|
| 680 | public List<ServerPlayer> getPlayersWithAddress(final String ip) {
|
| 681 | List<ServerPlayer> result = Lists.newArrayList();
|
| 682 |
|
| 683 | for (ServerPlayer player : this.players) {
|
| 684 | if (player.getIpAddress().equals(ip)) {
|
| 685 | result.add(player);
|
| 686 | }
|
| 687 | }
|
| 688 |
|
| 689 | return result;
|
| 690 | }
|
| 691 |
|
| 692 | public int getViewDistance() {
|
| 693 | return this.viewDistance;
|
| 694 | }
|
| 695 |
|
| 696 | public int getSimulationDistance() {
|
| 697 | return this.simulationDistance;
|
| 698 | }
|
| 699 |
|
| 700 | public MinecraftServer getServer() {
|
| 701 | return this.server;
|
| 702 | }
|
| 703 |
|
| 704 | public void removeAll() {
|
| 705 | for (int i = 0; i < this.players.size(); i++) {
|
| 706 | this.players.get(i).connection.disconnect(Component.translatable("multiplayer.disconnect.server_shutdown"));
|
| 707 | }
|
| 708 | }
|
| 709 |
|
| 710 | public void broadcastSystemMessage(final Component message, final boolean overlay) {
|
| 711 | this.broadcastSystemMessage(message, player -> message, overlay);
|
| 712 | }
|
| 713 |
|
| 714 | public void broadcastSystemMessage(final Component message, final Function<ServerPlayer, Component> playerMessages, final boolean overlay) {
|
| 715 | this.server.sendSystemMessage(message);
|
| 716 |
|
| 717 | for (ServerPlayer player : this.players) {
|
| 718 | Component playerMessage = playerMessages.apply(player);
|
| 719 | if (playerMessage != null) {
|
| 720 | player.sendSystemMessage(playerMessage, overlay);
|
| 721 | }
|
| 722 | }
|
| 723 | }
|
| 724 |
|
| 725 | public void broadcastChatMessage(final PlayerChatMessage message, final CommandSourceStack sender, final ChatType.Bound chatType) {
|
| 726 | this.broadcastChatMessage(message, sender::shouldFilterMessageTo, sender.getPlayer(), chatType);
|
| 727 | }
|
| 728 |
|
| 729 | public void broadcastChatMessage(final PlayerChatMessage message, final ServerPlayer sender, final ChatType.Bound chatType) {
|
| 730 | this.broadcastChatMessage(message, sender::shouldFilterMessageTo, sender, chatType);
|
| 731 | }
|
| 732 |
|
| 733 | private void broadcastChatMessage(
|
| 734 | final PlayerChatMessage message, final Predicate<ServerPlayer> isFiltered, final @Nullable ServerPlayer senderPlayer, final ChatType.Bound chatType
|
| 735 | ) {
|
| 736 | boolean trusted = this.verifyChatTrusted(message);
|
| 737 | this.server.logChatMessage(message.decoratedContent(), chatType, trusted ? null : "Not Secure");
|
| 738 | OutgoingChatMessage tracked = OutgoingChatMessage.create(message);
|
| 739 | boolean wasFullyFiltered = false;
|
| 740 |
|
| 741 | for (ServerPlayer player : this.players) {
|
| 742 | boolean filtered = isFiltered.test(player);
|
| 743 | player.sendChatMessage(tracked, filtered, chatType);
|
| 744 | wasFullyFiltered |= filtered && message.isFullyFiltered();
|
| 745 | }
|
| 746 |
|
| 747 | if (wasFullyFiltered && senderPlayer != null) {
|
| 748 | senderPlayer.sendSystemMessage(CHAT_FILTERED_FULL);
|
| 749 | }
|
| 750 | }
|
| 751 |
|
| 752 | private boolean verifyChatTrusted(final PlayerChatMessage message) {
|
| 753 | return message.hasSignature() && !message.hasExpiredServer(Instant.now());
|
| 754 | }
|
| 755 |
|
| 756 | public ServerStatsCounter getPlayerStats(final Player player) {
|
| 757 | GameProfile gameProfile = player.getGameProfile();
|
| 758 | return this.stats.computeIfAbsent(gameProfile.id(), id -> {
|
| 759 | Path targetFile = this.locateStatsFile(gameProfile);
|
| 760 | return new ServerStatsCounter(this.server, targetFile);
|
| 761 | });
|
| 762 | }
|
| 763 |
|
| 764 | private Path locateStatsFile(final GameProfile gameProfile) {
|
| 765 | Path statFolder = this.server.getWorldPath(LevelResource.PLAYER_STATS_DIR);
|
| 766 | Path uuidStatsFile = statFolder.resolve(gameProfile.id() + ".json");
|
| 767 | if (Files.exists(uuidStatsFile)) {
|
| 768 | return uuidStatsFile;
|
| 769 | }
|
| 770 |
|
| 771 | String playerNameStatsFile = gameProfile.name() + ".json";
|
| 772 | if (FileUtil.isValidPathSegment(playerNameStatsFile)) {
|
| 773 | Path playerNameStatsPath = statFolder.resolve(playerNameStatsFile);
|
| 774 | if (Files.isRegularFile(playerNameStatsPath)) {
|
| 775 | try {
|
| 776 | return Files.move(playerNameStatsPath, uuidStatsFile);
|
| 777 | } catch (IOException e) {
|
| 778 | LOGGER.warn("Failed to copy file {} to {}", playerNameStatsFile, uuidStatsFile);
|
| 779 | return playerNameStatsPath;
|
| 780 | }
|
| 781 | }
|
| 782 | }
|
| 783 |
|
| 784 | return uuidStatsFile;
|
| 785 | }
|
| 786 |
|
| 787 | public PlayerAdvancements getPlayerAdvancements(final ServerPlayer player) {
|
| 788 | UUID uuid = player.getUUID();
|
| 789 | PlayerAdvancements result = this.advancements.get(uuid);
|
| 790 | if (result == null) {
|
| 791 | Path uuidStatsFile = this.server.getWorldPath(LevelResource.PLAYER_ADVANCEMENTS_DIR).resolve(uuid + ".json");
|
| 792 | result = new PlayerAdvancements(this.server.getFixerUpper(), this, this.server.getAdvancements(), uuidStatsFile, player);
|
| 793 | this.advancements.put(uuid, result);
|
| 794 | }
|
| 795 |
|
| 796 | result.setPlayer(player);
|
| 797 | return result;
|
| 798 | }
|
| 799 |
|
| 800 | public void setViewDistance(final int viewDistance) {
|
| 801 | this.viewDistance = viewDistance;
|
| 802 | this.broadcastAll(new ClientboundSetChunkCacheRadiusPacket(viewDistance));
|
| 803 |
|
| 804 | for (ServerLevel level : this.server.getAllLevels()) {
|
| 805 | level.getChunkSource().setViewDistance(viewDistance);
|
| 806 | }
|
| 807 | }
|
| 808 |
|
| 809 | public void setSimulationDistance(final int simulationDistance) {
|
| 810 | this.simulationDistance = simulationDistance;
|
| 811 | this.broadcastAll(new ClientboundSetSimulationDistancePacket(simulationDistance));
|
| 812 |
|
| 813 | for (ServerLevel level : this.server.getAllLevels()) {
|
| 814 | level.getChunkSource().setSimulationDistance(simulationDistance);
|
| 815 | }
|
| 816 | }
|
| 817 |
|
| 818 | public List<ServerPlayer> getPlayers() {
|
| 819 | return this.players;
|
| 820 | }
|
| 821 |
|
| 822 | public Map<UUID, ServerPlayer> getPlayersByUUID() {
|
| 823 | return this.playersByUUID;
|
| 824 | }
|
| 825 |
|
| 826 | public @Nullable ServerPlayer getPlayer(final UUID uuid) {
|
| 827 | return this.playersByUUID.get(uuid);
|
| 828 | }
|
| 829 |
|
| 830 | public @Nullable ServerPlayer getPlayer(final String playerName) {
|
| 831 | for (ServerPlayer player : this.players) {
|
| 832 | if (player.getGameProfile().name().equalsIgnoreCase(playerName)) {
|
| 833 | return player;
|
| 834 | }
|
| 835 | }
|
| 836 |
|
| 837 | return null;
|
| 838 | }
|
| 839 |
|
| 840 | public boolean canBypassPlayerLimit(final NameAndId nameAndId) {
|
| 841 | return false;
|
| 842 | }
|
| 843 |
|
| 844 | public void reloadResources() {
|
| 845 | for (PlayerAdvancements advancements : this.advancements.values()) {
|
| 846 | advancements.reload(this.server.getAdvancements());
|
| 847 | }
|
| 848 |
|
| 849 | this.broadcastAll(new ClientboundUpdateTagsPacket(TagNetworkSerialization.serializeTagsToNetwork(this.registries)));
|
| 850 | RecipeManager recipeManager = this.server.getRecipeManager();
|
| 851 | ClientboundUpdateRecipesPacket recipes = new ClientboundUpdateRecipesPacket(
|
| 852 | recipeManager.getSynchronizedItemProperties(), recipeManager.getSynchronizedStonecutterRecipes()
|
| 853 | );
|
| 854 |
|
| 855 | for (ServerPlayer player : this.players) {
|
| 856 | player.connection.send(recipes);
|
| 857 | player.getRecipeBook().sendInitialRecipeBook(player);
|
| 858 | }
|
| 859 | }
|
| 860 | }
|
| 861 |
|