Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement string reading limits #94

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions src/main/java/ua/nanit/limbo/protocol/ByteMessage.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import io.netty.handler.codec.EncoderException;
import io.netty.util.ByteProcessor;
import net.kyori.adventure.nbt.*;
import org.jetbrains.annotations.NotNull;
import ua.nanit.limbo.protocol.registry.Version;

import java.io.IOException;
Expand Down Expand Up @@ -107,13 +108,22 @@ private void writeVarIntFull(final int value) {
}
}

public String readString() {
return readString(readVarInt());
public @NotNull String readString() throws DecoderException {
return readString(Short.MAX_VALUE);
}

public String readString(int length) {
String str = buf.toString(buf.readerIndex(), length, StandardCharsets.UTF_8);
buf.skipBytes(length);
public @NotNull String readString(int cap) throws DecoderException {
final int length = readVarInt();
return readString(cap, length);
}

public @NotNull String readString(int cap, int length) throws DecoderException {
if (length < 0) throw new DecoderException("Got a negative-length string");
if (length > cap * 3) throw new DecoderException("Bad string size");
if (!buf.isReadable(length)) throw new DecoderException("Tried to read a too-long string");
final String str = buf.toString(buf.readerIndex(), length, StandardCharsets.UTF_8);
buf.readerIndex(buf.readerIndex() + length);
if (str.length() > cap) throw new DecoderException("Got a too-long string");
return str;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public void decode(ByteMessage msg, Version version) {
this.version = Version.UNDEFINED;
}

this.host = msg.readString();
this.host = msg.readString(261);
this.port = msg.readUnsignedShort();
this.nextState = State.getById(msg.readVarInt());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public String getUsername() {

@Override
public void decode(ByteMessage msg, Version version) {
this.username = msg.readString();
this.username = msg.readString(16);
}

@Override
Expand Down