https://bz.apache.org/bugzilla/show_bug.cgi?id=70321
Bug ID: 70321
Summary: InputBuffer.read(byte[], int, int) zero-length-read
fix (commit e9ff675a, "Return 0 rather than -1 for
zero-length reads from InputBuffer at end of
stream...") silently breaks the extremely common while
((n = in.read(buf, off, len)) != -1)
Product: Tomcat 11
Version: 11.0.27
Hardware: PC
Status: NEW
Severity: normal
Priority: P2
Component: Catalina
Assignee: [email protected]
Reporter: [email protected]
Target Milestone: -------
Tomcat 9.0.123 and 11.0.27 changed
org.apache.catalina.connector.InputBuffer.read(byte[] b, int off, int len) to
return 0 immediately when len == 0, instead of falling through to the
end-of-stream check (which previously returned -1):
// 9.0.122 / 11.0.26 and earlier:
public int read(byte[] b, int off, int len) throws IOException {
throwIfClosed();
if (checkByteBufferEof()) {
return -1;
}
...
}
// 9.0.123 / 11.0.27 and later:
public int read(byte[] b, int off, int len) throws IOException {
throwIfClosed();
if (len == 0) {
return 0;
}
if (checkByteBufferEof()) {
return -1;
}
...
}
This change silently changes observable behavior for any caller using the
common idiom of looping on the return value of read() itself as the only
loop-termination condition, rather than checking the remaining byte count
before calling read() again. For example:
int contentLength = request.getContentLength();
byte[] data = new byte[contentLength];
InputStream in = request.getInputStream();
int totalRead = 0;
int bytesLeft = contentLength;
int n;
while ((n = in.read(data, totalRead, bytesLeft)) != -1) {
totalRead += n;
bytesLeft -= n;
}
This is a widely-used pattern and relies on the fact that once bytesLeft
reaches 0 (because a prior read() call satisfied the entire remaining request
in one call — the normal case for small request bodies that fit in the
socket/application buffer in a single read), the next loop iteration calls
read(data, totalRead, 0). Previously, this zero-length call fell through to the
EOF check and correctly returned -1, terminating the loop as intended. After
this fix, it now returns 0, which does not satisfy the loop's != -1 termination
condition, so the loop never terminates on its own — it busy-spins calling
read() with len=0 indefinitely, consuming CPU on the request-processing thread,
until some unrelated external timeout (e.g., an application-level read timeout,
or eventually a client/connection timeout) intervenes.
It is not mentioned anywhere in the changelog bullets as a
compatibility-impacting change, despite being a silent, non-configurable
behavior change with this consequence. Please look into how can this be fixed
without breaking compatibility for applications.
--
You are receiving this mail because:
You are the assignee for the bug.
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]