Java Code Examples for com.comphenix.protocol.events.PacketEvent

The following examples show how to use com.comphenix.protocol.events.PacketEvent. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: BetonQuest   Source File: EntityHider.java    License: GNU General Public License v3.0 10 votes vote down vote up
/**
 * Construct the packet listener that will be used to intercept every
 * entity-related packet.
 *
 * @param plugin - the parent plugin.
 * @return The packet listener.
 */
private PacketAdapter constructProtocol(Plugin plugin) {
    return new PacketAdapter(plugin, ENTITY_PACKETS) {

        @Override
        public void onPacketSending(PacketEvent event) {
            int index = event.getPacketType() == COMBAT_EVENT ? 1 : 0;

            Integer entityID = event.getPacket().getIntegers().readSafely(index);
            if (entityID != null) {
                if (!isVisible(event.getPlayer(), entityID)) {
                    event.setCancelled(true);
                }
            }
        }
    };
}
 
Example 2
Source Project: helper   Source File: ProtocolSubscriptionBuilderImpl.java    License: MIT License 6 votes vote down vote up
@Nonnull
@Override
public ProtocolSubscriptionBuilder expireIf(@Nonnull BiPredicate<ProtocolSubscription, PacketEvent> predicate, @Nonnull ExpiryTestStage... testPoints) {
    Objects.requireNonNull(testPoints, "testPoints");
    Objects.requireNonNull(predicate, "predicate");
    for (ExpiryTestStage testPoint : testPoints) {
        switch (testPoint) {
            case PRE:
                this.preExpiryTests.add(predicate);
                break;
            case POST_FILTER:
                this.midExpiryTests.add(predicate);
                break;
            case POST_HANDLE:
                this.postExpiryTests.add(predicate);
                break;
            default:
                throw new IllegalArgumentException("Unknown ExpiryTestPoint: " + testPoint);
        }
    }
    return this;
}
 
Example 3
Source Project: AACAdditionPro   Source File: KeepAlive.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onPacketSending(PacketEvent event)
{
    if (event.isPlayerTemporary()) {
        return;
    }

    final User user = UserManager.getUser(event.getPlayer().getUniqueId());

    // Not bypassed
    if (User.isUserInvalid(user, this.getModuleType())) {
        return;
    }

    // The actual processing of the KeepAlive packet is done in the DataUpdaterEvents!
    vlManager.flag(user.getPlayer(), keepAliveIgnoredPattern.apply(user, event), -1, () -> {}, () -> {});
}
 
Example 4
@Override
protected int process(User user, PacketEvent packetEvent)
{
    final IWrapperPlayClientLook lookWrapper = packetEvent::getPacket;

    // Not flying (may trigger some fps)
    if (!user.getPlayer().getAllowFlight() &&
        // Player is in an inventory
        user.hasOpenInventory() &&
        // Head-Rotation has changed (detection)
        (user.getPlayer().getLocation().getYaw() != lookWrapper.getYaw() ||
         user.getPlayer().getLocation().getPitch() != lookWrapper.getPitch()) &&
        // No recently tp
        !user.hasTeleportedRecently(this.teleportTime) &&
        !user.hasChangedWorldsRecently(this.worldChangeTime) &&
        // The player has opened his inventory for at least one second.
        user.notRecentlyOpenedInventory(1000))
    {
        message = "Inventory-Verbose | Player: " + user.getPlayer().getName() + " sent new rotations while having an open inventory.";
        return 1;
    }
    return 0;
}
 
Example 5
Source Project: AACAdditionPro   Source File: MovePattern.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void cancelAction(User user, PacketEvent packetEvent)
{
    final IWrapperPlayPosition positionWrapper = packetEvent::getPacket;

    final Vector moveTo = new Vector(positionWrapper.getX(),
                                     positionWrapper.getY(),
                                     positionWrapper.getZ());

    final Location knownPosition = user.getPlayer().getLocation();

    // Not many blocks moved to prevent exploits and world change problems.
    if (moveTo.distanceSquared(knownPosition.toVector()) < 4) {
        // Teleport back the next tick.
        Bukkit.getScheduler().runTask(AACAdditionPro.getInstance(), () -> user.getPlayer().teleport(knownPosition, PlayerTeleportEvent.TeleportCause.UNKNOWN));
    }
}
 
