Skip to content

Commit 88409ed

Browse files
committed
HTTP/2 error handling improvements
1 parent eaea185 commit 88409ed

6 files changed

Lines changed: 878 additions & 5 deletions

File tree

‎java/org/apache/coyote/http2/Http2UpgradeHandler.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -477,7 +477,7 @@ public SocketState upgradeDispatch(SocketEvent status) {
477477
if (stream == null) {
478478
sendStreamReset(null, se);
479479
} else {
480-
stream.close(se);
480+
stream.closeOnStreamError(se);
481481
}
482482
} finally {
483483
if (isOverheadLimitExceeded()) {

‎java/org/apache/coyote/http2/Stream.java‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
import org.apache.tomcat.util.http.parser.HttpParser;
5757
import org.apache.tomcat.util.http.parser.Priority;
5858
import org.apache.tomcat.util.net.ApplicationBufferHandler;
59+
import org.apache.tomcat.util.net.SocketEvent;
5960
import org.apache.tomcat.util.net.WriteBuffer;
6061
import org.apache.tomcat.util.res.StringManager;
6162

@@ -114,6 +115,11 @@ class Stream extends AbstractNonZeroStream implements HeaderEmitter {
114115

115116
private final Object recycledLock = new Object();
116117
private volatile boolean recycled = false;
118+
// The processor handling the request for this stream. Set when the processor is created.
119+
private volatile StreamProcessor streamProcessor = null;
120+
// A stream error raised by the connection thread while the processor was still processing the request.
121+
private volatile StreamException streamError = null;
122+
private final AtomicBoolean streamErrorNotified = new AtomicBoolean(false);
117123

118124

119125
Stream(Integer identifier, Http2UpgradeHandler handler) {
@@ -885,6 +891,74 @@ final boolean isInputFinished() {
885891
}
886892

887893

894+
/**
895+
* Closes the stream following a stream error detected by the connection thread while processing incoming frames.
896+
* <p>
897+
* If a {@link StreamProcessor} is still processing the request, the request is, or may become, asynchronous. A
898+
* waiting processor can only complete its clean-up (remove itself from the waiting processors and recycle itself)
899+
* when it processes an event so it must be notified of the error. If the request is already in asynchronous mode
900+
* that is done here. Otherwise it is done by the processor once the request becomes asynchronous.
901+
*
902+
* @param streamException The stream error
903+
*/
904+
@SuppressWarnings("null") // processor is not null when it is referenced
905+
final void closeOnStreamError(StreamException streamException) {
906+
StreamProcessor processor = streamProcessor;
907+
close(streamException);
908+
if (processor != null && !recycled) {
909+
/*
910+
* Record the error before checking if the request is asynchronous. The processor checks for a recorded
911+
* error after it has started asynchronous processing (see notifyProcessorOfStreamError()). With both
912+
* fields volatile, at least one of the two threads is guaranteed to see the other's update so the processor
913+
* is always notified, whichever thread wins the race.
914+
*/
915+
streamError = streamException;
916+
if (processor.isAsync()) {
917+
notifyProcessorOfStreamError(processor);
918+
}
919+
}
920+
}
921+
922+
923+
/**
924+
* Called by the {@link StreamProcessor} once the request has started asynchronous processing. If the connection
925+
* thread raised a stream error before asynchronous processing started it will not have notified the processor, so
926+
* do so now. Without the notification, nothing would clean up the processor until the asynchronous timeout fired
927+
* (or never, if there is no timeout).
928+
*
929+
* @param processor The processor for this stream
930+
*/
931+
final void notifyProcessorOfStreamError(StreamProcessor processor) {
932+
// Notify once only, whichever thread gets here first
933+
if (streamError != null && !recycled && streamErrorNotified.compareAndSet(false, true)) {
934+
/*
935+
* The request is deliberately not touched here. This may be called from a thread that does not own the
936+
* request and the attributes of the request are not thread-safe. The processor sets the error attribute on
937+
* the request when it processes the event (see StreamProcessor.process()).
938+
*
939+
* If the processor has already cleaned up before the event is processed, it ignores the event.
940+
*/
941+
processor.processSocketEvent(SocketEvent.ERROR, true);
942+
}
943+
}
944+
945+
946+
/**
947+
* Obtain the stream error, if any, that was raised by the connection thread while the request for this stream was
948+
* still being processed.
949+
*
950+
* @return The stream error or {@code null}
951+
*/
952+
final StreamException getStreamError() {
953+
return streamError;
954+
}
955+
956+
957+
final void setStreamProcessor(StreamProcessor streamProcessor) {
958+
this.streamProcessor = streamProcessor;
959+
}
960+
961+
888962
final void close(Http2Exception http2Exception) {
889963
if (http2Exception instanceof ConnectionException) {
890964
handler.closeConnection(http2Exception);

‎java/org/apache/coyote/http2/StreamProcessor.java‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ class StreamProcessor extends AbstractProcessor implements NonPipeliningProcesso
6363
private final Lock processLock = new ReentrantLock();
6464
private final Http2UpgradeHandler handler;
6565
private final Stream stream;
66+
// True while this processor is registered as a waiting processor. Only modified while holding processLock.
67+
private volatile boolean waiting = false;
6668
private SendfileData sendfileData = null;
6769
private SendfileState sendfileState = null;
6870

@@ -77,6 +79,7 @@ class StreamProcessor extends AbstractProcessor implements NonPipeliningProcesso
7779
super(adapter, stream.getCoyoteRequest(), stream.getCoyoteResponse());
7880
this.handler = handler;
7981
this.stream = stream;
82+
stream.setStreamProcessor(this);
8083
setSocketWrapper(socketWrapper);
8184
}
8285

@@ -93,7 +96,13 @@ final void process(SocketEvent event) {
9396
* replaced it should not be used for processing any further events. When it is known that processing is
9497
* going to be a NO-OP, exit early.
9598
*/
96-
if (!stream.equals(handler.getStream(stream.getIdAsInt()))) {
99+
/*
100+
* The exception is a processor that is registered as a waiting processor (asynchronous processing).
101+
* The connection thread replaces the stream when it raises a stream error. A waiting processor can only
102+
* complete its clean-up (remove itself from the waiting processors and recycle itself) by processing
103+
* an event so it must not ignore events just because the stream has been replaced.
104+
*/
105+
if (!waiting && !stream.equals(handler.getStream(stream.getIdAsInt()))) {
97106
return;
98107
}
99108
// Avoid duplicate timeout events
@@ -103,6 +112,17 @@ final void process(SocketEvent event) {
103112
SocketState state = SocketState.CLOSED;
104113
boolean reuseRequestAndResponse = false;
105114
try {
115+
if (event == SocketEvent.ERROR) {
116+
/*
117+
* If the connection thread raised a stream error while the request was being processed, make
118+
* the error visible to the application. It is set here, on the thread that owns the request,
119+
* and not by the connection thread, since the attributes of the request are not thread-safe.
120+
*/
121+
StreamException streamError = stream.getStreamError();
122+
if (streamError != null && request.getAttribute(RequestDispatcher.ERROR_EXCEPTION) == null) {
123+
request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, streamError);
124+
}
125+
}
106126
state = process(socketWrapper, event);
107127
/*
108128
* The request and response may only be returned to the pool for re-use if the stream ended cleanly.
@@ -117,14 +137,20 @@ final void process(SocketEvent event) {
117137
}
118138

119139
if (state == SocketState.LONG) {
140+
waiting = true;
120141
handler.getProtocol().getHttp11Protocol().addWaitingProcessor(this);
142+
// The connection thread may have raised a stream error before the request became async
143+
stream.notifyProcessorOfStreamError(this);
121144
} else if (state == SocketState.CLOSED) {
145+
waiting = false;
122146
handler.getProtocol().getHttp11Protocol().removeWaitingProcessor(this);
123-
if (!stream.isInputFinished() && getErrorState().isIoAllowed()) {
147+
if (!stream.isInputFinished() && getErrorState().isIoAllowed() && stream.canReset()) {
124148
// The request has been processed but the request body has not been
125149
// fully read. This typically occurs when Tomcat rejects an upload
126150
// of some form (e.g. PUT or POST). Need to tell the client not to
127-
// send any more data on this stream (reset).
151+
// send any more data on this stream (reset). If the stream can no
152+
// longer be reset (e.g. a reset has already been sent) there is
153+
// nothing to send. The final else block performs the clean-up.
128154
StreamException se =
129155
new StreamException(sm.getString("streamProcessor.cancel", stream.getConnectionId(),
130156
stream.getIdAsString()), Http2Error.NO_ERROR, stream.getIdAsInt());

0 commit comments

Comments
 (0)