Skip to content
Closed
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
42 changes: 24 additions & 18 deletions java/org/apache/tomcat/util/net/SocketWrapperBase.java
Original file line number Diff line number Diff line change
Expand Up @@ -1358,14 +1358,17 @@ public void completed(Long nBytes, OperationState<A> state) {
state.state = currentState;
}
state.end();
if (completion && state.handler != null && state.callHandler.compareAndSet(true, false)) {
state.handler.completed(Long.valueOf(state.nBytes), state.attachment);
}
synchronized (state) {
state.completionDone = true;
if (notify) {
state.state = currentState;
state.notify();
try {
if (completion && state.handler != null && state.callHandler.compareAndSet(true, false)) {
state.handler.completed(Long.valueOf(state.nBytes), state.attachment);
}
} finally {
synchronized (state) {
state.completionDone = true;
if (notify) {
state.state = currentState;
state.notify();
}
}
}
} else {
Expand Down Expand Up @@ -1404,14 +1407,17 @@ public void failed(Throwable exc, OperationState<A> state) {
state.state = state.isInline() ? CompletionState.ERROR : CompletionState.DONE;
}
state.end();
if (state.handler != null && state.callHandler.compareAndSet(true, false)) {
state.handler.failed(exc, state.attachment);
}
synchronized (state) {
state.completionDone = true;
if (notify) {
state.state = state.isInline() ? CompletionState.ERROR : CompletionState.DONE;
state.notify();
try {
if (state.handler != null && state.callHandler.compareAndSet(true, false)) {
state.handler.failed(exc, state.attachment);
}
} finally {
synchronized (state) {
state.completionDone = true;
if (notify) {
state.state = state.isInline() ? CompletionState.ERROR : CompletionState.DONE;
state.notify();
}
}
}
}
Expand Down Expand Up @@ -1726,8 +1732,8 @@ protected final <A> CompletionState vectoredOperation(boolean read, ByteBuffer[]

/**
* The completion thread has claimed the right to call the handler but has not yet finished doing so. Wait for it to
* finish (it updates the state and notifies once the handler has returned) so that the caller does not return
* before the handler has been called. The caller must hold the monitor for the state.
* finish (it updates the state and notifies once the handler has returned or thrown) so that the caller does not
* return before the handler has been called. The caller must hold the monitor for the state.
*/
private void awaitHandlerCompletion(OperationState<?> state) {
boolean interrupted = false;
Expand Down
163 changes: 163 additions & 0 deletions test/org/apache/coyote/http11/upgrade/TestUpgradeInternalHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@
import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

import javax.net.SocketFactory;

Expand Down Expand Up @@ -79,6 +82,55 @@ public void testUpgradeInternal() throws Exception {
pw.close();
}

// A blocking read whose completion handler throws must still return. Each of these tests prints the stack trace
// of the expected exception from the container thread that ran the handler.
@Test
public void testBlockingReadCompletedThrowsBeforeTimeout() throws Exception {
// The handler throws while the caller is still in its timed wait
doBlockingReadHandlerThrows(BlockingReadThrowingHandler.Mode.COMPLETED_THROWS, 2000, 0, false,
CompletionState.DONE);
}

@Test
public void testBlockingReadCompletedThrowsAfterTimeout() throws Exception {
// The read times out while the handler (claimed by the completion thread) is still running, so the caller
// waits for the handler to finish; the handler then throws
doBlockingReadHandlerThrows(BlockingReadThrowingHandler.Mode.COMPLETED_THROWS, 200, 1000, false,
CompletionState.ERROR);
}

@Test
public void testBlockingReadFailedThrows() throws Exception {
// End of stream: the completion thread calls failed(), which throws
doBlockingReadHandlerThrows(BlockingReadThrowingHandler.Mode.FAILED_THROWS, 2000, 0, true,
CompletionState.DONE);
}

private void doBlockingReadHandlerThrows(BlockingReadThrowingHandler.Mode mode, long readTimeoutMillis,
long handlerDelayMillis, boolean endOfStream, CompletionState expected) throws Exception {
BlockingReadThrowingHandler.reset(mode, readTimeoutMillis, handlerDelayMillis);
UpgradeConnection uc = doUpgrade(BlockingReadThrowingHandler.class);
try {
Assert.assertTrue(BlockingReadThrowingHandler.readStarting.await(10, TimeUnit.SECONDS));
// Give the read time to register with the poller so that it does not complete inline
Thread.sleep(100);
if (endOfStream) {
uc.shutdownOutput();
} else {
uc.getWriter().write('x');
uc.getWriter().flush();
}

Assert.assertTrue("Blocking read did not return after the completion handler threw",
BlockingReadThrowingHandler.readReturned.await(10, TimeUnit.SECONDS));
Assert.assertTrue("The completion handler was not called",
BlockingReadThrowingHandler.handlerCalled.get());
Assert.assertEquals(expected, BlockingReadThrowingHandler.readState.get());
} finally {
uc.close();
}
}

private UpgradeConnection doUpgrade(
Class<? extends HttpUpgradeHandler> upgradeHandlerClass) throws Exception {
// Setup Tomcat instance
Expand Down Expand Up @@ -183,6 +235,10 @@ public void shutdownOutput() throws IOException {
public void shutdownInput() throws IOException {
socket.shutdownInput();
}

public void close() throws IOException {
socket.close();
}
}


Expand Down Expand Up @@ -283,4 +339,111 @@ public void setSslSupport(SSLSupport sslSupport) {
}
}


public static class BlockingReadThrowingHandler implements InternalHttpUpgradeHandler {

enum Mode {
COMPLETED_THROWS,
FAILED_THROWS
}

private static volatile Mode mode;
private static volatile long readTimeoutMillis;
private static volatile long handlerDelayMillis;
private static volatile CountDownLatch readStarting;
private static volatile CountDownLatch readReturned;
private static final AtomicBoolean handlerCalled = new AtomicBoolean();
private static final AtomicReference<CompletionState> readState = new AtomicReference<>();

private SocketWrapperBase<?> wrapper;

static void reset(Mode mode, long readTimeoutMillis, long handlerDelayMillis) {
BlockingReadThrowingHandler.mode = mode;
BlockingReadThrowingHandler.readTimeoutMillis = readTimeoutMillis;
BlockingReadThrowingHandler.handlerDelayMillis = handlerDelayMillis;
readStarting = new CountDownLatch(1);
readReturned = new CountDownLatch(1);
handlerCalled.set(false);
readState.set(null);
}

@Override
public void init(WebConnection connection) {
final ByteBuffer buffer = ByteBuffer.allocate(1024);
try {
readStarting.countDown();
readState.set(wrapper.read(BlockingMode.BLOCK, readTimeoutMillis, TimeUnit.MILLISECONDS, null, null,
new CompletionHandler<Long,Void>() {
@Override
public void completed(Long result, Void attachment) {
if (mode == Mode.COMPLETED_THROWS) {
throwExpectedFailure();
}
}

@Override
public void failed(Throwable exc, Void attachment) {
if (mode == Mode.FAILED_THROWS) {
throwExpectedFailure();
}
}
}, buffer));
} finally {
readReturned.countDown();
}
}

private static void throwExpectedFailure() {
handlerCalled.set(true);
if (handlerDelayMillis > 0) {
try {
Thread.sleep(handlerDelayMillis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
throw new IllegalStateException("Expected failure in the completion handler");
}

@Override
public void pause() {
// NO-OP
}

@Override
public void destroy() {
// NO-OP
}

@Override
public SocketState upgradeDispatch(SocketEvent status) {
switch (status) {
case OPEN_READ:
case OPEN_WRITE:
break;
case STOP:
case DISCONNECT:
case ERROR:
case TIMEOUT:
case CONNECT_FAIL:
return SocketState.CLOSED;
}
return SocketState.UPGRADED;
}

@Override
public void timeoutAsync(long now) {
// NO-OP
}

@Override
public void setSocketWrapper(SocketWrapperBase<?> wrapper) {
this.wrapper = wrapper;
}

@Override
public void setSslSupport(SSLSupport sslSupport) {
// NO-OP
}
}
}
4 changes: 4 additions & 0 deletions webapps/docs/changelog.xml
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,10 @@
waiting to be processed continues to count towards the limit on the
number of concurrent streams until that work has been processed. (markt)
</fix>
<fix>
Ensure that a blocking read or write using asynchronous I/O does not
wait indefinitely if its completion handler throws an exception.
</fix>
</changelog>
</subsection>
<subsection name="Jasper">
Expand Down