Example 6
Source Project: AACAdditionPro   Source File: Inventory.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onPacketReceiving(PacketEvent event)
{
    if (event.isPlayerTemporary()) {
        return;
    }

    final User user = UserManager.getUser(event.getPlayer().getUniqueId());

    // Not bypassed
    if (User.isUserInvalid(user, this.getModuleType())) {
        return;
    }

    vlManager.flag(user.getPlayer(), movePattern.apply(user, event), movePattern.getCancelVl(), () -> movePattern.cancelAction(user, event), () -> {});
    vlManager.flag(user.getPlayer(), rotationPattern.apply(user, event), -1, () -> {}, () -> {});
}
 
Example 7
@Override
protected int process(User user, PacketEvent packetEvent)
{
    if (packetEvent.getPacketType() == PacketType.Play.Client.ARM_ANIMATION) {
        user.getDataMap().setValue(DataKey.PACKET_ANALYSIS_ANIMATION_EXPECTED, false);
    } else {
        if (user.getDataMap().getBoolean(DataKey.PACKET_ANALYSIS_ANIMATION_EXPECTED)) {
            user.getDataMap().setValue(DataKey.PACKET_ANALYSIS_ANIMATION_EXPECTED, false);
            message = "PacketAnalysisData-Verbose | Player: " + user.getPlayer().getName() + " did not send animation packet after an attack.";
            return 10;
        }
    }

    if (packetEvent.getPacketType() == PacketType.Play.Client.USE_ENTITY) {
        // Make sure an arm animation packet is sent directly after an attack as it is the next packet in the client
        // code.
        final WrapperPlayClientUseEntity useEntityWrapper = new WrapperPlayClientUseEntity(packetEvent.getPacket());
        if (useEntityWrapper.getType() == EnumWrappers.EntityUseAction.ATTACK) {
            user.getDataMap().setValue(DataKey.PACKET_ANALYSIS_ANIMATION_EXPECTED, true);
        }
        return 0;
    }
    return 0;
}
 
Example 8
@Override
public void onPacketSending(PacketEvent event)
{
    if (event.isPlayerTemporary()) {
        return;
    }

    final User user = UserManager.getUser(event.getPlayer().getUniqueId());

    // Not bypassed
    if (User.isUserInvalid(user, this.getModuleType())) {
        return;
    }

    if (event.getPacketType() == PacketType.Play.Server.POSITION) {
        final WrapperPlayServerPosition newPositionWrapper = new WrapperPlayServerPosition(event.getPacket());

        // Ignore relative teleports.
        if (!newPositionWrapper.getFlags().isEmpty()) {
            return;
        }

        user.getDataMap().setValue(DataKey.PACKET_ANALYSIS_LAST_POSITION_FORCE_LOCATION, newPositionWrapper.getLocation(user.getPlayer().getWorld()));
        user.getTimestampMap().updateTimeStamp(TimestampKey.PACKET_ANALYSIS_LAST_POSITION_FORCE);
    }
}
 
Example 9
Source Project: FastLogin   Source File: ProtocolLibListener.java    License: MIT License 6 votes vote down vote up
@Override
public void onPacketReceiving(PacketEvent packetEvent) {
    if (packetEvent.isCancelled()
            || plugin.getCore().getAuthPluginHook()== null
            || !plugin.isServerFullyStarted()) {
        return;
    }

    Player sender = packetEvent.getPlayer();
    PacketType packetType = packetEvent.getPacketType();
    if (packetType == START) {
        if (!rateLimiter.tryAcquire()) {
            plugin.getLog().warn("Rate Limit hit - Ignoring player {}", sender);
            return;
        }

        onLogin(packetEvent, sender);
    } else {
        onEncryptionBegin(packetEvent, sender);
    }
}
 
