Spicy Disabler module 1 files, 136 lines

Spicy Disabler: Full Source Analysis

Spicy's Disabler is a Hypixel-targeted packet cocktail with three live ingredients and one dead one.

info/spicyclient/modules/player/Disabler.java · GitHub source ↗

Published 2026-08-13 · Updated 2026-08-13

Analysis

Overview

Spicy's Disabler is a Hypixel-targeted packet cocktail with three live ingredients and one dead one. Every update tick it builds a PlayerCapabilities with isFlying, allowFlying and isCreativeMode all true and a fly speed drawn randomly from 0.1 to 9.0 (vanilla's cap is 0.05), sends it as C13PacketPlayerAbilities through sendPacketNoEvent so the module's own send interception cannot see it, and doubles the send while Spicy's Fly module is enabled. Every outgoing C0FPacketConfirmTransaction is buffered and cancelled, then replayed one per update once a 500-1250ms timer fires, so confirmations arrive late with their original window and uid. Every C0CPacketInput is cancelled outright. The keepalive branch, which would cancel C00PacketKeepAlive echoes, is entirely commented out, and the buffer is flushed at once on disable and cleared on C00 handshake and S00 disconnect.

Abilities spam

The EventUpdate pre handler fabricates a PlayerCapabilities each tick: isFlying and allowFlying true, isCreativeMode true, and a fly speed from Math.random() scaled to 0.1-9.0, far beyond the 0.05 the protocol permits. It is sent via NetworkManager.sendPacketNoEvent, which pushes the packet straight to the wire without firing the module's own EventSendPacket, so the spam never re-enters the interception logic. Vanilla NMS only honors the isFlying claim when the player is already in creative mode, so on a survival server the per-tick C13s are inert; the module's purpose is Hypixel's custom flying detection, where the constant re-assertion of flight and the absurd fly speed are meant to desynchronize the anticheat's ability state.

Transaction delay

Every C0F is captured in the static C0FPackets list and cancelled, and the EventUpdate handler drains it at a rate of one packet per 500-1250ms (ping.hasTimeElapsed(500 + random(750), true) then sendPacketNoEvent(C0FPackets.remove(0))). The replays keep the original window id and uid, so the server's processConfirmTransaction matches them against its ledger and accepts the confirmations late, which inflates the round-trip measurements servers use for ping- and timer-based tolerance. onDisable flushes the entire backlog in one sendPacketNoEvent loop, and the buffer is cleared on S00PacketDisconnect and on C00Handshake, so a fresh connection starts empty.

Input and keepalive handling

Every C0CPacketInput is cancelled in the send handler, so the server never receives the client's per-tick input state (strafe, forward, jump, sneak); vanilla ignores C0C for players not riding, which is why the cancel is safe on foot. The C00PacketKeepAlive branch is fully commented out, including a buffered keepalive-cancel variant: in the shipped build keepalives pass through untouched, and the import plus the dead code are the only reason C00 appears anywhere in the module. onEnable posts a 'Relog for the disabler to take effect' notification and resets the watchdog flag, signalling that the module's state only becomes coherent on a fresh connection.

source Disabler.java

Disabler.java136 lines · JavaOriginal ↗
1
package info.spicyclient.modules.player;
2
3
import java.util.ArrayList;
4
import java.util.Random;
5
6
import org.lwjgl.input.Keyboard;
7
8
import info.spicyclient.SpicyClient;
9
import info.spicyclient.chatCommands.Command;
10
import info.spicyclient.events.Event;
11
import info.spicyclient.events.listeners.EventPacket;
12
import info.spicyclient.events.listeners.EventSendPacket;
13
import info.spicyclient.events.listeners.EventUpdate;
14
import info.spicyclient.modules.Module;
15
import info.spicyclient.notifications.Color;
16
import info.spicyclient.notifications.NotificationManager;
17
import info.spicyclient.notifications.Type;
18
import info.spicyclient.util.MovementUtils;
19
import info.spicyclient.util.Timer;
20
import net.minecraft.entity.player.PlayerCapabilities;
21
import net.minecraft.network.Packet;
22
import net.minecraft.network.handshake.client.C00Handshake;
23
import net.minecraft.network.login.server.S00PacketDisconnect;
24
import net.minecraft.network.play.client.C00PacketKeepAlive;
25
import net.minecraft.network.play.client.C03PacketPlayer;
26
import net.minecraft.network.play.client.C0CPacketInput;
27
import net.minecraft.network.play.client.C0FPacketConfirmTransaction;
28
import net.minecraft.network.play.client.C13PacketPlayerAbilities;
29
import net.minecraft.network.play.server.S08PacketPlayerPosLook;
30
import net.minecraft.network.play.server.S32PacketConfirmTransaction;
31
32
public class Disabler extends Module {
33
	public Disabler() {
34
		super("Disabler", Keyboard.KEY_NONE, Category.PLAYER);
35
	}
36
	
37
	public static transient boolean watchdog = false;
38
	public static transient ArrayList<C0FPacketConfirmTransaction> C0FPackets = new ArrayList<C0FPacketConfirmTransaction>();
39
	public static transient Timer ping = new Timer();
40
	
41
	@Override
42
	public void onEnable() {
43
		NotificationManager.getNotificationManager().createNotification("Relog for the disabler to take effect", "", true, 5000, Type.INFO, Color.PINK);
44
		watchdog = false;
45
	}
46
	
47
	@Override
48
	public void onDisable() {
49
		watchdog = false;
50
		
51
		for (C0FPacketConfirmTransaction p : C0FPackets) {
52
			
53
			mc.getNetHandler().getNetworkManager().sendPacketNoEvent(p);
54
			
55
		}
56
		
57
		C0FPackets.clear();
58
		
59
	}
60
	
61
	@Override
62
	public void onEvent(Event e) {
63
		
64
		if (e instanceof EventUpdate && e.isPre()) {
65
			
66
			this.additionalInformation = "Hypixel";
67
			
68
            PlayerCapabilities playerCapabilities = new PlayerCapabilities();
69
            playerCapabilities.isFlying = true;
70
            playerCapabilities.allowFlying = true;
71
            //playerCapabilities.setFlySpeed((float) ((Math.random() * (9.0 - 0.1)) + 0.1));
72
            playerCapabilities.setFlySpeed((float) ((Math.random() * (9.0 - 0.1)) + 0.1));
73
            playerCapabilities.isCreativeMode = true;
74
            mc.getNetHandler().getNetworkManager().sendPacketNoEvent(new C13PacketPlayerAbilities(playerCapabilities));
75
            
76
            // Added this
77
            if (SpicyClient.config.fly.isEnabled()) {
78
            	mc.getNetHandler().getNetworkManager().sendPacketNoEvent(new C13PacketPlayerAbilities(playerCapabilities));
79
            }
80
            
81
            if (ping.hasTimeElapsed(500 + (new Random()).nextInt(750), true) && C0FPackets.size() > 0) {
82
            	mc.getNetHandler().getNetworkManager().sendPacketNoEvent(C0FPackets.get(0));
83
            	C0FPackets.remove(0);
84
            }
85
            
86
		}
87
		
88
		if (e instanceof EventPacket && e.isPre()) {
89
			
90
			if (((EventPacket)e).packet instanceof S00PacketDisconnect) {
91
				C0FPackets.clear();
92
			}
93
			
94
		}
95
		
96
		if (e instanceof EventSendPacket && e.isPre()) {
97
			
98
			EventSendPacket event = (EventSendPacket) e;
99
			
100
			if (event.packet instanceof C00Handshake) {
101
				C0FPackets.clear();
102
			}
103
			
104
            if (event.packet instanceof C0FPacketConfirmTransaction) {
105
            	
106
                C0FPacketConfirmTransaction packetConfirmTransaction = (C0FPacketConfirmTransaction)event.packet;
107
                
108
                //mc.getNetHandler().getNetworkManager().sendPacketNoEvent(new C0FPacketConfirmTransaction(2147483647, packetConfirmTransaction.getUid(), false));
109
                //mc.getNetHandler().getNetworkManager().sendPacketNoEvent(new C0FPacketConfirmTransaction(1147483647, packetConfirmTransaction.getUid(), false));
110
                
111
                
112
                //packetConfirmTransaction.setAccepted(new Random().nextBoolean());
113
                //packetConfirmTransaction.setWindowId(Integer.MIN_VALUE + new Random().nextInt(1000));
114
                //packetConfirmTransaction.setUid(Short.MAX_VALUE);
115
            	//mc.getNetHandler().getNetworkManager().sendPacketNoEvent(new C0FPacketConfirmTransaction(Integer.MIN_VALUE, Short.MAX_VALUE, true));
116
                
117
                C0FPackets.add(packetConfirmTransaction);
118
                e.setCanceled(true);
119
            }
120
121
            if (event.packet instanceof C00PacketKeepAlive) {
122
            	
123
            	//mc.getNetHandler().getNetworkManager().sendPacketNoEvent(new C00PacketKeepAlive(-2147483648 + (new Random()).nextInt(100)));
124
                //e.setCanceled(true);
125
                
126
            }
127
            
128
			if (event.packet instanceof C0CPacketInput) {
129
				e.setCanceled(true);
130
			}
131
            
132
		}
133
		
134
	}
135
	
136
}

