Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -27,26 +27,50 @@

package org.apache.hc.core5.testing.nio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.EntityDetails;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.HttpVersion;
import org.apache.hc.core5.http.URIScheme;
import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester;
import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer;
import org.apache.hc.core5.http.io.entity.AbstractHttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
import org.apache.hc.core5.http.message.BasicHttpResponse;
import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
import org.apache.hc.core5.http.nio.CapacityChannel;
import org.apache.hc.core5.http.nio.DataStreamChannel;
import org.apache.hc.core5.http.nio.ResponseChannel;
import org.apache.hc.core5.http.nio.support.classic.ClassicToAsyncRequestProducer;
import org.apache.hc.core5.http.nio.support.classic.ClassicToAsyncResponseConsumer;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.reactor.ListenerEndpoint;
import org.apache.hc.core5.testing.classic.RandomEntity;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

Expand Down Expand Up @@ -97,4 +121,137 @@ void test_request_handling_no_keep_alive(final int contentSize) throws Exception
}
}

/**
* An entity that writes a first chunk, then fails before writing the rest of the body it
* declared itself to still owe the peer.
*/
private static final class FailingEntity extends AbstractHttpEntity {

private final byte[] firstChunk;

FailingEntity(final byte[] firstChunk) {
super(ContentType.TEXT_PLAIN, null);
this.firstChunk = firstChunk;
}

@Override
public boolean isRepeatable() {
return false;
}

@Override
public long getContentLength() {
return -1;
}

@Override
public InputStream getContent() {
throw new UnsupportedOperationException();
}

@Override
public boolean isStreaming() {
return true;
}

@Override
public void writeTo(final OutputStream outStream) throws IOException {
outStream.write(firstChunk);
outStream.flush();
throw new IOException("simulated mid-body failure");
}

@Override
public void close() {
}
}

@Test
void test_failed_entity_write_does_not_report_request_body_as_complete() throws Exception {
final AtomicInteger bytesReceived = new AtomicInteger();
final AtomicBoolean streamEnded = new AtomicBoolean();
final CountDownLatch handlerDone = new CountDownLatch(1);

// registerHandler must run before start(): H2AsyncServerResource#start() calls
// bootstrap.create() once and freezes the router, so a later registerHandler call
// (as the sibling test above does) silently has no effect on the running server.
registerHandler("/truncate", () -> new AsyncServerExchangeHandler() {

private volatile ResponseChannel responseChannel;

@Override
public void handleRequest(final HttpRequest request, final EntityDetails entityDetails,
final ResponseChannel responseChannel, final HttpContext context) {
this.responseChannel = responseChannel;
}

@Override
public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
capacityChannel.update(Integer.MAX_VALUE);
}

@Override
public void consume(final ByteBuffer src) {
bytesReceived.addAndGet(src.remaining());
}

@Override
public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
streamEnded.set(true);
responseChannel.sendResponse(new BasicHttpResponse(HttpStatus.SC_OK), null, null);
}

@Override
public int available() {
return 0;
}

@Override
public void produce(final DataStreamChannel channel) throws IOException {
channel.endStream();
}

@Override
public void failed(final Exception cause) {
handlerDone.countDown();
}

@Override
public void releaseResources() {
handlerDone.countDown();
}
});

final HttpAsyncServer server = serverResource.start();
final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), scheme);
final ListenerEndpoint listener = future.get();
final InetSocketAddress address = (InetSocketAddress) listener.getAddress();
final HttpAsyncRequester requester = clientResource.start();
final HttpHost target = new HttpHost(scheme.id, "localhost", address.getPort());

final byte[] firstChunk = "FIRST-CHUNK-SENT-OK".getBytes(StandardCharsets.US_ASCII);

final ClassicHttpRequest request = ClassicRequestBuilder.post()
.setHttpHost(target)
.setPath("/truncate")
.setEntity(new FailingEntity(firstChunk))
.build();

final ClassicToAsyncRequestProducer requestProducer = new ClassicToAsyncRequestProducer(request, TIMEOUT);
final ClassicToAsyncResponseConsumer responseConsumer = new ClassicToAsyncResponseConsumer(TIMEOUT);

requester.execute(requestProducer, responseConsumer, TIMEOUT, null);

Assertions.assertThatThrownBy(() -> requestProducer.blockWaiting().execute())
.isInstanceOf(IOException.class);

Assertions.assertThat(handlerDone.await(5, TimeUnit.SECONDS)).isTrue();

// The entity never wrote the rest of the body it declared; the server must not treat
// the request as having ended cleanly just because the output stream was closed.
Assertions.assertThat(streamEnded.get())
.as("server treated a request body that failed mid-write as complete")
.isFalse();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,16 @@ public IORunnable blockWaiting() throws IOException, InterruptedException {
return () -> {
final HttpEntity requestEntity = request.getEntity();
if (requestEntity != null) {
try (final InternalOutputStream outputStream = new InternalOutputStream(outputBuffer)) {
final InternalOutputStream outputStream = new InternalOutputStream(outputBuffer);
try {
requestEntity.writeTo(outputStream);
outputStream.close();
} catch (final IOException | RuntimeException ex) {
// writeTo failed partway: closing the stream here, as a bare
// try-with-resources would, marks the message complete on the wire
// even though it is not. Abort it instead.
outputBuffer.abort();
throw ex;
}
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ public void flush(final DataStreamChannel channel) throws IOException {
dataStreamChannel = channel;
hasCapacity = true;
setOutputMode();
ensureNotAborted();
if (buffer().hasRemaining()) {
dataStreamChannel.write(buffer());
}
Expand Down
Loading