com.velocitypowered.api.network.ProtocolVersion Java Examples

The following examples show how to use com.velocitypowered.api.network.ProtocolVersion. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TabCompleteRequest.java    From Velocity with MIT License 6 votes vote down vote up
@Override
public void encode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion version) {
  if (command == null) {
    throw new IllegalStateException("Command is not specified");
  }

  if (version.compareTo(MINECRAFT_1_13) >= 0) {
    ProtocolUtils.writeVarInt(buf, transactionId);
    ProtocolUtils.writeString(buf, command);
  } else {
    ProtocolUtils.writeString(buf, command);
    if (version.compareTo(MINECRAFT_1_9) >= 0) {
      buf.writeBoolean(assumeCommand);
    }
    buf.writeBoolean(hasPosition);
    if (hasPosition) {
      buf.writeLong(position);
    }
  }
}
 
Example #2
Source File: GS4QueryHandler.java    From Velocity with MIT License 6 votes vote down vote up
private QueryResponse createInitialResponse() {
  return QueryResponse.builder()
      .hostname(PlainComponentSerializer.INSTANCE
          .serialize(server.getConfiguration().getMotdComponent()))
      .gameVersion(ProtocolVersion.SUPPORTED_VERSION_STRING)
      .map(server.getConfiguration().getQueryMap())
      .currentPlayers(server.getPlayerCount())
      .maxPlayers(server.getConfiguration().getShowMaxPlayers())
      .proxyPort(server.getConfiguration().getBind().getPort())
      .proxyHost(server.getConfiguration().getBind().getHostString())
      .players(server.getAllPlayers().stream().map(Player::getUsername)
          .collect(Collectors.toList()))
      .proxyVersion("Velocity")
      .plugins(
          server.getConfiguration().shouldQueryShowPlugins() ? getRealPluginInformation()
              : Collections.emptyList())
      .build();
}
 
Example #3
Source File: VelocityServerHandler.java    From ViaVersion with MIT License 6 votes vote down vote up
@Subscribe
public void preServerConnect(ServerPreConnectEvent e) {
    try {
        UserConnection user = Via.getManager().getConnection(e.getPlayer().getUniqueId());
        if (user == null) return;
        if (!user.has(VelocityStorage.class)) {
            user.put(new VelocityStorage(user, e.getPlayer()));
        }

        int protocolId = ProtocolDetectorService.getProtocolId(e.getOriginalServer().getServerInfo().getName());
        List<Pair<Integer, Protocol>> protocols = ProtocolRegistry.getProtocolPath(user.getProtocolInfo().getProtocolVersion(), protocolId);

        // Check if ViaVersion can support that version
        Object connection = getMinecraftConnection.invoke(e.getPlayer());
        setNextProtocolVersion.invoke(connection, ProtocolVersion.getProtocolVersion(protocols == null
                ? user.getProtocolInfo().getProtocolVersion()
                : protocolId));

    } catch (IllegalAccessException | InvocationTargetException e1) {
        e1.printStackTrace();
    }
}
 
Example #4
Source File: ConnectedPlayer.java    From Velocity with MIT License 6 votes vote down vote up
/**
 * Determines whether or not we can forward a plugin message onto the client.
 * @param version the Minecraft protocol version
 * @param message the plugin message to forward to the client
 * @return {@code true} if the message can be forwarded, {@code false} otherwise
 */
public boolean canForwardPluginMessage(ProtocolVersion version, PluginMessage message) {
  boolean minecraftOrFmlMessage;

  // By default, all internal Minecraft and Forge channels are forwarded from the server.
  if (version.compareTo(ProtocolVersion.MINECRAFT_1_12_2) <= 0) {
    String channel = message.getChannel();
    minecraftOrFmlMessage = channel.startsWith("MC|")
        || channel.startsWith(LegacyForgeConstants.FORGE_LEGACY_HANDSHAKE_CHANNEL)
        || PluginMessageUtil.isLegacyRegister(message)
        || PluginMessageUtil.isLegacyUnregister(message);
  } else {
    minecraftOrFmlMessage = message.getChannel().startsWith("minecraft:");
  }

  // Otherwise, we need to see if the player already knows this channel or it's known by the
  // proxy.
  return minecraftOrFmlMessage || knownChannels.contains(message.getChannel());
}
 