Example 10
Source Project: FastLogin   Source File: ProtocolLibListener.java    License: MIT License 6 votes vote down vote up
private void onLogin(PacketEvent packetEvent, Player player) {
    //this includes ip:port. Should be unique for an incoming login request with a timeout of 2 minutes
    String sessionKey = player.getAddress().toString();

    //remove old data every time on a new login in order to keep the session only for one person
    plugin.removeSession(player.getAddress());

    //player.getName() won't work at this state
    PacketContainer packet = packetEvent.getPacket();

    String username = packet.getGameProfiles().read(0).getName();
    plugin.getLog().trace("GameProfile {} with {} connecting", sessionKey, username);

    packetEvent.getAsyncMarker().incrementProcessingDelay();
    Runnable nameCheckTask = new NameCheckTask(plugin, packetEvent, random, player, username, keyPair.getPublic());
    plugin.getScheduler().runAsync(nameCheckTask);
}
 
Example 11
Source Project: ScoreboardStats   Source File: PacketListener.java    License: MIT License 6 votes vote down vote up
@Override
public void onPacketSending(PacketEvent packetEvent) {
    Player player = packetEvent.getPlayer();
    if (packetEvent.isCancelled() || player instanceof Factory) {
        return;
    }

    PacketContainer packet = packetEvent.getPacket();
    if (packet.hasMetadata("ScoreboardStats")) {
        //it's our own packet
        return;
    }

    UUID playerUUID = player.getUniqueId();

    //handle async packets by other plugins
    if (Bukkit.isPrimaryThread()) {
        ensureMainThread(playerUUID, packet);
    } else {
        PacketContainer clone = packet.deepClone();
        Bukkit.getScheduler().runTask(plugin, () -> ensureMainThread(playerUUID, clone));
    }
}
 
Example 12
public static void printInformation(PacketEvent event) {
	String verb = event.isServerPacket() ? "Sent" : "Received";
	String format = event.isServerPacket() ? 
			"%s %s to %s" : 
			"%s %s from %s";
	
	String shortDescription = String.format(format,
			event.isCancelled() ? "Cancelled" : verb,
			event.getPacketType(),
			event.getPlayer().getName()
	);
	
	// Detailed will print the packet's content too
	try {			
		System.out.println(shortDescription + ":\n" + getPacketDescription(event.getPacket()));
	} catch (IllegalAccessException e) {
		e.printStackTrace();
		System.out.println("Unable to use reflection.");
	}
}
 
Example 13
Source Project: helper   Source File: ProtocolSubscriptionBuilderImpl.java    License: MIT License 5 votes vote down vote up
@Nonnull
@Override
public ProtocolSubscriptionBuilder filter(@Nonnull Predicate<PacketEvent> predicate) {
    Objects.requireNonNull(predicate, "predicate");
    this.filters.add(predicate);
    return this;
}
 
Example 14
Source Project: VoxelGamesLibv2   Source File: SkullPlaceHolders.java    License: MIT License 5 votes vote down vote up
public void init() {
    Bukkit.getPluginManager().registerEvents(this, voxelGamesLib);

    registerPlaceholders();

    // listener
    protocolManager.addPacketListener(new PacketAdapter(voxelGamesLib, PacketType.Play.Server.TILE_ENTITY_DATA) {
        @Override
        public void onPacketSending(PacketEvent event) {
            WrapperPlayServerTileEntityData packet = new WrapperPlayServerTileEntityData(event.getPacket());
            event.setPacket(modifySkull(packet, event.getPlayer()));
        }
    });

    // search for already loaded skulls
    Bukkit.getWorlds().stream()
            .flatMap(w -> Arrays.stream(w.getLoadedChunks()))
            .flatMap(s -> Arrays.stream(s.getTileEntities()))
            .filter(s -> s instanceof Skull)
            .map(s -> (Skull) s)
            .forEach(s -> lastSeenSkulls.put(s.getLocation(), s));

    // update task
    new BukkitRunnable() {

        @Override
        public void run() {
            lastSeenSkulls.forEach((loc, skull) -> skull.update());
        }
    }.runTaskTimer(voxelGamesLib, 20, 20);
}
 