What this file does

Three static fields carry the module's state: the watchdog flag, the C0FPackets buffer, and the ping Timer. onEnable arms the notification and clears watchdog; onDisable replays every buffered C0F through sendPacketNoEvent and clears the list, which is the one place the backlog becomes a burst. EventUpdate pre is the abilities spam and the C0F drain, EventPacket pre clears the buffer on S00 disconnect, and EventSendPacket pre owns the C0F capture, the C0C cancellation, and the buffer clear on C00Handshake.

The commented-out lines are the interesting archaeology: the C0F branch has experimental rewrites (window id Short.MAX_VALUE, random accepted flag, Integer.MIN_VALUE window) all disabled in favor of the plain buffer-and-replay, and the keepalive branch has a cancelled-echo variant commented out, leaving C00 untouched in the live build. The double-C13 send when SpicyClient.config.fly.isEnabled() is the module's only coupling to another module, and it exists because the disabler's whole job is to make the Fly module's server-side state believable.

anticheat Countering Checks

The anticheat code that detects or counters the techniques this module uses. Full source, with the detection mechanism explained below each box.

anticheat KeepAliveFrequency (keepalive ledger)

KeepAliveFrequency.java101 lines · Java
1
/*
2
 * This program is free software: you can redistribute it and/or modify
3
 *   it under the terms of the GNU General Public License as published by
4
 *   the Free Software Foundation, either version 3 of the License, or
5
 *   (at your option) any later version.
6
 *
7
 *   This program is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU General Public License
13
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
14
 */
15
package fr.neatmonster.nocheatplus.checks.net;
16
17
import org.bukkit.entity.Player;
18
19
import fr.neatmonster.nocheatplus.checks.Check;
20
import fr.neatmonster.nocheatplus.checks.CheckType;
21
import fr.neatmonster.nocheatplus.players.IPlayerData;
22
import fr.neatmonster.nocheatplus.utilities.CheckUtils;
23
24
public class KeepAliveFrequency extends Check {
25
26
    public KeepAliveFrequency() {
27
        super(CheckType.NET_KEEPALIVEFREQUENCY);
28
    }
29
    
30
    /**
31
     * Checks hasBypass on violation only.
32
     * @param player
33
     * @param time
34
     * @param data
35
     * @param cc
36
     * @return If to cancel.
37
     */
38
    public boolean check(final Player player, final long time, final NetData data, final NetConfig cc, final IPlayerData pData) {
39
        final long now = System.currentTimeMillis();
40
        final long joinTime = pData.getLastJoinTime();
41
        if (joinTime > 0L && now < joinTime + cc.keepAliveFrequencyStartupDelay) {
42
            return false;
43
        }
44
        if (data.keepAliveExpectedResponse && !data.keepAliveDuplicateId) {
45
            return false;
46
        }
47
        data.keepAliveFreq.add(time, 1f);
48
        final float first = data.keepAliveFreq.bucketScore(0);
49
        
50
        if (first > 1f) {
51
            // Trigger a violation.
52
            final float fullScore = data.keepAliveFreq.score(1f);
53
            if (isModeledBoundaryBurst(data, fullScore, first)) {
54
                return false;
55
            }
56
            final double vl = Math.max(first - getFirstBucketViolationLimit(data), fullScore - data.keepAliveFreq.numberOfBuckets());
57
            final boolean cancel = executeActions(player, vl, 1.0, cc.keepAliveFrequencyActions).willCancel();
58
            return cancel;
59
        }
60
        return false;
61
    }
62
63
    private boolean isModeledBoundaryBurst(final NetData data, final float fullScore, final float first) {
64
        // KeepAlive model: if outgoing tracking is unavailable, only treat small monotonic id bursts as timing leftovers.
65
        if (data.keepAliveDuplicateId || fullScore > data.keepAliveFreq.numberOfBuckets() + 2f) {
66
            return false;
67
        }
68
        // Folia/netty can timestamp two adjacent valid replies in the same millisecond; do not cancel a single pair.
69
        return first <= 2f || isUntrackedMonotonicBurst(data, fullScore, first);
70
    }
71
72
    private boolean isUntrackedMonotonicBurst(final NetData data, final float fullScore, final float first) {
73
        if (data.keepAliveOutgoingSeen || fullScore > data.keepAliveFreq.numberOfBuckets()) {
74
            return false;
75
        }
76
        if (!data.keepAlivePacketIdAvailable || !data.keepAlivePreviousPacketIdAvailable) {
77
            return false;
78
        }
79
        if (data.keepAlivePacketId <= data.keepAlivePreviousPacketId) {
80
            return false;
81
        }
82
        return first <= getFallbackFirstBucketLimit(data);
83
    }
84
85
    private float getFirstBucketViolationLimit(final NetData data) {
86
        if (data.keepAliveDuplicateId) {
87
            return 1f;
88
        }
89
        if (!data.keepAliveOutgoingSeen
90
                && data.keepAlivePacketIdAvailable
91
                && data.keepAlivePreviousPacketIdAvailable
92
                && data.keepAlivePacketId > data.keepAlivePreviousPacketId) {
93
            return getFallbackFirstBucketLimit(data);
94
        }
95
        return 2f;
96
    }
97
98
    private float getFallbackFirstBucketLimit(final NetData data) {
99
        return Math.max(3f, Math.min(6f, data.keepAliveFreq.numberOfBuckets() / 4f));
100
    }
101
}

How it counteracts this module

NoCheatPlus replaces vanilla's accept-any-echo keepalive model with an id-tracked ledger. The ProtocolLib KeepAliveAdapter records every outgoing S00 id into NetData.keepAliveRequests and matches each incoming C00 against it (KeepAliveAdapter lines 73-104, NetData lines 290-341), and KeepAliveFrequency checks every reply: data.keepAliveFreq, an ActionFrequency(20, 1000) (NetData line 150), scores one point per reply, the newest second's bucket is compared against a first-bucket limit (2f normally, tightened to 1f for duplicate ids, lines 85-96), and the full 20-second window score is compared against the bucket count (lines 50-58), with a modeled-boundary-burst exemption for tiny monotonic id runs (lines 63-83).