Example #5
Source File: TabCompleteRequest.java    From Velocity with MIT License 6 votes vote down vote up
@Override
public void decode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion version) {
  if (version.compareTo(MINECRAFT_1_13) >= 0) {
    this.transactionId = ProtocolUtils.readVarInt(buf);
    this.command = ProtocolUtils.readString(buf, VANILLA_MAX_TAB_COMPLETE_LEN);
  } else {
    this.command = ProtocolUtils.readString(buf, VANILLA_MAX_TAB_COMPLETE_LEN);
    if (version.compareTo(MINECRAFT_1_9) >= 0) {
      this.assumeCommand = buf.readBoolean();
    }
    this.hasPosition = buf.readBoolean();
    if (hasPosition) {
      this.position = buf.readLong();
    }
  }
}
 
Example #6
Source File: PluginMessageUtil.java    From Velocity with MIT License 5 votes vote down vote up
/**
 * Constructs a channel (un)register packet.
 * @param protocolVersion the client/server's protocol version
 * @param channels the channels to register
 * @return the plugin message to send
 */
public static PluginMessage constructChannelsPacket(ProtocolVersion protocolVersion,
                                                    Collection<String> channels) {
  Preconditions.checkNotNull(channels, "channels");
  Preconditions.checkArgument(channels.size() > 0, "no channels specified");
  String channelName = protocolVersion.compareTo(ProtocolVersion.MINECRAFT_1_13) >= 0
      ? REGISTER_CHANNEL : REGISTER_CHANNEL_LEGACY;
  PluginMessage message = new PluginMessage();
  message.setChannel(channelName);
  message.setData(String.join("\0", channels).getBytes(StandardCharsets.UTF_8));
  return message;
}
 
Example #7
Source File: StateRegistry.java    From Velocity with MIT License 5 votes vote down vote up
PacketRegistry(Direction direction) {
  this.direction = direction;

  Map<ProtocolVersion, ProtocolRegistry> mutableVersions = new EnumMap<>(ProtocolVersion.class);
  for (ProtocolVersion version : ProtocolVersion.values()) {
    if (!version.isLegacy() && !version.isUnknown()) {
      mutableVersions.put(version, new ProtocolRegistry(version));
    }
  }

  this.versions = Collections.unmodifiableMap(mutableVersions);
}
 
Example #8
Source File: ServerLoginSuccess.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void decode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion version) {
  if (version.compareTo(ProtocolVersion.MINECRAFT_1_16) >= 0) {
    uuid = ProtocolUtils.readUuidIntArray(buf);
  } else {
    uuid = UUID.fromString(ProtocolUtils.readString(buf, 36));
  }
  username = ProtocolUtils.readString(buf, 16);
}
 
Example #9
Source File: ScoreboardScore.java    From TAB with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion version) {
	ProtocolUtils.writeString(buf, itemName);
	buf.writeByte(action);
	if (version.getProtocol() >= ProtocolVersion.MINECRAFT_1_8.getProtocol()) {
		ProtocolUtils.writeString(buf, scoreName);
		if (action != 1) {
			ProtocolUtils.writeVarInt(buf, value);
		}
	} else if (action != 1) {
		ProtocolUtils.writeString(buf, scoreName);
		buf.writeInt(value);
	}
}
 
Example #10
Source File: ResourcePackResponse.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void encode(ByteBuf buf, Direction direction, ProtocolVersion protocolVersion) {
  if (protocolVersion.compareTo(ProtocolVersion.MINECRAFT_1_9_4) <= 0) {
    ProtocolUtils.writeString(buf, hash);
  }
  ProtocolUtils.writeVarInt(buf, status.ordinal());
}
 
Example #11
Source File: ClientSettings.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void decode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion version) {
  this.locale = ProtocolUtils.readString(buf, 16);
  this.viewDistance = buf.readByte();
  this.chatVisibility = ProtocolUtils.readVarInt(buf);
  this.chatColors = buf.readBoolean();
  this.skinParts = buf.readUnsignedByte();

  if (version.compareTo(ProtocolVersion.MINECRAFT_1_9) >= 0) {
    this.mainHand = ProtocolUtils.readVarInt(buf);
  }
}
 
Example #12
Source File: KeepAlive.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void encode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion version) {
  if (version.compareTo(ProtocolVersion.MINECRAFT_1_12_2) >= 0) {
    buf.writeLong(randomId);
  } else {
    ProtocolUtils.writeVarInt(buf, (int) randomId);
  }
}
 