Example 15
@Override
protected int process(User user, PacketEvent packetEvent)
{
    final int ignored = user.getKeepAliveData().getIgnoredKeepAlives().getAndSet(0);

    // Only send message on violation.
    if (ignored != 0) {
        VerboseSender.getInstance().sendVerboseMessage("PacketAnalysisData-Verbose | Player: " + user.getPlayer().getName() + " ignored " + ignored + "KeepAlive packets");
    }

    return ignored * 10;
}
 
Example 16
Source Project: AACAdditionPro   Source File: Fastswitch.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onPacketReceiving(final PacketEvent event)
{
    if (event.isPlayerTemporary()) {
        return;
    }

    final User user = UserManager.getUser(event.getPlayer().getUniqueId());

    // Not bypassed
    if (User.isUserInvalid(user, this.getModuleType())) {
        return;
    }

    // Tps are high enough
    if (ServerUtil.getTPS() > 19 &&
        event.getPacket().getBytes().readSafely(0) != null &&
        // Prevent the detection of scrolling
        !canBeLegit(user.getPlayer().getInventory().getHeldItemSlot(), event.getPacket().getBytes().readSafely(0)))
    {
        // Already switched in the given timeframe
        if (user.getTimestampMap().recentlyUpdated(TimestampKey.LAST_HOTBAR_SWITCH, switchMilliseconds)
            // The ping is valid and in the borders that are set in the config
            && (maxPing < 0 || ServerUtil.getPing(user.getPlayer()) < maxPing))
        {
            vlManager.flag(user.getPlayer(),
                           cancelVl,
                           () -> event.setCancelled(true),
                           () -> InventoryUtils.syncUpdateInventory(user.getPlayer()));
        }

        user.getTimestampMap().updateTimeStamp(TimestampKey.LAST_HOTBAR_SWITCH);
    }
}
 
Example 17
@Override
public void onPacketReceiving(final PacketEvent event)
{
    if (event.isPlayerTemporary()) {
        return;
    }

    final User user = UserManager.getUser(event.getPlayer().getUniqueId());

    // Not bypassed
    if (User.isUserInvalid(user, this.getModuleType())) {
        return;
    }

    // --------------------------------------------- CombatOrder ---------------------------------------------- //

    vlManager.flag(user.getPlayer(), this.animationPattern.apply(user, event), -1, () -> {}, () -> {});

    // --------------------------------------------- EqualRotation ---------------------------------------------- //

    vlManager.flag(user.getPlayer(), this.equalRotationPattern.apply(user, event), -1, () -> {}, () -> {});
    vlManager.flag(user.getPlayer(), this.illegalPitchPattern.apply(user, event), -1, () -> {}, () -> {});

    // ----------------------------------------- Compare + PositionSpoof ---------------------------------------- //
    if (user.getDataMap().getValue(DataKey.PACKET_ANALYSIS_LAST_POSITION_FORCE_LOCATION) != null) {
        // Special code to update the timestamp of the last compare flag.
        vlManager.flag(user.getPlayer(), this.comparePattern.apply(user, event), -1, () -> {}, () -> user.getTimestampMap().updateTimeStamp(TimestampKey.PACKET_ANALYSIS_LAST_COMPARE_FLAG));
        vlManager.flag(user.getPlayer(), this.positionSpoofPattern.apply(user, event), -1, () -> {}, () -> {});

        // No continuous flagging.
        user.getDataMap().setValue(DataKey.PACKET_ANALYSIS_LAST_POSITION_FORCE_LOCATION, null);
    }
}
 