This is the check that governs the technique the module's commented-out keepalive branch implements: were the cancelled-echo variant re-enabled, every suppressed echo would be an unexpected reply or a duplicate id once the request aged out or the replay lagged, feeding the frequency counters and tripping the duplicate-id path, which forgives nothing. The shipped build sends its keepalives untouched and replays no echoes, so it sails past this check; the ledger still matters to the module's design because the C00Handshake buffer clear and the relog requirement exist precisely because the C0F delay scheme must not survive across connections.

anticheat AbilitiesEvent and HawkPlayer.setFlying (server-state gate)

HawkPlayer.java1121 lines · Java
1
/*
2
 * This file is part of Hawk Anticheat.
3
 * Copyright (C) 2018 Hawk Development Team
4
 *
5
 * This program is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17
 */
18
19
package me.islandscout.hawk;
20
21
import me.islandscout.hawk.check.Check;
22
import me.islandscout.hawk.util.*;
23
import me.islandscout.hawk.wrap.block.WrappedBlock;
24
import me.islandscout.hawk.wrap.entity.MetaData;
25
import me.islandscout.hawk.wrap.entity.WrappedEntity;
26
import me.islandscout.hawk.wrap.entity.human.WrappedEntityHuman;
27
import org.bukkit.*;
28
import org.bukkit.block.Block;
29
import org.bukkit.entity.Entity;
30
import org.bukkit.entity.Player;
31
import org.bukkit.event.player.PlayerTeleportEvent;
32
import org.bukkit.inventory.ItemStack;
33
import org.bukkit.util.Vector;
34
35
import java.util.*;
36
import java.util.concurrent.ConcurrentHashMap;
37
import java.util.concurrent.CopyOnWriteArrayList;
38
39
/**
40
 * Represents a client. Provides essential and additional tools
41
 * to analyze players during packet interception. Recommended
42
 * to use this rather than Bukkit's implementation.
43
 *
44
 * Fields here should be faithful to the client they represent
45
 * as much as possible, regardless of any modifications that the
46
 * anti-cheat makes to the incoming packets. Caution: that means
47
 * some of these fields can be spoofed!
48
 */
