Java Code Examples for com.comphenix.protocol.events.PacketEvent#getPacket()

The following examples show how to use com.comphenix.protocol.events.PacketEvent#getPacket() . 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 File: AnimationPattern.java    From AACAdditionPro with GNU General Public License v3.0 6 votes vote down vote up
@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 2
Source File: PacketAnalysis.java    From AACAdditionPro with 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;
    }

    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 3
Source File: DataUpdaterEvents.java    From AACAdditionPro with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onPacketSending(final PacketEvent event)
{
    if (event.isPlayerTemporary()) {
        return;
    }

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

    // Not bypassed
    if (user == null) {
        return;
    }

    final WrapperPlayKeepAlive wrapper = new WrapperPlayServerKeepAlive(event.getPacket());

    // Register the KeepAlive
    synchronized (user.getKeepAliveData().getKeepAlives()) {
        user.getKeepAliveData().getKeepAlives().bufferObject(new KeepAliveData.KeepAlivePacketData(wrapper.getKeepAliveId()));
    }
}
 
Example 4
Source File: ForceFieldAdapter.java    From CombatLogX with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onPacketSending(PacketEvent e) {
    if(e.isCancelled()) return;

    Player player = e.getPlayer();
    ICombatManager combatManager = this.plugin.getCombatManager();
    if(!combatManager.isInCombat(player)) return;

    UUID uuid = player.getUniqueId();
    PacketContainer packet = e.getPacket();
    World world = player.getWorld();

    WrapperPlayServerBlockChange block = new WrapperPlayServerBlockChange(packet);
    Location location = packet.getBlockPositionModifier().read(0).toLocation(world);
    if(this.forceField.fakeBlocks.containsKey(uuid) && this.forceField.isSafe(location, player) && this.forceField.isSafeSurround(location, player) && ForceField.canPlace(location) && this.forceField.fakeBlocks.get(uuid).contains(location)) {
        block.setBlockData(this.forceField.wrappedData(block.getBlockData()));
    }
}
 
Example 5
Source File: ProtocolLibListener.java    From FastLogin with 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 6
Source File: PacketListener.java    From ScoreboardStats with 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 7
Source File: PositionSpoofPattern.java    From AACAdditionPro with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected int process(User user, PacketEvent packetEvent)
{
    final WrapperPlayClientPositionLook clientPositionLookWrapper = new WrapperPlayClientPositionLook(packetEvent.getPacket());

    // Only check if the player has been teleported recently
    if (user.hasTeleportedRecently(1000) &&
        // World changes and respawns are exempted
        !user.hasRespawnedRecently(2500) &&
        !user.hasChangedWorldsRecently(2500) &&
        // Lag occurrences after login.
        !user.hasLoggedInRecently(10000))
    {
        // The position packet might not be exactly the same position.
        // Squared values of 10, 5 and 3
        final double allowedDistanceSquared = user.getPlayer().isFlying() ?
                                              100 :
                                              (user.getPlayer().isSprinting() ? 25 : 9);

        final Location forcedLocation = (Location) user.getDataMap().getValue(DataKey.PACKET_ANALYSIS_LAST_POSITION_FORCE_LOCATION);

        if (forcedLocation.getWorld().getUID().equals(user.getPlayer().getWorld().getUID())) {
            final double distanceSquared = forcedLocation.distanceSquared(clientPositionLookWrapper.getLocation(user.getPlayer().getWorld()));

            if (distanceSquared > allowedDistanceSquared) {
                VerboseSender.getInstance().sendVerboseMessage("PacketAnalysisData-Verbose | Player: " + user.getPlayer().getName() + " tried to spoof position packets. | DS: " + distanceSquared + " ADS: " + allowedDistanceSquared);
                return 10;
            }
        } else {
            VerboseSender.getInstance().sendVerboseMessage("PacketAnalysisData-Verbose | Player: " + user.getPlayer().getName() + " diff world.");
        }
    }
    return 0;
}
 
Example 8
Source File: CFIPacketListener.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
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 9
Source File: CFIPacketListener.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
private Vector getRelative(PacketEvent container, Vector pt) {
    PacketContainer packet = container.getPacket();
    StructureModifier<EnumWrappers.Direction> dirs = packet.getDirections();
    EnumWrappers.Direction dir = dirs.readSafely(0);
    if (dir == null) return pt;
    switch (dir.ordinal()) {
        case 0: return pt.add(0, -1, 0);
        case 1: return pt.add(0, 1, 0);
        case 2: return pt.add(0, 0, -1);
        case 3: return pt.add(0, 0, 1);
        case 4: return pt.add(-1, 0, 0);
        case 5: return pt.add(1, 0, 0);
        default: return pt;
    }
}
 