Example 18
@Override
protected int process(User user, PacketEvent packetEvent)
{
    final double offset;
    try {
        offset = MathUtils.offset(
                user.getKeepAliveData().recentKeepAliveResponseTime(),
                user.getTimestampMap().passedTime(TimestampKey.PACKET_ANALYSIS_LAST_POSITION_FORCE) - allowedOffset);
        // recentKeepAliveResponseTime() might throw an IllegalStateException if there are not enough answered
        // KeepAlive packets in the queue.
    } catch (IllegalStateException tooFewDataPoints) {
        return 0;
    }

    // Should flag
    if (offset > 0) {
        // Minimum time between flags to decrease lag spike effects.
        if (!user.getTimestampMap().recentlyUpdated(TimestampKey.PACKET_ANALYSIS_LAST_COMPARE_FLAG, violationTime)) {

            // Increment fails.
            final long incrementFails = user.getDataMap().getLong(DataKey.PACKET_ANALYSIS_COMPARE_FAILS) + 1;
            user.getDataMap().setValue(DataKey.PACKET_ANALYSIS_COMPARE_FAILS, incrementFails);

            // Minimum fails to mitigate some fluctuations
            if (incrementFails >= this.violationThreshold) {
                message = "PacketAnalysisData-Verbose | Player: " + user.getPlayer().getName() + " sends packets with different delays. Mitigated Offset: " + offset;
                return Math.min(Math.max(1, (int) (offset / 50)), 9);
            }
        }
    } else if (user.getDataMap().getLong(DataKey.PACKET_ANALYSIS_COMPARE_FAILS) > 0) {
        final long decrementFails = user.getDataMap().getLong(DataKey.PACKET_ANALYSIS_COMPARE_FAILS) - 1;
        user.getDataMap().setValue(DataKey.PACKET_ANALYSIS_COMPARE_FAILS, decrementFails);
    }
    return 0;
}
 
Example 19
Source Project: AACAdditionPro   Source File: PatternModule.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public Integer apply(User user, PacketEvent packetEvent)
{
    if (this.isEnabled() &&
        packetTypesProcessed.contains(packetEvent.getPacketType()))
    {
        final int process = process(user, packetEvent);

        if (process > 0 && message != null) {
            VerboseSender.getInstance().sendVerboseMessage(message);
        }
        return process;
    }
    return 0;
}
 
Example 20
@Override
public void onPacketReceiving(final PacketEvent event)
{
    if (event.getPlayer() == null || event.isPlayerTemporary()) {
        return;
    }

    final User user = UserManager.getUser(event.getPlayer().getUniqueId());

    if (user != null) {
        user.getTimestampMap().updateTimeStamp(TimestampKey.LAST_VELOCITY_CHANGE);

        // The player wasn't hurt and got velocity for that.
        if (user.getPlayer().getNoDamageTicks() == 0
            // Recent teleports can cause bugs
            && !user.hasTeleportedRecently(1000))
        {
            final IWrapperPlayPosition position = event::getPacket;

            final boolean updatedPositiveVelocity = user.getPlayer().getLocation().getY() < position.getY();

            if (updatedPositiveVelocity != user.getDataMap().getBoolean(DataKey.POSITIVE_VELOCITY)) {
                user.getDataMap().setValue(DataKey.POSITIVE_VELOCITY, updatedPositiveVelocity);
                user.getTimestampMap().updateTimeStamp(TimestampKey.LAST_VELOCITY_CHANGE_NO_EXTERNAL_CAUSES);
            }
        }
    }
}
 
Example 21
@Override
public void onPacketSending(PacketEvent packetEvent) {
    Player player = packetEvent.getPlayer();
    PacketContainer packet = packetEvent.getPacket();

    int windowId = packet.getIntegers().read(0);
    if (windowId == PLAYER_INVENTORY && shouldHideInventory(player.getName())) {
        packetEvent.setCancelled(true);
    }
}
 
Example 22
@Override
public void onPacketSending(PacketEvent event)
{
	if (!event.isCancelled())
	{
		Player player = event.getPlayer();
		if (!player.isValid()) //Work around, getIfPresent is broken inside WG due to using LocalPlayer as key instead of CacheKey
		{
			return;
		}

		try
		{
			Session session = WorldGuardExtraFlagsPlugin.getPlugin().getWorldGuardCommunicator().getSessionManager().get(player);
			
			GiveEffectsFlagHandler giveEffectsHandler = session.getHandler(GiveEffectsFlagHandler.class);
			if (giveEffectsHandler.isSupressRemovePotionPacket())
			{
				event.setCancelled(true);
			}
		}
		catch(IllegalStateException wgBug)
		{
			
		}
	}
}
 