Example #13
Source File: KeepAlive.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void decode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion version) {
  if (version.compareTo(ProtocolVersion.MINECRAFT_1_12_2) >= 0) {
    randomId = buf.readLong();
  } else {
    randomId = ProtocolUtils.readVarInt(buf);
  }
}
 
Example #14
Source File: ScoreboardScore.java    From TAB with Apache License 2.0 5 votes vote down vote up
@Override
public void decode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion version) {
	itemName = ProtocolUtils.readString(buf);
	action = buf.readByte();
	if (version.getProtocol() >= ProtocolVersion.MINECRAFT_1_8.getProtocol()) {
		scoreName = ProtocolUtils.readString(buf);
		if (action != 1) {
			value = ProtocolUtils.readVarInt(buf);
		}
	} else if (action != 1) {
		scoreName = ProtocolUtils.readString(buf);
		value = buf.readInt();
	}
}
 
Example #15
Source File: MinecraftConnection.java    From Velocity with MIT License 5 votes vote down vote up
/**
 * Sets the new protocol version for the connection.
 * @param protocolVersion the protocol version to use
 */
public void setProtocolVersion(ProtocolVersion protocolVersion) {
  ensureInEventLoop();

  this.protocolVersion = protocolVersion;
  this.nextProtocolVersion = protocolVersion;
  if (protocolVersion != ProtocolVersion.LEGACY) {
    this.channel.pipeline().get(MinecraftEncoder.class).setProtocolVersion(protocolVersion);
    this.channel.pipeline().get(MinecraftDecoder.class).setProtocolVersion(protocolVersion);
  } else {
    // Legacy handshake handling
    this.channel.pipeline().remove(MINECRAFT_ENCODER);
    this.channel.pipeline().remove(MINECRAFT_DECODER);
  }
}
 
Example #16
Source File: PacketRegistryTest.java    From Velocity with MIT License 5 votes vote down vote up
@Test
void failOnNoMappings() {
  StateRegistry.PacketRegistry registry = new StateRegistry.PacketRegistry(
      ProtocolUtils.Direction.CLIENTBOUND);
  assertThrows(IllegalArgumentException.class,
      () -> registry.register(Handshake.class, Handshake::new));
  assertThrows(IllegalArgumentException.class,
      () -> registry.getProtocolRegistry(ProtocolVersion.UNKNOWN).getPacketId(new Handshake()));
}
 
Example #17
Source File: HandshakeSessionHandler.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public boolean handle(LegacyPing packet) {
  connection.setProtocolVersion(ProtocolVersion.LEGACY);
  StatusSessionHandler handler = new StatusSessionHandler(server, connection,
      new LegacyInboundConnection(connection, packet));
  connection.setSessionHandler(handler);
  handler.handle(packet);
  return true;
}
 
Example #18
Source File: PacketRegistryTest.java    From Velocity with MIT License 5 votes vote down vote up
@Test
void shouldNotFailWhenRegisterLatestProtocolVersion() {
  StateRegistry.PacketRegistry registry = new StateRegistry.PacketRegistry(
      ProtocolUtils.Direction.CLIENTBOUND);
  assertDoesNotThrow(() -> registry.register(Handshake.class, Handshake::new,
      new StateRegistry.PacketMapping(0x00, MINECRAFT_1_8, false),
      new StateRegistry.PacketMapping(0x01, getLast(ProtocolVersion.SUPPORTED_VERSIONS),
          false)));
}
 
Example #19
Source File: BossBar.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void decode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion version) {
  this.uuid = ProtocolUtils.readUuid(buf);
  this.action = ProtocolUtils.readVarInt(buf);
  switch (action) {
    case ADD:
      this.name = ProtocolUtils.readString(buf);
      this.percent = buf.readFloat();
      this.color = ProtocolUtils.readVarInt(buf);
      this.overlay = ProtocolUtils.readVarInt(buf);
      this.flags = buf.readUnsignedByte();
      break;
    case REMOVE:
      break;
    case UPDATE_PERCENT:
      this.percent = buf.readFloat();
      break;
    case UPDATE_NAME:
      this.name = ProtocolUtils.readString(buf);
      break;
    case UPDATE_STYLE:
      this.color = ProtocolUtils.readVarInt(buf);
      this.overlay = ProtocolUtils.readVarInt(buf);
      break;
    case UPDATE_PROPERTIES:
      this.flags = buf.readUnsignedByte();
      break;
    default:
      throw new UnsupportedOperationException("Unknown action " + action);
  }
}
 
