Add some failsafe length preconditions

This commit is contained in:
md_5 2013-12-02 18:49:39 +11:00
parent aad83d787f
commit 63d49ac296

View File

@ -1,6 +1,7 @@
package net.md_5.bungee.protocol;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import io.netty.buffer.ByteBuf;
import lombok.RequiredArgsConstructor;
@ -10,7 +11,8 @@ public abstract class DefinedPacket
public static void writeString(String s, ByteBuf buf)
{
// TODO: Check len - use Guava?
Preconditions.checkArgument( s.length() <= Short.MAX_VALUE, "Cannot send string longer than Short.MAX_VALUE (got %s characters)", s.length() );
byte[] b = s.getBytes( Charsets.UTF_8 );
writeVarInt( b.length, buf );
buf.writeBytes( b );
@ -19,6 +21,8 @@ public abstract class DefinedPacket
public static String readString(ByteBuf buf)
{
int len = readVarInt( buf );
Preconditions.checkArgument( len <= Short.MAX_VALUE, "Cannot receive string longer than Short.MAX_VALUE (got %s characters)", len );
byte[] b = new byte[ len ];
buf.readBytes( b );
@ -27,15 +31,17 @@ public abstract class DefinedPacket
public static void writeArray(byte[] b, ByteBuf buf)
{
// TODO: Check len - use Guava?
Preconditions.checkArgument( b.length <= Short.MAX_VALUE, "Cannot send array longer than Short.MAX_VALUE (got %s bytes)", b.length );
buf.writeShort( b.length );
buf.writeBytes( b );
}
public static byte[] readArray(ByteBuf buf)
{
// TODO: Check len - use Guava?
short len = buf.readShort();
Preconditions.checkArgument( len <= Short.MAX_VALUE, "Cannot receive array longer than Short.MAX_VALUE (got %s bytes)", len );
byte[] ret = new byte[ len ];
buf.readBytes( ret );
return ret;