Improve handling of malformed LiveReload request header

Closes gh-50142
This commit is contained in:
Andy Wilkinson
2026-04-22 20:50:44 +01:00
parent 3dbfa22d17
commit aa5089e3f6
2 changed files with 18 additions and 2 deletions
@@ -31,6 +31,8 @@ class ConnectionInputStream extends FilterInputStream {
private static final int BUFFER_SIZE = 4096;
private static final int MAX_HEADER_SIZE = 8192;
ConnectionInputStream(InputStream in) {
super(in);
}
@@ -45,11 +47,16 @@ class ConnectionInputStream extends FilterInputStream {
String readHeader() throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
StringBuilder content = new StringBuilder(BUFFER_SIZE);
while (content.indexOf(HEADER_END) == -1) {
while (content.indexOf(HEADER_END) == -1 && content.length() < MAX_HEADER_SIZE) {
int amountRead = checkedRead(buffer, 0, BUFFER_SIZE);
content.append(new String(buffer, 0, amountRead));
}
return content.substring(0, content.indexOf(HEADER_END));
int endIndex = content.indexOf(HEADER_END);
if (endIndex == -1) {
throw new IOException("Malformed header");
}
return content.substring(0, endIndex);
}
/**
@@ -20,6 +20,7 @@ import java.io.ByteArrayInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import org.junit.jupiter.api.Test;
@@ -47,6 +48,14 @@ class ConnectionInputStreamTests {
assertThat(inputStream.readHeader()).isEqualTo(header);
}
@Test
void readHeaderThrowsWhenHeaderIsMalformed() {
byte[] header = new byte[10000];
new Random().nextBytes(header);
ConnectionInputStream inputStream = new ConnectionInputStream(new ByteArrayInputStream(header));
assertThatIOException().isThrownBy(inputStream::readHeader).withMessage("Malformed header");
}
@Test
void readFully() throws Exception {
byte[] bytes = "the data that we want to read fully".getBytes();