Skip to content

Commit 82845b7

Browse files
committed
HTTP/2 error handling improvements
1 parent 161394f commit 82845b7

6 files changed

Lines changed: 882 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
@@ -479,7 +479,7 @@ public SocketState upgradeDispatch(SocketEvent status) {
479479
if (stream == null) {
480480
sendStreamReset(null, se);
481481
} else {
482-
stream.close(se);
482+
stream.closeOnStreamError(se);
483483
}
484484
} finally {
485485
if (isOverheadLimitExceeded()) {

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

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
import org.apache.tomcat.util.http.parser.HttpParser;
5353
import org.apache.tomcat.util.http.parser.Priority;
5454
import org.apache.tomcat.util.net.ApplicationBufferHandler;
55+
import org.apache.tomcat.util.net.SocketEvent;
5556
import org.apache.tomcat.util.net.WriteBuffer;
5657
import org.apache.tomcat.util.res.StringManager;
5758

@@ -110,6 +111,11 @@ class Stream extends AbstractNonZeroStream implements HeaderEmitter {
110111

111112
private final Object recycledLock = new Object();
112113
private volatile boolean recycled = false;
114+
// The processor handling the request for this stream. Set when the processor is created.
115+
private volatile StreamProcessor streamProcessor = null;
116+
// A stream error raised by the connection thread while the processor was still processing the request.
117+
private volatile StreamException streamError = null;
118+
private final AtomicBoolean streamErrorNotified = new AtomicBoolean(false);
113119

114120

115121
Stream(Integer identifier, Http2UpgradeHandler handler) {
@@ -874,6 +880,74 @@ final boolean isInputFinished() {
874880
}
875881

876882

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