Example #20
Source File: VelocityChannelRegistrar.java    From Velocity with MIT License 5 votes vote down vote up
/**
 * Returns all the channel names to register depending on the Minecraft protocol version.
 * @param protocolVersion the protocol version in use
 * @return the list of channels to register
 */
public Collection<String> getChannelsForProtocol(ProtocolVersion protocolVersion) {
  if (protocolVersion.compareTo(ProtocolVersion.MINECRAFT_1_13) >= 0) {
    return getModernChannelIds();
  }
  return getLegacyChannelIds();
}
 
Example #21
Source File: PlayerListItem.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void encode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion version) {
  ProtocolUtils.writeVarInt(buf, action);
  ProtocolUtils.writeVarInt(buf, items.size());
  for (Item item : items) {
    ProtocolUtils.writeUuid(buf, item.getUuid());
    switch (action) {
      case ADD_PLAYER:
        ProtocolUtils.writeString(buf, item.getName());
        ProtocolUtils.writeProperties(buf, item.getProperties());
        ProtocolUtils.writeVarInt(buf, item.getGameMode());
        ProtocolUtils.writeVarInt(buf, item.getLatency());

        writeDisplayName(buf, item.getDisplayName());
        break;
      case UPDATE_GAMEMODE:
        ProtocolUtils.writeVarInt(buf, item.getGameMode());
        break;
      case UPDATE_LATENCY:
        ProtocolUtils.writeVarInt(buf, item.getLatency());
        break;
      case UPDATE_DISPLAY_NAME:
        writeDisplayName(buf, item.getDisplayName());
        break;
      case REMOVE_PLAYER:
        //Do nothing, all that is needed is the uuid
        break;
      default:
        throw new UnsupportedOperationException("Unknown action " + action);
    }
  }
}
 
Example #22
Source File: AvailableCommands.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void decode(ByteBuf buf, Direction direction, ProtocolVersion protocolVersion) {
  int commands = ProtocolUtils.readVarInt(buf);
  WireNode[] wireNodes = new WireNode[commands];
  for (int i = 0; i < commands; i++) {
    wireNodes[i] = deserializeNode(buf, i);
  }

  // Iterate over the deserialized nodes and attempt to form a graph. We also resolve any cycles
  // that exist.
  Queue<WireNode> nodeQueue = new ArrayDeque<>(Arrays.asList(wireNodes));
  while (!nodeQueue.isEmpty()) {
    boolean cycling = false;

    for (Iterator<WireNode> it = nodeQueue.iterator(); it.hasNext(); ) {
      WireNode node = it.next();
      if (node.toNode(wireNodes)) {
        cycling = true;
        it.remove();
      }
    }

    if (!cycling) {
      // Uh-oh. We can't cycle. This is bad.
      throw new IllegalStateException("Stopped cycling; the root node can't be built.");
    }
  }

  int rootIdx = ProtocolUtils.readVarInt(buf);
  rootNode = (RootCommandNode<Object>) wireNodes[rootIdx].built;
}
 
Example #23
Source File: PlayerListItem.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void decode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion version) {
  action = ProtocolUtils.readVarInt(buf);
  int length = ProtocolUtils.readVarInt(buf);

  for (int i = 0; i < length; i++) {
    Item item = new Item(ProtocolUtils.readUuid(buf));
    items.add(item);
    switch (action) {
      case ADD_PLAYER:
        item.setName(ProtocolUtils.readString(buf));
        item.setProperties(ProtocolUtils.readProperties(buf));
        item.setGameMode(ProtocolUtils.readVarInt(buf));
        item.setLatency(ProtocolUtils.readVarInt(buf));
        item.setDisplayName(readOptionalComponent(buf));
        break;
      case UPDATE_GAMEMODE:
        item.setGameMode(ProtocolUtils.readVarInt(buf));
        break;
      case UPDATE_LATENCY:
        item.setLatency(ProtocolUtils.readVarInt(buf));
        break;
      case UPDATE_DISPLAY_NAME:
        item.setDisplayName(readOptionalComponent(buf));
        break;
      case REMOVE_PLAYER:
        //Do nothing, all that is needed is the uuid
        break;
      default:
        throw new UnsupportedOperationException("Unknown action " + action);
    }
  }
}
 
