/** * Find a packet class by case-insensitive substring of the class name. * If multiple packets match, the shortest name wins. */ public static @Nullable Class<?> findPacketType(String name) { int minExtra = Integer.MAX_VALUE; Class<? extends Packet> best = null; name = name.toLowerCase(); for(Class<? extends Packet> type : packets) { if(type.getName().toLowerCase().contains(name)) { int extra = type.getName().length() - name.length(); if(extra < minExtra) { best = type; minExtra = extra; } else if(extra == minExtra) { best = null; } } } return best; }
@Override protected void encode(ChannelHandlerContext context, Packet packet, ByteBuf buffer) throws Exception { final NetworkManager networkManager = context.pipeline().get(NetworkManager.class); final Integer id = context.channel().attr(NetworkManager.c).get().a(EnumProtocolDirection.CLIENTBOUND, packet, networkManager.protocolVersion); if (id == null) { throw new IOException("Cannot encode unregistered packet class " + packet.getClass()); } else { try { final PacketTracer dumper = new PacketTracer(buffer, logger, client); dumper.d(id); // write VarInt packet.b(dumper); // write packet dumper.packet(">>>", id, packet); } catch (Throwable e) { logger.log(Level.SEVERE, "Exception writing " + packet.getClass().getSimpleName(), e); } } }
@Override protected void decode(ChannelHandlerContext context, ByteBuf buffer, List<Object> messages) throws Exception { if(buffer.readableBytes() > 0) { final PacketTracer dumper = new PacketTracer(buffer, logger, client); final int id = dumper.g(); // read VarInt final NetworkManager networkManager = context.pipeline().get(NetworkManager.class); final Packet packet = context.channel().attr(NetworkManager.c).get().a(EnumProtocolDirection.SERVERBOUND, id, networkManager.protocolVersion); if (packet == null) { throw new IOException("Cannot decode unregistered packet ID " + id); } else { packet.a(dumper); // read packet if (dumper.readableBytes() > 0) { throw new IOException(dumper.readableBytes() + " extra bytes after reading packet " + packet.getClass().getSimpleName()); } else { messages.add(packet); dumper.packet("<<<", id, packet); } } } }
public static Packet teamPacket(int operation, String name, String displayName, String prefix, String suffix, boolean friendlyFire, boolean seeFriendlyInvisibles, String nameTagVisibility, String collisionRule, Collection<String> players) { int flags = 0; if(friendlyFire) { flags |= 1; } if(seeFriendlyInvisibles) { flags |= 2; } return new PacketPlayOutScoreboardTeam(operation, name, displayName, prefix, suffix, 0, // color nameTagVisibility, collisionRule, flags, players); }
/** * processPackets. Remove up to 1000 packets from the queue and process * them. This method should only be called from the main server thread. */ public void b() { for ( int i = 1000; !syncPackets.isEmpty() && i >= 0; i-- ) { if ( connection instanceof PendingConnection ? ( (PendingConnection) connection ).b : ( (PlayerConnection) connection ).disconnected ) { syncPackets.clear(); break; } Packet packet = PacketListener.callReceived( this, connection, syncPackets.poll() ); if ( packet != null ) { packet.handle( connection ); } } // Disconnect via the handler - this performs all plugin related cleanup + logging if ( !connected && ( dcReason != null || dcArgs != null ) ) { connection.a( dcReason, dcArgs ); } }
private void playDeathAnimation(final Player player) { Bukkit.getScheduler().scheduleSyncDelayedTask(Cardinal.getInstance(), new Runnable() { @Override public void run() { EntityPlayer nmsPlayer = ((CraftPlayer) player).getHandle(); List<Packet> packets = new ArrayList<>(); for (EnumItemSlot slot : EnumItemSlot.values()) { packets.add(new PacketPlayOutEntityEquipment(nmsPlayer.getId(), slot, net.minecraft.server.ItemStack.a)); // Removes armor, otherwise, a client-side glitch makes items } packets.add(PacketUtils.createMetadataPacket(nmsPlayer.getId(), Watchers.getHealth(0))); packets.add(new PacketPlayOutEntityStatus(nmsPlayer, (byte) 3)); for (Player online : Bukkit.getOnlinePlayers()) { if (!online.equals(player)){ for (Packet packet : packets) { PacketUtils.sendPacket(online, packet); } } } } }, 1L); }
public void sendSpawnPackets(Player viewer) { if (viewers.contains(viewer.getUniqueId())) return; Player player = Bukkit.getPlayer(this.player); Location loc = player.getLocation(); int i = 0; for (int x = -1; x < 2; x += 2) { for (int z = -1; z < 2; z += 2) { Packet spawnPacket = new PacketPlayOutSpawnEntityLiving( zombieID.get(i++), UUID.randomUUID(), 54, // Entity id, UUID, and type (Zombie) loc.getX() + (x * DamageIndicator.OFFSET), loc.getY(),// X, Y loc.getZ() + (z * DamageIndicator.OFFSET), // and Z coords 0, 0, 0, // X, Y and Z Motion (byte) 2, (byte) 0, (byte) 2, // Yaw, Pitch and Head Pitch Watchers.toList(Watchers.INVISIBLE)); // Metadata PacketUtils.sendPacket(viewer, spawnPacket); } } viewers.add(viewer.getUniqueId()); }
private void spawnSnowflakes(Player player, int count) { count = Math.min(12, Math.max(2, count)); int[] entities = new int[count]; List<Packet> packets = Lists.newArrayList(); Vector loc = player.getLocation().position().plus(0, 2, 0); for (int i = 0; i < count; i++) { int id = Bukkit.allocateEntityId(); entities[i] = id; int motX = (int) ((float) (Math.random() * 0.20000000298023224D - 0.10000000149011612D) * 8000), motY = (int) (0.2D * 8000), motZ = (int) ((float) (Math.random() * 0.20000000298023224D - 0.10000000149011612D) * 8000); packets.add(new PacketPlayOutSpawnEntity( id, UUID.randomUUID(), // Entity id and Entity UUID loc.getX(), loc.getY(), loc.getZ(),// X, Y and Z Position motX, motY, motZ, // X, Y and Z Motion (byte) 2, (byte) 0, // Pitch, Yaw 2, 0 // Type and data )); packets.add(PacketUtils.createMetadataPacket(id, Watchers.toList(Watchers.SNOWFLAKE))); } for (Packet packet : packets) PacketUtils.sendPacket(player, packet); scheduleSnowflakeRemove(player, entities); }
public static Packet teamCreatePacket(String name, String displayName, String prefix, String suffix, boolean friendlyFire, boolean seeFriendlyInvisibles, String nameTagVisibility, String collisionRule, Collection<String> players) { return teamPacket(0, name, displayName, prefix, suffix, friendlyFire, seeFriendlyInvisibles, nameTagVisibility, collisionRule, players); }
public static Packet teamCreatePacket(String name, String displayName, String prefix, String suffix, boolean friendlyFire, boolean seeFriendlyInvisibles, Collection<String> players) { return teamCreatePacket(name, displayName, prefix, suffix, friendlyFire, seeFriendlyInvisibles, "always", "always", players); }
public static Packet spawnEntityPacket(Class<? extends Entity> type, int data, int entityId, UUID uuid, Location location, Vector velocity) { checkArgument(ENTITY_TYPE_IDS.containsKey(type)); return new PacketPlayOutSpawnEntity(entityId, uuid, location.getX(), location.getY(), location.getZ(), encodeVelocity(velocity.getX()), encodeVelocity(velocity.getY()), encodeVelocity(velocity.getZ()), encodeAngle(location.getPitch()), encodeAngle(location.getYaw()), ENTITY_TYPE_IDS.get(type), data); }
public static Packet spawnPlayerPacket(int entityId, UUID uuid, Location location, Player player) { return new PacketPlayOutNamedEntitySpawn(entityId, uuid, location.getX(), location.getY(), location.getZ(), encodeAngle(location.getYaw()), encodeAngle(location.getPitch()), copyEntityMetadata(player)); }
public static Packet spawnPlayerPacket(int entityId, UUID uuid, Location location, List<DataWatcher.Item<?>> metadata) { return new PacketPlayOutNamedEntitySpawn(entityId, uuid, location.getX(), location.getY(), location.getZ(), encodeAngle(location.getYaw()), encodeAngle(location.getPitch()), metadata); }
public static Packet moveEntityRelativePacket(int entityId, Vector delta, boolean onGround) { return new PacketPlayOutEntity.PacketPlayOutRelEntityMove(entityId, encodePosition(delta.getX()), encodePosition(delta.getY()), encodePosition(delta.getZ()), onGround); }
public static Packet teleportEntityPacket(int entityId, Location location) { return new PacketPlayOutEntityTeleport(entityId, location.getX(), location.getY(), location.getZ(), encodeAngle(location.getYaw()), encodeAngle(location.getPitch()), true); }
public void finish() { if(!this.removePacket.isEmpty()) this.send(this.removePacket); if(!this.addPacket.isEmpty()) this.send(this.addPacket); if(!this.updatePacket.isEmpty()) this.send(this.updatePacket); for(Packet packet : this.deferredPackets) { this.send(packet); } }
static Packet callReceived(INetworkManager networkManager, Connection connection, Packet packet) { for ( PacketListener listener : baked ) { try { packet = listener.packetReceived( networkManager, connection, packet ); } catch ( Throwable t ) { Bukkit.getServer().getLogger().log( Level.SEVERE, "Error whilst firing receive hook for packet", t ); } } return packet; }
static Packet callQueued(INetworkManager networkManager, Connection connection, Packet packet) { for ( PacketListener listener : baked ) { try { packet = listener.packetQueued( networkManager, connection, packet ); } catch ( Throwable t ) { Bukkit.getServer().getLogger().log( Level.SEVERE, "Error whilst firing queued hook for packet", t ); } } return packet; }
@Override protected void channelRead0(ChannelHandlerContext ctx, final Packet msg) throws Exception { if ( connected ) { if ( msg instanceof Packet252KeyResponse ) { secret = ( (Packet252KeyResponse) msg ).a( key ); Cipher decrypt = NettyServerConnection.getCipher( Cipher.DECRYPT_MODE, secret ); channel.pipeline().addBefore( "decoder", "decrypt", new CipherDecoder( decrypt ) ); } if ( msg.a_() ) { threadPool.submit( new Runnable() { public void run() { Packet packet = PacketListener.callReceived( NettyNetworkManager.this, connection, msg ); if ( packet != null ) { packet.handle( connection ); } } } ); } else { syncPackets.add( msg ); } } }
/** * queue. Queue a packet for sending, or in this case send it to be write it * straight to the channel. * * @param packet the packet to queue */ public void queue(final Packet packet) { // Only send if channel is still connected if ( connected ) { // Process packet via handler final Packet packet0 = PacketListener.callQueued( this, connection, packet ); highPriorityQueue.add( packet0 ); // If handler indicates packet send if ( packet0 != null ) { if ( channel.eventLoop().inEventLoop() ) { queue0( packet0 ); } else { channel.eventLoop().execute( new Runnable() { public void run() { queue0( packet0 ); } } ); } } } }
private void queue0(Packet packet) { if ( packet instanceof Packet255KickDisconnect ) { writer.lastFlush = 0; } writer.write( channel, this, packet ); if ( packet instanceof Packet252KeyResponse ) { Cipher encrypt = NettyServerConnection.getCipher( Cipher.ENCRYPT_MODE, secret ); channel.pipeline().addBefore( "decoder", "encrypt", new CipherEncoder( encrypt ) ); } }
public void teleportBoundingBox(Vector to, boolean onGround) { int i = 0; for (int x = -1; x < 2; x += 2) { for (int z = -1; z < 2; z += 2) { Packet teleportPacket = new PacketPlayOutEntityTeleport(zombieID.get(i), to.getX() + (x * DamageIndicator.OFFSET), to.getY() , to.getZ() + (z * DamageIndicator.OFFSET), (byte) 2, (byte) 0, onGround); PacketUtils.broadcastPacketByUUID(teleportPacket, viewers); i++; } } }
private void sendSlotPackets(Player player, boolean set) { PacketPlayOutScoreboardScore.EnumScoreboardAction action = set ? PacketPlayOutScoreboardScore.EnumScoreboardAction.CHANGE : PacketPlayOutScoreboardScore.EnumScoreboardAction.REMOVE; Packet blankSlot = getScoreboardPacket("", -1, action); Packet scoreSlot = getScoreboardPacket(ChatColor.WHITE + " D:" + ChatColor.RED, -2, action); PacketUtils.sendPacket(player, blankSlot); PacketUtils.sendPacket(player, scoreSlot); }
public static void fakeDelta(Player observer, Player victim, Vector delta) { Packet packet = new PacketPlayOutEntity.PacketPlayOutRelEntityMove(((CraftPlayer) victim).getHandle().getId(), (byte) (delta.getX() * 32), (byte) (delta.getY() * 32), (byte) (delta.getZ() * 32), false /* on ground */); sendPacket((CraftPlayer) observer, packet); }
private static void sendPacket(CraftPlayer player, Packet packet) { player.getHandle().playerConnection.sendPacket(packet); }
/** * Include or exclude the given packet class from tracing */ public static void filter(Class<?> type, boolean include) { filter.put(type.asSubclass(Packet.class), include); }
public static void sendPacket(Player bukkitPlayer, Object packet) { if (bukkitPlayer.isOnline()) { EntityPlayer nmsPlayer = ((CraftPlayer) bukkitPlayer).getHandle(); nmsPlayer.playerConnection.sendPacket((Packet) packet); } }
private static void sendPacketToViewers(Entity entity, Object packet) { EntityTrackerEntry entry = getTrackerEntry(entity); for(EntityPlayer viewer : entry.trackedPlayers) { viewer.playerConnection.sendPacket((Packet) packet); } }
public static Packet playerListAddPacket(UUID uuid, String name, @Nullable BaseComponent displayName, GameMode gamemode, int ping, @Nullable Skin skin) { PacketPlayOutPlayerInfo packet = new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER); packet.add(playerListPacketData(packet, uuid, name, displayName, gamemode, ping, skin)); return packet; }
public static Packet teamRemovePacket(String name) { return teamPacket(1, name, null, null, null, false, false, null, null, Lists.<String>newArrayList()); }
public static Packet teamJoinPacket(String name, Collection<String> players) { return teamPacket(3, name, null, null, null, false, false, null, null, players); }
public static Packet teamLeavePacket(String name, Collection<String> players) { return teamPacket(4, name, null, null, null, false, false, null, null, players); }
public static Packet destroyEntitiesPacket(int... entityIds) { return new PacketPlayOutEntityDestroy(entityIds); }
public static Packet setPassengerPacket(int vehicleId, int riderId) { return new PacketPlayOutMount(vehicleId, riderId); }
private static Packet entityMetadataPacket(int entityId, net.minecraft.server.Entity nmsEntity, boolean complete) { return new PacketPlayOutEntityMetadata(entityId, nmsEntity.getDataWatcher(), complete); }
public static Packet entityMetadataPacket(int entityId, Entity entity, boolean complete) { return entityMetadataPacket(entityId, ((CraftEntity) entity).getHandle(), complete); }
public static Packet entityMetadataPacket(net.minecraft.server.Entity nmsEntity, boolean complete) { return entityMetadataPacket(nmsEntity.getId(), nmsEntity, complete); }
public static Packet entityHelmetPacket(int entityId, org.bukkit.inventory.ItemStack helmet) { return new PacketPlayOutEntityEquipment(entityId, EnumItemSlot.HEAD, CraftItemStack.asNMSCopy(helmet)); }
protected Packet<?> spawnPacket() { return new PacketPlayOutSpawnEntityLiving(entity); }
private Packet destroyPacket() { if(destroyPacket == null) { destroyPacket = destroyEntitiesPacket(entityId()); } return destroyPacket; }