Skip to content

Commit 74861ac

Browse files
committed
Fix premature termination of incomplete chunked messages
Prevent chunked transfer codecs from writing the terminating chunk when entity serialization fails. Preserve early response handling and close inconsistent connections after write failures.
1 parent 428c959 commit 74861ac

4 files changed

Lines changed: 110 additions & 4 deletions

File tree

‎httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/DefaultBHttpClientConnection.java‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
import org.apache.hc.core5.http.io.HttpMessageWriterFactory;
6262
import org.apache.hc.core5.http.io.ResponseOutOfOrderStrategy;
6363
import org.apache.hc.core5.http.message.MessageSupport;
64+
import org.apache.hc.core5.io.CloseMode;
6465
import org.apache.hc.core5.util.Args;
6566

6667
/**
@@ -209,7 +210,7 @@ public void sendRequestEntity(final ClassicHttpRequest request) throws HttpExcep
209210
if (len == ContentLengthStrategy.UNDEFINED) {
210211
throw new LengthRequiredException();
211212
}
212-
try (final OutputStream outStream = createContentOutputStream(
213+
final OutputStream outStream = createContentOutputStream(
213214
len, this.outbuffer, new OutputStream() {
214215

215216
final OutputStream socketOutputStream = socketHolder.getOutputStream();
@@ -281,15 +282,22 @@ public void close() throws IOException {
281282
socketOutputStream.close();
282283
}
283284

284-
}, entity.getTrailers())) {
285+
}, entity.getTrailers());
286+
try {
285287
entity.writeTo(outStream);
288+
outStream.close();
286289
} catch (final ResponseOutOfOrderException ex) {
287-
if (len > 0) {
290+
if (len != 0) {
288291
this.consistent = false;
289292
}
293+
} catch (final IOException | RuntimeException ex) {
294+
this.consistent = false;
295+
close(CloseMode.IMMEDIATE);
296+
throw ex;
290297
}
291298
}
292299

300+
293301
@Override
294302
public boolean isConsistent() {
295303
return this.consistent;

‎httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/DefaultBHttpServerConnection.java‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
import org.apache.hc.core5.http.io.HttpMessageWriter;
5353
import org.apache.hc.core5.http.io.HttpMessageWriterFactory;
5454
import org.apache.hc.core5.http.io.HttpServerConnection;
55+
import org.apache.hc.core5.io.CloseMode;
5556
import org.apache.hc.core5.util.Args;
5657

5758
/**
@@ -193,8 +194,17 @@ public void sendResponseEntity(final ClassicHttpResponse response)
193194
return;
194195
}
195196
final long len = this.outgoingContentStrategy.determineLength(response);
196-
try (final OutputStream outStream = createContentOutputStream(len, this.outbuffer, socketHolder.getOutputStream(), entity.getTrailers())) {
197+
final OutputStream outStream = createContentOutputStream(
198+
len, this.outbuffer, socketHolder.getOutputStream(), entity.getTrailers());
199+
boolean completed = false;
200+
try {
197201
entity.writeTo(outStream);
202+
outStream.close();
203+
completed = true;
204+
} finally {
205+
if (!completed) {
206+
close(CloseMode.IMMEDIATE);
207+
}
198208
}
199209
}
200210
}

‎httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestDefaultBHttpClientConnection.java‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@
2828

2929
import java.io.ByteArrayInputStream;
3030
import java.io.ByteArrayOutputStream;
31+
import java.io.EOFException;
3132
import java.io.InputStream;
33+
import java.io.OutputStream;
3234
import java.net.Socket;
3335
import java.nio.charset.StandardCharsets;
3436

@@ -230,6 +232,67 @@ void testReadResponseNoEntity() throws Exception {
230232
Assertions.assertInstanceOf(IdentityInputStream.class, content);
231233
}
232234

235+
@Test
236+
void testEarlyResponseDoesNotAbortConnection() throws Exception {
237+
final ByteArrayOutputStream output = new ByteArrayOutputStream();
238+
final ByteArrayInputStream input = new ByteArrayInputStream(
239+
"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n"
240+
.getBytes(StandardCharsets.US_ASCII));
241+
Mockito.when(socket.getOutputStream()).thenReturn(output);
242+
Mockito.when(socket.getInputStream()).thenReturn(input);
243+
244+
final org.apache.hc.core5.http.io.ResponseOutOfOrderStrategy strategy =
245+
Mockito.mock(org.apache.hc.core5.http.io.ResponseOutOfOrderStrategy.class);
246+
Mockito.when(strategy.isEarlyResponseDetected(
247+
Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong()))
248+
.thenReturn(true);
249+
250+
conn = new DefaultBHttpClientConnection(
251+
Http1Config.DEFAULT, null, null,
252+
DefaultContentLengthStrategy.INSTANCE,
253+
DefaultContentLengthStrategy.INSTANCE,
254+
strategy,
255+
DefaultHttpRequestWriterFactory.INSTANCE,
256+
DefaultHttpResponseParserFactory.INSTANCE);
257+
conn.bind(socket);
258+
259+
final ClassicHttpRequest request = new BasicClassicHttpRequest(Method.POST, "/stuff");
260+
request.addHeader("Transfer-Encoding", "chunked");
261+
request.setEntity(new ByteArrayEntity(new byte[16384], ContentType.TEXT_PLAIN, true));
262+
263+
conn.sendRequestHeader(request);
264+
Assertions.assertDoesNotThrow(() -> conn.sendRequestEntity(request));
265+
Assertions.assertTrue(conn.isOpen());
266+
Assertions.assertFalse(conn.isConsistent());
267+
Assertions.assertEquals(400, conn.receiveResponseHeader().getCode());
268+
Assertions.assertFalse(new String(output.toByteArray(), StandardCharsets.US_ASCII)
269+
.endsWith("0\r\n\r\n"));
270+
}
271+
272+
@Test
273+
void testChunkedEntityFailureDoesNotTerminateMessage() throws Exception {
274+
final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
275+
Mockito.when(socket.getOutputStream()).thenReturn(outStream);
276+
conn.bind(socket);
277+
278+
final HttpEntity entity = Mockito.mock(HttpEntity.class);
279+
Mockito.doAnswer(invocation -> {
280+
final OutputStream out = invocation.getArgument(0);
281+
out.write("123".getBytes(StandardCharsets.US_ASCII));
282+
throw new EOFException("source stream failed");
283+
}).when(entity).writeTo(Mockito.any(OutputStream.class));
284+
285+
final ClassicHttpRequest request = new BasicClassicHttpRequest(Method.POST, "/stuff");
286+
request.addHeader("Transfer-Encoding", "chunked");
287+
request.setEntity(entity);
288+
conn.sendRequestHeader(request);
289+
Assertions.assertThrows(EOFException.class, () -> conn.sendRequestEntity(request));
290+
Assertions.assertFalse(conn.isConsistent());
291+
Assertions.assertFalse(conn.isOpen());
292+
Assertions.assertFalse(new String(outStream.toByteArray(), StandardCharsets.US_ASCII)
293+
.endsWith("0\r\n\r\n"));
294+
}
295+
233296
@Test
234297
void testWriteRequestHead() throws Exception {
235298
final ByteArrayOutputStream outStream = new ByteArrayOutputStream();

‎httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestDefaultBHttpServerConnection.java‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@
2828

2929
import java.io.ByteArrayInputStream;
3030
import java.io.ByteArrayOutputStream;
31+
import java.io.EOFException;
3132
import java.io.InputStream;
33+
import java.io.OutputStream;
3234
import java.net.Socket;
3335
import java.nio.charset.StandardCharsets;
3436

@@ -210,6 +212,29 @@ void testReadRequestNoEntity() throws Exception {
210212
Assertions.assertNull(entity);
211213
}
212214

215+
@Test
216+
void testChunkedEntityFailureDoesNotTerminateMessage() throws Exception {
217+
final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
218+
Mockito.when(socket.getOutputStream()).thenReturn(outStream);
219+
conn.bind(socket);
220+
221+
final HttpEntity entity = Mockito.mock(HttpEntity.class);
222+
Mockito.doAnswer(invocation -> {
223+
final OutputStream out = invocation.getArgument(0);
224+
out.write("123".getBytes(StandardCharsets.US_ASCII));
225+
throw new EOFException("source stream failed");
226+
}).when(entity).writeTo(Mockito.any(OutputStream.class));
227+
228+
final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK");
229+
response.addHeader("Transfer-Encoding", "chunked");
230+
response.setEntity(entity);
231+
conn.sendResponseHeader(response);
232+
Assertions.assertThrows(EOFException.class, () -> conn.sendResponseEntity(response));
233+
Assertions.assertFalse(conn.isOpen());
234+
Assertions.assertFalse(new String(outStream.toByteArray(), StandardCharsets.US_ASCII)
235+
.endsWith("0\r\n\r\n"));
236+
}
237+
213238
@Test
214239
void testWriteResponseHead() throws Exception {
215240
final ByteArrayOutputStream outStream = new ByteArrayOutputStream();

0 commit comments

Comments
 (0)