49
public class HawkPlayer {
50
51
    //Represents a queue of commands sent from server to client. Simulates latency as it is ticked.
52
    //Can be used to simulate commands that the client doesn't show any clear acknowledgement for,
53
    //such as inventory window opening/closing.
54
    private final List<Pair<Runnable, Long>> simulatedCmds;
55
56
    private final UUID uuid;
57
    private final Map<Check, Double> vl;
58
    private boolean digging;
59
    private boolean receiveNotifications;
60
    private boolean online;
61
    private final Player p;
62
    private long lastTeleportAcceptTick;
63
    private final Hawk hawk;
64
65
    //Be careful when playing with these fields.
66
    //World is not sync'd to position, yaw, nor pitch.
67
    //private World world; //updated by server
68
    private Vector position; //updated by server and client
69
    private Vector positionRaw; //updated by client
70
    private Location altSetbackLoc; //updated by server
71
    private float yaw; //updated by server and client
72
    private float pitch; //updated by server and client
73
74
    private Vector predictedPosition; //ticked by client
75
    private Vector previousPredictedPosition;
76
    private Vector predictedVelocity;
77
    private Vector previousPredictedVelocity;
78
79
    private Map<Location, List<AABB>> trackedBlockCollisions; //Private. Used to update ignoredBlockCollisions.
80
    private Set<Location> ignoredBlockCollisions; //is accessible via getter
81
82
    private Vector velocity;
83
    private Vector previousVelocity;
84
    private float deltaYaw;
85
    private float deltaPitch;
86
    private boolean onGround;
87
    private boolean prevTickOnGround;
88
    private boolean onGroundReally;
89
    private boolean sentPosUpdate;
90
    private boolean liquidExit;
91
    private float friction;
92
    private int ping;
93
    private short pingJitter;
94
    private long lastMoveTime;
95
    private long currentTick;
96
    private boolean sneaking;
97
    private boolean sprinting;
98
    private boolean blocking;
99
    private boolean pullingBow;
100
    private boolean consumingItem;
101
    private byte inventoryOpen; //0 for closed; 1 for own inventory; 2 for any other inventory. Updated by server & client
102
    private boolean inWater;
103
    private boolean inLava;
104
    private boolean swimming;
105
    private boolean inVehicle; //updated by server
106
    private boolean allowedToFly; //updated by server
107
    private boolean flying; //updated by server and client
108
    private boolean inCreative; //updated by server
109
    private long itemUseTick;
110
    private long lastAttackedPlayerTick;
111
    private long lastEntityInteractTick;
112
    private long lastInLiquidToggleTick;
113
    private long lastSlotSwitchTick;
114
    private long lastMoveTick;
115
    private long hitSlowdownTick;
116
    private long lastVelocityAcceptTick;
117
    private long lastLandTick;
118
    private ItemStack itemUsedForAttack;
119
    private double maxY;
120
    private double jumpedHeight;
121
    private long flyPendingTime;
122
    private int heldItemSlot;
123
    private int itemConsumeTicks;
124
    private final Map<Location, ClientBlock> clientBlocks;
125
    private final List<Pair<Vector, Long>> pendingVelocities;
126
    private final List<Pair<Location, Long>> pendingTeleports;
127
    private final Set<Direction> boxSidesTouchingBlocks;
128
    private Vector waterFlowForce;
129
    private List<Pair<MetaData, Long>> metaDataUpdates;
130
    private Set<Entity> entitiesInteractedInThisTick;
131
    private List<Double> lastPings;
132
    private int clientVersion;
133
134
    HawkPlayer(Player p, Hawk hawk) {
135
        this.uuid = p.getUniqueId();
136
        vl = new ConcurrentHashMap<>();
137
        receiveNotifications = true;
138
        this.p = p;
139
        Location defaultLocation = p.getLocation();
140
        this.position = defaultLocation.toVector();
141
        this.positionRaw = defaultLocation.toVector();
142
        altSetbackLoc = defaultLocation;
143
        this.yaw = defaultLocation.getYaw();
144
        this.pitch = defaultLocation.getPitch();
145
        this.velocity = new Vector();
146
        this.previousVelocity = new Vector();
147
        this.predictedPosition = defaultLocation.toVector();
148
        this.previousPredictedPosition = defaultLocation.toVector();
149
        this.predictedVelocity = new Vector();
150
        this.onGround = ((Entity) p).isOnGround();
151
        this.hawk = hawk;
152
        this.ping = ServerUtils.getPing(p);
153
        this.heldItemSlot = p.getInventory().getHeldItemSlot();
154
        clientBlocks = new ConcurrentHashMap<>();
155
        pendingVelocities = new CopyOnWriteArrayList<>();
156
        pendingTeleports = new CopyOnWriteArrayList<>();
157
        boxSidesTouchingBlocks = new HashSet<>();
158
        this.waterFlowForce = new Vector();
159
        trackedBlockCollisions = new HashMap<>();
160
        ignoredBlockCollisions = new HashSet<>();
161
        simulatedCmds = new CopyOnWriteArrayList<>();
162
        metaDataUpdates = new CopyOnWriteArrayList<>();
163
        entitiesInteractedInThisTick = new HashSet<>();
164
        lastPings = new CopyOnWriteArrayList<>();
165
        clientVersion = ServerUtils.getProtocolVersion(p) == 47 ? 8 : 7;
166
167
        //do this a little later since these values are a little slow
168
        Bukkit.getScheduler().scheduleSyncDelayedTask(hawk, new Runnable() {
169
            @Override
170
            public void run() {
171
                allowedToFly = p.getAllowFlight();
172
                flying = p.isFlying();
173
                inCreative = p.getGameMode() == GameMode.CREATIVE;
174
            }
175
        });
176
177
    }
178
179
    public void tick() {
180
        this.currentTick++;
181
        manageClientBlocks();
182
        executeTasks();
183
        cleanUpOldMetaDataUpdates();
184
        cleanUpOldPendingTeleports();
185
        entitiesInteractedInThisTick.clear();
186
        predictNextPosition();
187
        if(consumingItem)
188
            itemConsumeTicks++;
189
    }
190
191
    public int getVL(Check check) {
192
        return (int) (double) vl.getOrDefault(check, 0D);
193
    }
194
195
    public Map<Check, Double> getVLs() {
196
        return vl;
197
    }
198
199
    public void setVL(Check check, double vl) {
200
        this.vl.put(check, vl);
201
    }
202
203
    public void incrementVL(Check check) {
204
        this.vl.put(check, vl.getOrDefault(check, 0D) + 1D);
205
    }
206
207
    public void addVL(Check check, double amnt) {
208
        this.vl.put(check, vl.getOrDefault(check, 0D) + amnt);
209
    }
210
211
    public void multiplyVL(Check check, double factor) {
212
        vl.put(check, vl.getOrDefault(check, 0D) * factor);
213
    }
214
215
    public UUID getUuid() {
216
        return uuid;
217
    }
218
219
    public boolean isDigging() {
220
        return digging && p.getGameMode() != GameMode.CREATIVE;
221
    }
222
223
    //this should really not be public
224
    public void setDigging(boolean digging) {
225
        this.digging = digging;
226
    }
227
228
    public boolean getReceiveNotificationsPreference() {
229
        return receiveNotifications;
230
    }
231
232
    public void setReceiveNotificationsPreference(boolean status) {
233
        receiveNotifications = status;
234
    }
235
236
    public boolean isOnline() {
237
        return online;
238
    }
239
240
    public void setOnline(boolean online) {
241
        this.online = online;
242
    }
243
244
    public boolean isTeleporting() {
245
        return !getPendingTeleports().isEmpty();
246
    }
247
248
    public long getLastTeleportAcceptTick() {
249
        return lastTeleportAcceptTick;
250
    }
251
252
    public void setLastTeleportAcceptTick(long lastTeleportAcceptTick) {
253
        this.lastTeleportAcceptTick = lastTeleportAcceptTick;
254
    }
255
256
    public boolean isOnGround() {
257
        return onGround;
258
    }
259
260
    //this should really not be public
261
    public void setOnGround(boolean onGround) {
262
        this.prevTickOnGround = this.onGround;
263
        this.onGround = onGround;
264
    }
265
266
    //why do I need to make this???
267
    public boolean wasOnGround() {
268
        return prevTickOnGround;
269
    }
270
271
    public boolean isOnGroundReally() {
272
        return onGroundReally;
273
    }
274
275
    public void setOnGroundReally(boolean onGroundReally) {
276
        this.onGroundReally = onGroundReally;
277
    }
278
279
    public int getPing() {
280
        return ping;
281
    }
282
283
    public void setPing(int ping) {
284
        this.ping = ping;
285
        this.lastPings.add((double)ping);
286
        if(lastPings.size() > 10) {
287
            lastPings.remove(0);
288
        }
289
        pingJitter = (short)MathPlus.range(lastPings);
290
    }
291
292
    public short getPingJitter() {
293
        return pingJitter;
294
    }
295
296
    public long getLastMoveTime() {
297
        return lastMoveTime;
298
    }
299
300
    public void setLastMoveTime(long lastMoveTime) {
301
        this.lastMoveTime = lastMoveTime;
302
    }
303
304
    public World getWorld() {
305
        return p.getWorld();
306
    }
307
308
    //currently doesn't support when in vehicle
309
    public Vector getPosition() {
310
        return position;
311
    }
312
313
    //the player's position since the last flying packet; completely untouched
314
    public Vector getPositionRaw() {
315
        return positionRaw;
316
    }
317
318
    //currently doesn't support when in vehicle
319
    public Vector getHeadPosition() {
320
        Vector add = new Vector(0, 0, 0);
321
        add.setY(isSneaking() ? 1.54 : 1.62);
322
        return position.clone().add(add);
323
    }
324
325
    public Vector getPositionCloned() {
326
        return position.clone();
327
    }
328
329
    //Returns the current predicted position of the HawkPlayer, assuming no user input.
330
    public Vector getPositionPredicted() {
331
        return predictedPosition;
332
    }
333
334
    public Vector getPreviousPositionPredicted() {
335
        return previousPredictedPosition;
336
    }
337
338
    public void updatePositionYawPitch(Vector position, float yaw, float pitch, boolean isPosUpdate) {
339
        this.previousVelocity = this.velocity;
340
        this.velocity = new Vector(
341
                position.getX() - this.position.getX(),
342
                position.getY() - this.position.getY(),
343
                position.getZ() - this.position.getZ());
344
        this.deltaYaw = yaw - this.yaw;
345
        this.deltaPitch = pitch - this.pitch;
346
347
        this.position = position;
348
        this.yaw = yaw;
349
        this.pitch = pitch;
350
        if(isPosUpdate) {
351
            predictedPosition = position.clone();
352
            if(hasSentPosUpdate())
353
                predictedVelocity = velocity.clone();
354
        }
355
    }
356
357
    public void setPositionRaw(Vector positionRaw) {
358
        this.positionRaw = positionRaw;
359
    }
360
361
    public float getYaw() {
362
        return yaw;
363
    }
364
365
    public void setYaw(float yaw) {
366
        this.yaw = yaw;
367
    }
368
369
    public float getPitch() {
370
        return pitch;
371
    }
372
373
    public void setPitch(float pitch) {
374
        this.pitch = pitch;
375
    }
376
377
    public void setVelocity(Vector velocity) {
378
        this.velocity = velocity;
379
    }
380
381
    public Vector getVelocity() {
382
        return velocity;
383
    }
384
385
    public Vector getVelocityPredicted() {
386
        return predictedVelocity;
387
    }
388
389
    public Vector getPreviousVelocity() {
390
        return previousVelocity;
391
    }
392
393
    public Vector getPreviousPredictedVelocity() {
394
        return previousPredictedVelocity;
395
    }
396
397
    public float getDeltaYaw() {
398
        return deltaYaw;
399
    }
400
401
    public float getDeltaPitch() {
402
        return deltaPitch;
403
    }
404
405
    public long getCurrentTick() {
406
        return currentTick;
407
    }
408
409
    public boolean isSneaking() {
410
        return sneaking;
411
    }
412
413
    public void setSneaking(boolean sneaking) {
414
        this.sneaking = sneaking;
415
    }
416
417
    public boolean isSprinting() {
418
        return sprinting;
419
    }
420
421
    public void setSprinting(boolean sprinting) {
422
        this.sprinting = sprinting;
423
    }
424
425
    public boolean isBlocking() {
426
        return blocking;
427
    }
428
429
    public void setBlocking(boolean blocking) {
430
        this.blocking = blocking;
431
        if(blocking)
432
            itemUseTick = currentTick;
433
    }
434
435
    public boolean isPullingBow() {
436
        return pullingBow;
437
    }
438
439
    public void setPullingBow(boolean pullingBow) {
440
        this.pullingBow = pullingBow;
441
        if(pullingBow)
442
            itemUseTick = currentTick;
443
    }
444
445
    public byte hasInventoryOpen() {
446
        return inventoryOpen;
447
    }
448
449
    public void setInventoryOpen(byte status) {
450
        this.inventoryOpen = status;
451
    }
452
453
    public double getFallDistance() {
454
        return maxY - position.getY();
455
    }
456
457
    public int getHeldItemSlot() {
458
        return heldItemSlot;
459
    }
460
461
    public void setHeldItemSlot(int heldItemSlot) {
462
        this.heldItemSlot = heldItemSlot;
463
    }
464
465
    public boolean isConsumingItem() {
466
        return consumingItem;
467
    }
468
469
    public void setConsumingItem(boolean consumingItem) {
470
        this.consumingItem = consumingItem;
471
        if(consumingItem)
472
            itemUseTick = currentTick;
473
        else
474
            itemConsumeTicks = 0;
475
    }
476
477
    public boolean isInWater() {
478
        return inWater;
479
    }
480
481
    public void setInWater(boolean inWater) {
482
        if(this.inWater != inWater) {
483
            lastInLiquidToggleTick = currentTick;
484
            this.inWater = inWater;
485
        }
486
    }
487
488
    public boolean isInLava() {
489
        return inLava;
490
    }
491
492
    public void setInLava(boolean inLava) {
493
        this.inLava = inLava;
494
    }
495
496
    @Deprecated
497
    public boolean isFlyingClientside() {
498
        return (p.getAllowFlight() && hasFlyPending()) || p.isFlying();
499
    }
500
501
    public long getLastItemUseTick() {
502
        return itemUseTick;
503
    }
504
505
    public long getLastAttackedPlayerTick() {
506
        return lastAttackedPlayerTick;
507
    }
508
509
    public void updateLastAttackedPlayerTick() {
510
        this.lastAttackedPlayerTick = currentTick;
511
    }
512
513
    public long getLastEntityInteractTick() {
514
        return lastEntityInteractTick;
515
    }
516
517
    public void updateLastEntityInteractTick() {
518
        this.lastEntityInteractTick = currentTick;
519
    }
520
521
    public long getLastInLiquidToggleTick() {
522
        return lastInLiquidToggleTick;
523
    }
524
525
    public long getLastSlotSwitchTick() {
526
        return lastSlotSwitchTick;
527
    }
528
529
    public void updateLastSlotSwitchTick() {
530
        this.lastSlotSwitchTick = currentTick;
531
    }
532
533
    public long getHitSlowdownTick() {
534
        return hitSlowdownTick;
535
    }
536
537
    public void updateHitSlowdownTick() {
538
        this.hitSlowdownTick = currentTick;
539
    }
540
541
    public long getLastVelocityAcceptTick() {
542
        return lastVelocityAcceptTick;
543
    }
544
545
    public void updateLastVelocityAcceptTick() {
546
        this.lastVelocityAcceptTick = currentTick;
547
    }
548
549
    public boolean hasHitSlowdown() {
550
        return hitSlowdownTick == currentTick;
551
    }
552
553
    public boolean isSwimming() {
554
        return swimming;
555
    }
556
557
    public void setSwimming(boolean swimming) {
558
        this.swimming = swimming;
559
    }
560
561
    public ItemStack getItemUsedForAttack() {
562
        return itemUsedForAttack;
563
    }
564
565
    public void updateItemUsedForAttack() {
566
        this.itemUsedForAttack = getHeldItem();
567
    }
568
569
    public ItemStack getHeldItem() {
570
        return p.getInventory().getItem(heldItemSlot);
571
    }
572
573
    //call this before updating whether on ground or not
574
    public void updateFallDistance(Location loc) {
575
        if (onGround)
576
            maxY = loc.getY();
577
        else
578
            maxY = Math.max(loc.getY(), maxY);
579
580
    }
581
582
    public double getTotalAscensionSinceGround() {
583
        return jumpedHeight;
584
    }
585
586
    //call this before updating whether on ground or not
587
    public void updateTotalAscensionSinceGround(double y1, double y2) {
588
        if (onGround) {
589
            jumpedHeight = 0;
590
            return;
591
        }
592
        double deltaY = y2 - y1;
593
        if(deltaY > 0)
594
            jumpedHeight += deltaY;
595
    }
596
597
    public boolean hasFlyPending() {
598
        return System.currentTimeMillis() - flyPendingTime <= 100;
599
    }
600
601
    public void setFlyPendingTime(long time) {
602
        flyPendingTime = time;
603
    }
604
605
    public Player getPlayer() {
606
        return p;
607
    }
608
609
    public Map<Location, ClientBlock> getClientBlocks() {
610
        return clientBlocks;
611
    }
612
613
    public void addClientBlock(Location loc, ClientBlock pBlock) {
614
        if (clientBlocks.size() >= ClientBlock.MAX_PER_PLAYER)
615
            return;
616
        clientBlocks.put(loc, pBlock);
617
    }
618
619
    private void manageClientBlocks() {
620
        for (Location loc : clientBlocks.keySet()) {
621
            ClientBlock clientBlock = clientBlocks.get(loc);
622
            if (currentTick - clientBlock.getInitTick() > ClientBlock.CLIENTTICKS_UNTIL_EXPIRE) {
623
                clientBlocks.remove(loc);
624
            }
625
        }
626
    }
627
628
    //TODO shrink this code
629
    //TODO TEST BEFORE RELEASING 2001
630
    private void predictNextPosition() {
631
        Vector move = predictedVelocity.clone();
632
        previousPredictedPosition = predictedPosition.clone();
633
        previousPredictedVelocity = predictedVelocity.clone();
634
635
        World world = getWorld();
636
637
        Block blockAtPos = ServerUtils.getBlockAsync(predictedPosition.toLocation(getWorld()));
638
        boolean onClimbable = blockAtPos != null && (blockAtPos.getType() == Material.LADDER || blockAtPos.getType() == Material.VINE);
639
640
        Set<Material> oldTouchedMats = WrappedEntity.getWrappedEntity(p).getCollisionBox(predictedPosition).getMaterials(getWorld());
641
642
        //compute new predicted motion values
643
        double pdX = move.getX() * getFriction();
644
        double pdY = move.getY() * 0.98;
645
        double pdZ = move.getZ() * getFriction();
646
647
        if(!isFlying())
648
            pdY += -0.0784;
649
650
        if(oldTouchedMats.contains(Material.WEB)) {
651
            pdX *= 0.25;
652
            pdY *= 0.05;
653
            pdZ *= 0.25;
654
        }
655
656
        if(Math.abs(pdX) < 0.005) {
657
            pdX = 0;
658
        }
659
        if(Math.abs(pdY) < 0.005 || (onClimbable && sneaking)) {
660
            pdY = 0;
661
        }
662
        if(Math.abs(pdZ) < 0.005) {
663
            pdZ = 0;
664
        }
665
666
        move.setX(pdX);
667
        move.setY(pdY);
668
        move.setZ(pdZ);
669
670
        AABB box = WrappedEntity.getWrappedEntity(p).getCollisionBox(predictedPosition);
671
        AABB preBox = box.clone();
672
        preBox.expand(-0.0001, -0.0001, -0.0001);
673
        List<AABB> collidedBlocksBefore = preBox.getBlockAABBs(world, getClientVersion(), Material.WEB);
674
675
        boolean collidedVertically = false;
676
677
        //clipping order: X, Z, Y
678
        //X
679
        box.expand(-0.00000001, -0.00000001, -0.00000001);
680
        boolean positive = pdX > 0;
681
        box.translate(new Vector(pdX, 0, 0));
682
        List<AABB> collidedBlocks = box.getBlockAABBs(world, getClientVersion(), Material.WEB);
683
        collidedBlocks.removeAll(collidedBlocksBefore);
684
685
        double highestPoint = positive ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
686
        for(AABB aabb : collidedBlocks) {
687
            double point = positive ? aabb.getMin().getX() : aabb.getMax().getX();
688
            if(positive && point < highestPoint)
689
                highestPoint = point;
690
            else if(!positive && point > highestPoint)
691
                highestPoint = point;
692
        }
693
        if(Double.isFinite(highestPoint)) {
694
            double invPenetrationDist = positive ? highestPoint - box.getMax().getX() - 0.00000001 : highestPoint - box.getMin().getX() + 0.00000001;
695
            box.translate(new Vector(invPenetrationDist, 0, 0));
696
            pdX += invPenetrationDist;
697
        }
698
699
        //Z
700
        positive = pdZ > 0;
701
        box.translate(new Vector(0, 0, pdZ));
702
        collidedBlocks = box.getBlockAABBs(world, getClientVersion(), Material.WEB);
703
        collidedBlocks.removeAll(collidedBlocksBefore);
704
705
        highestPoint = positive ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
706
        for(AABB aabb : collidedBlocks) {
707
            double point = positive ? aabb.getMin().getZ() : aabb.getMax().getZ();
708
            if(positive && point < highestPoint)
709
                highestPoint = point;
710
            else if(!positive && point > highestPoint)
711
                highestPoint = point;
712
        }
713
        if(Double.isFinite(highestPoint)) {
714
            double invPenetrationDist = positive ? highestPoint - box.getMax().getZ() - 0.00000001 : highestPoint - box.getMin().getZ() + 0.00000001;
715
            box.translate(new Vector(0, 0, invPenetrationDist));
716
            pdZ += invPenetrationDist;
717
        }
718
719
        //Y
720
        positive = pdY > 0;
721
        box.translate(new Vector(0, pdY, 0));
722
        collidedBlocks = box.getBlockAABBs(world, getClientVersion(), Material.WEB);
723
        collidedBlocks.removeAll(collidedBlocksBefore);
724
725
        highestPoint = positive ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
726
        for(AABB aabb : collidedBlocks) {
727
            double point = positive ? aabb.getMin().getY() : aabb.getMax().getY();
728
            if(positive && point < highestPoint)
729
                highestPoint = point;
730
            else if(!positive && point > highestPoint)
731
                highestPoint = point;
732
        }
733
        if(Double.isFinite(highestPoint)) {
734
            double invPenetrationDist = positive ? highestPoint - box.getMax().getY() - 0.00000001 : highestPoint - box.getMin().getY() + 0.00000001;
735
            box.translate(new Vector(0, invPenetrationDist, 0));
736
            pdY += invPenetrationDist;
737
            collidedVertically = true;
738
        }
739
740
        //crude way of handling sneaking
741
        boolean sneakHalt;
742
        if(sneaking) {
743
            Vector min = predictedPosition.clone().add(new Vector(-0.3, -0.001, -0.3));
744
            Vector max = predictedPosition.clone().add(new Vector(0.3, 0, 0.3));
745
            AABB feet = new AABB(min, max);
746
            boolean wasOnGround = feet.getBlockAABBs(world, clientVersion, Material.WEB).size() > 0;
747
748
            feet.translate(new Vector(pdX, pdY, pdZ));
749
            boolean isOnGround = feet.getBlockAABBs(world, clientVersion, Material.WEB).size() > 0;
750
751
            if(wasOnGround && !isOnGround) {
752
                //use max.getY() to save a clone()
753
                Vector check = new Vector(pdX, max.getY() - 1, pdZ);
754
                Block checkBlock = ServerUtils.getBlockAsync(check.toLocation(world));
755
                if(checkBlock == null) {
756
                    sneakHalt = true;
757
                }
758
                else {
759
                    sneakHalt = true;
760
                    for(AABB aabb : WrappedBlock.getWrappedBlock(checkBlock, clientVersion).getCollisionBoxes()) {
761
                        if(aabb.containsPoint(check)) {
762
                            sneakHalt = false;
763
                            break;
764
                        }
765
                    }
766
                }
767
            }
768
            else {
769
                sneakHalt = false;
770
            }
771
        }
772
        else {
773
            sneakHalt = false;
774
        }
775
        if(sneakHalt) {
776
            predictedVelocity = new Vector(0, 0, 0);
777
            return;
778
        }
779
780
        //move predicted position
781
        Vector clippedVel = new Vector(MathPlus.round(pdX, 10), MathPlus.round(pdY, 10), MathPlus.round(pdZ, 10));
782
        predictedPosition.add(clippedVel);
783
784
        //AABB a = AABB.playerCollisionBox.clone();
785
        //a.translate(predictedPosition);
786
        //a.highlight(hawk, getWorld(), 0.299);
787
788
        Set<Material> newTouchedMats = WrappedEntity.getWrappedEntity(p).getCollisionBox(predictedPosition).getMaterials(getWorld());
789
        if(newTouchedMats.contains(Material.WEB)) {
790
            predictedVelocity = new Vector();
791
        } else if(collidedVertically) {
792
            Block b = ServerUtils.getBlockAsync(predictedPosition.clone().add(new Vector(0, -0.2, 0)).toLocation(getWorld()));
793
            if(Hawk.getServerVersion() == 8 && !isSneaking() && b != null && b.getType() == Material.SLIME_BLOCK && move.getY() < 0) {
794
                predictedVelocity.setY(-move.getY());
795
            } else {
796
                predictedVelocity = clippedVel; //touched ground
797
            }
798
        }
799
        else {
800
            predictedVelocity = clippedVel; //air
801
        }
802
    }
803
804
    //Handles block AABB updates and teleportations to assist collision-based checks
805
    public void updateIgnoredBlockCollisions(Vector to, Vector from, boolean teleported) {
806
        final double expand = -0.0001; //TODO perhaps make this equal to NMS's margin to prevent bypasses via /sethome abuse?
807
        AABB bbox = WrappedEntity.getWrappedEntity(p).getCollisionBox(to);
808
        bbox.expand(expand, expand, expand);
809
810
        //handle teleportation INTO a block
811
        if(teleported) {
812
            AABB lastbbox = WrappedEntity.getWrappedEntity(p).getCollisionBox(from);
813
            lastbbox.expand(expand, expand, expand);
814
815
            //add new entries
816
            Set<Location> addIgnored = new HashSet<>();
817
            for(Block b : bbox.getBlocks(getWorld())) {
818
                for(AABB aabb : WrappedBlock.getWrappedBlock(b, getClientVersion()).getCollisionBoxes()) {
819
                    if(aabb.isColliding(bbox) && !aabb.isColliding(lastbbox)) { //Must enter an AABB. This patches a Phase bypass.
820
                        addIgnored.add(b.getLocation());
821
                        break;
822
                    }
823
                }
824
            }
825
826
            //remove old entries
827
            Set<Location> removeIgnored = new HashSet<>();
828
            for(Location loc : ignoredBlockCollisions) {
829
                Block b = ServerUtils.getBlockAsync(loc);
830
                if(b == null) {
831
                    removeIgnored.add(loc);
832
                    continue;
833
                }
834
835
                boolean colliding = false;
836
                for(AABB aabb : WrappedBlock.getWrappedBlock(b, getClientVersion()).getCollisionBoxes()) {
837
                    if(aabb.isColliding(bbox)) {
838
                        colliding = true;
839
                        break;
840
                    }
841
                }
842
843
                if(!colliding) {
844
                    removeIgnored.add(loc);
845
                }
846
            }
847
848
            ignoredBlockCollisions.removeAll(removeIgnored);
849
            ignoredBlockCollisions.addAll(addIgnored);
850
        }
851
852
        //handle AABB updates within player bounds
853
        //TODO Phase false when player moves out of block
854
        //TODO to fix concurrency issues with checks such as Phase, have these blocks/AABBs in this method copied and stored in a shared list in MoveEvent so that Phase can compare using the same block data
855
        else {
856
            Map<Location, List<AABB>> blocksInBBNew = new HashMap<>();
857
            for(Block b : bbox.getBlocks(getWorld())) {
858
                Location loc = b.getLocation();
859
                List<AABB> aabbs = Arrays.asList(WrappedBlock.getWrappedBlock(b, getClientVersion()).getCollisionBoxes());
860
                blocksInBBNew.put(loc, aabbs);
861
            }
862
863
            Map<Location, List<AABB>> blocksInBBOld = trackedBlockCollisions;
864
            Set<Location> ignored = new HashSet<>();
865
            for(Location entry : blocksInBBNew.keySet()) {
866
                if (blocksInBBOld.containsKey(entry) && !blocksInBBOld.get(entry).equals(blocksInBBNew.get(entry))) {
867
                    for(AABB aabb : blocksInBBNew.get(entry)) {
868
                        if(aabb.isColliding(bbox)) {
869
                            ignored.add(entry);
870
                            break;
871
                        }
872
                    }
873
                }
874
            }
875
876
            trackedBlockCollisions = blocksInBBNew;
877
            Set<Location> ignoredOld = ignoredBlockCollisions;
878
            for(Location loc : ignoredOld) {
879
                Block b = ServerUtils.getBlockAsync(loc);
880
                if(b == null)
881
                    continue;
882
                for(AABB aabb : WrappedBlock.getWrappedBlock(b, getClientVersion()).getCollisionBoxes()) {
883
                    if(aabb.isColliding(bbox)) {
884
                        ignored.add(loc);
885
                        break;
886
                    }
887
                }
888
            }
889
            ignoredBlockCollisions = ignored;
890
        }
891
    }
892
893
    //Get locations of blocks that had their AABB updated within the player's AABB
894
    public Set<Location> getIgnoredBlockCollisions() {
895
        return ignoredBlockCollisions;
896
    }
897
898
    public Set<Direction> getBoxSidesTouchingBlocks() {
899
        return boxSidesTouchingBlocks;
900
    }
901
902
    public Vector getWaterFlowForce() {
903
        return waterFlowForce;
904
    }
905
906
    public void setWaterFlowForce(Vector waterFlowForce) {
907
        this.waterFlowForce = waterFlowForce;
908
    }
909
910
    public long getLastMoveTick() {
911
        return lastMoveTick;
912
    }
913
914
    public long getClientTicksSinceLastMove() {
915
        return getCurrentTick() - lastMoveTick;
916
    }
917
918
    public void setHasMoved() {
919
        this.lastMoveTick = getCurrentTick();
920
    }
921
922
    public long getLastLandTick() {
923
        return lastLandTick;
924
    }
925
926
    public void updateLastLandTick() {
927
        this.lastLandTick = currentTick;
928
    }
929
930
    public List<Pair<Vector, Long>> getPendingVelocities() {
931
        return pendingVelocities;
932
    }
933
934
    public float getFriction() {
935
        return friction;
936
    }
937
938
    public void setFriction(float friction) {
939
        this.friction = friction;
940
    }
941
942
    //DO NOT USE THIS IN CHECKS. USE MoveEvent#isLiquidExit()
943
    public boolean isExitingLiquidTemp() {
944
        return liquidExit;
945
    }
946
947
    public void setLiquidExit(boolean liquidExit) {
948
        this.liquidExit = liquidExit;
949
    }
950
951
    //safely kill the connection
952
    public void kickPlayer(String reason) {
953
        online = false;
954
        Bukkit.getScheduler().scheduleSyncDelayedTask(hawk, () -> p.kickPlayer(reason), 0L);
955
    }
956
957
    //safely force player to release item (bow, consumable, or sword blocking)
958
    public void releaseItem() {
959
        Bukkit.getScheduler().scheduleSyncDelayedTask(hawk, () -> ((WrappedEntityHuman)WrappedEntity.getWrappedEntity(p)).releaseItem());
960
        sendSimulatedAction(() -> {
961
            setBlocking(false);
962
            setPullingBow(false);
963
            setConsumingItem(false);
964
        });
965
    }
966
967
    public void addPendingTeleport(Location loc) {
968
        pendingTeleports.add(new Pair<>(loc, currentTick));
969
        if(pendingTeleports.size() > 200) {
970
            pendingTeleports.remove(0);
971
        }
972
    }
973
974
    private void cleanUpOldPendingTeleports() {
975
        if(pendingTeleports.size() == 0)
976
            return;
977
        while(pendingTeleports.size() > 0 && currentTick - pendingTeleports.get(0).getValue() > (ping + 2000) / 50) {
978
            pendingTeleports.remove(0);
979
        }
980
    }
981
982
    public List<Pair<Location, Long>> getPendingTeleports() {
983
        return pendingTeleports;
984
    }
985
986
    //This method simulates the reaction of the client by a server packet.
987
    //This is accomplished by simulating latency.
988
    //This can be used to simulate sprint-update or inventory-open packets
989
    public void sendSimulatedAction(Runnable action) {
990
        simulatedCmds.add(new Pair<>(action, System.currentTimeMillis()));
991
    }
992
993
    private void executeTasks() {
994
        if(simulatedCmds.size() == 0)
995
            return;
996
        int ping = ServerUtils.getPing(p);
997
        long currTime = System.currentTimeMillis();
998
        while(simulatedCmds.size() > 0 && currTime - simulatedCmds.get(0).getValue() >= ping) {
999
            simulatedCmds.get(0).getKey().run();
1000
            simulatedCmds.remove(0);
1001
        }
1002
    }
1003
1004
    public void addMetaDataUpdate(MetaData metaData) {
1005
        metaDataUpdates.add(new Pair<>(metaData, System.currentTimeMillis()));
1006
        //in case something happens, let's not hog memory...
1007
        if(metaDataUpdates.size() > 200) {
1008
            metaDataUpdates.remove(0);
1009
        }
1010
    }
1011
1012
    public List<Pair<MetaData, Long>> getMetaDataUpdates() {
1013
        return metaDataUpdates;
1014
    }
1015
1016
    private void cleanUpOldMetaDataUpdates() {
1017
        if(metaDataUpdates.size() == 0)
1018
            return;
1019
        long currTime = System.currentTimeMillis();
1020
        while(metaDataUpdates.size() > 0 && currTime - metaDataUpdates.get(0).getValue() > ping + 2000) {
1021
            metaDataUpdates.remove(0);
1022
        }
1023
    }
1024
1025
    public Set<Entity> getEntitiesInteractedInThisTick() {
1026
        return entitiesInteractedInThisTick;
1027
    }
1028
1029
    public void addEntityToEntitiesInteractedInThisTick(Entity entity) {
1030
        entitiesInteractedInThisTick.add(entity);
1031
    }
1032
1033
    public AABB getCollisionBox() {
1034
        return WrappedEntity.getWrappedEntity(p).getCollisionBox(position);
1035
    }
1036
1037
    public AABB getHitBox() {
1038
        return WrappedEntity.getWrappedEntity(p).getHitbox(position);
1039
    }
1040
1041
    public int getClientVersion() {
1042
        return clientVersion;
1043
    }
1044
1045
    public void setClientVersion(int protocolVersion) {
1046
        clientVersion = protocolVersion == 47 ? 8 : 7;
1047
    }
1048
1049
    public boolean isInVehicle() {
1050
        return inVehicle;
1051
    }
1052
1053
    public void setInVehicle(boolean inVehicle) {
1054
        this.inVehicle = inVehicle;
1055
    }
1056
1057
    public int getItemConsumeTicks() {
1058
        return itemConsumeTicks;
1059
    }
1060
1061
    //Dedicated method for approximating whether a player is consuming or charging bow.
1062
    //Factors in meta-data updates sent from server. Damn it, Mojang. >:(
1063
    public boolean isConsumingOrPullingBowMetadataIncluded() {
1064
        boolean consumingOrBow = isConsumingItem() || isPullingBow();
1065
        long currTime = System.currentTimeMillis();
1066
        int ping = ServerUtils.getPing(p) + 100;
1067
        for(Pair<MetaData, Long> metaDataPair : getMetaDataUpdates()) {
1068
            //Ideally it would be +/-50ms leniency, but let's do +/-100ms just because of network jitter.
1069
            if(Math.abs(metaDataPair.getValue() + ping - currTime) < 100) {
1070
                MetaData metaData = metaDataPair.getKey();
1071
                if(metaData.getType() == MetaData.Type.USE_ITEM && !metaData.getValue()) {
1072
                    consumingOrBow = false;
1073
                    break;
1074
                }
1075
            }
1076
        }
1077
        return consumingOrBow;
1078
    }
1079
1080
    public boolean isAllowedToFly() {
1081
        return allowedToFly;
1082
    }
1083
1084
    public void setAllowedToFly(boolean allowedToFly) {
1085
        this.allowedToFly = allowedToFly;
1086
    }
1087
1088
    public boolean isFlying() {
1089
        return flying;
1090
    }
1091
1092
    public void setFlying(boolean flying) {
1093
        if(!isAllowedToFly() && flying)
1094
            return;
1095
        this.flying = flying;
1096
    }
1097
1098
    public boolean isInCreative() {
1099
        return inCreative;
1100
    }
1101
1102
    public void setInCreative(boolean inCreative) {
1103
        this.inCreative = inCreative;
1104
    }
1105
1106
    public boolean hasSentPosUpdate() {
1107
        return sentPosUpdate;
1108
    }
1109
1110
    public void setSentPosUpdate(boolean hasSentPosUpdate) {
1111
        this.sentPosUpdate = hasSentPosUpdate;
1112
    }
1113
1114
    public Location getAltSetbackLoc() {
1115
        return altSetbackLoc;
1116
    }
1117
1118
    public void setAltSetbackLoc(Location altSetbackLoc) {
1119
        this.altSetbackLoc = altSetbackLoc;
1120
    }
1121
}