Example 10
Source File: PacketInterceptor.java    From BetonQuest with 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 11
Source File: ProtocolLibHandler.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
@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 12
Source File: InventoryPacketAdapter.java    From AuthMeReloaded with GNU General Public License v3.0 5 votes vote down vote up
@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 13
Source File: ProtocolHandshakeListener.java    From BungeeGuard with MIT License 4 votes vote down vote up
@Override
public void onPacketReceiving(PacketEvent event) {
    PacketContainer packet = event.getPacket();

    // only handle the LOGIN phase
    PacketType.Protocol state = packet.getProtocols().read(0);
    if (state != PacketType.Protocol.LOGIN) {
        return;
    }

    String handshake = packet.getStrings().read(0);
    BungeeCordHandshake decoded = BungeeCordHandshake.decodeAndVerify(handshake, ProtocolHandshakeListener.this.tokenStore);

    if (decoded instanceof BungeeCordHandshake.Fail) {
        BungeeCordHandshake.Fail fail = (BungeeCordHandshake.Fail) decoded;
        ProtocolHandshakeListener.this.logger.warning("Denying connection from " + fail.describeConnection() + " - reason: " + fail.reason().name());

        String kickMessage;
        if (fail.reason() == BungeeCordHandshake.Fail.Reason.INVALID_HANDSHAKE) {
            kickMessage = ProtocolHandshakeListener.this.noDataKickMessage;
        } else {
            kickMessage = ProtocolHandshakeListener.this.invalidTokenKickMessage;
        }

        try {
            closeConnection(event.getPlayer(), kickMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // just in-case the connection didn't close, screw up the hostname
        // so Spigot can't pick up anything that might've been spoofed in nms.HandshakeListener
        packet.getStrings().write(0, "null");

        return;
    }

    // great, handshake was decoded and verified successfully.
    // we can re-encode the handshake now so Spigot can pick up the spoofed stuff.
    BungeeCordHandshake.Success data = (BungeeCordHandshake.Success) decoded;
    packet.getStrings().write(0, data.encode());
}
 
Example 14
Source File: KeepAlive.java    From AACAdditionPro with GNU General Public License v3.0 4 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;
    }

    final WrapperPlayKeepAlive wrapper = new WrapperPlayClientKeepAlive(event.getPacket());

    final long keepAliveId = wrapper.getKeepAliveId();
    KeepAliveData.KeepAlivePacketData keepAlivePacketData = null;

    int offset = 0;
    synchronized (user.getKeepAliveData().getKeepAlives()) {
        final Iterator<KeepAliveData.KeepAlivePacketData> iterator = user.getKeepAliveData().getKeepAlives().descendingIterator();
        KeepAliveData.KeepAlivePacketData current;
        while (iterator.hasNext()) {
            current = iterator.next();

            if (current.getKeepAliveID() == keepAliveId) {
                keepAlivePacketData = current;
                break;
            }

            offset++;
        }
    }

    // A packet with the same data must have been sent before.
    if (keepAlivePacketData == null ||
        // If the packet already has a response something is off.
        keepAlivePacketData.hasRegisteredResponse())
    {
        VerboseSender.getInstance().sendVerboseMessage("PacketAnalysisData-Verbose | Player: " + user.getPlayer().getName() + " sent unregistered KeepAlive packet.");
        vlManager.flag(user.getPlayer(), 20, -1, () -> {}, () -> {});
    } else {
        keepAlivePacketData.registerResponse();
        vlManager.flag(user.getPlayer(), keepAliveOffsetPattern.apply(user, offset), -1, () -> {}, () -> {});
    }
}
 
Example 15
Source File: ChatPacketValidator.java    From ChatItem with GNU General Public License v3.0 4 votes vote down vote up
public void onPacketSending(PacketEvent e){
    if(ChatItem.supportsActionBar()) { //only if action bar messages are supported in this version of minecraft
        if(ChatItem.supportsChatTypeEnum()){
            if(((Enum)e.getPacket().getSpecificModifier(ChatItem.getChatMessageTypeClass()).read(0)).name().equals("GAME_INFO")){
                return; //It means it's an actionbar message, and we ain't intercepting those
            }
        }else if (e.getPacket().getBytes().readSafely(0) == (byte) 2) {
            return;  //It means it's an actionbar message, and we ain't intercepting those
        }
    }
    boolean usesBaseComponents = false;
    PacketContainer packet = e.getPacket();
    String json;
    if(packet.getChatComponents().readSafely(0)==null){  //null check for some cases of messages sent using spigot's Chat Component API or other means
        if(ChatItem.supportsChatComponentApi()){  //only if the API is supported in this server distribution
            BaseComponent[] components = packet.getSpecificModifier(BaseComponent[].class).readSafely(0);
            if(components == null){
                return;
            }
            json = ComponentSerializer.toString(components);
            usesBaseComponents = true;
        }else{
            return; //We don't know how to deal with anything else. Most probably some mod message we shouldn't mess with anyways
        }
    }else{
        json = packet.getChatComponents().readSafely(0).getJson();
    }

    boolean found = false;
    for (String rep : c.PLACEHOLDERS)
        if (json.contains(rep)) {
            found = true;
            break;
        }
    if (!found) {
        return; //then it's just a normal message without placeholders, so we leave it alone
    }
    if(json.lastIndexOf("\\u0007")==-1){ //if the message doesn't contain the BELL separator, then it's certainly NOT a message we want to parse
        return;
    }

    packet.addMetadata("parse", true); //We mark this packet to be parsed by the packet listener
    packet.addMetadata("base-component", usesBaseComponents); //We also tell it whether this packet uses the base component API
    packet.addMetadata("json", json); //And we finally provide it with the json we already got from the packet
}