Example 23
@Override
public void onPacketSending(PacketEvent e) {
    try {
        final FileConfiguration settings = plugin.getSettings();
        if (!settings.getBoolean("ExternalInvisibility.ServerList.AdjustAmountOfOnlinePlayers")
                && !settings.getBoolean("ExternalInvisibility.ServerList.AdjustListOfLoggedInPlayers"))
            return;
        WrappedServerPing ping = e.getPacket().getServerPings().read(0);
        Collection<UUID> onlineVanishedPlayers = plugin.getVanishStateMgr().getOnlineVanishedPlayers();
        int vanishedPlayersCount = plugin.getVanishStateMgr().getOnlineVanishedPlayers().size(),
                playerCount = Bukkit.getOnlinePlayers().size();
        if (settings.getBoolean("ExternalInvisibility.ServerList.AdjustAmountOfOnlinePlayers")) {
            ping.setPlayersOnline(playerCount - vanishedPlayersCount);
        }
        if (settings.getBoolean("ExternalInvisibility.ServerList.AdjustListOfLoggedInPlayers")) {
            List<WrappedGameProfile> wrappedGameProfiles = new ArrayList<>(ping.getPlayers());
            Iterator<WrappedGameProfile> iterator = wrappedGameProfiles.iterator();
            while (iterator.hasNext()) {
                if (onlineVanishedPlayers.contains(iterator.next().getUUID())) {
                    iterator.remove();
                }
            }
            ping.setPlayers(wrappedGameProfiles);
        }
    } catch (Exception er) {
        plugin.logException(er);
    }
}
 
Example 24
private Vector getRelPos(PacketEvent event, VirtualWorld generator) {
    PacketContainer packet = event.getPacket();
    StructureModifier<BlockPosition> position = packet.getBlockPositionModifier();
    BlockPosition loc = position.readSafely(0);
    if (loc == null) return null;
    Vector origin = generator.getOrigin();
    Vector pt = new Vector(loc.getX() - origin.getBlockX(), loc.getY() - origin.getBlockY(), loc.getZ() - origin.getBlockZ());
    return pt;
}
 
Example 25
private void handleBlockEvent(PacketEvent event, boolean relative, RunnableVal3<PacketEvent, VirtualWorld, Vector> task) {
    VirtualWorld gen = getGenerator(event);
    if (gen != null) {
        Vector pt = getRelPos(event, gen);
        if (pt != null) {
            if (relative) pt = getRelative(event, pt);
            if (gen.contains(pt)) {
                event.setCancelled(true);
                task.run(event, gen, pt);
            }
        }
    }
}
 
Example 26
Source Project: FastLogin   Source File: VerifyResponseTask.java    License: MIT License 5 votes vote down vote up
public VerifyResponseTask(FastLoginBukkit plugin, PacketEvent packetEvent, Player player,
                          byte[] sharedSecret, KeyPair keyPair) {
    this.plugin = plugin;
    this.packetEvent = packetEvent;
    this.player = player;
    this.sharedSecret = Arrays.copyOf(sharedSecret, sharedSecret.length);
    this.serverKey = keyPair;
}
 
Example 27
@Override // Handshake
public void onPacketReceiving(PacketEvent event) {
    if (bukkit.getCore() == null) return; // Too early, we haven't finished initializing yet

    PacketContainer packet = event.getPacket();
    if (packet.getProtocols().read(0) != PacketType.Protocol.STATUS) return;

    StatusRequest request = bukkit.getRequest(event.getPlayer().getAddress());
    request.setProtocolVersion(packet.getIntegers().read(0));

    String host = packet.getStrings().read(0);
    int port = packet.getIntegers().read(1);
    request.setTarget(host, port);
}
 
Example 28
Source Project: FastLogin   Source File: NameCheckTask.java    License: MIT License 5 votes vote down vote up
public NameCheckTask(FastLoginBukkit plugin, PacketEvent packetEvent, Random random,
                     Player player, String username, PublicKey publicKey) {
    super(plugin.getCore(), plugin.getCore().getAuthPluginHook());

    this.plugin = plugin;
    this.packetEvent = packetEvent;
    this.publicKey = publicKey;
    this.random = random;
    this.player = player;
    this.username = username;
}
 