How it counteracts this module

Hawk gates the client's flying claim on server-granted state. PacketConverter7 and PacketConverter8 convert every C13 into an AbilitiesEvent whose flying field is packet.isFlying() AND p.getAllowFlight() (PacketConverter7 line 277, PacketConverter8 line 306), so a flying claim is only recorded when the server has already granted allow flight. HawkPlayer.setFlying adds a second guard: if the player is not allowed to fly, the flying state is refused outright (HawkPlayer lines 1092-1096), and the server-side abilities handler keeps allowedToFly and inCreative synced from the S39 the server actually sent (HawkPlayer lines 171-173).

The module's per-tick C13 spam with isFlying true is therefore inert against Hawk: on a survival player the server never granted allow flight, so the claim never reaches Hawk's flying state, and every movement check that keys off pp.isFlying() (Fly, Speed, FastFall and the rest) keeps judging the player as a grounded survival player. The random 0.1-9.0 fly speed never factors in either, because Hawk's expected-speed math reads the server-side fly speed from the Bukkit player, not from the client's C13. The spoof cannot change what the server measured, so the disabler's only server-visible effect against Hawk is the extra C13 traffic itself.

anticheat PacketFrequency (global client-packet rate)

PacketFrequency.java79 lines · Java
1
/*
2
 * This program is free software: you can redistribute it and/or modify
3
 *   it under the terms of the GNU General Public License as published by
4
 *   the Free Software Foundation, either version 3 of the License, or
5
 *   (at your option) any later version.
6
 *
7
 *   This program is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU General Public License
13
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
14
 */
