/
DenizenNetworkManagerImpl.java
516 lines (472 loc) · 23.2 KB
/
DenizenNetworkManagerImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
package com.denizenscript.denizen.nms.v1_14.impl.packets.handlers;
import com.denizenscript.denizen.nms.v1_14.impl.ProfileEditorImpl;
import com.denizenscript.denizen.nms.v1_14.impl.packets.*;
import com.denizenscript.denizen.nms.v1_14.impl.blocks.BlockLightImpl;
import com.denizenscript.denizen.nms.v1_14.impl.entities.EntityFakePlayerImpl;
import com.denizenscript.denizen.nms.interfaces.packets.PacketHandler;
import com.denizenscript.denizen.nms.interfaces.packets.PacketOutSpawnEntity;
import com.denizenscript.denizen.objects.LocationTag;
import com.denizenscript.denizen.utilities.blocks.ChunkCoordinate;
import com.denizenscript.denizen.utilities.blocks.FakeBlock;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import com.denizenscript.denizen.nms.NMSHandler;
import com.denizenscript.denizen.nms.util.ReflectionHelper;
import com.denizenscript.denizencore.utilities.debugging.Debug;
import net.minecraft.server.v1_14_R1.*;
import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_14_R1.block.data.CraftBlockData;
import org.bukkit.craftbukkit.v1_14_R1.entity.CraftPlayer;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import javax.crypto.SecretKey;
import java.lang.invoke.MethodHandle;
import java.lang.reflect.Field;
import java.net.SocketAddress;
import java.util.UUID;
public class DenizenNetworkManagerImpl extends NetworkManager {
public final NetworkManager oldManager;
public final DenizenPacketListenerImpl packetListener;
public final EntityPlayer player;
public final PacketHandler packetHandler;
public DenizenNetworkManagerImpl(EntityPlayer entityPlayer, NetworkManager oldManager, PacketHandler packetHandler) {
super(getProtocolDirection(oldManager));
this.oldManager = oldManager;
this.channel = oldManager.channel;
this.packetListener = new DenizenPacketListenerImpl(this, entityPlayer);
oldManager.setPacketListener(packetListener);
this.player = this.packetListener.player;
this.packetHandler = packetHandler;
}
public static void setNetworkManager(Player player, PacketHandler packetHandler) {
EntityPlayer entityPlayer = ((CraftPlayer) player).getHandle();
PlayerConnection playerConnection = entityPlayer.playerConnection;
setNetworkManager(playerConnection, new DenizenNetworkManagerImpl(entityPlayer, playerConnection.networkManager, packetHandler));
}
@Override
public void channelActive(ChannelHandlerContext channelhandlercontext) throws Exception {
oldManager.channelActive(channelhandlercontext);
}
@Override
public void setProtocol(EnumProtocol enumprotocol) {
oldManager.setProtocol(enumprotocol);
}
@Override
public void channelInactive(ChannelHandlerContext channelhandlercontext) throws Exception {
oldManager.channelInactive(channelhandlercontext);
}
@Override
public void exceptionCaught(ChannelHandlerContext channelhandlercontext, Throwable throwable) {
oldManager.exceptionCaught(channelhandlercontext, throwable);
}
@Override
protected void channelRead0(ChannelHandlerContext channelhandlercontext, Packet packet) throws Exception { // TODO: Check mapping update. Previously overrode 'a', and channelRead0 was overriden separately.
if (oldManager.channel.isOpen()) {
try {
packet.a(this.packetListener);
}
catch (Exception e) {
// Do nothing
//dB.echoError(e);
}
}
}
@Override
public void setPacketListener(PacketListener packetlistener) {
oldManager.setPacketListener(packetlistener);
}
public static Field ENTITY_ID_PACKENT = ReflectionHelper.getFields(PacketPlayOutEntity.class).get("a");
public static Field ENTITY_ID_PACKVELENT = ReflectionHelper.getFields(PacketPlayOutEntityVelocity.class).get("a");
public static Field ENTITY_ID_PACKTELENT = ReflectionHelper.getFields(PacketPlayOutEntityTeleport.class).get("a");
public static Field POS_X_PACKTELENT = ReflectionHelper.getFields(PacketPlayOutEntityTeleport.class).get("b");
public static Field POS_Y_PACKTELENT = ReflectionHelper.getFields(PacketPlayOutEntityTeleport.class).get("c");
public static Field POS_Z_PACKTELENT = ReflectionHelper.getFields(PacketPlayOutEntityTeleport.class).get("d");
public static Field POS_X_PACKENT = ReflectionHelper.getFields(PacketPlayOutEntity.class).get("b");
public static Field POS_Y_PACKENT = ReflectionHelper.getFields(PacketPlayOutEntity.class).get("c");
public static Field POS_Z_PACKENT = ReflectionHelper.getFields(PacketPlayOutEntity.class).get("d");
public static Field BLOCKPOS_BLOCKCHANGE = ReflectionHelper.getFields(PacketPlayOutBlockChange.class).get("a");
public static Field CHUNKCOORD_MULTIBLOCKCHANGE = ReflectionHelper.getFields(PacketPlayOutMultiBlockChange.class).get("a");
public static Field INFOARRAY_MULTIBLOCKCHANGE = ReflectionHelper.getFields(PacketPlayOutMultiBlockChange.class).get("b");
public static Object duplo(Object a) {
try {
Class clazz = a.getClass();
Object reter = clazz.newInstance();
for (Field f : clazz.getDeclaredFields()) {
f.setAccessible(true);
f.set(reter, f.get(a));
}
Class subc = clazz;
while (subc.getSuperclass() != null) {
subc = subc.getSuperclass();
for (Field f : subc.getDeclaredFields()) {
f.setAccessible(true);
f.set(reter, f.get(a));
}
}
return reter;
}
catch (Exception e) {
Debug.echoError(e);
return null;
}
}
@Override
public void sendPacket(Packet<?> packet) {
sendPacket(packet, null);
}
@Override
public void sendPacket(Packet<?> packet, GenericFutureListener<? extends Future<? super Void>> genericfuturelistener) {
if (NMSHandler.debugPackets) {
Debug.log("Packet: " + packet.getClass().getCanonicalName() + " sent to " + player.getName());
}
if (processAttachToForPacket(packet)
|| processHiddenEntitiesForPacket(packet)
|| processPacketHandlerForPacket(packet)) {
return;
}
processMirrorForPacket(packet);
processShowFakeForPacket(packet);
processBlockLightForPacket(packet);
oldManager.sendPacket(packet, genericfuturelistener);
}
public boolean isAttached(Entity e) {
UUID attached = NMSHandler.getInstance().attachmentsA.get(e.getUniqueID());
return attached != null && attached.equals(player.getUniqueID());
}
public boolean processAttachToForPacket(Packet<?> packet) {
try {
if (packet instanceof PacketPlayOutEntity) {
int ider = ENTITY_ID_PACKENT.getInt(packet);
Entity e = player.getWorld().getEntity(ider);
if (e == null) {
return false;
}
UUID att = NMSHandler.getInstance().attachments2.get(e.getUniqueID());
if (att != null) {
org.bukkit.entity.Entity target = Bukkit.getEntity(att);
if (target != null) {
Packet pNew = (Packet) duplo(packet);
ENTITY_ID_PACKENT.setInt(pNew, target.getEntityId());
Vector offset = NMSHandler.getInstance().attachmentOffsets.get(att);
if (offset != null && (packet instanceof PacketPlayOutEntity.PacketPlayOutRelEntityMove || packet instanceof PacketPlayOutEntity.PacketPlayOutRelEntityMoveLook)) {
boolean rotationBasis = NMSHandler.getInstance().attachmentRotations.contains(att);
Vector goalPosition;
if (!rotationBasis) {
goalPosition = new Vector(e.locX, e.locY, e.locZ).add(offset);
}
else {
goalPosition = new Vector(e.locX, e.locY, e.locZ).add(NMSHandler.fixOffset(offset, -e.yaw, e.pitch));
}
Vector oldPos = NMSHandler.getInstance().visiblePositions.get(target.getUniqueId());
if (oldPos == null) {
oldPos = target.getLocation().toVector();
}
Vector moveNeeded = goalPosition.clone().subtract(oldPos);
NMSHandler.getInstance().visiblePositions.put(target.getUniqueId(), goalPosition.clone());
int offX = (int) (moveNeeded.getX() * (32 * 128));
int offY = (int) (moveNeeded.getY() * (32 * 128));
int offZ = (int) (moveNeeded.getZ() * (32 * 128));
if (offX < Short.MIN_VALUE || offX > Short.MAX_VALUE
|| offY < Short.MIN_VALUE || offY > Short.MAX_VALUE
|| offZ < Short.MIN_VALUE || offZ > Short.MAX_VALUE) {
PacketPlayOutEntityTeleport newTeleportPacket = new PacketPlayOutEntityTeleport(e);
ENTITY_ID_PACKTELENT.setInt(newTeleportPacket, target.getEntityId());
POS_X_PACKTELENT.setDouble(newTeleportPacket, goalPosition.getX());
POS_Y_PACKTELENT.setDouble(newTeleportPacket, goalPosition.getY());
POS_Z_PACKTELENT.setDouble(newTeleportPacket, goalPosition.getZ());
oldManager.sendPacket(newTeleportPacket);
return true;
}
POS_X_PACKENT.setInt(pNew, MathHelper.clamp(offX, Short.MIN_VALUE, Short.MAX_VALUE));
POS_Y_PACKENT.setInt(pNew, MathHelper.clamp(offY, Short.MIN_VALUE, Short.MAX_VALUE));
POS_Z_PACKENT.setInt(pNew, MathHelper.clamp(offZ, Short.MIN_VALUE, Short.MAX_VALUE));
}
oldManager.sendPacket(pNew);
return true;
}
}
return isAttached(e);
}
else if (packet instanceof PacketPlayOutEntityVelocity) {
int ider = ENTITY_ID_PACKVELENT.getInt(packet);
Entity e = player.getWorld().getEntity(ider);
if (e == null) {
return false;
}
UUID att = NMSHandler.getInstance().attachments2.get(e.getUniqueID());
if (att != null) {
org.bukkit.entity.Entity target = Bukkit.getEntity(att);
if (target != null) {
Packet pNew = (Packet) duplo(packet);
ENTITY_ID_PACKVELENT.setInt(pNew, target.getEntityId());
oldManager.sendPacket(pNew);
return true;
}
}
return isAttached(e);
}
else if (packet instanceof PacketPlayOutEntityTeleport) {
int ider = ENTITY_ID_PACKTELENT.getInt(packet);
Entity e = player.getWorld().getEntity(ider);
if (e == null) {
return false;
}
UUID att = NMSHandler.getInstance().attachments2.get(e.getUniqueID());
if (att != null) {
org.bukkit.entity.Entity target = Bukkit.getEntity(att);
if (target != null) {
Packet pNew = (Packet) duplo(packet);
ENTITY_ID_PACKTELENT.setInt(pNew, target.getEntityId());
Vector offset = NMSHandler.getInstance().attachmentOffsets.get(att);
Vector resultPos = new Vector(POS_X_PACKTELENT.getDouble(pNew), POS_Y_PACKTELENT.getDouble(pNew), POS_Z_PACKTELENT.getDouble(pNew));
if (offset != null) {
boolean rotationBasis = NMSHandler.getInstance().attachmentRotations.contains(att);
Vector goalOffset;
if (!rotationBasis) {
goalOffset = offset;
}
else {
goalOffset = NMSHandler.fixOffset(offset, -e.yaw, e.pitch);
}
POS_X_PACKTELENT.setDouble(pNew, POS_X_PACKTELENT.getDouble(pNew) + goalOffset.getX());
POS_Y_PACKTELENT.setDouble(pNew, POS_Y_PACKTELENT.getDouble(pNew) + goalOffset.getY());
POS_Z_PACKTELENT.setDouble(pNew, POS_Z_PACKTELENT.getDouble(pNew) + goalOffset.getZ());
resultPos.add(goalOffset);
}
NMSHandler.getInstance().visiblePositions.put(target.getUniqueId(), resultPos);
oldManager.sendPacket(pNew);
return true;
}
}
return isAttached(e);
}
}
catch (Exception ex) {
Debug.echoError(ex);
}
return false;
}
public boolean isHidden(Entity entity) {
return e != null && NMSHandler.getEntityHelper().isHidden(player.getBukkitEntity(), entity.getBukkitEntity());
}
public boolean processHiddenEntitiesForPacket(Packet<?> packet) {
try {
if (packet instanceof PacketPlayOutNamedEntitySpawn
|| packet instanceof PacketPlayOutSpawnEntity
|| packet instanceof PacketPlayOutSpawnEntityLiving
|| packet instanceof PacketPlayOutSpawnEntityPainting
|| packet instanceof PacketPlayOutSpawnEntityExperienceOrb) {
PacketOutSpawnEntity spawnEntity = new PacketOutSpawnEntityImpl(player, packet);
Entity entity = player.getWorld().getEntity(spawnEntity.getEntityId());
if (isHidden(entity)) {
return true;
}
processFakePlayerSpawn(entity);
}
if (packet instanceof PacketPlayOutEntity) {
int ider = ENTITY_ID_PACKENT.getInt(packet);
Entity e = player.getWorld().getEntity(ider);
if (isHidden(e)) {
return true;
}
}
else if (packet instanceof PacketPlayOutEntityVelocity) {
int ider = ENTITY_ID_PACKVELENT.getInt(packet);
Entity e = player.getWorld().getEntity(ider);
if (isHidden(e)) {
return true;
}
}
else if (packet instanceof PacketPlayOutEntityTeleport) {
int ider = ENTITY_ID_PACKTELENT.getInt(packet);
Entity e = player.getWorld().getEntity(ider);
if (isHidden(e)) {
return true;
}
}
}
catch (Exception ex) {
Debug.echoError(ex);
}
return false;
}
public void processFakePlayerSpawn(Entity entity) {
if (entity instanceof EntityFakePlayerImpl) {
final EntityFakePlayerImpl fakePlayer = (EntityFakePlayerImpl) entity;
sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, fakePlayer));
Bukkit.getScheduler().runTaskLater(NMSHandler.getJavaPlugin(),
() -> sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.REMOVE_PLAYER, fakePlayer)), 5);
}
}
public void processMirrorForPacket(Packet<?> packet) {
if (packet instanceof PacketPlayOutPlayerInfo) {
PacketPlayOutPlayerInfo playerInfo = (PacketPlayOutPlayerInfo) packet;
if (ProfileEditorImpl.handleMirrorProfiles(playerInfo, this)) {
ProfileEditorImpl.updatePlayerProfiles(playerInfo);
oldManager.sendPacket(playerInfo);
}
}
}
public boolean processPacketHandlerForPacket(Packet<?> packet) {
if (packet instanceof PacketPlayOutChat) {
return packetHandler.sendPacket(player.getBukkitEntity(), new PacketOutChatImpl((PacketPlayOutChat) packet));
}
else if (packet instanceof PacketPlayOutEntityMetadata) {
return packetHandler.sendPacket(player.getBukkitEntity(), new PacketOutEntityMetadataImpl((PacketPlayOutEntityMetadata) packet));
}
else if (packet instanceof PacketPlayOutSetSlot) {
return packetHandler.sendPacket(player.getBukkitEntity(), new PacketOutSetSlotImpl((PacketPlayOutSetSlot) packet));
}
else if (packet instanceof PacketPlayOutWindowItems) {
return packetHandler.sendPacket(player.getBukkitEntity(), new PacketOutWindowItemsImpl((PacketPlayOutWindowItems) packet));
}
else if (packet instanceof PacketPlayOutOpenWindowMerchant) {
return packetHandler.sendPacket(player.getBukkitEntity(), new PacketOutTradeListImpl((PacketPlayOutOpenWindowMerchant) packet));
}
return false;
}
public IBlockData getNMSState(FakeBlock block) {
return ((CraftBlockData) block.material.getModernData().data).getState();
}
public void processShowFakeForPacket(Packet<?> packet) {
try {
if (packet instanceof PacketPlayOutMapChunk) {
}
else if (packet instanceof PacketPlayOutMultiBlockChange) {
FakeBlock.FakeBlockMap map = FakeBlock.blocks.get(player.getUniqueID());
if (map == null) {
return;
}
ChunkCoordIntPair coord = (ChunkCoordIntPair) CHUNKCOORD_MULTIBLOCKCHANGE.get(packet);
ChunkCoordinate coordinateDenizen = new ChunkCoordinate(coord.x, coord.z, player.getWorld().getWorld().getName());
if (!map.byChunk.containsKey(coordinateDenizen)) {
return;
}
LocationTag location = new LocationTag(player.getWorld().getWorld(), 0, 0, 0);
PacketPlayOutMultiBlockChange.MultiBlockChangeInfo[] changeArr = (PacketPlayOutMultiBlockChange.MultiBlockChangeInfo[]) INFOARRAY_MULTIBLOCKCHANGE.get(packet);
for (int i = 0; i < changeArr.length; i++) {
short blockInd = changeArr[i].b();
int x = blockInd & 0xF0;
int y = (blockInd & 0x00FF) >> 8;
int z = (blockInd & 0X0F) >> 4;
location.setX((coord.x << 4) + x);
location.setY(y);
location.setZ((coord.z << 4) + z);
FakeBlock block = map.byLocation.get(location);
if (block != null) {
changeArr[i] = ((PacketPlayOutMultiBlockChange) packet).new MultiBlockChangeInfo(blockInd, getNMSState(block));
}
}
}
else if (packet instanceof PacketPlayOutBlockChange) {
BlockPosition pos = (BlockPosition) BLOCKPOS_BLOCKCHANGE.get(packet);
LocationTag loc = new LocationTag(player.getWorld().getWorld(), pos.getX(), pos.getY(), pos.getZ());
FakeBlock block = FakeBlock.getFakeBlockFor(player.getUniqueID(), loc);
if (block != null) {
((PacketPlayOutBlockChange) packet).block = getNMSState(block);
}
}
}
catch (Exception ex) {
Debug.echoError(ex);
}
}
public void processBlockLightForPacket(Packet<?> packet) {
if (packet instanceof PacketPlayOutLightUpdate) {
BlockLightImpl.checkIfLightsBrokenByPacket((PacketPlayOutLightUpdate) packet, player.world);
}
else if (packet instanceof PacketPlayOutBlockChange) {
BlockLightImpl.checkIfLightsBrokenByPacket((PacketPlayOutBlockChange) packet, player.world);
}
}
@Override
public void a() {
oldManager.a();
}
@Override
public SocketAddress getSocketAddress() {
return oldManager.getSocketAddress();
}
@Override
public void close(IChatBaseComponent ichatbasecomponent) {
oldManager.close(ichatbasecomponent);
}
@Override
public boolean isLocal() {
return oldManager.isLocal();
}
@Override
public void a(SecretKey secretkey) {
oldManager.a(secretkey);
}
@Override
public boolean isConnected() {
return oldManager.isConnected();
}
@Override
public boolean h() {
return oldManager.h();
}
@Override
public PacketListener i() {
return oldManager.i();
}
@Override
public IChatBaseComponent j() {
return oldManager.j();
}
@Override
public void stopReading() {
oldManager.stopReading();
}
@Override
public void setCompressionLevel(int i) {
oldManager.setCompressionLevel(i);
}
@Override
public void handleDisconnection() {
oldManager.handleDisconnection();
}
@Override
public SocketAddress getRawAddress() {
return oldManager.getRawAddress();
}
//////////////////////////////////
//// Reflection Methods/Fields
///////////
private static final Field protocolDirectionField;
private static final MethodHandle networkManagerField;
static {
Field directionField = null;
MethodHandle managerField = null;
try {
directionField = NetworkManager.class.getDeclaredField("h");
directionField.setAccessible(true);
managerField = ReflectionHelper.getFinalSetter(PlayerConnection.class, "networkManager");
}
catch (Exception e) {
Debug.echoError(e);
}
protocolDirectionField = directionField;
networkManagerField = managerField;
}
private static EnumProtocolDirection getProtocolDirection(NetworkManager networkManager) {
EnumProtocolDirection direction = null;
try {
direction = (EnumProtocolDirection) protocolDirectionField.get(networkManager);
}
catch (Exception e) {
Debug.echoError(e);
}
return direction;
}
private static void setNetworkManager(PlayerConnection playerConnection, NetworkManager networkManager) {
try {
networkManagerField.invoke(playerConnection, networkManager);
}
catch (Throwable ex) {
Debug.echoError(ex);
}
}
}