Example 29
Source Project: BetonQuest   Source File: PacketInterceptor.java    License: GNU General Public License v3.0 5 votes vote down vote up
public PacketInterceptor(Conversation conv, String playerID) {
    this.conv = conv;
    this.player = PlayerConverter.getPlayer(playerID);

    // Intercept Packets
    packetAdapter = new PacketAdapter(BetonQuest.getInstance(), ListenerPriority.HIGHEST,
            PacketType.Play.Server.CHAT

    ) {
        @Override
        public void onPacketSending(PacketEvent event) {
            if (event.getPlayer() != player) {
                return;
            }

            if (event.getPacketType().equals(PacketType.Play.Server.CHAT)) {
                PacketContainer packet = event.getPacket();
                BaseComponent[] bc = (BaseComponent[]) packet.getModifier().read(1);
                if (bc != null && bc.length > 0 && ((TextComponent) bc[0]).getText().contains("_bq_")) {
                    packet.getModifier().write(1, Arrays.copyOfRange(bc, 1, bc.length));
                    event.setPacket(packet);
                    return;
                }

                // Else save message to replay later
                WrapperPlayServerChat chat = new WrapperPlayServerChat(event.getPacket());
                event.setCancelled(true);
                messages.add(chat);
            }
        }
    };

    ProtocolLibrary.getProtocolManager().addPacketListener(packetAdapter);
}
 
Example 30
@Override // Status ping
public void onPacketSending(PacketEvent event) {
    if (bukkit.getCore() == null) return; // Too early, we haven't finished initializing yet

    final WrappedServerPing ping = event.getPacket().getServerPings().read(0);
    // Make sure players have not been hidden when getting the player count
    boolean playersVisible = ping.isPlayersVisible();

    InetSocketAddress client = event.getPlayer().getAddress();
    StatusRequest request = bukkit.getRequest(client);
    bukkit.requestCompleted(event.getPlayer().getAddress());

    StatusResponse response = request.createResponse(bukkit.getCore().getStatus(),
                    // Return unknown player counts if it has been hidden
                    new ResponseFetcher() {
                        @Override
                        public Integer getOnlinePlayers() {
                            return ping.getPlayersOnline();
                        }

                        @Override
                        public Integer getMaxPlayers() {
                            return ping.getPlayersMaximum();
                        }

                        @Override
                        public int getProtocolVersion() {
                            return ping.getVersionProtocol();
                        }
                    });

    // Description is modified in BukkitEventHandler, but we modify it here again,
    // because the BukkitEventHandler has no access to information like virtual hosts.
    String message = response.getDescription();
    if (message != null) ping.setMotD(message);

    // Version name
    message = response.getVersion();
    if (message != null) ping.setVersionName(message);
    // Protocol version
    Integer protocol = response.getProtocolVersion();
    if (protocol != null) ping.setVersionProtocol(protocol);

    if (playersVisible) {
        if (response.hidePlayers()) {
            ping.setPlayersVisible(false);
        } else {
            // Online players
            Integer count = response.getOnlinePlayers();
            if (count != null) ping.setPlayersOnline(count);

            // Max players are modified in BukkitEventHandler
            count = response.getMaxPlayers();
            if (count != null) ping.setPlayersMaximum(count);

            // Player hover
            message = response.getPlayerHover();
            if (message != null) {
                if (message.isEmpty()) {
                    ping.setPlayers(Collections.<WrappedGameProfile>emptyList());
                } else if (response.useMultipleSamples()) {
                    count = response.getDynamicSamples();

                    ping.setPlayers(Iterables.transform(
                            count != null ? Helper.splitLines(message, count) : Helper.splitLines(message),
                            new Function<String, WrappedGameProfile>() {
                        @Override
                        public WrappedGameProfile apply(String input) {
                            return new WrappedGameProfile(StatusManager.EMPTY_UUID, input);
                        }
                    }));
                } else
                    ping.setPlayers(Collections.singleton(
                            new WrappedGameProfile(StatusManager.EMPTY_UUID, message)));
            }
        }
    }
}