15
package fr.neatmonster.nocheatplus.checks.net;
16
17
import org.bukkit.entity.Player;
18
19
import fr.neatmonster.nocheatplus.checks.Check;
20
import fr.neatmonster.nocheatplus.checks.CheckType;
21
import fr.neatmonster.nocheatplus.utilities.TickTask;
22
23
/**
24
 * Fall-back check for pre 1.9: Limit the overall packet frequency, aiming at
25
 * crash exploits only. Thus the default actions should be kicking, as this
26
 * won't distinguish type of packets with the global packet count.
27
 * 
28
 * @author asofold
29
 *
30
 */
31
public class PacketFrequency extends Check {
32
33
    public PacketFrequency() {
34
        super(CheckType.NET_PACKETFREQUENCY);
35
    }
36
37
    /**
38
     * Actual state.
39
     * 
40
     * @param player
41
     * @param data
42
     *           
43
     * @param cc
44
     *            
45
     * @return If to cancel a packet event.
46
     */
47
    public boolean check(final Player player, final NetData data, final NetConfig cc) {
48
        data.packetFrequency.add(System.currentTimeMillis(), 1f);
49
        final long fDur = data.packetFrequency.bucketDuration() * data.packetFrequency.numberOfBuckets();
50
        double amount = data.packetFrequency.score(1f) * 1000f / (float) fDur;
51
        //        if (data.debug) {
52
        //            debug(player, "Basic amount: " + amount);
53
        //        }
54
        if (amount > cc.packetFrequencyPacketsPerSecond) {
55
            amount /= TickTask.getLag(fDur);
56
            if (amount > cc.packetFrequencyPacketsPerSecond) {
57
                if (executeActions(player, amount - cc.packetFrequencyPacketsPerSecond, 1.0, cc.packetFrequencyActions).willCancel()) {
58
                    return true;
59
                }
60
            }
61
        }
62
        return false; // Cancel state.
63
    }
64
65
    /**
66
     * Allow to relax the count by 1, e.g. with outgoing teleport.
67
     * 
68
     * @param player
69
     * @param data
70
     * 
71
     * @param cc
72
     * 
73
     * @return
74
     */
75
    public void relax(final Player player, final NetData data, final NetConfig cc) {
76
        // TODO: Concept (not more locking, instead a counter (optimistic)).
77
    }
78
79
}

How it counteracts this module

NCP's CatchAllAdapter (NCPCompatProtocolLib, checks/net/protocollib/CatchAllAdapter.java) subscribes to every Play.Client packet type at LOWEST priority and runs packetFrequency.check on each one, scoring every incoming client packet into data.packetFrequency and comparing the per-second rate against packetFrequencyPacketsPerSecond, default 300 (DefaultConfig line 569, with the comment noting legit 1.8 clients can reach 200). A violation cancels the packet (PacketFrequency lines 47-63, CatchAllAdapter lines 70-92).

This is the only ledger among NCP, Arc v2 and Hawk that counts the module's traffic at all: none of the three parse C0F content, so the delayed-confirmation technique itself is unopposed by this pool. What the ledger does see is the volume. The on-disable flush replays the entire C0F backlog in one tick, and with the Fly module enabled the abilities spam doubles to two C13s per tick; a long session with heavy window interaction can accumulate a backlog large enough that the flush registers as a multi-hundred-packet second, approaching the 300/s ceiling that is otherwise only reached by crash-flood clients. The default actions escalate to a kick, which turns the module's own clean-up routine into its most detectable moment.

← Back to Analysis Hub