Example #24
Source File: LoginPluginMessage.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void encode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion version) {
  ProtocolUtils.writeVarInt(buf, id);
  if (channel == null) {
    throw new IllegalStateException("Channel is not specified!");
  }
  ProtocolUtils.writeString(buf, channel);
  buf.writeBytes(data);
}
 
Example #25
Source File: Handshake.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void encode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion ignored) {
  ProtocolUtils.writeVarInt(buf, this.protocolVersion.getProtocol());
  ProtocolUtils.writeString(buf, this.serverAddress);
  buf.writeShort(this.port);
  ProtocolUtils.writeVarInt(buf, this.nextStatus);
}
 
Example #26
Source File: ConnectedPlayer.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void sendMessage(Component component, MessagePosition position) {
  Preconditions.checkNotNull(component, "component");
  Preconditions.checkNotNull(position, "position");

  byte pos = (byte) position.ordinal();
  String json;
  if (position == MessagePosition.ACTION_BAR) {
    if (getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_11) >= 0) {
      // We can use the title packet instead.
      TitlePacket pkt = new TitlePacket();
      pkt.setAction(TitlePacket.SET_ACTION_BAR);
      pkt.setComponent(GsonComponentSerializer.INSTANCE.serialize(component));
      minecraftConnection.write(pkt);
      return;
    } else {
      // Due to issues with action bar packets, we'll need to convert the text message into a
      // legacy message and then inject the legacy text into a component... yuck!
      JsonObject object = new JsonObject();
      object.addProperty("text", LegacyComponentSerializer.legacy().serialize(component));
      json = object.toString();
    }
  } else {
    json = GsonComponentSerializer.INSTANCE.serialize(component);
  }

  Chat chat = new Chat();
  chat.setType(pos);
  chat.setMessage(json);
  minecraftConnection.write(chat);
}
 
Example #27
Source File: ResourcePackRequest.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void encode(ByteBuf buf, Direction direction, ProtocolVersion protocolVersion) {
  if (url == null || hash == null) {
    throw new IllegalStateException("Packet not fully filled in yet!");
  }
  ProtocolUtils.writeString(buf, url);
  ProtocolUtils.writeString(buf, hash);
}
 
Example #28
Source File: StatusSessionHandler.java    From Velocity with MIT License 5 votes vote down vote up
private ServerPing createInitialPing() {
  VelocityConfiguration configuration = server.getConfiguration();
  ProtocolVersion shownVersion = ProtocolVersion.isSupported(connection.getProtocolVersion())
      ? connection.getProtocolVersion() : ProtocolVersion.MAXIMUM_VERSION;
  return new ServerPing(
      new ServerPing.Version(shownVersion.getProtocol(),
          "Velocity " + ProtocolVersion.SUPPORTED_VERSION_STRING),
      new ServerPing.Players(server.getPlayerCount(), configuration.getShowMaxPlayers(),
          ImmutableList.of()),
      configuration.getMotdComponent(),
      configuration.getFavicon().orElse(null),
      configuration.isAnnounceForge() ? ModInfo.DEFAULT : null
  );
}
 
Example #29
Source File: BossBar.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void encode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion version) {
  if (uuid == null) {
    throw new IllegalStateException("No boss bar UUID specified");
  }
  ProtocolUtils.writeUuid(buf, uuid);
  ProtocolUtils.writeVarInt(buf, action);
  switch (action) {
    case ADD:
      if (name == null) {
        throw new IllegalStateException("No name specified!");
      }
      ProtocolUtils.writeString(buf, name);
      buf.writeFloat(percent);
      ProtocolUtils.writeVarInt(buf, color);
      ProtocolUtils.writeVarInt(buf, overlay);
      buf.writeByte(flags);
      break;
    case REMOVE:
      break;
    case UPDATE_PERCENT:
      buf.writeFloat(percent);
      break;
    case UPDATE_NAME:
      if (name == null) {
        throw new IllegalStateException("No name specified!");
      }
      ProtocolUtils.writeString(buf, name);
      break;
    case UPDATE_STYLE:
      ProtocolUtils.writeVarInt(buf, color);
      ProtocolUtils.writeVarInt(buf, overlay);
      break;
    case UPDATE_PROPERTIES:
      buf.writeByte(flags);
      break;
    default:
      throw new UnsupportedOperationException("Unknown action " + action);
  }
}
 
Example #30
Source File: Disconnect.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void encode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersion version) {
  if (reason == null) {
    throw new IllegalStateException("No reason specified.");
  }
  ProtocolUtils.writeString(buf, reason);
}