You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tomee.apache.org by rz...@apache.org on 2023/10/12 05:38:32 UTC

[tomee] branch tomee-9.x updated (c75f76167c -> 71f6475a25)

This is an automated email from the ASF dual-hosted git repository.

rzo1 pushed a change to branch tomee-9.x
in repository https://gitbox.apache.org/repos/asf/tomee.git


    from c75f76167c Avoid duplicate bouncycastle jars in the libs due to invalid excludes from previous dependency upgrades
     new ff8b6aa779 TOMEE-4255 - Add unpatched classes in preparation of backporting changes from https://github.com/apache/tomcat/commit/76bb4bfbfeae827dce896f650655bbf6e251ed49#diff-9105b119c42abec1b9a22cd5d6fc2c0b4edc63175a12858b8b383fb7554ab57f for CVE-2023-44487
     new 87136d0eac TOMEE-4255 - Add patched classes from https://github.com/apache/tomcat/commit/76bb4bfbfeae827dce896f650655bbf6e251ed49#diff-9105b119c42abec1b9a22cd5d6fc2c0b4edc63175a12858b8b383fb7554ab57f for CVE-2023-44487.
     new 314ea5ac41 TOMEE-4256 - Add unpatched classes for backporting changes from https://github.com/apache/tomcat/commit/8ecff306507be8e4fd3adee1ae5de1ea6661a8f4 for CVE-2023-45648
     new e0b4d659c9 TOMEE-4256 - Add patched classes from https://github.com/apache/tomcat/commit/8ecff306507be8e4fd3adee1ae5de1ea6661a8f4 for CVE-2023-45648
     new 95521287ab TOMEE-4254 - Add unpatched classes to backport https://github.com/apache/tomcat/commit/9375d67106f8df9eb9d7b360b2bef052fe67d3d4
     new 71f6475a25 TOMEE-4254 - Backport changes from https://github.com/apache/tomcat/commit/9375d67106f8df9eb9d7b360b2bef052fe67d3d4

The 6 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 tomee/apache-tomee/pom.xml                         |    4 +
 .../catalina/connector/LocalStrings.properties     |   96 +
 .../org/apache/catalina/connector/Request.java     |    7 +-
 .../catalina/core/ApplicationHttpRequest.java      | 1001 ++++++++++
 .../apache/catalina/core/LocalStrings.properties   |  313 +++
 .../apache/coyote/http11/Http11InputBuffer.java    | 1252 ++++++++++++
 .../coyote/http11/filters/ChunkedInputFilter.java  |  653 ++++++
 .../coyote/http11/filters/LocalStrings.properties  |   29 +
 .../org/apache/coyote/http2/Http2AsyncParser.java  |  337 ++++
 .../org/apache/coyote/http2/Http2Protocol.java     |  396 ++++
 .../apache/coyote/http2/Http2UpgradeHandler.java   | 2100 ++++++++++++++++++++
 .../org/apache/tomcat/util/buf/B2CConverter.java   |  271 +++
 .../org/apache/tomcat/util/buf/C2BConverter.java   |  204 ++
 .../apache/tomcat/util/buf/LocalStrings.properties |   37 +
 14 files changed, 6697 insertions(+), 3 deletions(-)
 create mode 100644 tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/LocalStrings.properties
 create mode 100644 tomee/apache-tomee/src/patch/java/org/apache/catalina/core/ApplicationHttpRequest.java
 create mode 100644 tomee/apache-tomee/src/patch/java/org/apache/catalina/core/LocalStrings.properties
 create mode 100644 tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/Http11InputBuffer.java
 create mode 100644 tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
 create mode 100644 tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/filters/LocalStrings.properties
 create mode 100644 tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2AsyncParser.java
 create mode 100644 tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2Protocol.java
 create mode 100644 tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2UpgradeHandler.java
 create mode 100644 tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/B2CConverter.java
 create mode 100644 tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/C2BConverter.java
 create mode 100644 tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/LocalStrings.properties


[tomee] 06/06: TOMEE-4254 - Backport changes from https://github.com/apache/tomcat/commit/9375d67106f8df9eb9d7b360b2bef052fe67d3d4

Posted by rz...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rzo1 pushed a commit to branch tomee-9.x
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 71f6475a25d0d6abf2fcbc0568c7be13103b7bb9
Author: Richard Zowalla <rz...@apache.org>
AuthorDate: Wed Oct 11 15:46:38 2023 +0200

    TOMEE-4254 - Backport changes from https://github.com/apache/tomcat/commit/9375d67106f8df9eb9d7b360b2bef052fe67d3d4
---
 tomee/apache-tomee/pom.xml                                 |  4 ++++
 .../org/apache/catalina/connector/LocalStrings.properties  |  1 +
 .../patch/java/org/apache/catalina/connector/Request.java  |  7 ++++---
 .../org/apache/catalina/core/ApplicationHttpRequest.java   |  8 +++++++-
 .../java/org/apache/catalina/core/LocalStrings.properties  |  1 +
 .../java/org/apache/tomcat/util/buf/B2CConverter.java      | 11 ++++++++++-
 .../java/org/apache/tomcat/util/buf/C2BConverter.java      | 14 +++++++++++++-
 .../org/apache/tomcat/util/buf/LocalStrings.properties     |  4 ++++
 8 files changed, 44 insertions(+), 6 deletions(-)

diff --git a/tomee/apache-tomee/pom.xml b/tomee/apache-tomee/pom.xml
index 670319e4e1..bdc55c50ac 100644
--- a/tomee/apache-tomee/pom.xml
+++ b/tomee/apache-tomee/pom.xml
@@ -584,6 +584,8 @@
                   <bcpkix-jdk15to18-1.76.jar>org.bouncycastle:bcpkix-jdk15to18:jar:1.76</bcpkix-jdk15to18-1.76.jar>
                   <bcprov-jdk15to18-1.76.jar>org.bouncycastle:bcprov-jdk15to18:jar:1.76</bcprov-jdk15to18-1.76.jar>
                   <bcutil-jdk15to18-1.76.jar>org.bouncycastle:bcutil-jdk15to18:jar:1.76</bcutil-jdk15to18-1.76.jar>
+                  <!-- Don't modify bootstrap.jar. Current patch plugin 0.10 has an ambiguity adding classes in more than one target jar if the packages are matching -->
+                  <bootstrap.jar>bootstrap.jar</bootstrap.jar>
                 </jars>
               </skips>
             </configuration>
@@ -817,6 +819,8 @@
                   <bcpkix-jdk15to18-1.76.jar>org.bouncycastle:bcpkix-jdk15to18:jar:1.76</bcpkix-jdk15to18-1.76.jar>
                   <bcprov-jdk15to18-1.76.jar>org.bouncycastle:bcprov-jdk15to18:jar:1.76</bcprov-jdk15to18-1.76.jar>
                   <bcutil-jdk15to18-1.76.jar>org.bouncycastle:bcutil-jdk15to18:jar:1.76</bcutil-jdk15to18-1.76.jar>
+                  <!-- Don't modify bootstrap.jar. Current patch plugin 0.10 has an ambiguity adding classes in more than one target jar if the packages are matching -->
+                  <bootstrap.jar>bootstrap.jar</bootstrap.jar>
                 </jars>
               </skips>
             </configuration>
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/LocalStrings.properties b/tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/LocalStrings.properties
index 5cfd969f13..b0b9bba438 100644
--- a/tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/LocalStrings.properties
+++ b/tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/LocalStrings.properties
@@ -47,6 +47,7 @@ coyoteRequest.attributeEvent=Exception thrown by attributes event listener
 coyoteRequest.authenticate.ise=Cannot call authenticate() after the response has been committed
 coyoteRequest.changeSessionId=Cannot change session ID. There is no session associated with this request.
 coyoteRequest.chunkedPostTooLarge=Parameters were not parsed because the size of the posted data was too big. Because this request was a chunked request, it could not be processed further. Use the maxPostSize attribute of the connector to resolve this if the application should accept large POSTs.
+coyoteRequest.deletePartFailed=Failed to deleted temporary file used for part [{0}]
 coyoteRequest.filterAsyncSupportUnknown=Unable to determine if any filters do not support async processing
 coyoteRequest.getContextPath.ise=Unable to find match between the canonical context path [{0}] and the URI presented by the user agent [{1}]
 coyoteRequest.getInputStream.ise=getReader() has already been called for this request
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/Request.java b/tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/Request.java
index 5f0b56e826..3d4faf26dc 100644
--- a/tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/Request.java
+++ b/tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/Request.java
@@ -449,8 +449,9 @@ public class Request implements HttpServletRequest {
             for (Part part: parts) {
                 try {
                     part.delete();
-                } catch (IOException ignored) {
-                    // ApplicationPart.delete() never throws an IOEx
+                } catch (Throwable t) {
+                    ExceptionUtils.handleThrowable(t);
+                    log.warn(sm.getString("coyoteRequest.deletePartFailed", part.getName()), t);
                 }
             }
             parts = null;
@@ -503,8 +504,8 @@ public class Request implements HttpServletRequest {
         asyncSupported = null;
         if (asyncContext!=null) {
             asyncContext.recycle();
+            asyncContext = null;
         }
-        asyncContext = null;
     }
 
 
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/ApplicationHttpRequest.java b/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/ApplicationHttpRequest.java
index 6d6dd6fe38..0c36f12a0b 100644
--- a/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/ApplicationHttpRequest.java
+++ b/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/ApplicationHttpRequest.java
@@ -48,6 +48,7 @@ import org.apache.catalina.connector.RequestFacade;
 import org.apache.catalina.util.ParameterMap;
 import org.apache.catalina.util.RequestUtil;
 import org.apache.catalina.util.URLEncoder;
+import org.apache.tomcat.util.ExceptionUtils;
 import org.apache.tomcat.util.buf.B2CConverter;
 import org.apache.tomcat.util.buf.MessageBytes;
 import org.apache.tomcat.util.http.Parameters;
@@ -650,7 +651,12 @@ class ApplicationHttpRequest extends HttpServletRequestWrapper {
      */
     public void recycle() {
         if (session != null) {
-            session.endAccess();
+            try {
+                session.endAccess();
+            } catch (Throwable t) {
+                ExceptionUtils.handleThrowable(t);
+                context.getLogger().warn(sm.getString("applicationHttpRequest.sessionEndAccessFail"), t);
+            }
         }
     }
 
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/LocalStrings.properties b/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/LocalStrings.properties
index bc9778aa87..07b47be594 100644
--- a/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/LocalStrings.properties
+++ b/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/LocalStrings.properties
@@ -59,6 +59,7 @@ applicationFilterRegistration.nullInitParam=Unable to set initialisation paramet
 applicationFilterRegistration.nullInitParams=Unable to set initialisation parameters for filter due to null name and/or value. Name [{0}], Value [{1}]
 
 applicationHttpRequest.fragmentInDispatchPath=The fragment in dispatch path [{0}] has been removed
+applicationHttpRequest.sessionEndAccessFail=Exception triggered ending access to session while recycling request
 
 applicationPushBuilder.methodInvalid=The HTTP method for a push request must be both cacheable and safe but [{0}] is not
 applicationPushBuilder.methodNotToken=HTTP methods must be tokens but [{0}] contains a non-token character
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/B2CConverter.java b/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/B2CConverter.java
index 532c209ec9..98f989b0f7 100644
--- a/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/B2CConverter.java
+++ b/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/B2CConverter.java
@@ -27,6 +27,9 @@ import java.nio.charset.CodingErrorAction;
 import java.nio.charset.StandardCharsets;
 import java.util.Locale;
 
+import org.apache.juli.logging.Log;
+import org.apache.juli.logging.LogFactory;
+import org.apache.tomcat.util.ExceptionUtils;
 import org.apache.tomcat.util.res.StringManager;
 
 /**
@@ -34,6 +37,7 @@ import org.apache.tomcat.util.res.StringManager;
  */
 public class B2CConverter {
 
+    private static final Log log = LogFactory.getLog(B2CConverter.class);
     private static final StringManager sm = StringManager.getManager(B2CConverter.class);
 
     private static final CharsetCache charsetCache = new CharsetCache();
@@ -106,7 +110,12 @@ public class B2CConverter {
      * Reset the decoder state.
      */
     public void recycle() {
-        decoder.reset();
+        try {
+            decoder.reset();
+        } catch (Throwable t) {
+            ExceptionUtils.handleThrowable(t);
+            log.warn(sm.getString("b2cConverter.decoderResetFail", decoder.charset()), t);
+        }
         leftovers.position(0);
     }
 
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/C2BConverter.java b/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/C2BConverter.java
index 4b27f6c980..d637d8931c 100644
--- a/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/C2BConverter.java
+++ b/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/C2BConverter.java
@@ -24,11 +24,18 @@ import java.nio.charset.CharsetEncoder;
 import java.nio.charset.CoderResult;
 import java.nio.charset.CodingErrorAction;
 
+import org.apache.juli.logging.Log;
+import org.apache.juli.logging.LogFactory;
+import org.apache.tomcat.util.ExceptionUtils;
+import org.apache.tomcat.util.res.StringManager;
+
 /**
  * NIO based character encoder.
  */
 public final class C2BConverter {
 
+    private static final Log log = LogFactory.getLog(C2BConverter.class);
+    private static final StringManager sm = StringManager.getManager(C2BConverter.class);
     private final CharsetEncoder encoder;
     private ByteBuffer bb = null;
     private CharBuffer cb = null;
@@ -50,7 +57,12 @@ public final class C2BConverter {
      * Reset the encoder state.
      */
     public void recycle() {
-        encoder.reset();
+        try {
+            encoder.reset();
+        } catch (Throwable t) {
+            ExceptionUtils.handleThrowable(t);
+            log.warn(sm.getString("c2bConverter.decoderResetFail", encoder.charset()), t);
+        }
         leftovers.position(0);
     }
 
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/LocalStrings.properties b/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/LocalStrings.properties
index cd883e6f57..3890677cbb 100644
--- a/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/LocalStrings.properties
+++ b/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/LocalStrings.properties
@@ -16,10 +16,14 @@
 asn1Parser.lengthInvalid=Invalid length [{0}] bytes reported when the input data length is [{1}] bytes
 asn1Parser.tagMismatch=Expected to find value [{0}] but found value [{1}]
 
+
+b2cConverter.decoderResetFail=Failed to reset instance of decoder for character set [{0}]
 b2cConverter.unknownEncoding=The character encoding [{0}] is not supported
 
 byteBufferUtils.cleaner=Cannot use direct ByteBuffer cleaner, memory leaking may occur
 
+c2bConverter.encoderResetFail=Failed to reset instance of encoder for character set [{0}]
+
 chunk.overflow=Buffer overflow and no sink is set, limit [{0}] and buffer length [{1}]
 
 encodedSolidusHandling.invalid=The value [{0}] is not recognised


[tomee] 01/06: TOMEE-4255 - Add unpatched classes in preparation of backporting changes from https://github.com/apache/tomcat/commit/76bb4bfbfeae827dce896f650655bbf6e251ed49#diff-9105b119c42abec1b9a22cd5d6fc2c0b4edc63175a12858b8b383fb7554ab57f for CVE-2023-44487

Posted by rz...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rzo1 pushed a commit to branch tomee-9.x
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit ff8b6aa779965bdb839d723e189003e807dacf42
Author: Richard Zowalla <rz...@apache.org>
AuthorDate: Wed Oct 11 08:42:57 2023 +0200

    TOMEE-4255 - Add unpatched classes in preparation of backporting changes from https://github.com/apache/tomcat/commit/76bb4bfbfeae827dce896f650655bbf6e251ed49#diff-9105b119c42abec1b9a22cd5d6fc2c0b4edc63175a12858b8b383fb7554ab57f for CVE-2023-44487
---
 .../org/apache/coyote/http2/Http2AsyncParser.java  |  334 ++++
 .../org/apache/coyote/http2/Http2Protocol.java     |  378 ++++
 .../apache/coyote/http2/Http2UpgradeHandler.java   | 2094 ++++++++++++++++++++
 3 files changed, 2806 insertions(+)

diff --git a/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2AsyncParser.java b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2AsyncParser.java
new file mode 100644
index 0000000000..d01497051d
--- /dev/null
+++ b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2AsyncParser.java
@@ -0,0 +1,334 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.coyote.http2;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.CompletionHandler;
+import java.util.concurrent.TimeUnit;
+
+import jakarta.servlet.http.WebConnection;
+
+import org.apache.coyote.ProtocolException;
+import org.apache.tomcat.util.net.SocketEvent;
+import org.apache.tomcat.util.net.SocketWrapperBase;
+import org.apache.tomcat.util.net.SocketWrapperBase.BlockingMode;
+import org.apache.tomcat.util.net.SocketWrapperBase.CompletionCheck;
+import org.apache.tomcat.util.net.SocketWrapperBase.CompletionHandlerCall;
+import org.apache.tomcat.util.net.SocketWrapperBase.CompletionState;
+
+class Http2AsyncParser extends Http2Parser {
+
+    private final SocketWrapperBase<?> socketWrapper;
+    private final Http2AsyncUpgradeHandler upgradeHandler;
+    private volatile Throwable error = null;
+
+    Http2AsyncParser(String connectionId, Input input, Output output, SocketWrapperBase<?> socketWrapper, Http2AsyncUpgradeHandler upgradeHandler) {
+        super(connectionId, input, output);
+        this.socketWrapper = socketWrapper;
+        socketWrapper.getSocketBufferHandler().expand(input.getMaxFrameSize());
+        this.upgradeHandler = upgradeHandler;
+    }
+
+
+    @Override
+    void readConnectionPreface(WebConnection webConnection, Stream stream) throws Http2Exception {
+        byte[] prefaceData = new byte[CLIENT_PREFACE_START.length];
+        ByteBuffer preface = ByteBuffer.wrap(prefaceData);
+        ByteBuffer header = ByteBuffer.allocate(9);
+        ByteBuffer framePayload = ByteBuffer.allocate(input.getMaxFrameSize());
+        PrefaceCompletionHandler handler = new PrefaceCompletionHandler(webConnection, stream, prefaceData, preface, header, framePayload);
+        socketWrapper.read(BlockingMode.NON_BLOCK, socketWrapper.getReadTimeout(), TimeUnit.MILLISECONDS, null,
+                handler, handler, preface, header, framePayload);
+    }
+
+
+    private class PrefaceCompletionHandler extends FrameCompletionHandler {
+
+        private final WebConnection webConnection;
+        private final Stream stream;
+        private final byte[] prefaceData;
+
+        private volatile boolean prefaceValidated = false;
+
+        private PrefaceCompletionHandler(WebConnection webConnection, Stream stream, byte[] prefaceData, ByteBuffer... buffers) {
+            super(FrameType.SETTINGS, buffers);
+            this.webConnection = webConnection;
+            this.stream = stream;
+            this.prefaceData = prefaceData;
+        }
+
+        @Override
+        public CompletionHandlerCall callHandler(CompletionState state, ByteBuffer[] buffers, int offset, int length) {
+            if (offset != 0 || length != 3) {
+                try {
+                    throw new IllegalArgumentException(sm.getString("http2Parser.invalidBuffers"));
+                } catch (IllegalArgumentException e) {
+                    error = e;
+                    return CompletionHandlerCall.DONE;
+                }
+            }
+            if (!prefaceValidated) {
+                if (buffers[0].hasRemaining()) {
+                    // The preface must be fully read before being validated
+                    return CompletionHandlerCall.CONTINUE;
+                }
+                // Validate preface content
+                for (int i = 0; i < CLIENT_PREFACE_START.length; i++) {
+                    if (CLIENT_PREFACE_START[i] != prefaceData[i]) {
+                        error = new ProtocolException(sm.getString("http2Parser.preface.invalid"));
+                        return CompletionHandlerCall.DONE;
+                    }
+                }
+                prefaceValidated = true;
+            }
+            return validate(state, buffers[1], buffers[2]);
+        }
+
+        @Override
+        public void completed(Long result, Void attachment) {
+            if (streamException || error == null) {
+                ByteBuffer payload = buffers[2];
+                payload.flip();
+                try {
+                    if (streamException) {
+                        swallowPayload(streamId, frameTypeId, payloadSize, false, payload);
+                    } else {
+                        readSettingsFrame(flags, payloadSize, payload);
+                    }
+                } catch (RuntimeException | IOException | Http2Exception e) {
+                    error = e;
+                }
+                // Any extra frame is not processed yet, so put back any leftover data
+                if (payload.hasRemaining()) {
+                    socketWrapper.unRead(payload);
+                }
+                // Finish processing the connection
+                upgradeHandler.processConnectionCallback(webConnection, stream);
+            } else {
+                upgradeHandler.closeConnection(new ConnectionException(error.getMessage(), Http2Error.PROTOCOL_ERROR, error));
+            }
+            // Continue reading frames
+            upgradeHandler.upgradeDispatch(SocketEvent.OPEN_READ);
+        }
+    }
+
+    @Override
+    protected boolean readFrame(boolean block, FrameType expected)
+            throws IOException, Http2Exception {
+        handleAsyncException();
+        ByteBuffer header = ByteBuffer.allocate(9);
+        ByteBuffer framePayload = ByteBuffer.allocate(input.getMaxFrameSize());
+        FrameCompletionHandler handler = new FrameCompletionHandler(expected, header, framePayload);
+        CompletionState state =
+                socketWrapper.read(block ? BlockingMode.BLOCK : BlockingMode.NON_BLOCK, socketWrapper.getReadTimeout(), TimeUnit.MILLISECONDS, null, handler, handler, header, framePayload);
+        if (state == CompletionState.ERROR || state == CompletionState.INLINE) {
+            handleAsyncException();
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    private void handleAsyncException()
+            throws IOException, Http2Exception {
+        if (error != null) {
+            Throwable error = this.error;
+            this.error = null;
+            if (error instanceof Http2Exception) {
+                throw (Http2Exception) error;
+            } else if (error instanceof IOException) {
+                throw (IOException) error;
+            } else if (error instanceof RuntimeException) {
+                throw (RuntimeException) error;
+            } else {
+                throw new RuntimeException(error);
+            }
+        }
+    }
+
+    private class FrameCompletionHandler implements CompletionCheck, CompletionHandler<Long, Void> {
+
+        private final FrameType expected;
+        protected final ByteBuffer[] buffers;
+
+        private volatile boolean parsedFrameHeader = false;
+        private volatile boolean validated = false;
+        private volatile CompletionState state = null;
+        protected volatile int payloadSize;
+        protected volatile int frameTypeId;
+        protected volatile FrameType frameType;
+        protected volatile int flags;
+        protected volatile int streamId;
+        protected volatile boolean streamException = false;
+
+        private FrameCompletionHandler(FrameType expected, ByteBuffer... buffers) {
+            this.expected = expected;
+            this.buffers = buffers;
+        }
+
+        @Override
+        public CompletionHandlerCall callHandler(CompletionState state,
+                ByteBuffer[] buffers, int offset, int length) {
+            if (offset != 0 || length != 2) {
+                try {
+                    throw new IllegalArgumentException(sm.getString("http2Parser.invalidBuffers"));
+                } catch (IllegalArgumentException e) {
+                    error = e;
+                    return CompletionHandlerCall.DONE;
+                }
+            }
+            return validate(state, buffers[0], buffers[1]);
+        }
+
+        protected CompletionHandlerCall validate(CompletionState state, ByteBuffer frameHeaderBuffer, ByteBuffer payload) {
+            if (!parsedFrameHeader) {
+                // The first buffer should be 9 bytes long
+                if (frameHeaderBuffer.position() < 9) {
+                    return CompletionHandlerCall.CONTINUE;
+                }
+                parsedFrameHeader = true;
+                payloadSize = ByteUtil.getThreeBytes(frameHeaderBuffer, 0);
+                frameTypeId = ByteUtil.getOneByte(frameHeaderBuffer, 3);
+                frameType = FrameType.valueOf(frameTypeId);
+                flags = ByteUtil.getOneByte(frameHeaderBuffer, 4);
+                streamId = ByteUtil.get31Bits(frameHeaderBuffer, 5);
+            }
+            this.state = state;
+
+            if (!validated) {
+                validated = true;
+                try {
+                    validateFrame(expected, frameType, streamId, flags, payloadSize);
+                } catch (StreamException e) {
+                    error = e;
+                    streamException = true;
+                } catch (Http2Exception e) {
+                    error = e;
+                    // The problem will be handled later, consider the frame read is done
+                    return CompletionHandlerCall.DONE;
+                }
+            }
+
+            if (payload.position() < payloadSize) {
+                return CompletionHandlerCall.CONTINUE;
+            }
+
+            return CompletionHandlerCall.DONE;
+        }
+
+        @Override
+        public void completed(Long result, Void attachment) {
+            if (streamException || error == null) {
+                ByteBuffer payload = buffers[1];
+                payload.flip();
+                try {
+                    boolean continueParsing;
+                    do {
+                        continueParsing = false;
+                        if (streamException) {
+                            swallowPayload(streamId, frameTypeId, payloadSize, false, payload);
+                        } else {
+                            switch (frameType) {
+                            case DATA:
+                                readDataFrame(streamId, flags, payloadSize, payload);
+                                break;
+                            case HEADERS:
+                                readHeadersFrame(streamId, flags, payloadSize, payload);
+                                break;
+                            case PRIORITY:
+                                readPriorityFrame(streamId, payload);
+                                break;
+                            case RST:
+                                readRstFrame(streamId, payload);
+                                break;
+                            case SETTINGS:
+                                readSettingsFrame(flags, payloadSize, payload);
+                                break;
+                            case PUSH_PROMISE:
+                                readPushPromiseFrame(streamId, flags, payloadSize, payload);
+                                break;
+                            case PING:
+                                readPingFrame(flags, payload);
+                                break;
+                            case GOAWAY:
+                                readGoawayFrame(payloadSize, payload);
+                                break;
+                            case WINDOW_UPDATE:
+                                readWindowUpdateFrame(streamId, payload);
+                                break;
+                            case CONTINUATION:
+                                readContinuationFrame(streamId, flags, payloadSize, payload);
+                                break;
+                            case UNKNOWN:
+                                readUnknownFrame(streamId, frameTypeId, flags, payloadSize, payload);
+                            }
+                        }
+                        // See if there is a new 9 byte header and continue parsing if possible
+                        if (payload.remaining() >= 9) {
+                            int position = payload.position();
+                            payloadSize = ByteUtil.getThreeBytes(payload, position);
+                            frameTypeId = ByteUtil.getOneByte(payload, position + 3);
+                            frameType = FrameType.valueOf(frameTypeId);
+                            flags = ByteUtil.getOneByte(payload, position + 4);
+                            streamId = ByteUtil.get31Bits(payload, position + 5);
+                            streamException = false;
+                            if (payload.remaining() - 9 >= payloadSize) {
+                                continueParsing = true;
+                                // Now go over frame header
+                                payload.position(payload.position() + 9);
+                                try {
+                                    validateFrame(null, frameType, streamId, flags, payloadSize);
+                                } catch (StreamException e) {
+                                    error = e;
+                                    streamException = true;
+                                } catch (Http2Exception e) {
+                                    error = e;
+                                    continueParsing = false;
+                                }
+                            }
+                        }
+                    } while (continueParsing);
+                } catch (RuntimeException | IOException | Http2Exception e) {
+                    error = e;
+                }
+                if (payload.hasRemaining()) {
+                    socketWrapper.unRead(payload);
+                }
+            }
+            if (state == CompletionState.DONE) {
+                // The call was not completed inline, so must start reading new frames
+                // or process the stream exception
+                upgradeHandler.upgradeDispatch(SocketEvent.OPEN_READ);
+            }
+        }
+
+        @Override
+        public void failed(Throwable e, Void attachment) {
+            // Always a fatal IO error
+            error = e;
+            if (log.isDebugEnabled()) {
+                log.debug(sm.getString("http2Parser.error", connectionId, Integer.valueOf(streamId), frameType), e);
+            }
+            if (state == null || state == CompletionState.DONE) {
+                upgradeHandler.upgradeDispatch(SocketEvent.ERROR);
+            }
+        }
+
+    }
+
+}
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2Protocol.java b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2Protocol.java
new file mode 100644
index 0000000000..46b49d926c
--- /dev/null
+++ b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2Protocol.java
@@ -0,0 +1,378 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.coyote.http2;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Enumeration;
+
+import javax.management.ObjectName;
+
+import org.apache.coyote.AbstractProtocol;
+import org.apache.coyote.Adapter;
+import org.apache.coyote.ContinueResponseTiming;
+import org.apache.coyote.Processor;
+import org.apache.coyote.Request;
+import org.apache.coyote.RequestGroupInfo;
+import org.apache.coyote.Response;
+import org.apache.coyote.UpgradeProtocol;
+import org.apache.coyote.UpgradeToken;
+import org.apache.coyote.http11.AbstractHttp11Protocol;
+import org.apache.coyote.http11.upgrade.InternalHttpUpgradeHandler;
+import org.apache.coyote.http11.upgrade.UpgradeProcessorInternal;
+import org.apache.juli.logging.Log;
+import org.apache.juli.logging.LogFactory;
+import org.apache.tomcat.util.modeler.Registry;
+import org.apache.tomcat.util.net.SocketWrapperBase;
+import org.apache.tomcat.util.res.StringManager;
+
+public class Http2Protocol implements UpgradeProtocol {
+
+    private static final Log log = LogFactory.getLog(Http2Protocol.class);
+    private static final StringManager sm = StringManager.getManager(Http2Protocol.class);
+
+    static final long DEFAULT_READ_TIMEOUT = 5000;
+    static final long DEFAULT_WRITE_TIMEOUT = 5000;
+    static final long DEFAULT_KEEP_ALIVE_TIMEOUT = 20000;
+    static final long DEFAULT_STREAM_READ_TIMEOUT = 20000;
+    static final long DEFAULT_STREAM_WRITE_TIMEOUT = 20000;
+    // The HTTP/2 specification recommends a minimum default of 100
+    static final long DEFAULT_MAX_CONCURRENT_STREAMS = 100;
+    // Maximum amount of streams which can be concurrently executed over
+    // a single connection
+    static final int DEFAULT_MAX_CONCURRENT_STREAM_EXECUTION = 20;
+
+    static final int DEFAULT_OVERHEAD_COUNT_FACTOR = 10;
+    // Not currently configurable. This makes the practical limit for
+    // overheadCountFactor to be ~20. The exact limit will vary with traffic
+    // patterns.
+    static final int DEFAULT_OVERHEAD_REDUCTION_FACTOR = -20;
+    static final int DEFAULT_OVERHEAD_CONTINUATION_THRESHOLD = 1024;
+    static final int DEFAULT_OVERHEAD_DATA_THRESHOLD = 1024;
+    static final int DEFAULT_OVERHEAD_WINDOW_UPDATE_THRESHOLD = 1024;
+
+    private static final String HTTP_UPGRADE_NAME = "h2c";
+    private static final String ALPN_NAME = "h2";
+    private static final byte[] ALPN_IDENTIFIER = ALPN_NAME.getBytes(StandardCharsets.UTF_8);
+
+    // All timeouts in milliseconds
+    // These are the socket level timeouts
+    private long readTimeout = DEFAULT_READ_TIMEOUT;
+    private long writeTimeout = DEFAULT_WRITE_TIMEOUT;
+    private long keepAliveTimeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
+    // These are the stream level timeouts
+    private long streamReadTimeout = DEFAULT_STREAM_READ_TIMEOUT;
+    private long streamWriteTimeout = DEFAULT_STREAM_WRITE_TIMEOUT;
+
+    private long maxConcurrentStreams = DEFAULT_MAX_CONCURRENT_STREAMS;
+    private int maxConcurrentStreamExecution = DEFAULT_MAX_CONCURRENT_STREAM_EXECUTION;
+    // To advertise a different default to the client specify it here but DO NOT
+    // change the default defined in ConnectionSettingsBase.
+    private int initialWindowSize = ConnectionSettingsBase.DEFAULT_INITIAL_WINDOW_SIZE;
+    // Limits
+    private int maxHeaderCount = Constants.DEFAULT_MAX_HEADER_COUNT;
+    private int maxTrailerCount = Constants.DEFAULT_MAX_TRAILER_COUNT;
+    private int overheadCountFactor = DEFAULT_OVERHEAD_COUNT_FACTOR;
+    private int overheadContinuationThreshold = DEFAULT_OVERHEAD_CONTINUATION_THRESHOLD;
+    private int overheadDataThreshold = DEFAULT_OVERHEAD_DATA_THRESHOLD;
+    private int overheadWindowUpdateThreshold = DEFAULT_OVERHEAD_WINDOW_UPDATE_THRESHOLD;
+
+    private boolean initiatePingDisabled = false;
+    private boolean useSendfile = true;
+    // Reference to HTTP/1.1 protocol that this instance is configured under
+    private AbstractHttp11Protocol<?> http11Protocol = null;
+
+    private RequestGroupInfo global = new RequestGroupInfo();
+
+    @Override
+    public String getHttpUpgradeName(boolean isSSLEnabled) {
+        if (isSSLEnabled) {
+            return null;
+        } else {
+            return HTTP_UPGRADE_NAME;
+        }
+    }
+
+    @Override
+    public byte[] getAlpnIdentifier() {
+        return ALPN_IDENTIFIER;
+    }
+
+    @Override
+    public String getAlpnName() {
+        return ALPN_NAME;
+    }
+
+    @Override
+    public Processor getProcessor(SocketWrapperBase<?> socketWrapper, Adapter adapter) {
+        String upgradeProtocol = getUpgradeProtocolName();
+        UpgradeProcessorInternal processor = new UpgradeProcessorInternal(socketWrapper,
+                new UpgradeToken(getInternalUpgradeHandler(socketWrapper, adapter, null), null, null, upgradeProtocol),
+                null);
+        return processor;
+    }
+
+
+    @Override
+    public InternalHttpUpgradeHandler getInternalUpgradeHandler(SocketWrapperBase<?> socketWrapper,
+            Adapter adapter, Request coyoteRequest) {
+        return socketWrapper.hasAsyncIO()
+                ? new Http2AsyncUpgradeHandler(this, adapter, coyoteRequest)
+                : new Http2UpgradeHandler(this, adapter, coyoteRequest);
+    }
+
+
+    @Override
+    public boolean accept(Request request) {
+        // Should only be one HTTP2-Settings header
+        Enumeration<String> settings = request.getMimeHeaders().values("HTTP2-Settings");
+        int count = 0;
+        while (settings.hasMoreElements()) {
+            count++;
+            settings.nextElement();
+        }
+        if (count != 1) {
+            return false;
+        }
+
+        Enumeration<String> connection = request.getMimeHeaders().values("Connection");
+        boolean found = false;
+        while (connection.hasMoreElements() && !found) {
+            found = connection.nextElement().contains("HTTP2-Settings");
+        }
+        return found;
+    }
+
+
+    public long getReadTimeout() {
+        return readTimeout;
+    }
+
+
+    public void setReadTimeout(long readTimeout) {
+        this.readTimeout = readTimeout;
+    }
+
+
+    public long getWriteTimeout() {
+        return writeTimeout;
+    }
+
+
+    public void setWriteTimeout(long writeTimeout) {
+        this.writeTimeout = writeTimeout;
+    }
+
+
+    public long getKeepAliveTimeout() {
+        return keepAliveTimeout;
+    }
+
+
+    public void setKeepAliveTimeout(long keepAliveTimeout) {
+        this.keepAliveTimeout = keepAliveTimeout;
+    }
+
+
+    public long getStreamReadTimeout() {
+        return streamReadTimeout;
+    }
+
+
+    public void setStreamReadTimeout(long streamReadTimeout) {
+        this.streamReadTimeout = streamReadTimeout;
+    }
+
+
+    public long getStreamWriteTimeout() {
+        return streamWriteTimeout;
+    }
+
+
+    public void setStreamWriteTimeout(long streamWriteTimeout) {
+        this.streamWriteTimeout = streamWriteTimeout;
+    }
+
+
+    public long getMaxConcurrentStreams() {
+        return maxConcurrentStreams;
+    }
+
+
+    public void setMaxConcurrentStreams(long maxConcurrentStreams) {
+        this.maxConcurrentStreams = maxConcurrentStreams;
+    }
+
+
+    public int getMaxConcurrentStreamExecution() {
+        return maxConcurrentStreamExecution;
+    }
+
+
+    public void setMaxConcurrentStreamExecution(int maxConcurrentStreamExecution) {
+        this.maxConcurrentStreamExecution = maxConcurrentStreamExecution;
+    }
+
+
+    public int getInitialWindowSize() {
+        return initialWindowSize;
+    }
+
+
+    public void setInitialWindowSize(int initialWindowSize) {
+        this.initialWindowSize = initialWindowSize;
+    }
+
+
+    public boolean getUseSendfile() {
+        return useSendfile;
+    }
+
+
+    public void setUseSendfile(boolean useSendfile) {
+        this.useSendfile = useSendfile;
+    }
+
+
+    boolean isTrailerHeaderAllowed(String headerName) {
+        return http11Protocol.isTrailerHeaderAllowed(headerName);
+    }
+
+
+    public void setMaxHeaderCount(int maxHeaderCount) {
+        this.maxHeaderCount = maxHeaderCount;
+    }
+
+
+    public int getMaxHeaderCount() {
+        return maxHeaderCount;
+    }
+
+
+    public int getMaxHeaderSize() {
+        return http11Protocol.getMaxHttpRequestHeaderSize();
+    }
+
+
+    public void setMaxTrailerCount(int maxTrailerCount) {
+        this.maxTrailerCount = maxTrailerCount;
+    }
+
+
+    public int getMaxTrailerCount() {
+        return maxTrailerCount;
+    }
+
+
+    public int getMaxTrailerSize() {
+        return http11Protocol.getMaxTrailerSize();
+    }
+
+
+    public int getOverheadCountFactor() {
+        return overheadCountFactor;
+    }
+
+
+    public void setOverheadCountFactor(int overheadCountFactor) {
+        this.overheadCountFactor = overheadCountFactor;
+    }
+
+
+    public int getOverheadContinuationThreshold() {
+        return overheadContinuationThreshold;
+    }
+
+
+    public void setOverheadContinuationThreshold(int overheadContinuationThreshold) {
+        this.overheadContinuationThreshold = overheadContinuationThreshold;
+    }
+
+
+    public int getOverheadDataThreshold() {
+        return overheadDataThreshold;
+    }
+
+
+    public void setOverheadDataThreshold(int overheadDataThreshold) {
+        this.overheadDataThreshold = overheadDataThreshold;
+    }
+
+
+    public int getOverheadWindowUpdateThreshold() {
+        return overheadWindowUpdateThreshold;
+    }
+
+
+    public void setOverheadWindowUpdateThreshold(int overheadWindowUpdateThreshold) {
+        this.overheadWindowUpdateThreshold = overheadWindowUpdateThreshold;
+    }
+
+
+    public void setInitiatePingDisabled(boolean initiatePingDisabled) {
+        this.initiatePingDisabled = initiatePingDisabled;
+    }
+
+
+    public boolean getInitiatePingDisabled() {
+        return initiatePingDisabled;
+    }
+
+
+    public boolean useCompression(Request request, Response response) {
+        return http11Protocol.useCompression(request, response);
+    }
+
+
+    public ContinueResponseTiming getContinueResponseTimingInternal() {
+        return http11Protocol.getContinueResponseTimingInternal();
+    }
+
+
+    public AbstractProtocol<?> getHttp11Protocol() {
+        return this.http11Protocol;
+    }
+
+
+    @Override
+    public void setHttp11Protocol(AbstractHttp11Protocol<?> http11Protocol) {
+        this.http11Protocol = http11Protocol;
+
+        try {
+            ObjectName oname = this.http11Protocol.getONameForUpgrade(getUpgradeProtocolName());
+            // This can be null when running the testsuite
+            if (oname != null) {
+                Registry.getRegistry(null, null).registerComponent(global, oname, null);
+            }
+        } catch (Exception e) {
+            log.warn(sm.getString("http2Protocol.jmxRegistration.fail"), e);
+        }
+    }
+
+
+    public String getUpgradeProtocolName() {
+        if (http11Protocol.isSSLEnabled()) {
+            return ALPN_NAME;
+        } else {
+            return HTTP_UPGRADE_NAME;
+        }
+    }
+
+
+    public RequestGroupInfo getGlobal() {
+        return global;
+    }
+}
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2UpgradeHandler.java b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2UpgradeHandler.java
new file mode 100644
index 0000000000..549594354d
--- /dev/null
+++ b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2UpgradeHandler.java
@@ -0,0 +1,2094 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.coyote.http2;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Queue;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ConcurrentNavigableMap;
+import java.util.concurrent.ConcurrentSkipListMap;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+
+import jakarta.servlet.http.WebConnection;
+
+import org.apache.coyote.Adapter;
+import org.apache.coyote.ProtocolException;
+import org.apache.coyote.Request;
+import org.apache.coyote.http11.upgrade.InternalHttpUpgradeHandler;
+import org.apache.coyote.http2.HpackDecoder.HeaderEmitter;
+import org.apache.coyote.http2.HpackEncoder.State;
+import org.apache.coyote.http2.Http2Parser.Input;
+import org.apache.coyote.http2.Http2Parser.Output;
+import org.apache.juli.logging.Log;
+import org.apache.juli.logging.LogFactory;
+import org.apache.tomcat.util.codec.binary.Base64;
+import org.apache.tomcat.util.http.MimeHeaders;
+import org.apache.tomcat.util.log.UserDataHelper;
+import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState;
+import org.apache.tomcat.util.net.SSLSupport;
+import org.apache.tomcat.util.net.SendfileState;
+import org.apache.tomcat.util.net.SocketEvent;
+import org.apache.tomcat.util.net.SocketWrapperBase;
+import org.apache.tomcat.util.res.StringManager;
+
+/**
+ * This represents an HTTP/2 connection from a client to Tomcat. It is designed
+ * on the basis that there will never be more than one thread performing I/O at
+ * a time.
+ * <br>
+ * For reading, this implementation is blocking within frames and non-blocking
+ * between frames.
+ * <br>
+ * Note:
+ * <ul>
+ * <li>You will need to nest an &lt;UpgradeProtocol
+ *     className="org.apache.coyote.http2.Http2Protocol" /&gt; element inside
+ *     a TLS enabled Connector element in server.xml to enable HTTP/2 support.
+ *     </li>
+ * </ul>
+ */
+class Http2UpgradeHandler extends AbstractStream implements InternalHttpUpgradeHandler,
+        Input, Output {
+
+    protected static final Log log = LogFactory.getLog(Http2UpgradeHandler.class);
+    protected static final StringManager sm = StringManager.getManager(Http2UpgradeHandler.class);
+
+    private static final AtomicInteger connectionIdGenerator = new AtomicInteger(0);
+    private static final Integer STREAM_ID_ZERO = Integer.valueOf(0);
+
+    protected static final int FLAG_END_OF_STREAM = 1;
+    protected static final int FLAG_END_OF_HEADERS = 4;
+
+    protected static final byte[] PING = { 0x00, 0x00, 0x08, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00};
+    protected static final byte[] PING_ACK = { 0x00, 0x00, 0x08, 0x06, 0x01, 0x00, 0x00, 0x00, 0x00 };
+
+    protected static final byte[] SETTINGS_ACK = { 0x00, 0x00, 0x00, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00 };
+
+    protected static final byte[] GOAWAY = { 0x07, 0x00, 0x00, 0x00, 0x00, 0x00 };
+
+    private static final String HTTP2_SETTINGS_HEADER = "HTTP2-Settings";
+
+    private static final HeaderSink HEADER_SINK = new HeaderSink();
+
+    private final Object priorityTreeLock = new Object();
+
+    protected final String connectionId;
+
+    protected final Http2Protocol protocol;
+    private final Adapter adapter;
+    protected volatile SocketWrapperBase<?> socketWrapper;
+    private volatile SSLSupport sslSupport;
+
+    private volatile Http2Parser parser;
+
+    // Simple state machine (sequence of states)
+    private AtomicReference<ConnectionState> connectionState = new AtomicReference<>(ConnectionState.NEW);
+    private volatile long pausedNanoTime = Long.MAX_VALUE;
+
+    /**
+     * Remote settings are settings defined by the client and sent to Tomcat
+     * that Tomcat must use when communicating with the client.
+     */
+    private final ConnectionSettingsRemote remoteSettings;
+    /**
+     * Local settings are settings defined by Tomcat and sent to the client that
+     * the client must use when communicating with Tomcat.
+     */
+    protected final ConnectionSettingsLocal localSettings;
+
+    private HpackDecoder hpackDecoder;
+    private HpackEncoder hpackEncoder;
+
+    private final ConcurrentNavigableMap<Integer,AbstractNonZeroStream> streams = new ConcurrentSkipListMap<>();
+    protected final AtomicInteger activeRemoteStreamCount = new AtomicInteger(0);
+    // Start at -1 so the 'add 2' logic in closeIdleStreams() works
+    private volatile int maxActiveRemoteStreamId = -1;
+    private volatile int maxProcessedStreamId;
+    private final AtomicInteger nextLocalStreamId = new AtomicInteger(2);
+    private final PingManager pingManager = getPingManager();
+    private volatile int newStreamsSinceLastPrune = 0;
+    private final Set<AbstractStream> backLogStreams = Collections.newSetFromMap(new ConcurrentHashMap<>());
+    private long backLogSize = 0;
+    // The time at which the connection will timeout unless data arrives before
+    // then. -1 means no timeout.
+    private volatile long connectionTimeout = -1;
+
+    // Stream concurrency control
+    private AtomicInteger streamConcurrency = null;
+    private Queue<StreamRunnable> queuedRunnable = null;
+
+    // Track 'overhead' frames vs 'request/response' frames
+    private final AtomicLong overheadCount;
+    private volatile int lastNonFinalDataPayload;
+    private volatile int lastWindowUpdate;
+
+    protected final UserDataHelper userDataHelper = new UserDataHelper(log);
+
+
+    Http2UpgradeHandler(Http2Protocol protocol, Adapter adapter, Request coyoteRequest) {
+        super (STREAM_ID_ZERO);
+        this.protocol = protocol;
+        this.adapter = adapter;
+        this.connectionId = Integer.toString(connectionIdGenerator.getAndIncrement());
+
+        // Defaults to -10 * the count factor.
+        // i.e. when the connection opens, 10 'overhead' frames in a row will
+        // cause the connection to be closed.
+        // Over time the count should be a slowly decreasing negative number.
+        // Therefore, the longer a connection is 'well-behaved', the greater
+        // tolerance it will have for a period of 'bad' behaviour.
+        overheadCount = new AtomicLong(-10 * protocol.getOverheadCountFactor());
+
+        lastNonFinalDataPayload = protocol.getOverheadDataThreshold() * 2;
+        lastWindowUpdate = protocol.getOverheadWindowUpdateThreshold() * 2;
+
+        remoteSettings = new ConnectionSettingsRemote(connectionId);
+        localSettings = new ConnectionSettingsLocal(connectionId);
+
+        localSettings.set(Setting.MAX_CONCURRENT_STREAMS, protocol.getMaxConcurrentStreams());
+        localSettings.set(Setting.INITIAL_WINDOW_SIZE, protocol.getInitialWindowSize());
+
+        pingManager.initiateDisabled = protocol.getInitiatePingDisabled();
+
+        // Initial HTTP request becomes stream 1.
+        if (coyoteRequest != null) {
+            if (log.isDebugEnabled()) {
+                log.debug(sm.getString("upgradeHandler.upgrade", connectionId));
+            }
+            Integer key = Integer.valueOf(1);
+            Stream stream = new Stream(key, this, coyoteRequest);
+            streams.put(key, stream);
+            maxActiveRemoteStreamId = 1;
+            activeRemoteStreamCount.set(1);
+            maxProcessedStreamId = 1;
+        }
+    }
+
+
+    protected PingManager getPingManager() {
+        return new PingManager();
+    }
+
+
+    @Override
+    public void init(WebConnection webConnection) {
+        if (log.isDebugEnabled()) {
+            log.debug(sm.getString("upgradeHandler.init", connectionId, connectionState.get()));
+        }
+
+        if (!connectionState.compareAndSet(ConnectionState.NEW, ConnectionState.CONNECTED)) {
+            return;
+        }
+
+        // Init concurrency control if needed
+        if (protocol.getMaxConcurrentStreamExecution() < localSettings.getMaxConcurrentStreams()) {
+            streamConcurrency = new AtomicInteger(0);
+            queuedRunnable = new ConcurrentLinkedQueue<>();
+        }
+
+        parser = getParser(connectionId);
+
+        Stream stream = null;
+
+        socketWrapper.setReadTimeout(protocol.getReadTimeout());
+        socketWrapper.setWriteTimeout(protocol.getWriteTimeout());
+
+        if (webConnection != null) {
+            // HTTP/2 started via HTTP upgrade.
+            // The initial HTTP/1.1 request is available as Stream 1.
+
+            try {
+                // Process the initial settings frame
+                stream = getStream(1, true);
+                String base64Settings = stream.getCoyoteRequest().getHeader(HTTP2_SETTINGS_HEADER);
+                byte[] settings = Base64.decodeBase64URLSafe(base64Settings);
+
+                // Settings are only valid on stream 0
+                FrameType.SETTINGS.check(0, settings.length);
+
+                for (int i = 0; i < settings.length % 6; i++) {
+                    int id = ByteUtil.getTwoBytes(settings, i * 6);
+                    long value = ByteUtil.getFourBytes(settings, (i * 6) + 2);
+                    Setting key = Setting.valueOf(id);
+                    if (key == Setting.UNKNOWN) {
+                        log.warn(sm.getString("connectionSettings.unknown",
+                            connectionId, Integer.toString(id), Long.toString(value)));
+                    }
+                    remoteSettings.set(key, value);
+                }
+            } catch (Http2Exception e) {
+                throw new ProtocolException(
+                        sm.getString("upgradeHandler.upgrade.fail", connectionId));
+            }
+        }
+
+        // Send the initial settings frame
+        writeSettings();
+
+        // Make sure the client has sent a valid connection preface before we
+        // send the response to the original request over HTTP/2.
+        try {
+            parser.readConnectionPreface(webConnection, stream);
+        } catch (Http2Exception e) {
+            String msg = sm.getString("upgradeHandler.invalidPreface", connectionId);
+            if (log.isDebugEnabled()) {
+                log.debug(msg, e);
+            }
+            throw new ProtocolException(msg);
+        }
+        if (log.isDebugEnabled()) {
+            log.debug(sm.getString("upgradeHandler.prefaceReceived", connectionId));
+        }
+
+        // Allow streams and connection to determine timeouts
+        socketWrapper.setReadTimeout(-1);
+        socketWrapper.setWriteTimeout(-1);
+
+        processConnection(webConnection, stream);
+    }
+
+    protected void processConnection(WebConnection webConnection, Stream stream) {
+        // Send a ping to get an idea of round trip time as early as possible
+        try {
+            pingManager.sendPing(true);
+        } catch (IOException ioe) {
+            throw new ProtocolException(sm.getString("upgradeHandler.pingFailed", connectionId), ioe);
+        }
+
+        if (webConnection != null) {
+            processStreamOnContainerThread(stream);
+        }
+    }
+
+    protected Http2Parser getParser(String connectionId) {
+        return new Http2Parser(connectionId, this, this);
+    }
+
+
+    protected void processStreamOnContainerThread(Stream stream) {
+        StreamProcessor streamProcessor = new StreamProcessor(this, stream, adapter, socketWrapper);
+        streamProcessor.setSslSupport(sslSupport);
+        processStreamOnContainerThread(streamProcessor, SocketEvent.OPEN_READ);
+    }
+
+
+    void processStreamOnContainerThread(StreamProcessor streamProcessor, SocketEvent event) {
+        StreamRunnable streamRunnable = new StreamRunnable(streamProcessor, event);
+        if (streamConcurrency == null) {
+            socketWrapper.execute(streamRunnable);
+        } else {
+            if (getStreamConcurrency() < protocol.getMaxConcurrentStreamExecution()) {
+                increaseStreamConcurrency();
+                socketWrapper.execute(streamRunnable);
+            } else {
+                queuedRunnable.offer(streamRunnable);
+            }
+        }
+    }
+
+
+    @Override
+    public void setSocketWrapper(SocketWrapperBase<?> wrapper) {
+        this.socketWrapper = wrapper;
+    }
+
+
+    @Override
+    public void setSslSupport(SSLSupport sslSupport) {
+        this.sslSupport = sslSupport;
+    }
+
+
+    @Override
+    public SocketState upgradeDispatch(SocketEvent status) {
+        if (log.isDebugEnabled()) {
+            log.debug(sm.getString("upgradeHandler.upgradeDispatch.entry", connectionId, status));
+        }
+
+        // WebConnection is not used so passing null here is fine
+        // Might not be necessary. init() will handle that.
+        init(null);
+
+        SocketState result = SocketState.CLOSED;
+
+        try {
+            switch(status) {
+            case OPEN_READ:
+                synchronized (socketWrapper) {
+                    if (socketWrapper.canWrite()) {
+                        // Only send a ping if there is no other data waiting to be sent.
+                        // Ping manager will ensure they aren't sent too frequently.
+                        pingManager.sendPing(false);
+                    }
+                }
+                try {
+                    // Disable the connection timeout while frames are processed
+                    setConnectionTimeout(-1);
+                    while (true) {
+                        try {
+                            if (!parser.readFrame()) {
+                                break;
+                            }
+                        } catch (StreamException se) {
+                            // Log the Stream error but not necessarily all of
+                            // them
+                            UserDataHelper.Mode logMode = userDataHelper.getNextMode();
+                            if (logMode != null) {
+                                String message = sm.getString("upgradeHandler.stream.error",
+                                        connectionId, Integer.toString(se.getStreamId()));
+                                switch (logMode) {
+                                    case INFO_THEN_DEBUG:
+                                        message += sm.getString("upgradeHandler.fallToDebug");
+                                        //$FALL-THROUGH$
+                                    case INFO:
+                                        log.info(message, se);
+                                        break;
+                                    case DEBUG:
+                                        log.debug(message, se);
+                                }
+                            }
+                            // Stream errors are not fatal to the connection so
+                            // continue reading frames
+                            Stream stream = getStream(se.getStreamId(), false);
+                            if (stream == null) {
+                                sendStreamReset(null, se);
+                            } else {
+                                stream.close(se);
+                            }
+                        } finally {
+                            if (overheadCount.get() > 0) {
+                                throw new ConnectionException(
+                                        sm.getString("upgradeHandler.tooMuchOverhead", connectionId),
+                                        Http2Error.ENHANCE_YOUR_CALM);
+                            }
+                        }
+                    }
+
+                    // Need to know the correct timeout before starting the read
+                    // but that may not be known at this time if one or more
+                    // requests are currently being processed so don't set a
+                    // timeout for the socket...
+                    socketWrapper.setReadTimeout(-1);
+
+                    // ...set a timeout on the connection
+                    setConnectionTimeoutForStreamCount(activeRemoteStreamCount.get());
+
+                } catch (Http2Exception ce) {
+                    // Really ConnectionException
+                    if (log.isDebugEnabled()) {
+                        log.debug(sm.getString("upgradeHandler.connectionError"), ce);
+                    }
+                    closeConnection(ce);
+                    break;
+                }
+
+                if (connectionState.get() != ConnectionState.CLOSED) {
+                    if (socketWrapper.hasAsyncIO()) {
+                        result = SocketState.ASYNC_IO;
+                    } else {
+                        result = SocketState.UPGRADED;
+                    }
+                }
+                break;
+
+            case OPEN_WRITE:
+                processWrites();
+                if (socketWrapper.hasAsyncIO()) {
+                    result = SocketState.ASYNC_IO;
+                } else {
+                    result = SocketState.UPGRADED;
+                }
+                break;
+
+            case TIMEOUT:
+                closeConnection(null);
+                break;
+
+            case DISCONNECT:
+            case ERROR:
+            case STOP:
+            case CONNECT_FAIL:
+                close();
+                break;
+            }
+        } catch (IOException ioe) {
+            if (log.isDebugEnabled()) {
+                log.debug(sm.getString("upgradeHandler.ioerror", connectionId), ioe);
+            }
+            close();
+        }
+
+        if (log.isDebugEnabled()) {
+            log.debug(sm.getString("upgradeHandler.upgradeDispatch.exit", connectionId, result));
+        }
+        return result;
+    }
+
+
+    /*
+     * Sets the connection timeout based on the current number of active
+     * streams.
+     */
+    protected void setConnectionTimeoutForStreamCount(int streamCount) {
+        if (streamCount == 0) {
+            // No streams currently active. Use the keep-alive
+            // timeout for the connection.
+            long keepAliveTimeout = protocol.getKeepAliveTimeout();
+            if (keepAliveTimeout == -1) {
+                setConnectionTimeout(-1);
+            } else {
+                setConnectionTimeout(System.currentTimeMillis() + keepAliveTimeout);
+            }
+        } else {
+            // Streams currently active. Individual streams have
+            // timeouts so keep the connection open.
+            setConnectionTimeout(-1);
+        }
+    }
+
+
+    private void setConnectionTimeout(long connectionTimeout) {
+        this.connectionTimeout = connectionTimeout;
+    }
+
+
+    @Override
+    public void timeoutAsync(long now) {
+        long connectionTimeout = this.connectionTimeout;
+        if (now == -1 || connectionTimeout > -1 && now > connectionTimeout) {
+            // Have to dispatch as this will be executed from a non-container
+            // thread.
+            socketWrapper.processSocket(SocketEvent.TIMEOUT, true);
+        }
+    }
+
+
+    ConnectionSettingsRemote getRemoteSettings() {
+        return remoteSettings;
+    }
+
+
+    ConnectionSettingsLocal getLocalSettings() {
+        return localSettings;
+    }
+
+
+    Http2Protocol getProtocol() {
+        return protocol;
+    }
+
+
+    @Override
+    public void pause() {
+        if (log.isDebugEnabled()) {
+            log.debug(sm.getString("upgradeHandler.pause.entry", connectionId));
+        }
+
+        if (connectionState.compareAndSet(ConnectionState.CONNECTED, ConnectionState.PAUSING)) {
+            pausedNanoTime = System.nanoTime();
+
+            try {
+                writeGoAwayFrame((1 << 31) - 1, Http2Error.NO_ERROR.getCode(), null);
+            } catch (IOException ioe) {
+                // This is fatal for the connection. Ignore it here. There will be
+                // further attempts at I/O in upgradeDispatch() and it can better
+                // handle the IO errors.
+            }
+        }
+    }
+
+
+    @Override
+    public void destroy() {
+        // NO-OP
+    }
+
+
+    void checkPauseState() throws IOException {
+        if (connectionState.get() == ConnectionState.PAUSING) {
+            if (pausedNanoTime + pingManager.getRoundTripTimeNano() < System.nanoTime()) {
+                connectionState.compareAndSet(ConnectionState.PAUSING, ConnectionState.PAUSED);
+                writeGoAwayFrame(maxProcessedStreamId, Http2Error.NO_ERROR.getCode(), null);
+            }
+        }
+    }
+
+
+    private int increaseStreamConcurrency() {
+        return streamConcurrency.incrementAndGet();
+    }
+
+    private int decreaseStreamConcurrency() {
+        return streamConcurrency.decrementAndGet();
+    }
+
+    private int getStreamConcurrency() {
+        return streamConcurrency.get();
+    }
+
+    void executeQueuedStream() {
+        if (streamConcurrency == null) {
+            return;
+        }
+        decreaseStreamConcurrency();
+        if (getStreamConcurrency() < protocol.getMaxConcurrentStreamExecution()) {
+            StreamRunnable streamRunnable = queuedRunnable.poll();
+            if (streamRunnable != null) {
+                increaseStreamConcurrency();
+                socketWrapper.execute(streamRunnable);
+            }
+        }
+    }
+
+
+    void sendStreamReset(StreamStateMachine state, StreamException se) throws IOException {
+
+        if (log.isDebugEnabled()) {
+            log.debug(sm.getString("upgradeHandler.rst.debug", connectionId,
+                    Integer.toString(se.getStreamId()), se.getError(), se.getMessage()));
+        }
+
+        // Write a RST frame
+        byte[] rstFrame = new byte[13];
+        // Length
+        ByteUtil.setThreeBytes(rstFrame, 0, 4);
+        // Type
+        rstFrame[3] = FrameType.RST.getIdByte();
+        // No flags
+        // Stream ID
+        ByteUtil.set31Bits(rstFrame, 5, se.getStreamId());
+        // Payload
+        ByteUtil.setFourBytes(rstFrame, 9, se.getError().getCode());
+
+        // Need to update state atomically with the sending of the RST
+        // frame else other threads currently working with this stream
+        // may see the state change and send a RST frame before the RST
+        // frame triggered by this thread. If that happens the client
+        // may see out of order RST frames which may hard to follow if
+        // the client is unaware the RST frames may be received out of
+        // order.
+        synchronized (socketWrapper) {
+            if (state != null) {
+                state.sendReset();
+            }
+            socketWrapper.write(true, rstFrame, 0, rstFrame.length);
+            socketWrapper.flush(true);
+        }
+    }
+
+
+    void closeConnection(Http2Exception ce) {
+        long code;
+        byte[] msg;
+        if (ce == null) {
+            code = Http2Error.NO_ERROR.getCode();
+            msg = null;
+        } else {
+            code = ce.getError().getCode();
+            msg = ce.getMessage().getBytes(StandardCharsets.UTF_8);
+        }
+        try {
+            writeGoAwayFrame(maxProcessedStreamId, code, msg);
+        } catch (IOException ioe) {
+            // Ignore. GOAWAY is sent on a best efforts basis and the original
+            // error has already been logged.
+        }
+        close();
+    }
+
+
+    /**
+     * Write the initial settings frame and any necessary supporting frames. If
+     * the initial settings increase the initial window size, it will also be
+     * necessary to send a WINDOW_UPDATE frame to increase the size of the flow
+     * control window for the connection (stream 0).
+     */
+    protected void writeSettings() {
+        // Send the initial settings frame
+        try {
+            byte[] settings = localSettings.getSettingsFrameForPending();
+            socketWrapper.write(true, settings, 0, settings.length);
+            byte[] windowUpdateFrame = createWindowUpdateForSettings();
+            if (windowUpdateFrame.length > 0) {
+                socketWrapper.write(true,  windowUpdateFrame, 0 , windowUpdateFrame.length);
+            }
+            socketWrapper.flush(true);
+        } catch (IOException ioe) {
+            String msg = sm.getString("upgradeHandler.sendPrefaceFail", connectionId);
+            if (log.isDebugEnabled()) {
+                log.debug(msg);
+            }
+            throw new ProtocolException(msg, ioe);
+        }
+    }
+
+
+    /**
+     * @return  The WINDOW_UPDATE frame if one is required or an empty array if
+     *          no WINDOW_UPDATE is required.
+     */
+    protected byte[] createWindowUpdateForSettings() {
+        // Build a WINDOW_UPDATE frame if one is required. If not, create an
+        // empty byte array.
+        byte[] windowUpdateFrame;
+        int increment = protocol.getInitialWindowSize() - ConnectionSettingsBase.DEFAULT_INITIAL_WINDOW_SIZE;
+        if (increment > 0) {
+            // Build window update frame for stream 0
+            windowUpdateFrame = new byte[13];
+            ByteUtil.setThreeBytes(windowUpdateFrame, 0,  4);
+            windowUpdateFrame[3] = FrameType.WINDOW_UPDATE.getIdByte();
+            ByteUtil.set31Bits(windowUpdateFrame, 9, increment);
+        } else {
+            windowUpdateFrame = new byte[0];
+        }
+
+        return windowUpdateFrame;
+    }
+
+
+    protected void writeGoAwayFrame(int maxStreamId, long errorCode, byte[] debugMsg)
+            throws IOException {
+        byte[] fixedPayload = new byte[8];
+        ByteUtil.set31Bits(fixedPayload, 0, maxStreamId);
+        ByteUtil.setFourBytes(fixedPayload, 4, errorCode);
+        int len = 8;
+        if (debugMsg != null) {
+            len += debugMsg.length;
+        }
+        byte[] payloadLength = new byte[3];
+        ByteUtil.setThreeBytes(payloadLength, 0, len);
+
+        synchronized (socketWrapper) {
+            socketWrapper.write(true, payloadLength, 0, payloadLength.length);
+            socketWrapper.write(true, GOAWAY, 0, GOAWAY.length);
+            socketWrapper.write(true, fixedPayload, 0, 8);
+            if (debugMsg != null) {
+                socketWrapper.write(true, debugMsg, 0, debugMsg.length);
+            }
+            socketWrapper.flush(true);
+        }
+    }
+
+    void writeHeaders(Stream stream, int pushedStreamId, MimeHeaders mimeHeaders,
+            boolean endOfStream, int payloadSize) throws IOException {
+        // This ensures the Stream processing thread has control of the socket.
+        synchronized (socketWrapper) {
+            doWriteHeaders(stream, pushedStreamId, mimeHeaders, endOfStream, payloadSize);
+        }
+        stream.sentHeaders();
+        if (endOfStream) {
+            stream.sentEndOfStream();
+        }
+    }
+
+
+    /*
+     * Separate method to allow Http2AsyncUpgradeHandler to call this code
+     * without synchronizing on socketWrapper since it doesn't need to.
+     */
+    protected HeaderFrameBuffers doWriteHeaders(Stream stream, int pushedStreamId,
+            MimeHeaders mimeHeaders, boolean endOfStream, int payloadSize) throws IOException {
+
+        if (log.isDebugEnabled()) {
+            if (pushedStreamId == 0) {
+                log.debug(sm.getString("upgradeHandler.writeHeaders", connectionId,
+                        stream.getIdAsString(), Boolean.valueOf(endOfStream)));
+            } else {
+                log.debug(sm.getString("upgradeHandler.writePushHeaders", connectionId,
+                        stream.getIdAsString(), Integer.valueOf(pushedStreamId),
+                        Boolean.valueOf(endOfStream)));
+            }
+        }
+
+        if (!stream.canWrite()) {
+            return null;
+        }
+
+        HeaderFrameBuffers headerFrameBuffers = getHeaderFrameBuffers(payloadSize);
+
+        byte[] pushedStreamIdBytes = null;
+        if (pushedStreamId > 0) {
+            pushedStreamIdBytes = new byte[4];
+            ByteUtil.set31Bits(pushedStreamIdBytes, 0, pushedStreamId);
+        }
+
+        boolean first = true;
+        State state = null;
+
+        while (state != State.COMPLETE) {
+            headerFrameBuffers.startFrame();
+            if (first && pushedStreamIdBytes != null) {
+                headerFrameBuffers.getPayload().put(pushedStreamIdBytes);
+            }
+            state = getHpackEncoder().encode(mimeHeaders, headerFrameBuffers.getPayload());
+            headerFrameBuffers.getPayload().flip();
+            if (state == State.COMPLETE || headerFrameBuffers.getPayload().limit() > 0) {
+                ByteUtil.setThreeBytes(headerFrameBuffers.getHeader(), 0, headerFrameBuffers.getPayload().limit());
+                if (first) {
+                    first = false;
+                    if (pushedStreamIdBytes == null) {
+                        headerFrameBuffers.getHeader()[3] = FrameType.HEADERS.getIdByte();
+                    } else {
+                        headerFrameBuffers.getHeader()[3] = FrameType.PUSH_PROMISE.getIdByte();
+                    }
+                    if (endOfStream) {
+                        headerFrameBuffers.getHeader()[4] = FLAG_END_OF_STREAM;
+                    }
+                } else {
+                    headerFrameBuffers.getHeader()[3] = FrameType.CONTINUATION.getIdByte();
+                }
+                if (state == State.COMPLETE) {
+                    headerFrameBuffers.getHeader()[4] += FLAG_END_OF_HEADERS;
+                }
+                if (log.isDebugEnabled()) {
+                    log.debug(headerFrameBuffers.getPayload().limit() + " bytes");
+                }
+                ByteUtil.set31Bits(headerFrameBuffers.getHeader(), 5, stream.getIdAsInt());
+                headerFrameBuffers.endFrame();
+            } else if (state == State.UNDERFLOW) {
+                headerFrameBuffers.expandPayload();
+            }
+        }
+        headerFrameBuffers.endHeaders();
+        return headerFrameBuffers;
+    }
+
+    protected HeaderFrameBuffers getHeaderFrameBuffers(int initialPayloadSize) {
+        return new DefaultHeaderFrameBuffers(initialPayloadSize);
+    }
+
+
+    protected HpackEncoder getHpackEncoder() {
+        if (hpackEncoder == null) {
+            hpackEncoder = new HpackEncoder();
+        }
+        // Ensure latest agreed table size is used
+        hpackEncoder.setMaxTableSize(remoteSettings.getHeaderTableSize());
+        return hpackEncoder;
+    }
+
+
+    void writeBody(Stream stream, ByteBuffer data, int len, boolean finished) throws IOException {
+        if (log.isDebugEnabled()) {
+            log.debug(sm.getString("upgradeHandler.writeBody", connectionId, stream.getIdAsString(),
+                    Integer.toString(len), Boolean.valueOf(finished)));
+        }
+
+        reduceOverheadCount(FrameType.DATA);
+
+        // Need to check this now since sending end of stream will change this.
+        boolean writable = stream.canWrite();
+        byte[] header = new byte[9];
+        ByteUtil.setThreeBytes(header, 0, len);
+        header[3] = FrameType.DATA.getIdByte();
+        if (finished) {
+            header[4] = FLAG_END_OF_STREAM;
+            stream.sentEndOfStream();
+            if (!stream.isActive()) {
+                setConnectionTimeoutForStreamCount(activeRemoteStreamCount.decrementAndGet());
+            }
+        }
+        if (writable) {
+            ByteUtil.set31Bits(header, 5, stream.getIdAsInt());
+            synchronized (socketWrapper) {
+                try {
+                    socketWrapper.write(true, header, 0, header.length);
+                    int orgLimit = data.limit();
+                    data.limit(data.position() + len);
+                    socketWrapper.write(true, data);
+                    data.limit(orgLimit);
+                    socketWrapper.flush(true);
+                } catch (IOException ioe) {
+                    handleAppInitiatedIOException(ioe);
+                }
+            }
+        }
+    }
+
+
+    /*
+     * Handles an I/O error on the socket underlying the HTTP/2 connection when
+     * it is triggered by application code (usually reading the request or
+     * writing the response). Such I/O errors are fatal so the connection is
+     * closed. The exception is re-thrown to make the client code aware of the
+     * problem.
+     *
+     * Note: We can not rely on this exception reaching the socket processor
+     *       since the application code may swallow it.
+     */
+    protected void handleAppInitiatedIOException(IOException ioe) throws IOException {
+        close();
+        throw ioe;
+    }
+
+
+    /*
+     * Needs to know if this was application initiated since that affects the
+     * error handling.
+     */
+    void writeWindowUpdate(AbstractNonZeroStream stream, int increment, boolean applicationInitiated)
+            throws IOException {
+        if (log.isDebugEnabled()) {
+            log.debug(sm.getString("upgradeHandler.windowUpdateConnection",
+                    getConnectionId(), Integer.valueOf(increment)));
+        }
+        synchronized (socketWrapper) {
+            // Build window update frame for stream 0
+            byte[] frame = new byte[13];
+            ByteUtil.setThreeBytes(frame, 0,  4);
+            frame[3] = FrameType.WINDOW_UPDATE.getIdByte();
+            ByteUtil.set31Bits(frame, 9, increment);
+            socketWrapper.write(true, frame, 0, frame.length);
+            boolean needFlush = true;
+            // No need to send update from closed stream
+            if (stream instanceof Stream && ((Stream) stream).canWrite()) {
+                int streamIncrement = ((Stream) stream).getWindowUpdateSizeToWrite(increment);
+                if (streamIncrement > 0) {
+                    if (log.isDebugEnabled()) {
+                        log.debug(sm.getString("upgradeHandler.windowUpdateStream",
+                                getConnectionId(), getIdAsString(), Integer.valueOf(streamIncrement)));
+                    }
+                    // Re-use buffer as connection update has already been written
+                    ByteUtil.set31Bits(frame, 5, stream.getIdAsInt());
+                    ByteUtil.set31Bits(frame, 9, streamIncrement);
+                    try {
+                        socketWrapper.write(true, frame, 0, frame.length);
+                        socketWrapper.flush(true);
+                        needFlush = false;
+                    } catch (IOException ioe) {
+                        if (applicationInitiated) {
+                            handleAppInitiatedIOException(ioe);
+                        } else {
+                            throw ioe;
+                        }
+                    }
+                }
+            }
+            if (needFlush) {
+                socketWrapper.flush(true);
+            }
+        }
+    }
+
+
+    protected void processWrites() throws IOException {
+        synchronized (socketWrapper) {
+            if (socketWrapper.flush(false)) {
+                socketWrapper.registerWriteInterest();
+            } else {
+                // Only send a ping if there is no other data waiting to be sent.
+                // Ping manager will ensure they aren't sent too frequently.
+                pingManager.sendPing(false);
+            }
+        }
+    }
+
+
+    int reserveWindowSize(Stream stream, int reservation, boolean block) throws IOException {
+        // Need to be holding the stream lock so releaseBacklog() can't notify
+        // this thread until after this thread enters wait()
+        int allocation = 0;
+        synchronized (stream) {
+            synchronized (this) {
+                if (!stream.canWrite()) {
+                    stream.doStreamCancel(sm.getString("upgradeHandler.stream.notWritable",
+                            stream.getConnectionId(), stream.getIdAsString()), Http2Error.STREAM_CLOSED);
+                }
+                long windowSize = getWindowSize();
+                if (stream.getConnectionAllocationMade() > 0) {
+                    allocation = stream.getConnectionAllocationMade();
+                    stream.setConnectionAllocationMade(0);
+                } else  if (windowSize < 1) {
+                    // Has this stream been granted an allocation
+                    if (stream.getConnectionAllocationMade() == 0) {
+                        stream.setConnectionAllocationRequested(reservation);
+                        backLogSize += reservation;
+                        backLogStreams.add(stream);
+                        // Add the parents as well
+                        AbstractStream parent = stream.getParentStream();
+                        while (parent != null && backLogStreams.add(parent)) {
+                            parent = parent.getParentStream();
+                        }
+                    }
+                } else if (windowSize < reservation) {
+                    allocation = (int) windowSize;
+                    decrementWindowSize(allocation);
+                } else {
+                    allocation = reservation;
+                    decrementWindowSize(allocation);
+                }
+            }
+            if (allocation == 0) {
+                if (block) {
+                    try {
+                        // Connection level window is empty. Although this
+                        // request is for a stream, use the connection
+                        // timeout
+                        long writeTimeout = protocol.getWriteTimeout();
+                        stream.waitForConnectionAllocation(writeTimeout);
+                        // Has this stream been granted an allocation
+                        if (stream.getConnectionAllocationMade() == 0) {
+                            String msg;
+                            Http2Error error;
+                            if (stream.isActive()) {
+                                if (log.isDebugEnabled()) {
+                                    log.debug(sm.getString("upgradeHandler.noAllocation",
+                                            connectionId, stream.getIdAsString()));
+                                }
+                                // No allocation
+                                // Close the connection. Do this first since
+                                // closing the stream will raise an exception.
+                                close();
+                                msg = sm.getString("stream.writeTimeout");
+                                error = Http2Error.ENHANCE_YOUR_CALM;
+                            } else {
+                                msg = sm.getString("stream.clientCancel");
+                                error = Http2Error.STREAM_CLOSED;
+                            }
+                            // Close the stream
+                            // This thread is in application code so need
+                            // to signal to the application that the
+                            // stream is closing
+                            stream.doStreamCancel(msg, error);
+                        } else {
+                            allocation = stream.getConnectionAllocationMade();
+                            stream.setConnectionAllocationMade(0);
+                        }
+                    } catch (InterruptedException e) {
+                        throw new IOException(sm.getString(
+                                "upgradeHandler.windowSizeReservationInterrupted", connectionId,
+                                stream.getIdAsString(), Integer.toString(reservation)), e);
+                    }
+                } else {
+                    stream.waitForConnectionAllocationNonBlocking();
+                    return 0;
+                }
+            }
+        }
+        return allocation;
+    }
+
+
+
+    @SuppressWarnings("sync-override") // notify() needs to be outside sync
+                                       // to avoid deadlock
+    @Override
+    protected void incrementWindowSize(int increment) throws Http2Exception {
+        Set<AbstractStream> streamsToNotify = null;
+
+        synchronized (this) {
+            long windowSize = getWindowSize();
+            if (windowSize < 1 && windowSize + increment > 0) {
+                // Connection window is exhausted. Assume there will be streams
+                // to notify. The overhead is minimal if there are none.
+                streamsToNotify = releaseBackLog((int) (windowSize +increment));
+            } else {
+                super.incrementWindowSize(increment);
+            }
+        }
+
+        if (streamsToNotify != null) {
+            for (AbstractStream stream : streamsToNotify) {
+                if (log.isDebugEnabled()) {
+                    log.debug(sm.getString("upgradeHandler.releaseBacklog",
+                            connectionId, stream.getIdAsString()));
+                }
+                // There is never any O/P on stream zero but it is included in
+                // the backlog as it simplifies the code. Skip it if it appears
+                // here.
+                if (this == stream) {
+                    continue;
+                }
+                ((Stream) stream).notifyConnection();
+            }
+        }
+    }
+
+
+    /**
+     * Process send file (if supported) for the given stream. The appropriate
+     * request attributes should be set before calling this method.
+     *
+     * @param sendfileData  The stream and associated data to process
+     *
+     * @return  The result of the send file processing
+     */
+    protected SendfileState processSendfile(SendfileData sendfileData) {
+        return SendfileState.DONE;
+    }
+
+
+    private synchronized Set<AbstractStream> releaseBackLog(int increment) throws Http2Exception {
+        Set<AbstractStream> result = new HashSet<>();
+        int remaining = increment;
+        if (backLogSize < remaining) {
+            // Can clear the whole backlog
+            for (AbstractStream stream : backLogStreams) {
+                if (stream.getConnectionAllocationRequested() > 0) {
+                    stream.setConnectionAllocationMade(stream.getConnectionAllocationRequested());
+                    stream.setConnectionAllocationRequested(0);
+                }
+            }
+            remaining -= backLogSize;
+            backLogSize = 0;
+            super.incrementWindowSize(remaining);
+
+            result.addAll(backLogStreams);
+            backLogStreams.clear();
+        } else {
+            allocate(this, remaining);
+            Iterator<AbstractStream> streamIter = backLogStreams.iterator();
+            while (streamIter.hasNext()) {
+                AbstractStream stream = streamIter.next();
+                if (stream.getConnectionAllocationMade() > 0) {
+                    backLogSize -= stream.getConnectionAllocationMade();
+                    backLogSize -= stream.getConnectionAllocationRequested();
+                    stream.setConnectionAllocationRequested(0);
+                    result.add(stream);
+                    streamIter.remove();
+                }
+            }
+        }
+        return result;
+    }
+
+
+    private synchronized int allocate(AbstractStream stream, int allocation) {
+        if (log.isDebugEnabled()) {
+            log.debug(sm.getString("upgradeHandler.allocate.debug", getConnectionId(),
+                    stream.getIdAsString(), Integer.toString(allocation)));
+        }
+
+        int leftToAllocate = allocation;
+
+        if (stream.getConnectionAllocationRequested() > 0) {
+            int allocatedThisTime;
+            if (allocation >= stream.getConnectionAllocationRequested()) {
+                allocatedThisTime = stream.getConnectionAllocationRequested();
+            } else {
+                allocatedThisTime = allocation;
+            }
+            stream.setConnectionAllocationRequested(stream.getConnectionAllocationRequested() - allocatedThisTime);
+            stream.setConnectionAllocationMade(stream.getConnectionAllocationMade() + allocatedThisTime);
+            leftToAllocate = leftToAllocate - allocatedThisTime;
+        }
+
+        if (leftToAllocate == 0) {
+            return 0;
+        }
+
+        if (log.isDebugEnabled()) {
+            log.debug(sm.getString("upgradeHandler.allocate.left",
+                    getConnectionId(), stream.getIdAsString(), Integer.toString(leftToAllocate)));
+        }
+
+        // Recipients are children of the current stream that are in the
+        // backlog.
+        Set<AbstractStream> recipients = new HashSet<>(stream.getChildStreams());
+        recipients.retainAll(backLogStreams);
+
+        // Loop until we run out of allocation or recipients
+        while (leftToAllocate > 0) {
+            if (recipients.size() == 0) {
+                if (stream.getConnectionAllocationMade() == 0) {
+                    backLogStreams.remove(stream);
+                }
+                if (stream.getIdAsInt() == 0) {
+                    throw new IllegalStateException();
+                }
+                return leftToAllocate;
+            }
+
+            int totalWeight = 0;
+            for (AbstractStream recipient : recipients) {
+                if (log.isDebugEnabled()) {
+                    log.debug(sm.getString("upgradeHandler.allocate.recipient",
+                            getConnectionId(), stream.getIdAsString(), recipient.getIdAsString(),
+                            Integer.toString(recipient.getWeight())));
+                }
+                totalWeight += recipient.getWeight();
+            }
+
+            // Use an Iterator so fully allocated children/recipients can be
+            // removed.
+            Iterator<AbstractStream> iter = recipients.iterator();
+            int allocated = 0;
+            while (iter.hasNext()) {
+                AbstractStream recipient = iter.next();
+                int share = leftToAllocate * recipient.getWeight() / totalWeight;
+                if (share == 0) {
+                    // This is to avoid rounding issues triggering an infinite
+                    // loop. It will cause a very slight over allocation but
+                    // HTTP/2 should cope with that.
+                    share = 1;
+                }
+                int remainder = allocate(recipient, share);
+                // Remove recipients that receive their full allocation so that
+                // they are excluded from the next allocation round.
+                if (remainder > 0) {
+                    iter.remove();
+                }
+                allocated += (share - remainder);
+            }
+            leftToAllocate -= allocated;
+        }
+
+        return 0;
+    }
+
+
+    private Stream getStream(int streamId) {
+        Integer key = Integer.valueOf(streamId);
+        AbstractStream result = streams.get(key);
+        if (result instanceof Stream) {
+            return (Stream) result;
+        }
+        return null;
+    }
+
+
+    private Stream getStream(int streamId, boolean unknownIsError) throws ConnectionException {
+        Stream result = getStream(streamId);
+        if (result == null && unknownIsError) {
+            // Stream has been closed and removed from the map
+            throw new ConnectionException(sm.getString("upgradeHandler.stream.closed", Integer.toString(streamId)),
+                    Http2Error.PROTOCOL_ERROR);
+        }
+        return result;
+    }
+
+
+    private AbstractNonZeroStream getAbstractNonZeroStream(int streamId) {
+        Integer key = Integer.valueOf(streamId);
+        return streams.get(key);
+    }
+
+
+    private AbstractNonZeroStream getAbstractNonZeroStream(int streamId, boolean unknownIsError)
+            throws ConnectionException {
+        AbstractNonZeroStream result = getAbstractNonZeroStream(streamId);
+        if (result == null && unknownIsError) {
+            // Stream has been closed and removed from the map
+            throw new ConnectionException(sm.getString("upgradeHandler.stream.closed", Integer.toString(streamId)),
+                    Http2Error.PROTOCOL_ERROR);
+        }
+        return result;
+    }
+
+
+    private Stream createRemoteStream(int streamId) throws ConnectionException {
+        Integer key = Integer.valueOf(streamId);
+
+        if (streamId %2 != 1) {
+            throw new ConnectionException(
+                    sm.getString("upgradeHandler.stream.even", key), Http2Error.PROTOCOL_ERROR);
+        }
+
+        pruneClosedStreams(streamId);
+
+        Stream result = new Stream(key, this);
+        streams.put(key, result);
+        return result;
+    }
+
+
+    private Stream createLocalStream(Request request) {
+        int streamId = nextLocalStreamId.getAndAdd(2);
+
+        Integer key = Integer.valueOf(streamId);
+
+        Stream result = new Stream(key, this, request);
+        streams.put(key, result);
+        return result;
+    }
+
+
+    private void close() {
+        ConnectionState previous = connectionState.getAndSet(ConnectionState.CLOSED);
+        if (previous == ConnectionState.CLOSED) {
+            // Already closed
+            return;
+        }
+
+        for (AbstractNonZeroStream stream : streams.values()) {
+            if (stream instanceof Stream) {
+                // The connection is closing. Close the associated streams as no
+                // longer required (also notifies any threads waiting for allocations).
+                ((Stream) stream).receiveReset(Http2Error.CANCEL.getCode());
+            }
+        }
+        try {
+            socketWrapper.close();
+        } catch (Exception e) {
+            log.debug(sm.getString("upgradeHandler.socketCloseFailed"), e);
+        }
+    }
+
+
+    private void pruneClosedStreams(int streamId) {
+        // Only prune every 10 new streams
+        if (newStreamsSinceLastPrune < 9) {
+            // Not atomic. Increments may be lost. Not a problem.
+            newStreamsSinceLastPrune++;
+            return;
+        }
+        // Reset counter
+        newStreamsSinceLastPrune = 0;
+
+        // RFC 7540, 5.3.4 endpoints should maintain state for at least the
+        // maximum number of concurrent streams.
+        long max = localSettings.getMaxConcurrentStreams();
+
+        // Only need ~+10% for streams that are in the priority tree,
+        // Ideally need to retain information for a "significant" amount of time
+        // after sending END_STREAM (RFC 7540, page 20) so we detect potential
+        // connection error. 5x seems reasonable. The client will have had
+        // plenty of opportunity to process the END_STREAM if another 5x max
+        // concurrent streams have been processed.
+        max = max * 5;
+        if (max > Integer.MAX_VALUE) {
+            max = Integer.MAX_VALUE;
+        }
+
+        final int size = streams.size();
+        if (log.isDebugEnabled()) {
+            log.debug(sm.getString("upgradeHandler.pruneStart", connectionId,
+                    Long.toString(max), Integer.toString(size)));
+        }
+
+        int toClose = size - (int) max;
+        if (toClose < 1) {
+            return;
+        }
+
+        // Need to try and close some streams.
+        // Try to close streams in this order
+        // 1. Completed streams used for a request with no children
+        // 2. Completed streams used for a request with children
+        // 3. Closed final streams
+        //
+        // The pruning halts as soon as enough streams have been pruned.
+
+        // Use these sets to track the different classes of streams
+        TreeSet<Integer> candidatesStepTwo = new TreeSet<>();
+        TreeSet<Integer> candidatesStepThree = new TreeSet<>();
+
+        // Step 1
+        // Iterator is in key order so we automatically have the oldest streams
+        // first
+        // Tests depend on parent/child relationship between streams so need to
+        // lock on priorityTreeLock to ensure a consistent view.
+        synchronized (priorityTreeLock) {
+            for (AbstractNonZeroStream stream : streams.values()) {
+                // Never remove active streams
+                if (stream instanceof Stream && ((Stream) stream).isActive()) {
+                    continue;
+                }
+
+                if (stream.isClosedFinal()) {
+                    // This stream went from IDLE to CLOSED and is likely to have
+                    // been created by the client as part of the priority tree.
+                    // Candidate for step 3.
+                    candidatesStepThree.add(stream.getIdentifier());
+                } else if (stream.getChildStreams().size() == 0) {
+                    // Prune it
+                    AbstractStream parent = stream.getParentStream();
+                    streams.remove(stream.getIdentifier());
+                    stream.detachFromParent();
+                    if (log.isDebugEnabled()) {
+                        log.debug(sm.getString("upgradeHandler.pruned", connectionId, stream.getIdAsString()));
+                    }
+                    if (--toClose < 1) {
+                        return;
+                    }
+
+                    // If removing this child made the parent childless then see if
+                    // the parent can be removed.
+                    // Don't try and remove Stream 0 as that is the connection
+                    // Don't try and remove 'newer' streams. We'll get to them as we
+                    // work through the ordered list of streams.
+                    while (toClose > 0 && parent.getIdAsInt() > 0 && parent.getIdAsInt() < stream.getIdAsInt() &&
+                            parent.getChildStreams().isEmpty()) {
+                        // This cast is safe since we know parent ID > 0 therefore
+                        // this isn't the connection
+                        stream = (AbstractNonZeroStream) parent;
+                        parent = stream.getParentStream();
+                        streams.remove(stream.getIdentifier());
+                        stream.detachFromParent();
+                        if (log.isDebugEnabled()) {
+                            log.debug(sm.getString("upgradeHandler.pruned", connectionId, stream.getIdAsString()));
+                        }
+                        if (--toClose < 1) {
+                            return;
+                        }
+                        // Also need to remove this stream from the step 2 list
+                        candidatesStepTwo.remove(stream.getIdentifier());
+                    }
+                } else {
+                    // Closed, with children. Candidate for step 2.
+                    candidatesStepTwo.add(stream.getIdentifier());
+                }
+            }
+        }
+
+        // Process the P2 list
+        for (Integer streamIdToRemove : candidatesStepTwo) {
+            removeStreamFromPriorityTree(streamIdToRemove);
+            if (log.isDebugEnabled()) {
+                log.debug(sm.getString("upgradeHandler.pruned", connectionId, streamIdToRemove));
+            }
+            if (--toClose < 1) {
+                return;
+            }
+        }
+
+        while (toClose > 0 && candidatesStepThree.size() > 0) {
+            Integer streamIdToRemove = candidatesStepThree.pollLast();
+            removeStreamFromPriorityTree(streamIdToRemove);
+            if (log.isDebugEnabled()) {
+                log.debug(sm.getString("upgradeHandler.prunedPriority", connectionId, streamIdToRemove));
+            }
+            if (--toClose < 1) {
+                return;
+            }
+        }
+
+        if (toClose > 0) {
+            log.warn(sm.getString("upgradeHandler.pruneIncomplete", connectionId,
+                    Integer.toString(streamId), Integer.toString(toClose)));
+        }
+    }
+
+
+    private void removeStreamFromPriorityTree(Integer streamIdToRemove) {
+        synchronized (priorityTreeLock) {
+            AbstractNonZeroStream streamToRemove = streams.remove(streamIdToRemove);
+            // Move the removed Stream's children to the removed Stream's
+            // parent.
+            Set<AbstractNonZeroStream> children = streamToRemove.getChildStreams();
+            if (children.size() == 1) {
+                // Shortcut
+                children.iterator().next().rePrioritise(
+                        streamToRemove.getParentStream(), streamToRemove.getWeight());
+            } else {
+                int totalWeight = 0;
+                for (AbstractNonZeroStream child : children) {
+                    totalWeight += child.getWeight();
+                }
+                for (AbstractNonZeroStream child : children) {
+                    children.iterator().next().rePrioritise(
+                            streamToRemove.getParentStream(),
+                            streamToRemove.getWeight() * child.getWeight() / totalWeight);
+                }
+            }
+            streamToRemove.detachFromParent();
+            children.clear();
+        }
+    }
+
+
+    void push(Request request, Stream associatedStream) throws IOException {
+        if (localSettings.getMaxConcurrentStreams() < activeRemoteStreamCount.incrementAndGet()) {
+            // If there are too many open streams, simply ignore the push
+            // request.
+            setConnectionTimeoutForStreamCount(activeRemoteStreamCount.decrementAndGet());
+            return;
+        }
+
+        Stream pushStream;
+
+        // Synchronized since PUSH_PROMISE frames have to be sent in order. Once
+        // the stream has been created we need to ensure that the PUSH_PROMISE
+        // is sent before the next stream is created for a PUSH_PROMISE.
+        synchronized (socketWrapper) {
+            pushStream = createLocalStream(request);
+            writeHeaders(associatedStream, pushStream.getIdAsInt(), request.getMimeHeaders(),
+                    false, Constants.DEFAULT_HEADERS_FRAME_SIZE);
+        }
+
+        pushStream.sentPushPromise();
+
+        processStreamOnContainerThread(pushStream);
+    }
+
+
+    @Override
+    protected final String getConnectionId() {
+        return connectionId;
+    }
+
+
+    @Override
+    protected final int getWeight() {
+        return 0;
+    }
+
+
+    private void reduceOverheadCount(FrameType frameType) {
+        // A non-overhead frame reduces the overhead count by
+        // Http2Protocol.DEFAULT_OVERHEAD_REDUCTION_FACTOR. A simple browser
+        // request is likely to have one non-overhead frame (HEADERS) and one
+        // overhead frame (REPRIORITISE). With the default settings the overhead
+        // count will reduce by 10 for each simple request.
+        // Requests and responses with bodies will create additional
+        // non-overhead frames, further reducing the overhead count.
+        updateOverheadCount(frameType, Http2Protocol.DEFAULT_OVERHEAD_REDUCTION_FACTOR);
+    }
+
+
+    private void increaseOverheadCount(FrameType frameType) {
+        // An overhead frame increases the overhead count by
+        // overheadCountFactor. By default, this means an overhead frame
+        // increases the overhead count by 10. A simple browser request is
+        // likely to have one non-overhead frame (HEADERS) and one overhead
+        // frame (REPRIORITISE). With the default settings the overhead count
+        // will reduce by 10 for each simple request.
+        updateOverheadCount(frameType, getProtocol().getOverheadCountFactor());
+    }
+
+
+    private void increaseOverheadCount(FrameType frameType, int increment) {
+        // Overhead frames that indicate inefficient (and potentially malicious)
+        // use of small frames trigger an increase that is inversely
+        // proportional to size. The default threshold for all three potential
+        // areas for abuse (HEADERS, DATA, WINDOW_UPDATE) is 1024 bytes. Frames
+        // with sizes smaller than this will trigger an increase of
+        // threshold/size.
+        // DATA and WINDOW_UPDATE take an average over the last two non-final
+        // frames to allow for client buffering schemes that can result in some
+        // small DATA payloads.
+        updateOverheadCount(frameType, increment);
+    }
+
+
+    private void updateOverheadCount(FrameType frameType, int increment) {
+        long newOverheadCount = overheadCount.addAndGet(increment);
+        if (log.isDebugEnabled()) {
+            log.debug(sm.getString("upgradeHandler.overheadChange",
+                    connectionId, getIdAsString(), frameType.name(), Long.valueOf(newOverheadCount)));
+        }
+    }
+
+
+    // ----------------------------------------------- Http2Parser.Input methods
+
+    @Override
+    public boolean fill(boolean block, byte[] data, int offset, int length) throws IOException {
+        int len = length;
+        int pos = offset;
+        boolean nextReadBlock = block;
+        int thisRead = 0;
+
+        while (len > 0) {
+            // Blocking reads use the protocol level read timeout. Non-blocking
+            // reads do not timeout. The intention is that once a frame has
+            // started to be read, the read timeout applies until it is
+            // completely read.
+            if (nextReadBlock) {
+                socketWrapper.setReadTimeout(protocol.getReadTimeout());
+            } else {
+                socketWrapper.setReadTimeout(-1);
+            }
+            thisRead = socketWrapper.read(nextReadBlock, data, pos, len);
+            if (thisRead == 0) {
+                if (nextReadBlock) {
+                    // Should never happen
+                    throw new IllegalStateException();
+                } else {
+                    return false;
+                }
+            } else if (thisRead == -1) {
+                if (connectionState.get().isNewStreamAllowed()) {
+                    throw new EOFException();
+                } else {
+                    return false;
+                }
+            } else {
+                pos += thisRead;
+                len -= thisRead;
+                nextReadBlock = true;
+            }
+        }
+
+        return true;
+    }
+
+
+    @Override
+    public int getMaxFrameSize() {
+        return localSettings.getMaxFrameSize();
+    }
+
+
+    // ---------------------------------------------- Http2Parser.Output methods
+
+    @Override
+    public HpackDecoder getHpackDecoder() {
+        if (hpackDecoder == null) {
+            hpackDecoder = new HpackDecoder(localSettings.getHeaderTableSize());
+        }
+        return hpackDecoder;
+    }
+
+
+    @Override
+    public ByteBuffer startRequestBodyFrame(int streamId, int payloadSize, boolean endOfStream) throws Http2Exception {
+        // DATA frames reduce the overhead count ...
+        reduceOverheadCount(FrameType.DATA);
+
+        // .. but lots of small payloads are inefficient so that will increase
+        // the overhead count unless it is the final DATA frame where small
+        // payloads are expected.
+
+        // See also https://bz.apache.org/bugzilla/show_bug.cgi?id=63690
+        // The buffering behaviour of some clients means that small data frames
+        // are much more frequent (roughly 1 in 20) than expected. Use an
+        // average over two frames to avoid false positives.
+        if (!endOfStream) {
+            int overheadThreshold = protocol.getOverheadDataThreshold();
+            int average = (lastNonFinalDataPayload >> 1) + (payloadSize >> 1);
+            lastNonFinalDataPayload = payloadSize;
+            // Avoid division by zero
+            if (average == 0) {
+                average = 1;
+            }
+            if (average < overheadThreshold) {
+                increaseOverheadCount(FrameType.DATA, overheadThreshold / average);
+            }
+        }
+
+        AbstractNonZeroStream abstractNonZeroStream = getAbstractNonZeroStream(streamId, true);
+        abstractNonZeroStream.checkState(FrameType.DATA);
+        abstractNonZeroStream.receivedData(payloadSize);
+        ByteBuffer result = abstractNonZeroStream.getInputByteBuffer();
+
+        if (log.isDebugEnabled()) {
+            log.debug(sm.getString("upgradeHandler.startRequestBodyFrame.result",
+                    getConnectionId(), abstractNonZeroStream.getIdAsString(), result));
+        }
+
+        return result;
+    }
+
+
+    @Override
+    public void endRequestBodyFrame(int streamId, int dataLength) throws Http2Exception, IOException {
+        AbstractNonZeroStream abstractNonZeroStream = getAbstractNonZeroStream(streamId, true);
+        if (abstractNonZeroStream instanceof Stream) {
+            ((Stream) abstractNonZeroStream).getInputBuffer().onDataAvailable();
+        } else {
+            // The Stream was recycled between the call in Http2Parser to
+            // startRequestBodyFrame() and the synchronized block that contains
+            // the call to this method. This means the bytes read will have been
+            // written to the original stream and, effectively, swallowed.
+            // Therefore, need to notify that those bytes were swallowed here.
+            onSwallowedDataFramePayload(streamId, dataLength);
+        }
+    }
+
+
+    @Override
+    public void receivedEndOfStream(int streamId) throws ConnectionException {
+        AbstractNonZeroStream abstractNonZeroStream =
+                getAbstractNonZeroStream(streamId, connectionState.get().isNewStreamAllowed());
+        if (abstractNonZeroStream instanceof Stream) {
+            Stream stream = (Stream) abstractNonZeroStream;
+            stream.receivedEndOfStream();
+            if (!stream.isActive()) {
+                setConnectionTimeoutForStreamCount(activeRemoteStreamCount.decrementAndGet());
+            }
+        }
+    }
+
+
+    @Override
+    public void onSwallowedDataFramePayload(int streamId, int swallowedDataBytesCount) throws IOException {
+        AbstractNonZeroStream abstractNonZeroStream = getAbstractNonZeroStream(streamId);
+        writeWindowUpdate(abstractNonZeroStream, swallowedDataBytesCount, false);
+    }
+
+
+    @Override
+    public HeaderEmitter headersStart(int streamId, boolean headersEndStream)
+            throws Http2Exception, IOException {
+
+        // Check the pause state before processing headers since the pause state
+        // determines if a new stream is created or if this stream is ignored.
+        checkPauseState();
+
+        if (connectionState.get().isNewStreamAllowed()) {
+            Stream stream = getStream(streamId, false);
+            if (stream == null) {
+                stream = createRemoteStream(streamId);
+            }
+            if (streamId < maxActiveRemoteStreamId) {
+                throw new ConnectionException(sm.getString("upgradeHandler.stream.old",
+                        Integer.valueOf(streamId), Integer.valueOf(maxActiveRemoteStreamId)),
+                        Http2Error.PROTOCOL_ERROR);
+            }
+            stream.checkState(FrameType.HEADERS);
+            stream.receivedStartOfHeaders(headersEndStream);
+            closeIdleStreams(streamId);
+            return stream;
+        } else {
+            if (log.isDebugEnabled()) {
+                log.debug(sm.getString("upgradeHandler.noNewStreams",
+                        connectionId, Integer.toString(streamId)));
+            }
+            reduceOverheadCount(FrameType.HEADERS);
+            // Stateless so a static can be used to save on GC
+            return HEADER_SINK;
+        }
+    }
+
+
+    private void closeIdleStreams(int newMaxActiveRemoteStreamId) {
+        final ConcurrentNavigableMap<Integer, AbstractNonZeroStream> subMap = streams.subMap(
+                Integer.valueOf(maxActiveRemoteStreamId), false,
+                Integer.valueOf(newMaxActiveRemoteStreamId), false);
+        for (AbstractNonZeroStream stream : subMap.values()) {
+            if (stream instanceof Stream) {
+                ((Stream)stream).closeIfIdle();
+            }
+        }
+        maxActiveRemoteStreamId = newMaxActiveRemoteStreamId;
+    }
+
+
+    @Override
+    public void reprioritise(int streamId, int parentStreamId,
+            boolean exclusive, int weight) throws Http2Exception {
+        if (streamId == parentStreamId) {
+            throw new ConnectionException(sm.getString("upgradeHandler.dependency.invalid",
+                    getConnectionId(), Integer.valueOf(streamId)), Http2Error.PROTOCOL_ERROR);
+        }
+
+        increaseOverheadCount(FrameType.PRIORITY);
+
+        synchronized (priorityTreeLock) {
+            // Need to look up stream and parent stream inside the lock else it
+            // is possible for a stream to be recycled before it is
+            // reprioritised. This can result in incorrect references to the
+            // non-recycled stream being retained after reprioritisation.
+            AbstractNonZeroStream abstractNonZeroStream = getAbstractNonZeroStream(streamId);
+            if (abstractNonZeroStream == null) {
+                abstractNonZeroStream = createRemoteStream(streamId);
+            }
+            AbstractStream parentStream = getAbstractNonZeroStream(parentStreamId);
+            if (parentStream == null) {
+                parentStream = this;
+            }
+            abstractNonZeroStream.rePrioritise(parentStream, exclusive, weight);
+        }
+    }
+
+
+    @Override
+    public void headersContinue(int payloadSize, boolean endOfHeaders) {
+        // Generally, continuation frames don't impact the overhead count but if
+        // they are small and the frame isn't the final header frame then that
+        // is indicative of an abusive client
+        if (!endOfHeaders) {
+            int overheadThreshold = getProtocol().getOverheadContinuationThreshold();
+            if (payloadSize < overheadThreshold) {
+                if (payloadSize == 0) {
+                    // Avoid division by zero
+                    increaseOverheadCount(FrameType.HEADERS, overheadThreshold);
+                } else {
+                    increaseOverheadCount(FrameType.HEADERS, overheadThreshold / payloadSize);
+                }
+            }
+        }
+    }
+
+
+    @Override
+    public void headersEnd(int streamId) throws Http2Exception {
+        AbstractNonZeroStream abstractNonZeroStream =
+                getAbstractNonZeroStream(streamId, connectionState.get().isNewStreamAllowed());
+        if (abstractNonZeroStream instanceof Stream) {
+            setMaxProcessedStream(streamId);
+            Stream stream = (Stream) abstractNonZeroStream;
+            if (stream.isActive()) {
+                if (stream.receivedEndOfHeaders()) {
+
+                    if (localSettings.getMaxConcurrentStreams() < activeRemoteStreamCount.incrementAndGet()) {
+                        setConnectionTimeoutForStreamCount(activeRemoteStreamCount.decrementAndGet());
+                        // Ignoring maxConcurrentStreams increases the overhead count
+                        increaseOverheadCount(FrameType.HEADERS);
+                        throw new StreamException(sm.getString("upgradeHandler.tooManyRemoteStreams",
+                                Long.toString(localSettings.getMaxConcurrentStreams())),
+                                Http2Error.REFUSED_STREAM, streamId);
+                    }
+                    // Valid new stream reduces the overhead count
+                    reduceOverheadCount(FrameType.HEADERS);
+
+                    processStreamOnContainerThread(stream);
+                }
+            }
+        }
+    }
+
+
+    private void setMaxProcessedStream(int streamId) {
+        if (maxProcessedStreamId < streamId) {
+            maxProcessedStreamId = streamId;
+        }
+    }
+
+
+    @Override
+    public void reset(int streamId, long errorCode) throws Http2Exception  {
+        if (log.isDebugEnabled()) {
+            log.debug(sm.getString("upgradeHandler.reset.receive", getConnectionId(), Integer.toString(streamId),
+                    Long.toString(errorCode)));
+        }
+        AbstractNonZeroStream abstractNonZeroStream = getAbstractNonZeroStream(streamId, true);
+        abstractNonZeroStream.checkState(FrameType.RST);
+        if (abstractNonZeroStream instanceof Stream) {
+            Stream stream = (Stream) abstractNonZeroStream;
+            boolean active = stream.isActive();
+            stream.receiveReset(errorCode);
+            if (active) {
+                activeRemoteStreamCount.decrementAndGet();
+            }
+        }
+    }
+
+
+    @Override
+    public void setting(Setting setting, long value) throws ConnectionException {
+
+        increaseOverheadCount(FrameType.SETTINGS);
+
+        // Possible with empty settings frame
+        if (setting == null) {
+            return;
+        }
+
+        // Special handling required
+        if (setting == Setting.INITIAL_WINDOW_SIZE) {
+            long oldValue = remoteSettings.getInitialWindowSize();
+            // Do this first in case new value is invalid
+            remoteSettings.set(setting, value);
+            int diff = (int) (value - oldValue);
+            for (AbstractNonZeroStream stream : streams.values()) {
+                try {
+                    stream.incrementWindowSize(diff);
+                } catch (Http2Exception h2e) {
+                    ((Stream) stream).close(new StreamException(sm.getString(
+                            "upgradeHandler.windowSizeTooBig", connectionId,
+                            stream.getIdAsString()),
+                            h2e.getError(), stream.getIdAsInt()));
+               }
+            }
+        } else {
+            remoteSettings.set(setting, value);
+        }
+    }
+
+
+    @Override
+    public void settingsEnd(boolean ack) throws IOException {
+        if (ack) {
+            if (!localSettings.ack()) {
+                // Ack was unexpected
+                log.warn(sm.getString(
+                        "upgradeHandler.unexpectedAck", connectionId, getIdAsString()));
+            }
+        } else {
+            synchronized (socketWrapper) {
+                socketWrapper.write(true, SETTINGS_ACK, 0, SETTINGS_ACK.length);
+                socketWrapper.flush(true);
+            }
+        }
+    }
+
+
+    @Override
+    public void pingReceive(byte[] payload, boolean ack) throws IOException {
+        if (!ack) {
+            increaseOverheadCount(FrameType.PING);
+        }
+        pingManager.receivePing(payload, ack);
+    }
+
+
+    @Override
+    public void goaway(int lastStreamId, long errorCode, String debugData) {
+        if (log.isDebugEnabled()) {
+            log.debug(sm.getString("upgradeHandler.goaway.debug", connectionId,
+                    Integer.toString(lastStreamId), Long.toHexString(errorCode), debugData));
+        }
+        close();
+    }
+
+
+    @Override
+    public void incrementWindowSize(int streamId, int increment) throws Http2Exception {
+        // See also https://bz.apache.org/bugzilla/show_bug.cgi?id=63690
+        // The buffering behaviour of some clients means that small data frames
+        // are much more frequent (roughly 1 in 20) than expected. Some clients
+        // issue a Window update for every DATA frame so a similar pattern may
+        // be observed. Use an average over two frames to avoid false positives.
+
+        int average = (lastWindowUpdate >> 1) + (increment >> 1);
+        int overheadThreshold = protocol.getOverheadWindowUpdateThreshold();
+        lastWindowUpdate = increment;
+        // Avoid division by zero
+        if (average == 0) {
+            average = 1;
+        }
+
+        if (streamId == 0) {
+            // Check for small increments which are inefficient
+            if (average < overheadThreshold) {
+                // The smaller the increment, the larger the overhead
+                increaseOverheadCount(FrameType.WINDOW_UPDATE, overheadThreshold / average);
+            }
+
+            incrementWindowSize(increment);
+        } else {
+            AbstractNonZeroStream stream = getAbstractNonZeroStream(streamId, true);
+
+            // Check for small increments which are inefficient
+            if (average < overheadThreshold) {
+                // For Streams, client might only release the minimum so check
+                // against current demand
+                if (increment < stream.getConnectionAllocationRequested()) {
+                    // The smaller the increment, the larger the overhead
+                    increaseOverheadCount(FrameType.WINDOW_UPDATE, overheadThreshold / average);
+                }
+            }
+
+            stream.checkState(FrameType.WINDOW_UPDATE);
+            stream.incrementWindowSize(increment);
+        }
+    }
+
+
+    @Override
+    public void onSwallowedUnknownFrame(int streamId, int frameTypeId, int flags, int size)
+            throws IOException {
+        // NO-OP.
+    }
+
+
+    void replaceStream(AbstractNonZeroStream original, AbstractNonZeroStream replacement) {
+        synchronized (priorityTreeLock) {
+            AbstractNonZeroStream current = streams.get(original.getIdentifier());
+            // Might already have been recycled or removed from the priority
+            // tree entirely. Only replace it if the full stream is still in the
+            // priority tree.
+            if (current instanceof Stream) {
+                streams.put(original.getIdentifier(), replacement);
+                original.replaceStream(replacement);
+            }
+        }
+    }
+
+
+    protected class PingManager {
+
+        protected boolean initiateDisabled = false;
+
+        // 10 seconds
+        protected final long pingIntervalNano = 10000000000L;
+
+        protected int sequence = 0;
+        protected long lastPingNanoTime = Long.MIN_VALUE;
+
+        protected Queue<PingRecord> inflightPings = new ConcurrentLinkedQueue<>();
+        protected Queue<Long> roundTripTimes = new ConcurrentLinkedQueue<>();
+
+        /**
+         * Check to see if a ping was sent recently and, if not, send one.
+         *
+         * @param force Send a ping, even if one was sent recently
+         *
+         * @throws IOException If an I/O issue prevents the ping from being sent
+         */
+        public void sendPing(boolean force) throws IOException {
+            if (initiateDisabled) {
+                return;
+            }
+            long now = System.nanoTime();
+            if (force || now - lastPingNanoTime > pingIntervalNano) {
+                lastPingNanoTime = now;
+                byte[] payload = new byte[8];
+                synchronized (socketWrapper) {
+                    int sentSequence = ++sequence;
+                    PingRecord pingRecord = new PingRecord(sentSequence, now);
+                    inflightPings.add(pingRecord);
+                    ByteUtil.set31Bits(payload, 4, sentSequence);
+                    socketWrapper.write(true, PING, 0, PING.length);
+                    socketWrapper.write(true, payload, 0, payload.length);
+                    socketWrapper.flush(true);
+                }
+            }
+        }
+
+        public void receivePing(byte[] payload, boolean ack) throws IOException {
+            if (ack) {
+                // Extract the sequence from the payload
+                int receivedSequence = ByteUtil.get31Bits(payload, 4);
+                PingRecord pingRecord = inflightPings.poll();
+                while (pingRecord != null && pingRecord.getSequence() < receivedSequence) {
+                    pingRecord = inflightPings.poll();
+                }
+                if (pingRecord == null) {
+                    // Unexpected ACK. Log it.
+                } else {
+                    long roundTripTime = System.nanoTime() - pingRecord.getSentNanoTime();
+                    roundTripTimes.add(Long.valueOf(roundTripTime));
+                    while (roundTripTimes.size() > 3) {
+                        // Ignore the returned value as we just want to reduce
+                        // the queue to 3 entries to use for the rolling average.
+                        roundTripTimes.poll();
+                    }
+                    if (log.isDebugEnabled()) {
+                        log.debug(sm.getString("pingManager.roundTripTime",
+                                connectionId, Long.valueOf(roundTripTime)));
+                    }
+                }
+
+            } else {
+                // Client originated ping. Echo it back.
+                synchronized (socketWrapper) {
+                    socketWrapper.write(true, PING_ACK, 0, PING_ACK.length);
+                    socketWrapper.write(true, payload, 0, payload.length);
+                    socketWrapper.flush(true);
+                }
+            }
+        }
+
+        public long getRoundTripTimeNano() {
+            return (long) roundTripTimes.stream().mapToLong(Long::longValue).average().orElse(0);
+        }
+    }
+
+
+    protected static class PingRecord {
+
+        private final int sequence;
+        private final long sentNanoTime;
+
+        public PingRecord(int sequence, long sentNanoTime) {
+            this.sequence = sequence;
+            this.sentNanoTime = sentNanoTime;
+        }
+
+        public int getSequence() {
+            return sequence;
+        }
+
+        public long getSentNanoTime() {
+            return sentNanoTime;
+        }
+    }
+
+
+    private enum ConnectionState {
+
+        NEW(true),
+        CONNECTED(true),
+        PAUSING(true),
+        PAUSED(false),
+        CLOSED(false);
+
+        private final boolean newStreamsAllowed;
+
+        private ConnectionState(boolean newStreamsAllowed) {
+            this.newStreamsAllowed = newStreamsAllowed;
+        }
+
+        public boolean isNewStreamAllowed() {
+            return newStreamsAllowed;
+        }
+    }
+
+
+    protected static interface HeaderFrameBuffers {
+        public void startFrame();
+        public void endFrame() throws IOException;
+        public void endHeaders() throws IOException;
+        public byte[] getHeader();
+        public ByteBuffer getPayload();
+        public void expandPayload();
+    }
+
+
+    private class DefaultHeaderFrameBuffers implements HeaderFrameBuffers {
+
+        private final byte[] header;
+        private ByteBuffer payload;
+
+        public DefaultHeaderFrameBuffers(int initialPayloadSize) {
+            header = new byte[9];
+            payload = ByteBuffer.allocate(initialPayloadSize);
+        }
+
+        @Override
+        public void startFrame() {
+            // NO-OP
+        }
+
+
+        @Override
+        public void endFrame() throws IOException {
+            try {
+                socketWrapper.write(true, header, 0, header.length);
+                socketWrapper.write(true, payload);
+                socketWrapper.flush(true);
+            } catch (IOException ioe) {
+                handleAppInitiatedIOException(ioe);
+            }
+            payload.clear();
+        }
+
+        @Override
+        public void endHeaders() {
+            // NO-OP
+        }
+
+        @Override
+        public byte[] getHeader() {
+            return header;
+        }
+
+        @Override
+        public ByteBuffer getPayload() {
+            return payload;
+        }
+
+        @Override
+        public void expandPayload() {
+            payload = ByteBuffer.allocate(payload.capacity() * 2);
+        }
+    }
+}


[tomee] 05/06: TOMEE-4254 - Add unpatched classes to backport https://github.com/apache/tomcat/commit/9375d67106f8df9eb9d7b360b2bef052fe67d3d4

Posted by rz...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rzo1 pushed a commit to branch tomee-9.x
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 95521287ab194d4d9f7561ea072322844b3f012c
Author: Richard Zowalla <rz...@apache.org>
AuthorDate: Wed Oct 11 14:49:57 2023 +0200

    TOMEE-4254 - Add unpatched classes to backport https://github.com/apache/tomcat/commit/9375d67106f8df9eb9d7b360b2bef052fe67d3d4
---
 .../catalina/connector/LocalStrings.properties     |  95 ++
 .../catalina/core/ApplicationHttpRequest.java      | 995 +++++++++++++++++++++
 .../apache/catalina/core/LocalStrings.properties   | 312 +++++++
 .../org/apache/tomcat/util/buf/B2CConverter.java   | 262 ++++++
 .../org/apache/tomcat/util/buf/C2BConverter.java   | 192 ++++
 .../apache/tomcat/util/buf/LocalStrings.properties |  33 +
 6 files changed, 1889 insertions(+)

diff --git a/tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/LocalStrings.properties b/tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/LocalStrings.properties
new file mode 100644
index 0000000000..5cfd969f13
--- /dev/null
+++ b/tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/LocalStrings.properties
@@ -0,0 +1,95 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+coyoteAdapter.accesslogFail=Exception while attempting to add an entry to the access log
+coyoteAdapter.asyncDispatch=Exception while processing an asynchronous request
+coyoteAdapter.authenticate=Authenticated user [{0}] provided by connector
+coyoteAdapter.authorize=Authorizing user [{0}] using Tomcat''s Realm
+coyoteAdapter.checkRecycled.request=Encountered a non-recycled request and recycled it forcedly.
+coyoteAdapter.checkRecycled.response=Encountered a non-recycled response and recycled it forcedly.
+coyoteAdapter.debug=The variable [{0}] has value [{1}]
+coyoteAdapter.nullRequest=An asynchronous dispatch may only happen on an existing request
+
+coyoteConnector.invalidEncoding=The encoding [{0}] is not recognised by the JRE. The Connector will continue to use [{1}]
+coyoteConnector.invalidPort=The connector cannot start since the specified port value of [{0}] is invalid
+coyoteConnector.notAsciiSuperset=The encoding [{0}] is not a superset of ASCII as required by RFC 7230. The Connector will continue to use [{1}]
+coyoteConnector.parseBodyMethodNoTrace=TRACE method MUST NOT include an entity (see RFC 2616 Section 9.6)
+coyoteConnector.protocolHandlerDestroyFailed=Protocol handler destroy failed
+coyoteConnector.protocolHandlerInitializationFailed=Protocol handler initialization failed
+coyoteConnector.protocolHandlerInstantiationFailed=Protocol handler instantiation failed
+coyoteConnector.protocolHandlerNoAprLibrary=The configured protocol [{0}] requires the APR/native library which is not available
+coyoteConnector.protocolHandlerNoAprListener=The configured protocol [{0}] requires the AprLifecycleListener which is not available
+coyoteConnector.protocolHandlerPauseFailed=Protocol handler pause failed
+coyoteConnector.protocolHandlerResumeFailed=Protocol handler resume failed
+coyoteConnector.protocolHandlerStartFailed=Protocol handler start failed
+coyoteConnector.protocolHandlerStopFailed=Protocol handler stop failed
+
+coyoteInputStream.nbNotready=In non-blocking mode you may not read from the ServletInputStream until the previous read has completed and isReady() returns true
+coyoteInputStream.null=The input buffer object has been recycled and is no longer associated with this facade
+
+coyoteOutputStream.nbNotready=In non-blocking mode you may not write to the ServletOutputStream until the previous write has completed and isReady() returns true
+coyoteOutputStream.null=The output buffer object has been recycled and is no longer associated with this facade
+
+coyoteRequest.alreadyAuthenticated=This request has already been authenticated
+coyoteRequest.attributeEvent=Exception thrown by attributes event listener
+coyoteRequest.authenticate.ise=Cannot call authenticate() after the response has been committed
+coyoteRequest.changeSessionId=Cannot change session ID. There is no session associated with this request.
+coyoteRequest.chunkedPostTooLarge=Parameters were not parsed because the size of the posted data was too big. Because this request was a chunked request, it could not be processed further. Use the maxPostSize attribute of the connector to resolve this if the application should accept large POSTs.
+coyoteRequest.filterAsyncSupportUnknown=Unable to determine if any filters do not support async processing
+coyoteRequest.getContextPath.ise=Unable to find match between the canonical context path [{0}] and the URI presented by the user agent [{1}]
+coyoteRequest.getInputStream.ise=getReader() has already been called for this request
+coyoteRequest.getReader.ise=getInputStream() has already been called for this request
+coyoteRequest.gssLifetimeFail=Failed to obtain remaining lifetime for user principal [{0}]
+coyoteRequest.maxPostSizeExceeded=The multi-part request contained parameter data (excluding uploaded files) that exceeded the limit for maxPostSize set on the associated connector
+coyoteRequest.noAsync=Unable to start async because the following classes in the processing chain do not support async [{0}]
+coyoteRequest.noMultipartConfig=Unable to process parts as no multi-part configuration has been provided
+coyoteRequest.parseParameters=Exception thrown whilst processing POSTed parameters
+coyoteRequest.postTooLarge=Parameters were not parsed because the size of the posted data was too big. Use the maxPostSize attribute of the connector to resolve this if the application should accept large POSTs.
+coyoteRequest.sendfileNotCanonical=Unable to determine canonical name of file [{0}] specified for use with sendfile
+coyoteRequest.sessionCreateCommitted=Cannot create a session after the response has been committed
+coyoteRequest.sessionEndAccessFail=Exception triggered ending access to session while recycling request
+coyoteRequest.setAttribute.namenull=Cannot call setAttribute with a null name
+coyoteRequest.trailersNotReady=It is illegal to call getTrailerFields() before isTrailerFieldsReady() has returned true
+coyoteRequest.uploadCreate=Creating the temporary upload location [{0}] as it is required by the servlet [{1}]
+coyoteRequest.uploadCreateFail=Failed to create the upload location [{0}]
+coyoteRequest.uploadLocationInvalid=The temporary upload location [{0}] is not valid
+
+coyoteResponse.encoding.invalid=The encoding [{0}] is not recognised by the JRE
+coyoteResponse.getOutputStream.ise=getWriter() has already been called for this response
+coyoteResponse.getWriter.ise=getOutputStream() has already been called for this response
+coyoteResponse.reset.ise=Cannot call reset() after response has been committed
+coyoteResponse.resetBuffer.ise=Cannot reset buffer after response has been committed
+coyoteResponse.sendError.ise=Cannot call sendError() after the response has been committed
+coyoteResponse.sendRedirect.ise=Cannot call sendRedirect() after the response has been committed
+coyoteResponse.sendRedirect.note=<html><body><p>Redirecting to <a href="{0}">{0}</a></p></body></html>
+coyoteResponse.setBufferSize.ise=Cannot change buffer size after data has been written
+
+inputBuffer.requiresNonBlocking=Not available in non blocking mode
+inputBuffer.streamClosed=Stream closed
+
+outputBuffer.writeNull=The String argument to write(String,int,int) may not be null
+
+request.asyncNotSupported=A filter or servlet of the current chain does not support asynchronous operations.
+request.fragmentInDispatchPath=The fragment in dispatch path [{0}] has been removed
+request.illegalWrap=The request wrapper must wrap the request obtained from getRequest()
+request.notAsync=It is illegal to call this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false)
+request.session.failed=Failed to load session [{0}] due to [{1}]
+
+requestFacade.nullRequest=The request object has been recycled and is no longer associated with this facade
+
+response.illegalWrap=The response wrapper must wrap the response obtained from getResponse()
+response.sendRedirectFail=Failed to redirect to [{0}]
+
+responseFacade.nullResponse=The response object has been recycled and is no longer associated with this facade
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/ApplicationHttpRequest.java b/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/ApplicationHttpRequest.java
new file mode 100644
index 0000000000..6d6dd6fe38
--- /dev/null
+++ b/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/ApplicationHttpRequest.java
@@ -0,0 +1,995 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.catalina.core;
+
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+
+import jakarta.servlet.DispatcherType;
+import jakarta.servlet.RequestDispatcher;
+import jakarta.servlet.ServletContext;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletRequestWrapper;
+import jakarta.servlet.http.HttpServletMapping;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequestWrapper;
+import jakarta.servlet.http.HttpSession;
+import jakarta.servlet.http.PushBuilder;
+
+import org.apache.catalina.Context;
+import org.apache.catalina.Globals;
+import org.apache.catalina.Manager;
+import org.apache.catalina.Session;
+import org.apache.catalina.connector.RequestFacade;
+import org.apache.catalina.util.ParameterMap;
+import org.apache.catalina.util.RequestUtil;
+import org.apache.catalina.util.URLEncoder;
+import org.apache.tomcat.util.buf.B2CConverter;
+import org.apache.tomcat.util.buf.MessageBytes;
+import org.apache.tomcat.util.http.Parameters;
+import org.apache.tomcat.util.res.StringManager;
+
+
+/**
+ * Wrapper around a <code>jakarta.servlet.http.HttpServletRequest</code>
+ * that transforms an application request object (which might be the original
+ * one passed to a servlet, or might be based on the 2.3
+ * <code>jakarta.servlet.http.HttpServletRequestWrapper</code> class)
+ * back into an internal <code>org.apache.catalina.HttpRequest</code>.
+ * <p>
+ * <strong>WARNING</strong>:  Due to Java's lack of support for multiple
+ * inheritance, all of the logic in <code>ApplicationRequest</code> is
+ * duplicated in <code>ApplicationHttpRequest</code>.  Make sure that you
+ * keep these two classes in synchronization when making changes!
+ *
+ * @author Craig R. McClanahan
+ * @author Remy Maucherat
+ */
+class ApplicationHttpRequest extends HttpServletRequestWrapper {
+
+    private static final StringManager sm = StringManager.getManager(ApplicationHttpRequest.class);
+
+    /**
+     * The set of attribute names that are special for request dispatchers.
+     */
+    protected static final String specials[] =
+    { RequestDispatcher.INCLUDE_REQUEST_URI,
+      RequestDispatcher.INCLUDE_CONTEXT_PATH,
+      RequestDispatcher.INCLUDE_SERVLET_PATH,
+      RequestDispatcher.INCLUDE_PATH_INFO,
+      RequestDispatcher.INCLUDE_QUERY_STRING,
+      RequestDispatcher.INCLUDE_MAPPING,
+      RequestDispatcher.FORWARD_REQUEST_URI,
+      RequestDispatcher.FORWARD_CONTEXT_PATH,
+      RequestDispatcher.FORWARD_SERVLET_PATH,
+      RequestDispatcher.FORWARD_PATH_INFO,
+      RequestDispatcher.FORWARD_QUERY_STRING,
+      RequestDispatcher.FORWARD_MAPPING};
+
+    private static final int SPECIALS_FIRST_FORWARD_INDEX = 6;
+
+
+    // ----------------------------------------------------------- Constructors
+
+
+    /**
+     * Construct a new wrapped request around the specified servlet request.
+     *
+     * @param request The servlet request being wrapped
+     * @param context The target context for the wrapped request
+     * @param crossContext {@code true} if the wrapped request will be a
+     *                     cross-context request, otherwise {@code false}
+     */
+    public ApplicationHttpRequest(HttpServletRequest request, Context context,
+                                  boolean crossContext) {
+
+        super(request);
+        this.context = context;
+        this.crossContext = crossContext;
+        setRequest(request);
+
+    }
+
+
+    // ----------------------------------------------------- Instance Variables
+
+
+    /**
+     * The context for this request.
+     */
+    protected final Context context;
+
+
+    /**
+     * The context path for this request.
+     */
+    protected String contextPath = null;
+
+
+    /**
+     * If this request is cross context, since this changes session access
+     * behavior.
+     */
+    protected final boolean crossContext;
+
+
+    /**
+     * The current dispatcher type.
+     */
+    protected DispatcherType dispatcherType = null;
+
+
+    /**
+     * The request parameters for this request.  This is initialized from the
+     * wrapped request.
+     */
+    protected Map<String, String[]> parameters = null;
+
+
+    /**
+     * Have the parameters for this request already been parsed?
+     */
+    private boolean parsedParams = false;
+
+
+    /**
+     * The path information for this request.
+     */
+    protected String pathInfo = null;
+
+
+    /**
+     * The query parameters for the current request.
+     */
+    private String queryParamString = null;
+
+
+    /**
+     * The query string for this request.
+     */
+    protected String queryString = null;
+
+
+    /**
+     * The current request dispatcher path.
+     */
+    protected Object requestDispatcherPath = null;
+
+
+    /**
+     * The request URI for this request.
+     */
+    protected String requestURI = null;
+
+
+    /**
+     * The servlet path for this request.
+     */
+    protected String servletPath = null;
+
+
+    /**
+     * The mapping for this request.
+     */
+    private HttpServletMapping mapping = null;
+
+
+    /**
+     * The currently active session for this request.
+     */
+    protected Session session = null;
+
+
+    /**
+     * Special attributes.
+     */
+    protected final Object[] specialAttributes = new Object[specials.length];
+
+
+    // ------------------------------------------------- ServletRequest Methods
+
+    @Override
+    public ServletContext getServletContext() {
+        if (context == null) {
+            return null;
+        }
+        return context.getServletContext();
+    }
+
+
+    /**
+     * Override the <code>getAttribute()</code> method of the wrapped request.
+     *
+     * @param name Name of the attribute to retrieve
+     */
+    @Override
+    public Object getAttribute(String name) {
+
+        if (name.equals(Globals.DISPATCHER_TYPE_ATTR)) {
+            return dispatcherType;
+        } else if (name.equals(Globals.DISPATCHER_REQUEST_PATH_ATTR)) {
+            if ( requestDispatcherPath != null ){
+                return requestDispatcherPath.toString();
+            } else {
+                return null;
+            }
+        }
+
+        int pos = getSpecial(name);
+        if (pos == -1) {
+            return getRequest().getAttribute(name);
+        } else {
+            if ((specialAttributes[pos] == null) &&
+                    (specialAttributes[SPECIALS_FIRST_FORWARD_INDEX] == null) &&
+                    (pos >= SPECIALS_FIRST_FORWARD_INDEX)) {
+                // If it's a forward special attribute, and null, it means this
+                // is an include, so we check the wrapped request since
+                // the request could have been forwarded before the include
+                return getRequest().getAttribute(name);
+            } else {
+                return specialAttributes[pos];
+            }
+        }
+
+    }
+
+
+    /**
+     * Override the <code>getAttributeNames()</code> method of the wrapped
+     * request.
+     */
+    @Override
+    public Enumeration<String> getAttributeNames() {
+        return new AttributeNamesEnumerator();
+    }
+
+
+    /**
+     * Override the <code>removeAttribute()</code> method of the
+     * wrapped request.
+     *
+     * @param name Name of the attribute to remove
+     */
+    @Override
+    public void removeAttribute(String name) {
+
+        if (!removeSpecial(name)) {
+            getRequest().removeAttribute(name);
+        }
+
+    }
+
+
+    /**
+     * Override the <code>setAttribute()</code> method of the
+     * wrapped request.
+     *
+     * @param name Name of the attribute to set
+     * @param value Value of the attribute to set
+     */
+    @Override
+    public void setAttribute(String name, Object value) {
+
+        if (name.equals(Globals.DISPATCHER_TYPE_ATTR)) {
+            dispatcherType = (DispatcherType)value;
+            return;
+        } else if (name.equals(Globals.DISPATCHER_REQUEST_PATH_ATTR)) {
+            requestDispatcherPath = value;
+            return;
+        }
+
+        if (!setSpecial(name, value)) {
+            getRequest().setAttribute(name, value);
+        }
+
+    }
+
+
+    /**
+     * Return a RequestDispatcher that wraps the resource at the specified
+     * path, which may be interpreted as relative to the current request path.
+     *
+     * @param path Path of the resource to be wrapped
+     */
+    @Override
+    public RequestDispatcher getRequestDispatcher(String path) {
+
+        if (context == null) {
+            return null;
+        }
+
+        if (path == null) {
+            return null;
+        }
+
+        int fragmentPos = path.indexOf('#');
+        if (fragmentPos > -1) {
+            context.getLogger().warn(sm.getString("applicationHttpRequest.fragmentInDispatchPath", path));
+            path = path.substring(0, fragmentPos);
+        }
+
+        // If the path is already context-relative, just pass it through
+        if (path.startsWith("/")) {
+            return context.getServletContext().getRequestDispatcher(path);
+        }
+
+        // Convert a request-relative path to a context-relative one
+        String servletPath =
+            (String) getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);
+        if (servletPath == null) {
+            servletPath = getServletPath();
+        }
+
+        // Add the path info, if there is any
+        String pathInfo = getPathInfo();
+        String requestPath = null;
+
+        if (pathInfo == null) {
+            requestPath = servletPath;
+        } else {
+            requestPath = servletPath + pathInfo;
+        }
+
+        int pos = requestPath.lastIndexOf('/');
+        String relative = null;
+        if (context.getDispatchersUseEncodedPaths()) {
+            if (pos >= 0) {
+                relative = URLEncoder.DEFAULT.encode(
+                        requestPath.substring(0, pos + 1), StandardCharsets.UTF_8) + path;
+            } else {
+                relative = URLEncoder.DEFAULT.encode(requestPath, StandardCharsets.UTF_8) + path;
+            }
+        } else {
+            if (pos >= 0) {
+                relative = requestPath.substring(0, pos + 1) + path;
+            } else {
+                relative = requestPath + path;
+            }
+        }
+
+        return context.getServletContext().getRequestDispatcher(relative);
+
+    }
+
+
+    /**
+     * Override the getDispatcherType() method of the wrapped request.
+     *
+     */
+    @Override
+    public DispatcherType getDispatcherType() {
+        return dispatcherType;
+    }
+
+
+    // --------------------------------------------- HttpServletRequest Methods
+
+
+    /**
+     * Override the <code>getContextPath()</code> method of the wrapped
+     * request.
+     */
+    @Override
+    public String getContextPath() {
+        return this.contextPath;
+    }
+
+
+    /**
+     * Override the <code>getParameter()</code> method of the wrapped request.
+     *
+     * @param name Name of the requested parameter
+     */
+    @Override
+    public String getParameter(String name) {
+        parseParameters();
+
+        String[] value = parameters.get(name);
+        if (value == null) {
+            return null;
+        }
+        return value[0];
+    }
+
+
+    /**
+     * Override the <code>getParameterMap()</code> method of the
+     * wrapped request.
+     */
+    @Override
+    public Map<String, String[]> getParameterMap() {
+        parseParameters();
+        return parameters;
+    }
+
+
+    /**
+     * Override the <code>getParameterNames()</code> method of the
+     * wrapped request.
+     */
+    @Override
+    public Enumeration<String> getParameterNames() {
+        parseParameters();
+        return Collections.enumeration(parameters.keySet());
+    }
+
+
+    /**
+     * Override the <code>getParameterValues()</code> method of the
+     * wrapped request.
+     *
+     * @param name Name of the requested parameter
+     */
+    @Override
+    public String[] getParameterValues(String name) {
+        parseParameters();
+        return parameters.get(name);
+    }
+
+
+    /**
+     * Override the <code>getPathInfo()</code> method of the wrapped request.
+     */
+    @Override
+    public String getPathInfo() {
+        return this.pathInfo;
+    }
+
+
+    /**
+     * Override the <code>getPathTranslated()</code> method of the wrapped
+     * request.
+     */
+    @Override
+    public String getPathTranslated() {
+        if (getPathInfo() == null || getServletContext() == null) {
+            return null;
+        }
+
+        return getServletContext().getRealPath(getPathInfo());
+    }
+
+
+    /**
+     * Override the <code>getQueryString()</code> method of the wrapped
+     * request.
+     */
+    @Override
+    public String getQueryString() {
+        return this.queryString;
+    }
+
+
+    /**
+     * Override the <code>getRequestURI()</code> method of the wrapped
+     * request.
+     */
+    @Override
+    public String getRequestURI() {
+        return this.requestURI;
+    }
+
+
+    /**
+     * Override the <code>getRequestURL()</code> method of the wrapped
+     * request.
+     */
+    @Override
+    public StringBuffer getRequestURL() {
+        return RequestUtil.getRequestURL(this);
+    }
+
+
+    /**
+     * Override the <code>getServletPath()</code> method of the wrapped
+     * request.
+     */
+    @Override
+    public String getServletPath() {
+        return this.servletPath;
+    }
+
+
+    @Override
+    public HttpServletMapping getHttpServletMapping() {
+        return mapping;
+    }
+
+
+    /**
+     * Return the session associated with this Request, creating one
+     * if necessary.
+     */
+    @Override
+    public HttpSession getSession() {
+        return getSession(true);
+    }
+
+
+    /**
+     * Return the session associated with this Request, creating one
+     * if necessary and requested.
+     *
+     * @param create Create a new session if one does not exist
+     */
+    @Override
+    public HttpSession getSession(boolean create) {
+
+        if (crossContext) {
+
+            // There cannot be a session if no context has been assigned yet
+            if (context == null) {
+                return null;
+            }
+
+            // Return the current session if it exists and is valid
+            if (session != null && session.isValid()) {
+                return session.getSession();
+            }
+
+            HttpSession other = super.getSession(false);
+            if (create && (other == null)) {
+                // First create a session in the first context: the problem is
+                // that the top level request is the only one which can
+                // create the cookie safely
+                other = super.getSession(true);
+            }
+            if (other != null) {
+                Session localSession = null;
+                try {
+                    localSession =
+                        context.getManager().findSession(other.getId());
+                    if (localSession != null && !localSession.isValid()) {
+                        localSession = null;
+                    }
+                } catch (IOException e) {
+                    // Ignore
+                }
+                if (localSession == null && create) {
+                    localSession =
+                        context.getManager().createSession(other.getId());
+                }
+                if (localSession != null) {
+                    localSession.access();
+                    session = localSession;
+                    return session.getSession();
+                }
+            }
+            return null;
+
+        } else {
+            return super.getSession(create);
+        }
+
+    }
+
+
+    /**
+     * Returns true if the request specifies a JSESSIONID that is valid within
+     * the context of this ApplicationHttpRequest, false otherwise.
+     *
+     * @return true if the request specifies a JSESSIONID that is valid within
+     * the context of this ApplicationHttpRequest, false otherwise.
+     */
+    @Override
+    public boolean isRequestedSessionIdValid() {
+
+        if (crossContext) {
+
+            String requestedSessionId = getRequestedSessionId();
+            if (requestedSessionId == null) {
+                return false;
+            }
+            if (context == null) {
+                return false;
+            }
+            Manager manager = context.getManager();
+            if (manager == null) {
+                return false;
+            }
+            Session session = null;
+            try {
+                session = manager.findSession(requestedSessionId);
+            } catch (IOException e) {
+                // Ignore
+            }
+            if ((session != null) && session.isValid()) {
+                return true;
+            } else {
+                return false;
+            }
+
+        } else {
+            return super.isRequestedSessionIdValid();
+        }
+    }
+
+
+    @Override
+    public PushBuilder newPushBuilder() {
+        ServletRequest current = getRequest();
+        while (current instanceof ServletRequestWrapper) {
+            current = ((ServletRequestWrapper) current).getRequest();
+        }
+        if (current instanceof RequestFacade) {
+            return ((RequestFacade) current).newPushBuilder(this);
+        } else {
+            return null;
+        }
+    }
+
+
+    // -------------------------------------------------------- Package Methods
+
+    /**
+     * Recycle this request
+     */
+    public void recycle() {
+        if (session != null) {
+            session.endAccess();
+        }
+    }
+
+
+    /**
+     * Set the context path for this request.
+     *
+     * @param contextPath The new context path
+     */
+    void setContextPath(String contextPath) {
+
+        this.contextPath = contextPath;
+
+    }
+
+
+    /**
+     * Set the path information for this request.
+     *
+     * @param pathInfo The new path info
+     */
+    void setPathInfo(String pathInfo) {
+
+        this.pathInfo = pathInfo;
+
+    }
+
+
+    /**
+     * Set the query string for this request.
+     *
+     * @param queryString The new query string
+     */
+    void setQueryString(String queryString) {
+
+        this.queryString = queryString;
+
+    }
+
+
+    /**
+     * Set the request that we are wrapping.
+     *
+     * @param request The new wrapped request
+     */
+    void setRequest(HttpServletRequest request) {
+
+        super.setRequest(request);
+
+        // Initialize the attributes for this request
+        dispatcherType = (DispatcherType)request.getAttribute(Globals.DISPATCHER_TYPE_ATTR);
+        requestDispatcherPath =
+            request.getAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR);
+
+        // Initialize the path elements for this request
+        contextPath = request.getContextPath();
+        pathInfo = request.getPathInfo();
+        queryString = request.getQueryString();
+        requestURI = request.getRequestURI();
+        servletPath = request.getServletPath();
+        mapping = request.getHttpServletMapping();
+    }
+
+
+    /**
+     * Set the request URI for this request.
+     *
+     * @param requestURI The new request URI
+     */
+    void setRequestURI(String requestURI) {
+
+        this.requestURI = requestURI;
+
+    }
+
+
+    /**
+     * Set the servlet path for this request.
+     *
+     * @param servletPath The new servlet path
+     */
+    void setServletPath(String servletPath) {
+
+        this.servletPath = servletPath;
+
+    }
+
+
+    /**
+     * Parses the parameters of this request.
+     *
+     * If parameters are present in both the query string and the request
+     * content, they are merged.
+     */
+    void parseParameters() {
+
+        if (parsedParams) {
+            return;
+        }
+
+        parameters = new ParameterMap<>();
+        parameters.putAll(getRequest().getParameterMap());
+        mergeParameters();
+        ((ParameterMap<String,String[]>) parameters).setLocked(true);
+        parsedParams = true;
+    }
+
+
+    /**
+     * Save query parameters for this request.
+     *
+     * @param queryString The query string containing parameters for this
+     *                    request
+     */
+    void setQueryParams(String queryString) {
+        this.queryParamString = queryString;
+    }
+
+
+    void setMapping(HttpServletMapping mapping) {
+        this.mapping = mapping;
+    }
+
+
+    // ------------------------------------------------------ Protected Methods
+
+    /**
+     * Is this attribute name one of the special ones that is added only for
+     * included servlets?
+     *
+     * @param name Attribute name to be tested
+     */
+    protected boolean isSpecial(String name) {
+
+        for (String special : specials) {
+            if (special.equals(name)) {
+                return true;
+            }
+        }
+        return false;
+
+    }
+
+
+    /**
+     * Get a special attribute.
+     *
+     * @return the special attribute pos, or -1 if it is not a special
+     *         attribute
+     */
+    protected int getSpecial(String name) {
+        for (int i = 0; i < specials.length; i++) {
+            if (specials[i].equals(name)) {
+                return i;
+            }
+        }
+        return -1;
+    }
+
+
+    /**
+     * Set a special attribute.
+     *
+     * @return true if the attribute was a special attribute, false otherwise
+     */
+    protected boolean setSpecial(String name, Object value) {
+        for (int i = 0; i < specials.length; i++) {
+            if (specials[i].equals(name)) {
+                specialAttributes[i] = value;
+                return true;
+            }
+        }
+        return false;
+    }
+
+
+    /**
+     * Remove a special attribute.
+     *
+     * @return true if the attribute was a special attribute, false otherwise
+     */
+    protected boolean removeSpecial(String name) {
+        for (int i = 0; i < specials.length; i++) {
+            if (specials[i].equals(name)) {
+                specialAttributes[i] = null;
+                return true;
+            }
+        }
+        return false;
+    }
+
+
+    /**
+     * Merge the two sets of parameter values into a single String array.
+     *
+     * @param values1 First set of values
+     * @param values2 Second set of values
+     */
+    private String[] mergeValues(String[] values1, String[] values2) {
+
+        List<Object> results = new ArrayList<>();
+
+        if (values1 == null) {
+            // Skip - nothing to merge
+        } else {
+            results.addAll(Arrays.asList(values1));
+        }
+
+        if (values2 == null) {
+            // Skip - nothing to merge
+        } else {
+            results.addAll(Arrays.asList(values2));
+        }
+
+        String values[] = new String[results.size()];
+        return results.toArray(values);
+    }
+
+
+    // ------------------------------------------------------ Private Methods
+
+
+    /**
+     * Merge the parameters from the saved query parameter string (if any), and
+     * the parameters already present on this request (if any), such that the
+     * parameter values from the query string show up first if there are
+     * duplicate parameter names.
+     */
+    private void mergeParameters() {
+
+        if ((queryParamString == null) || (queryParamString.length() < 1)) {
+            return;
+        }
+
+        // Parse the query string from the dispatch target
+        Parameters paramParser = new Parameters();
+        MessageBytes queryMB = MessageBytes.newInstance();
+        queryMB.setString(queryParamString);
+
+        // TODO
+        // - Should only use body encoding if useBodyEncodingForURI is true
+        // - Otherwise, should use URIEncoding
+        // - The problem is that the connector is not available...
+        // - To add to the fun, the URI default changed in Servlet 4.0 to UTF-8
+
+        String encoding = getCharacterEncoding();
+        Charset charset = null;
+        if (encoding != null) {
+            try {
+                charset = B2CConverter.getCharset(encoding);
+                queryMB.setCharset(charset);
+            } catch (UnsupportedEncodingException e) {
+                // Fall-back to default (ISO-8859-1)
+                charset = StandardCharsets.ISO_8859_1;
+            }
+        }
+
+        paramParser.setQuery(queryMB);
+        paramParser.setQueryStringCharset(charset);
+        paramParser.handleQueryParameters();
+
+        // Insert the additional parameters from the dispatch target
+        Enumeration<String> dispParamNames = paramParser.getParameterNames();
+        while (dispParamNames.hasMoreElements()) {
+            String dispParamName = dispParamNames.nextElement();
+            String[] dispParamValues = paramParser.getParameterValues(dispParamName);
+            String[] originalValues = parameters.get(dispParamName);
+            if (originalValues == null) {
+                parameters.put(dispParamName, dispParamValues);
+                continue;
+            }
+            parameters.put(dispParamName, mergeValues(dispParamValues, originalValues));
+        }
+    }
+
+
+    // ----------------------------------- AttributeNamesEnumerator Inner Class
+
+
+    /**
+     * Utility class used to expose the special attributes as being available
+     * as request attributes.
+     */
+    protected class AttributeNamesEnumerator implements Enumeration<String> {
+
+        protected int pos = -1;
+        protected final int last;
+        protected final Enumeration<String> parentEnumeration;
+        protected String next = null;
+
+        public AttributeNamesEnumerator() {
+            int last = -1;
+            parentEnumeration = getRequest().getAttributeNames();
+            for (int i = specialAttributes.length - 1; i >= 0; i--) {
+                if (getAttribute(specials[i]) != null) {
+                    last = i;
+                    break;
+                }
+            }
+            this.last = last;
+        }
+
+        @Override
+        public boolean hasMoreElements() {
+            return ((pos != last) || (next != null)
+                    || ((next = findNext()) != null));
+        }
+
+        @Override
+        public String nextElement() {
+            if (pos != last) {
+                for (int i = pos + 1; i <= last; i++) {
+                    if (getAttribute(specials[i]) != null) {
+                        pos = i;
+                        return specials[i];
+                    }
+                }
+            }
+            String result = next;
+            if (next != null) {
+                next = findNext();
+            } else {
+                throw new NoSuchElementException();
+            }
+            return result;
+        }
+
+        protected String findNext() {
+            String result = null;
+            while ((result == null) && (parentEnumeration.hasMoreElements())) {
+                String current = parentEnumeration.nextElement();
+                if (!isSpecial(current)) {
+                    result = current;
+                }
+            }
+            return result;
+        }
+
+    }
+
+
+}
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/LocalStrings.properties b/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/LocalStrings.properties
new file mode 100644
index 0000000000..bc9778aa87
--- /dev/null
+++ b/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/LocalStrings.properties
@@ -0,0 +1,312 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+applicationContext.addFilter.ise=Filters cannot be added to context [{0}] as the context has been initialised
+applicationContext.addJspFile.iae=The JSP file [{0}] is not valid
+applicationContext.addListener.iae.cnfe=Unable to create an instance of type [{0}]
+applicationContext.addListener.iae.init=Unable to add an instance of type [{0}] as a listener
+applicationContext.addListener.iae.sclNotAllowed=Once the first ServletContextListener has been called, no more ServletContextListeners may be added.
+applicationContext.addListener.iae.wrongType=The type specified [{0}] is not one of the expected listener types
+applicationContext.addListener.ise=Listeners cannot be added to context [{0}] as the context has been initialised
+applicationContext.addRole.ise=Roles cannot be added to context [{0}] as the context has been initialised
+applicationContext.addServlet.ise=Servlets cannot be added to context [{0}] as the context has been initialised
+applicationContext.attributeEvent=Exception thrown by attributes event listener
+applicationContext.illegalDispatchPath=An application attempted to obtain a request dispatcher with an illegal path [{0}] that was rejected because it contained an encoded directory traversal attempt
+applicationContext.invalidFilterName=Unable to add filter definition due to invalid filter name [{0}].
+applicationContext.invalidServletName=Unable to add servlet definition due to invalid servlet name [{0}].
+applicationContext.lookup.error=Failed to locate resource [{0}] in context [{1}]
+applicationContext.mapping.error=Error during mapping
+applicationContext.requestDispatcher.iae=Path [{0}] does not start with a "/" character
+applicationContext.resourcePaths.iae=Path [{0}] does not start with a "/" character
+applicationContext.role.iae=An individual role to declare for context [{0}] may not be null nor the empty string
+applicationContext.roles.iae=Array of roles to declare for context [{0}] cannot be null
+applicationContext.setAttribute.namenull=Name cannot be null
+applicationContext.setInitParam.ise=Initialization parameters cannot be set after the context has been initialized
+applicationContext.setRequestEncoding.ise=The request encoding cannot be set for context [{0}] as the context has been initialised
+applicationContext.setResponseEncoding.ise=The response encoding cannot be set for context [{0}] as the context has been initialised
+applicationContext.setSessionTimeout.ise=The session timeout cannot be set for context [{0}] as the context has been initialised
+applicationContext.setSessionTracking.iae.invalid=The session tracking mode [{0}] requested for context [{1}] is not supported by that context
+applicationContext.setSessionTracking.iae.ssl=The session tracking modes requested for context [{0}] included SSL and at least one other mode. SSL may not be configured with other modes.
+applicationContext.setSessionTracking.ise=The session tracking modes for context [{0}] cannot be set whilst the context is running
+
+applicationDispatcher.allocateException=Allocate exception for servlet [{0}]
+applicationDispatcher.deallocateException=Deallocate exception for servlet [{0}]
+applicationDispatcher.forward.ise=Cannot forward after response has been committed
+applicationDispatcher.isUnavailable=Servlet [{0}] is currently unavailable
+applicationDispatcher.serviceException=Servlet.service() for servlet [{0}] threw exception
+applicationDispatcher.specViolation.request=Original ServletRequest or wrapped original ServletRequest not passed to RequestDispatcher in violation of SRV.8.2 and SRV.14.2.5.1
+applicationDispatcher.specViolation.response=Original ServletResponse or wrapped original ServletResponse not passed to RequestDispatcher in violation of SRV.8.2 and SRV.14.2.5.1
+
+applicationFilterConfig.jmxRegisterFail=JMX registration failed for filter of type [{0}] and name [{1}]
+applicationFilterConfig.jmxUnregister=JMX de-registration complete for filter of type [{0}] and name [{1}]
+applicationFilterConfig.jmxUnregisterFail=JMX de-registration failed for filter of type [{0}] and name [{1}]
+applicationFilterConfig.preDestroy=Failed the call to preDestroy for the filter named [{0}] of type [{1}]
+applicationFilterConfig.release=Failed to destroy the filter named [{0}] of type [{1}]
+
+applicationFilterRegistration.nullInitParam=Unable to set initialisation parameter for filter due to null name and/or value. Name [{0}], Value [{1}]
+applicationFilterRegistration.nullInitParams=Unable to set initialisation parameters for filter due to null name and/or value. Name [{0}], Value [{1}]
+
+applicationHttpRequest.fragmentInDispatchPath=The fragment in dispatch path [{0}] has been removed
+
+applicationPushBuilder.methodInvalid=The HTTP method for a push request must be both cacheable and safe but [{0}] is not
+applicationPushBuilder.methodNotToken=HTTP methods must be tokens but [{0}] contains a non-token character
+
+applicationServletRegistration.setServletSecurity.iae=Null constraint specified for servlet [{0}] deployed to context with name [{1}]
+applicationServletRegistration.setServletSecurity.ise=Security constraints can''t be added to servlet [{0}] deployed to context with name [{1}] as the context has already been initialised
+
+applicationSessionCookieConfig.ise=Property [{0}] cannot be added to SessionCookieConfig for context [{1}] as the context has been initialised
+
+aprListener.aprDestroy=Failed shutdown of the Apache Tomcat Native library
+aprListener.aprInit=The Apache Tomcat Native library which allows using OpenSSL was not found on the java.library.path: [{0}]
+aprListener.aprInitDebug=The Apache Tomcat Native library could not be found using names [{0}] on the java.library.path [{1}]. The errors reported were [{2}]
+aprListener.aprInitError=The Apache Tomcat Native library failed to load. The error reported was [{0}]
+aprListener.currentFIPSMode=Current FIPS mode: [{0}]
+aprListener.enterAlreadyInFIPSMode=AprLifecycleListener is configured to force entering FIPS mode, but library is already in FIPS mode [{0}]
+aprListener.flags=APR capabilities: IPv6 [{0}], sendfile [{1}], accept filters [{2}], random [{3}], UDS [{4}].
+aprListener.FIPSProviderNotDefault=The FIPS provider must be configured as the default provider when the AprLifecycleListener is configured with FIPS mode [{0}]
+aprListener.initializeFIPSFailed=Failed to enter FIPS mode
+aprListener.initializeFIPSSuccess=Successfully entered FIPS mode
+aprListener.initializedOpenSSL=OpenSSL successfully initialized [{0}]
+aprListener.initializingFIPS=Initializing FIPS mode...
+aprListener.requireNotInFIPSMode=AprLifecycleListener is configured to require the library to already be in FIPS mode, but it was not in FIPS mode
+aprListener.skipFIPSInitialization=Already in FIPS mode; skipping FIPS initialization.
+aprListener.sslInit=Failed to initialize the SSLEngine.
+aprListener.sslRequired=[{0}] is not a valid value for SSLEngine when using version [{1}] of the Tomcat Native library since SSL is required for version 2.x onwards.
+aprListener.tcnInvalid=An incompatible version [{0}] of the Apache Tomcat Native library is installed, while Tomcat requires version [{1}]
+aprListener.tcnValid=Loaded Apache Tomcat Native library [{0}] using APR version [{1}].
+aprListener.tcnVersion=An older version [{0}] of the Apache Tomcat Native library is installed, while Tomcat recommends a minimum version of [{1}]
+aprListener.tooLateForFIPSMode=Cannot setFIPSMode: SSL has already been initialized
+aprListener.tooLateForSSLEngine=Cannot setSSLEngine: SSL has already been initialized
+aprListener.tooLateForSSLRandomSeed=Cannot setSSLRandomSeed: SSL has already been initialized
+aprListener.usingFIPSProvider=Using OpenSSL with the FIPS provider as the default provider
+aprListener.wrongFIPSMode=Unexpected value of FIPSMode option of AprLifecycleListener: [{0}]
+
+asyncContextImpl.asyncDispatchError=Error during asynchronous dispatch
+asyncContextImpl.asyncRunnableError=Error during processing of asynchronous Runnable via AsyncContext.start()
+asyncContextImpl.dispatchingStarted=Asynchronous dispatch operation has already been called. Additional asynchronous dispatch operation within the same asynchronous cycle is not allowed.
+asyncContextImpl.fireOnComplete=Firing onComplete() event for any AsyncListeners
+asyncContextImpl.fireOnError=Firing onError() event for any AsyncListeners
+asyncContextImpl.fireOnStartAsync=Firing onStartAsync() event for any AsyncListeners
+asyncContextImpl.fireOnTimeout=Firing onTimeout() event for any AsyncListeners
+asyncContextImpl.noAsyncDispatcher=The dispatcher returned from the ServletContext does not support asynchronous dispatching
+asyncContextImpl.onCompleteError=onComplete() call failed for listener of type [{0}]
+asyncContextImpl.onErrorError=onError() call failed for listener of type [{0}]
+asyncContextImpl.onStartAsyncError=onStartAsync() call failed for listener of type [{0}]
+asyncContextImpl.onTimeoutError=onTimeout() call failed for listener of type [{0}]
+asyncContextImpl.request.ise=It is illegal to call getRequest() after complete() or any of the dispatch() methods has been called
+asyncContextImpl.requestEnded=The request associated with the AsyncContext has already completed processing.
+asyncContextImpl.response.ise=It is illegal to call getResponse() after complete() or any of the dispatch() methods has been called
+
+containerBase.backgroundProcess.cluster=Exception processing cluster [{0}] background process
+containerBase.backgroundProcess.error=Exception processing background thread
+containerBase.backgroundProcess.realm=Exception processing realm [{0}] background process
+containerBase.backgroundProcess.valve=Exception processing valve [{0}] background process
+containerBase.child.destroy=Error destroying child
+containerBase.child.notUnique=Child name [{0}] is not unique
+containerBase.child.start=Error starting child
+containerBase.child.stop=Error stopping child
+containerBase.cluster.start=Error starting new cluster
+containerBase.cluster.stop=Error stopping old cluster
+containerBase.nullName=Container name cannot be null
+containerBase.realm.start=Error starting new realm
+containerBase.realm.stop=Error stopping old realm
+containerBase.threadedStartFailed=A child container failed during start
+containerBase.threadedStopFailed=A child container failed during stop
+
+defaultInstanceManager.invalidAnnotation=Invalid [{0}] annotation
+defaultInstanceManager.invalidInjection=Invalid method resource injection annotation
+defaultInstanceManager.postConstructNotFound=Post construct method [{0}] for class [{1}] is declared in deployment descriptor but cannot be found
+defaultInstanceManager.preDestroyNotFound=Pre destroy method [{0}] for class [{1}] is declared in deployment descriptor but cannot be found
+defaultInstanceManager.restrictedClass=Access to class [{0}] is forbidden. It is a restricted class. A web application must be configured as privileged to be able to load it
+defaultInstanceManager.restrictedContainerServlet=Access to class [{0}] is forbidden. It is a restricted class (implements ContainerServlet interface). A web application must be configured as privileged to be able to load it
+defaultInstanceManager.restrictedFiltersResource=Restricted filters property file not found [{0}]
+defaultInstanceManager.restrictedListenersResource=Restricted listeners property file not found [{0}]
+defaultInstanceManager.restrictedServletsResource=Restricted servlets property file not found [{0}]
+defaultInstanceManager.restrictedWrongValue=Wrong value in restricted classes property file [{0}] for class name [{1}]. Expected value: [restricted], actual value: [{2}]
+
+filterChain.filter=Filter execution threw an exception
+filterChain.servlet=Servlet execution threw an exception
+
+jniLifecycleListener.bothPathAndName=Either libraryName or libraryPath may be set, not both
+jniLifecycleListener.load.name=Loaded native library [{0}]
+jniLifecycleListener.load.path=Loaded native library from [{0}]
+jniLifecycleListener.missingPathOrName=One of libraryName or libraryPath must be set
+
+jreLeakListener.classToInitializeFail=Failed to load class [{0}] during Tomcat start to prevent possible memory leaks.
+jreLeakListener.gcDaemonFail=Failed to trigger creation of the GC Daemon thread during Tomcat start to prevent possible memory leaks. This is expected on non-Sun JVMs.
+jreLeakListener.jarUrlConnCacheFail=Failed to disable Jar URL connection caching by default
+jreLeakListener.ldapPoolManagerFail=Failed to trigger creation of the com.sun.jndi.ldap.LdapPoolManager class during Tomcat start to prevent possible memory leaks. This is expected on non-Sun JVMs.
+jreLeakListener.xmlParseFail=Error whilst attempting to prevent memory leaks during XML parsing
+
+listener.notServer=This listener must only be nested within Server elements, but is in [{0}].
+
+naming.addEnvEntry=Adding environment entry [{0}]
+naming.addResourceEnvRef=Adding resource env ref [{0}]
+naming.bindFailed=Failed to bind object: [{0}]
+naming.invalidEnvEntryType=Environment entry [{0}] has an invalid type
+naming.invalidEnvEntryValue=Environment entry [{0}] has an invalid value
+naming.jmxRegistrationFailed=Failed to register in JMX: [{0}]
+naming.namingContextCreationFailed=Creation of the naming context failed: [{0}]
+naming.unbindFailed=Failed to unbind object: [{0}]
+naming.wsdlFailed=Failed to find wsdl file: [{0}]
+
+noPluggabilityServletContext.notAllowed=Section 4.4 of the Servlet 3.0 specification does not permit this method to be called from a ServletContextListener that was not defined in web.xml, a web-fragment.xml file nor annotated with @WebListener
+
+pushBuilder.noPath=It is illegal to call push() before setting a path
+
+standardContext.applicationListener=Error configuring application listener of class [{0}]
+standardContext.applicationSkipped=Skipped installing application listeners due to previous error(s)
+standardContext.backgroundProcess.instanceManager=Exception processing instance manager [{0}] background process
+standardContext.backgroundProcess.loader=Exception processing loader [{0}] background process
+standardContext.backgroundProcess.manager=Exception processing manager [{0}] background process
+standardContext.backgroundProcess.resources=Exception processing resources [{0}] background process
+standardContext.cluster.managerError=Error creating new cluster session manager
+standardContext.cluster.noManager=No manager found. Checking if cluster manager should be used. Cluster configured: [{0}], Application distributable: [{1}]
+standardContext.configurationFail=One or more components marked the context as not correctly configured
+standardContext.cookieProcessor.null=It is not permitted to set the CookieProcessor for a Context to null
+standardContext.createWrapper.containerListenerError=Error creating container listener for the wrapper
+standardContext.createWrapper.error=Error creating new wrapper
+standardContext.createWrapper.listenerError=Error creating lifecycle listener for the wrapper
+standardContext.duplicateListener=The listener [{0}] is already configured for this context. The duplicate definition has been ignored.
+standardContext.errorPage.error=Error page location [{0}] must start with a ''/''
+standardContext.errorPage.required=ErrorPage cannot be null
+standardContext.errorPage.warning=WARNING: Error page location [{0}] must start with a ''/'' in Servlet 2.4
+standardContext.extensionValidationError=Error while attempting to validate required application extensions
+standardContext.filterFail=One or more Filters failed to start. Full details will be found in the appropriate container log file
+standardContext.filterMap.either=Filter mapping must specify either a <url-pattern> or a <servlet-name>
+standardContext.filterMap.name=Filter mapping specifies an unknown filter name [{0}]
+standardContext.filterMap.pattern=Invalid <url-pattern> [{0}] in filter mapping
+standardContext.filterStart=Exception starting filter [{0}]
+standardContext.invalidWrapperClass=[{0}] is not a subclass of StandardWrapper
+standardContext.isUnavailable=This application is not currently available
+standardContext.listenerFail=One or more listeners failed to start. Full details will be found in the appropriate container log file
+standardContext.listenerStart=Exception sending context initialized event to listener instance of class [{0}]
+standardContext.listenerStop=Exception sending context destroyed event to listener instance of class [{0}]
+standardContext.loadOnStartup.loadException=Servlet [{1}] in web application [{0}] threw load() exception
+standardContext.loginConfig.errorPage=Form error page [{0}] must start with a ''/''
+standardContext.loginConfig.errorWarning=WARNING: Form error page [{0}] must start with a ''/'' in Servlet 2.4
+standardContext.loginConfig.loginPage=Form login page [{0}] must start with a ''/''
+standardContext.loginConfig.loginWarning=WARNING: Form login page [{0}] must start with a ''/'' in Servlet 2.4
+standardContext.loginConfig.required=LoginConfig cannot be null
+standardContext.manager=Configured a manager of class [{0}]
+standardContext.managerFail=The session manager failed to start
+standardContext.namingResource.destroy.fail=Failed to destroy old naming resources
+standardContext.namingResource.init.fail=Failed to init new naming resources
+standardContext.notStarted=Context with name [{0}] has not yet been started
+standardContext.notWrapper=Child of a Context must be a Wrapper
+standardContext.parameter.duplicate=Duplicate context initialization parameter [{0}]
+standardContext.parameter.required=Both parameter name and parameter value are required
+standardContext.pathInvalid=A context path must either be an empty string or start with a ''/'' and do not end with a ''/''. The path [{0}] does not meet these criteria and has been changed to [{1}]
+standardContext.postconstruct.duplicate=Duplicate post construct method definition for class [{0}]
+standardContext.postconstruct.required=Both fully qualified class name and method name are required
+standardContext.predestroy.duplicate=Duplicate @PreDestroy method definition for class [{0}]
+standardContext.predestroy.required=Both fully qualified class name and method name are required
+standardContext.reloadingCompleted=Reloading Context with name [{0}] is completed
+standardContext.reloadingStarted=Reloading Context with name [{0}] has started
+standardContext.requestListener.requestInit=Exception sending request initialized lifecycle event to listener instance of class [{0}]
+standardContext.resourcesInit=Error initializing static Resources
+standardContext.resourcesStart=Error starting static Resources
+standardContext.resourcesStop=Error stopping static Resources
+standardContext.sciFail=Error during ServletContainerInitializer processing
+standardContext.securityConstraint.mixHttpMethod=It is not permitted to mix <http-method> and <http-method-omission> in the same web resource collection
+standardContext.securityConstraint.pattern=Invalid <url-pattern> [{0}] in security constraint
+standardContext.servletFail=One or more Servlets failed to load on startup. Full details will be found in the appropriate container log file
+standardContext.servletMap.name=Servlet mapping specifies an unknown servlet name [{0}]
+standardContext.servletMap.pattern=Invalid <url-pattern> [{0}] in servlet mapping
+standardContext.setLoader.start=Error starting new loader
+standardContext.setLoader.stop=Error stopping old loader
+standardContext.setManager.start=Error starting new manager
+standardContext.setManager.stop=Error stopping old manager
+standardContext.startFailed=Context [{0}] startup failed due to previous errors
+standardContext.startingContext=Exception starting Context with name [{0}]
+standardContext.stop.asyncWaitInterrupted=Interrupt received while waiting unloadDelay milliseconds for in-flight asynchronous requests to complete. Context stop will continue without further delay.
+standardContext.stoppingContext=Exception stopping Context with name [{0}]
+standardContext.suspiciousUrl=Suspicious URL pattern: [{0}] in context [{1}], see sections 12.1 and 12.2 of the Servlet specification
+standardContext.threadBindingListenerError=An error occurred in the thread binding listener configured for Context [{0}]
+standardContext.urlPattern.patternWarning=WARNING: URL pattern [{0}] must start with a ''/'' in Servlet 2.4
+standardContext.workCreateException=Failed to determine absolute work directory from directory [{0}] and CATALINA_HOME [{1}] for context [{2}]
+standardContext.workCreateFail=Failed to create work directory [{0}] for context [{1}]
+standardContext.workPath=Exception obtaining work path for context [{0}]
+
+standardContextValve.acknowledgeException=Failed to acknowledge request with a 100 (Continue) response
+
+standardEngine.jvmRouteFail=Failed to set Engine's jvmRoute attribute from system property
+standardEngine.notHost=Child of an Engine must be a Host
+standardEngine.notParent=Engine cannot have a parent Container
+standardEngine.start=Starting Servlet engine: [{0}]
+
+standardHost.clientAbort=Remote Client Aborted Request, IOException: [{0}]
+standardHost.invalidErrorReportValveClass=Couldn''t load specified error report valve class: [{0}]
+standardHost.noContext=No Context configured to process this request
+standardHost.notContext=Child of a Host must be a Context
+standardHost.nullName=Host name is required
+standardHost.problematicAppBase=Using an empty string for appBase on host [{0}] will set it to CATALINA_BASE, which is a bad idea
+standardHost.problematicLegacyAppBase=Using an empty string for legacyAppBase on host [{0}] will set it to CATALINA_BASE, which is a bad idea
+
+standardHostValue.customStatusFailed=Custom error page [{0}] could not be dispatched correctly
+
+standardPipeline.basic.start=Error starting new basic Valve
+standardPipeline.basic.stop=Error stopping old basic Valve
+standardPipeline.valve.destroy=Error destroying Valve
+standardPipeline.valve.start=Error starting Valve
+standardPipeline.valve.stop=Error stopping Valve
+
+standardServer.accept.error=An IO exception occurred trying to accept on the socket listening for the shutdown command
+standardServer.accept.readError=An IO exception occurred trying to read the shutdown command
+standardServer.accept.security=A security error occurred trying to accept on the socket listening for the shutdown command
+standardServer.accept.timeout=The socket listening for the shutdown command experienced an unexpected timeout [{0}] milliseconds after the call to accept(). Is this an instance of bug 56684?
+standardServer.awaitSocket.fail=Failed to create server shutdown socket on address [{0}] and port [{1}] (base port [{2}] and offset [{3}])
+standardServer.invalidShutdownCommand=Invalid shutdown command [{0}] received
+standardServer.periodicEventError=Error sending periodic event
+standardServer.portOffset.invalid=The value [{0}] for portOffset is not valid as portOffset may not be negative
+standardServer.shutdownViaPort=A valid shutdown command was received via the shutdown port. Stopping the Server instance.
+standardServer.storeConfig.contextError=Error storing context [{0}] configuration
+standardServer.storeConfig.error=Error storing server configuration
+standardServer.storeConfig.notAvailable=No StoreConfig implementation was registered as an MBean named [{0}] so no configuration could be saved. A suitable MBean is normally registered via the StoreConfigLifecycleListener.
+
+standardService.engine.startFailed=Failed to start associated Engine
+standardService.engine.stopFailed=Failed to stop associated Engine
+standardService.executor.start=Error starting new executor
+standardService.executor.stop=Error stopping old executor
+standardService.mapperListener.startFailed=Failed to start associated MapperListener
+standardService.mapperListener.stopFailed=Failed to stop associated MapperListener
+standardService.start.name=Starting service [{0}]
+standardService.stop.name=Stopping service [{0}]
+
+standardThreadExecutor.notStarted=The executor has not been started
+
+standardWrapper.allocate=Error allocating a servlet instance
+standardWrapper.allocateException=Allocate exception for servlet [{0}]
+standardWrapper.deallocateException=Deallocate exception for servlet [{0}]
+standardWrapper.destroyException=Servlet.destroy() for servlet [{0}] threw exception
+standardWrapper.destroyInstance=InstanceManager.destroy() for servlet [{0}] threw exception
+standardWrapper.initException=Servlet.init() for servlet [{0}] threw exception
+standardWrapper.instantiate=Error instantiating servlet class [{0}]
+standardWrapper.isUnavailable=Servlet [{0}] is currently unavailable
+standardWrapper.jspMonitorError=Error registering JSP monitor Mbean [{0}]
+standardWrapper.notChild=Wrapper container may not have child containers
+standardWrapper.notClass=No servlet class has been specified for servlet [{0}]
+standardWrapper.notContext=Parent container of a Wrapper must be a Context
+standardWrapper.notFound=Servlet [{0}] is not available
+standardWrapper.notServlet=Class [{0}] is not a Servlet
+standardWrapper.serviceException=Servlet.service() for servlet [{0}] in context with path [{1}] threw exception
+standardWrapper.serviceExceptionRoot=Servlet.service() for servlet [{0}] in context with path [{1}] threw exception [{2}] with root cause
+standardWrapper.unavailable=Marking servlet [{0}] as unavailable
+standardWrapper.unloadException=Servlet [{0}] threw unload() exception
+standardWrapper.unloading=Cannot allocate servlet [{0}] because it is being unloaded
+standardWrapper.waiting=Waiting for [{0}] instance(s) to be deallocated for Servlet [{1}]
+
+threadLocalLeakPreventionListener.containerEvent.error=Exception processing container event [{0}]
+threadLocalLeakPreventionListener.lifecycleEvent.error=Exception processing lifecycle event [{0}]
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/B2CConverter.java b/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/B2CConverter.java
new file mode 100644
index 0000000000..532c209ec9
--- /dev/null
+++ b/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/B2CConverter.java
@@ -0,0 +1,262 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.tomcat.util.buf;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.CoderResult;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.util.Locale;
+
+import org.apache.tomcat.util.res.StringManager;
+
+/**
+ * NIO based character decoder.
+ */
+public class B2CConverter {
+
+    private static final StringManager sm = StringManager.getManager(B2CConverter.class);
+
+    private static final CharsetCache charsetCache = new CharsetCache();
+
+
+    // Protected so unit tests can use it
+    protected static final int LEFTOVER_SIZE = 9;
+
+    /**
+     * Obtain the Charset for the given encoding
+     *
+     * @param enc The name of the encoding for the required charset
+     *
+     * @return The Charset corresponding to the requested encoding
+     *
+     * @throws UnsupportedEncodingException If the requested Charset is not
+     *                                      available
+     */
+    public static Charset getCharset(String enc) throws UnsupportedEncodingException {
+
+        // Encoding names should all be ASCII
+        String lowerCaseEnc = enc.toLowerCase(Locale.ENGLISH);
+
+        Charset charset = charsetCache.getCharset(lowerCaseEnc);
+
+        if (charset == null) {
+            // Pre-population of the cache means this must be invalid
+            throw new UnsupportedEncodingException(
+                    sm.getString("b2cConverter.unknownEncoding", lowerCaseEnc));
+        }
+        return charset;
+    }
+
+
+    private final CharsetDecoder decoder;
+    private ByteBuffer bb = null;
+    private CharBuffer cb = null;
+
+    /**
+     * Leftover buffer used for incomplete characters.
+     */
+    private final ByteBuffer leftovers;
+
+    public B2CConverter(Charset charset) {
+        this(charset, false);
+    }
+
+    public B2CConverter(Charset charset, boolean replaceOnError) {
+        byte[] left = new byte[LEFTOVER_SIZE];
+        leftovers = ByteBuffer.wrap(left);
+        CodingErrorAction action;
+        if (replaceOnError) {
+            action = CodingErrorAction.REPLACE;
+        } else {
+            action = CodingErrorAction.REPORT;
+        }
+        // Special case. Use the Apache Harmony based UTF-8 decoder because it
+        // - a) rejects invalid sequences that the JVM decoder does not
+        // - b) fails faster for some invalid sequences
+        if (charset.equals(StandardCharsets.UTF_8)) {
+            decoder = new Utf8Decoder();
+        } else {
+            decoder = charset.newDecoder();
+        }
+        decoder.onMalformedInput(action);
+        decoder.onUnmappableCharacter(action);
+    }
+
+    /**
+     * Reset the decoder state.
+     */
+    public void recycle() {
+        decoder.reset();
+        leftovers.position(0);
+    }
+
+    /**
+     * Convert the given bytes to characters.
+     *
+     * @param bc byte input
+     * @param cc char output
+     * @param endOfInput    Is this all of the available data
+     *
+     * @throws IOException If the conversion can not be completed
+     */
+    public void convert(ByteChunk bc, CharChunk cc, boolean endOfInput)
+            throws IOException {
+        if ((bb == null) || (bb.array() != bc.getBuffer())) {
+            // Create a new byte buffer if anything changed
+            bb = ByteBuffer.wrap(bc.getBuffer(), bc.getStart(), bc.getLength());
+        } else {
+            // Initialize the byte buffer
+            bb.limit(bc.getEnd());
+            bb.position(bc.getStart());
+        }
+        if ((cb == null) || (cb.array() != cc.getBuffer())) {
+            // Create a new char buffer if anything changed
+            cb = CharBuffer.wrap(cc.getBuffer(), cc.getEnd(),
+                    cc.getBuffer().length - cc.getEnd());
+        } else {
+            // Initialize the char buffer
+            cb.limit(cc.getBuffer().length);
+            cb.position(cc.getEnd());
+        }
+        CoderResult result = null;
+        // Parse leftover if any are present
+        if (leftovers.position() > 0) {
+            int pos = cb.position();
+            // Loop until one char is decoded or there is a decoder error
+            do {
+                leftovers.put(bc.subtractB());
+                leftovers.flip();
+                result = decoder.decode(leftovers, cb, endOfInput);
+                leftovers.position(leftovers.limit());
+                leftovers.limit(leftovers.array().length);
+            } while (result.isUnderflow() && (cb.position() == pos));
+            if (result.isError() || result.isMalformed()) {
+                result.throwException();
+            }
+            bb.position(bc.getStart());
+            leftovers.position(0);
+        }
+        // Do the decoding and get the results into the byte chunk and the char
+        // chunk
+        result = decoder.decode(bb, cb, endOfInput);
+        if (result.isError() || result.isMalformed()) {
+            result.throwException();
+        } else if (result.isOverflow()) {
+            // Propagate current positions to the byte chunk and char chunk, if
+            // this continues the char buffer will get resized
+            bc.setOffset(bb.position());
+            cc.setEnd(cb.position());
+        } else if (result.isUnderflow()) {
+            // Propagate current positions to the byte chunk and char chunk
+            bc.setOffset(bb.position());
+            cc.setEnd(cb.position());
+            // Put leftovers in the leftovers byte buffer
+            if (bc.getLength() > 0) {
+                leftovers.limit(leftovers.array().length);
+                leftovers.position(bc.getLength());
+                bc.subtract(leftovers.array(), 0, bc.getLength());
+            }
+        }
+    }
+
+    /**
+     * Convert the given bytes to characters.
+     *
+     * @param bc byte input
+     * @param cc char output
+     * @param ic byte input channel
+     * @param endOfInput    Is this all of the available data
+     *
+     * @throws IOException If the conversion can not be completed
+     */
+    public void convert(ByteBuffer bc, CharBuffer cc, ByteChunk.ByteInputChannel ic, boolean endOfInput)
+            throws IOException {
+        if ((bb == null) || (bb.array() != bc.array())) {
+            // Create a new byte buffer if anything changed
+            bb = ByteBuffer.wrap(bc.array(), bc.arrayOffset() + bc.position(), bc.remaining());
+        } else {
+            // Initialize the byte buffer
+            bb.limit(bc.limit());
+            bb.position(bc.position());
+        }
+        if ((cb == null) || (cb.array() != cc.array())) {
+            // Create a new char buffer if anything changed
+            cb = CharBuffer.wrap(cc.array(), cc.limit(), cc.capacity() - cc.limit());
+        } else {
+            // Initialize the char buffer
+            cb.limit(cc.capacity());
+            cb.position(cc.limit());
+        }
+        CoderResult result = null;
+        // Parse leftover if any are present
+        if (leftovers.position() > 0) {
+            int pos = cb.position();
+            // Loop until one char is decoded or there is a decoder error
+            do {
+                byte chr;
+                if (bc.remaining() == 0) {
+                    int n = ic.realReadBytes();
+                    chr = n < 0 ? -1 : bc.get();
+                } else {
+                    chr = bc.get();
+                }
+                leftovers.put(chr);
+                leftovers.flip();
+                result = decoder.decode(leftovers, cb, endOfInput);
+                leftovers.position(leftovers.limit());
+                leftovers.limit(leftovers.array().length);
+            } while (result.isUnderflow() && (cb.position() == pos));
+            if (result.isError() || result.isMalformed()) {
+                result.throwException();
+            }
+            bb.position(bc.position());
+            leftovers.position(0);
+        }
+        // Do the decoding and get the results into the byte chunk and the char
+        // chunk
+        result = decoder.decode(bb, cb, endOfInput);
+        if (result.isError() || result.isMalformed()) {
+            result.throwException();
+        } else if (result.isOverflow()) {
+            // Propagate current positions to the byte chunk and char chunk, if
+            // this continues the char buffer will get resized
+            bc.position(bb.position());
+            cc.limit(cb.position());
+        } else if (result.isUnderflow()) {
+            // Propagate current positions to the byte chunk and char chunk
+            bc.position(bb.position());
+            cc.limit(cb.position());
+            // Put leftovers in the leftovers byte buffer
+            if (bc.remaining() > 0) {
+                leftovers.limit(leftovers.array().length);
+                leftovers.position(bc.remaining());
+                bc.get(leftovers.array(), 0, bc.remaining());
+            }
+        }
+    }
+
+
+    public Charset getCharset() {
+        return decoder.charset();
+    }
+}
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/C2BConverter.java b/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/C2BConverter.java
new file mode 100644
index 0000000000..4b27f6c980
--- /dev/null
+++ b/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/C2BConverter.java
@@ -0,0 +1,192 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.tomcat.util.buf;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetEncoder;
+import java.nio.charset.CoderResult;
+import java.nio.charset.CodingErrorAction;
+
+/**
+ * NIO based character encoder.
+ */
+public final class C2BConverter {
+
+    private final CharsetEncoder encoder;
+    private ByteBuffer bb = null;
+    private CharBuffer cb = null;
+
+    /**
+     * Leftover buffer used for multi-characters characters.
+     */
+    private final CharBuffer leftovers;
+
+    public C2BConverter(Charset charset) {
+        encoder = charset.newEncoder();
+        encoder.onUnmappableCharacter(CodingErrorAction.REPLACE)
+                .onMalformedInput(CodingErrorAction.REPLACE);
+        char[] left = new char[4];
+        leftovers = CharBuffer.wrap(left);
+    }
+
+    /**
+     * Reset the encoder state.
+     */
+    public void recycle() {
+        encoder.reset();
+        leftovers.position(0);
+    }
+
+    public boolean isUndeflow() {
+        return (leftovers.position() > 0);
+    }
+
+    /**
+     * Convert the given characters to bytes.
+     *
+     * @param cc char input
+     * @param bc byte output
+     * @throws IOException An encoding error occurred
+     */
+    public void convert(CharChunk cc, ByteChunk bc) throws IOException {
+        if ((bb == null) || (bb.array() != bc.getBuffer())) {
+            // Create a new byte buffer if anything changed
+            bb = ByteBuffer.wrap(bc.getBuffer(), bc.getEnd(), bc.getBuffer().length - bc.getEnd());
+        } else {
+            // Initialize the byte buffer
+            bb.limit(bc.getBuffer().length);
+            bb.position(bc.getEnd());
+        }
+        if ((cb == null) || (cb.array() != cc.getBuffer())) {
+            // Create a new char buffer if anything changed
+            cb = CharBuffer.wrap(cc.getBuffer(), cc.getStart(), cc.getLength());
+        } else {
+            // Initialize the char buffer
+            cb.limit(cc.getEnd());
+            cb.position(cc.getStart());
+        }
+        CoderResult result = null;
+        // Parse leftover if any are present
+        if (leftovers.position() > 0) {
+            int pos = bb.position();
+            // Loop until one char is encoded or there is a encoder error
+            do {
+                leftovers.put((char) cc.subtract());
+                leftovers.flip();
+                result = encoder.encode(leftovers, bb, false);
+                leftovers.position(leftovers.limit());
+                leftovers.limit(leftovers.array().length);
+            } while (result.isUnderflow() && (bb.position() == pos));
+            if (result.isError() || result.isMalformed()) {
+                result.throwException();
+            }
+            cb.position(cc.getStart());
+            leftovers.position(0);
+        }
+        // Do the decoding and get the results into the byte chunk and the char
+        // chunk
+        result = encoder.encode(cb, bb, false);
+        if (result.isError() || result.isMalformed()) {
+            result.throwException();
+        } else if (result.isOverflow()) {
+            // Propagate current positions to the byte chunk and char chunk
+            bc.setEnd(bb.position());
+            cc.setOffset(cb.position());
+        } else if (result.isUnderflow()) {
+            // Propagate current positions to the byte chunk and char chunk
+            bc.setEnd(bb.position());
+            cc.setOffset(cb.position());
+            // Put leftovers in the leftovers char buffer
+            if (cc.getLength() > 0) {
+                leftovers.limit(leftovers.array().length);
+                leftovers.position(cc.getLength());
+                cc.subtract(leftovers.array(), 0, cc.getLength());
+            }
+        }
+    }
+
+    /**
+     * Convert the given characters to bytes.
+     *
+     * @param cc char input
+     * @param bc byte output
+     * @throws IOException An encoding error occurred
+     */
+    public void convert(CharBuffer cc, ByteBuffer bc) throws IOException {
+        if ((bb == null) || (bb.array() != bc.array())) {
+            // Create a new byte buffer if anything changed
+            bb = ByteBuffer.wrap(bc.array(), bc.limit(), bc.capacity() - bc.limit());
+        } else {
+            // Initialize the byte buffer
+            bb.limit(bc.capacity());
+            bb.position(bc.limit());
+        }
+        if ((cb == null) || (cb.array() != cc.array())) {
+            // Create a new char buffer if anything changed
+            cb = CharBuffer.wrap(cc.array(), cc.arrayOffset() + cc.position(), cc.remaining());
+        } else {
+            // Initialize the char buffer
+            cb.limit(cc.limit());
+            cb.position(cc.position());
+        }
+        CoderResult result = null;
+        // Parse leftover if any are present
+        if (leftovers.position() > 0) {
+            int pos = bb.position();
+            // Loop until one char is encoded or there is a encoder error
+            do {
+                leftovers.put(cc.get());
+                leftovers.flip();
+                result = encoder.encode(leftovers, bb, false);
+                leftovers.position(leftovers.limit());
+                leftovers.limit(leftovers.array().length);
+            } while (result.isUnderflow() && (bb.position() == pos));
+            if (result.isError() || result.isMalformed()) {
+                result.throwException();
+            }
+            cb.position(cc.position());
+            leftovers.position(0);
+        }
+        // Do the decoding and get the results into the byte chunk and the char
+        // chunk
+        result = encoder.encode(cb, bb, false);
+        if (result.isError() || result.isMalformed()) {
+            result.throwException();
+        } else if (result.isOverflow()) {
+            // Propagate current positions to the byte chunk and char chunk
+            bc.limit(bb.position());
+            cc.position(cb.position());
+        } else if (result.isUnderflow()) {
+            // Propagate current positions to the byte chunk and char chunk
+            bc.limit(bb.position());
+            cc.position(cb.position());
+            // Put leftovers in the leftovers char buffer
+            if (cc.remaining() > 0) {
+                leftovers.limit(leftovers.array().length);
+                leftovers.position(cc.remaining());
+                cc.get(leftovers.array(), 0, cc.remaining());
+            }
+        }
+    }
+
+    public Charset getCharset() {
+        return encoder.charset();
+    }
+}
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/LocalStrings.properties b/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/LocalStrings.properties
new file mode 100644
index 0000000000..cd883e6f57
--- /dev/null
+++ b/tomee/apache-tomee/src/patch/java/org/apache/tomcat/util/buf/LocalStrings.properties
@@ -0,0 +1,33 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+asn1Parser.lengthInvalid=Invalid length [{0}] bytes reported when the input data length is [{1}] bytes
+asn1Parser.tagMismatch=Expected to find value [{0}] but found value [{1}]
+
+b2cConverter.unknownEncoding=The character encoding [{0}] is not supported
+
+byteBufferUtils.cleaner=Cannot use direct ByteBuffer cleaner, memory leaking may occur
+
+chunk.overflow=Buffer overflow and no sink is set, limit [{0}] and buffer length [{1}]
+
+encodedSolidusHandling.invalid=The value [{0}] is not recognised
+
+hexUtils.fromHex.nonHex=The input must consist only of hex digits
+hexUtils.fromHex.oddDigits=The input must consist of an even number of hex digits
+
+uDecoder.eof=End of file (EOF)
+uDecoder.noSlash=The encoded slash character is not allowed
+uDecoder.urlDecode.conversionError=Failed to decode [{0}] using character set [{1}]
+uDecoder.urlDecode.missingDigit=Failed to decode [{0}] because the % character must be followed by two hexadecimal digits


[tomee] 03/06: TOMEE-4256 - Add unpatched classes for backporting changes from https://github.com/apache/tomcat/commit/8ecff306507be8e4fd3adee1ae5de1ea6661a8f4 for CVE-2023-45648

Posted by rz...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rzo1 pushed a commit to branch tomee-9.x
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 314ea5ac416fcdddbe2ecf50f377d2adf86cbb7a
Author: Richard Zowalla <rz...@apache.org>
AuthorDate: Wed Oct 11 09:04:18 2023 +0200

    TOMEE-4256 - Add unpatched classes for backporting changes from https://github.com/apache/tomcat/commit/8ecff306507be8e4fd3adee1ae5de1ea6661a8f4 for CVE-2023-45648
---
 .../apache/coyote/http11/Http11InputBuffer.java    | 1252 ++++++++++++++++++++
 .../coyote/http11/filters/ChunkedInputFilter.java  |  640 ++++++++++
 .../coyote/http11/filters/LocalStrings.properties  |   27 +
 3 files changed, 1919 insertions(+)

diff --git a/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/Http11InputBuffer.java b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/Http11InputBuffer.java
new file mode 100644
index 0000000000..ddd7e2d1e2
--- /dev/null
+++ b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/Http11InputBuffer.java
@@ -0,0 +1,1252 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.coyote.http11;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+
+import org.apache.coyote.CloseNowException;
+import org.apache.coyote.InputBuffer;
+import org.apache.coyote.Request;
+import org.apache.juli.logging.Log;
+import org.apache.juli.logging.LogFactory;
+import org.apache.tomcat.util.buf.MessageBytes;
+import org.apache.tomcat.util.http.HeaderUtil;
+import org.apache.tomcat.util.http.MimeHeaders;
+import org.apache.tomcat.util.http.parser.HttpParser;
+import org.apache.tomcat.util.net.ApplicationBufferHandler;
+import org.apache.tomcat.util.net.SocketWrapperBase;
+import org.apache.tomcat.util.res.StringManager;
+
+/**
+ * InputBuffer for HTTP that provides request header parsing as well as transfer
+ * encoding.
+ */
+public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler {
+
+    // -------------------------------------------------------------- Constants
+
+    private static final Log log = LogFactory.getLog(Http11InputBuffer.class);
+
+    /**
+     * The string manager for this package.
+     */
+    private static final StringManager sm = StringManager.getManager(Http11InputBuffer.class);
+
+
+    private static final byte[] CLIENT_PREFACE_START =
+            "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n".getBytes(StandardCharsets.ISO_8859_1);
+
+    /**
+     * Associated Coyote request.
+     */
+    private final Request request;
+
+
+    /**
+     * Headers of the associated request.
+     */
+    private final MimeHeaders headers;
+
+
+    private final boolean rejectIllegalHeader;
+
+    /**
+     * State.
+     */
+    private volatile boolean parsingHeader;
+
+
+    /**
+     * Swallow input ? (in the case of an expectation)
+     */
+    private boolean swallowInput;
+
+
+    /**
+     * The read buffer.
+     */
+    private ByteBuffer byteBuffer;
+
+
+    /**
+     * Pos of the end of the header in the buffer, which is also the
+     * start of the body.
+     */
+    private int end;
+
+
+    /**
+     * Wrapper that provides access to the underlying socket.
+     */
+    private SocketWrapperBase<?> wrapper;
+
+
+    /**
+     * Underlying input buffer.
+     */
+    private InputBuffer inputStreamInputBuffer;
+
+
+    /**
+     * Filter library.
+     * Note: Filter[Constants.CHUNKED_FILTER] is always the "chunked" filter.
+     */
+    private InputFilter[] filterLibrary;
+
+
+    /**
+     * Active filters (in order).
+     */
+    private InputFilter[] activeFilters;
+
+
+    /**
+     * Index of the last active filter.
+     */
+    private int lastActiveFilter;
+
+
+    /**
+     * Parsing state - used for non blocking parsing so that
+     * when more data arrives, we can pick up where we left off.
+     */
+    private byte prevChr = 0;
+    private byte chr = 0;
+    private volatile boolean parsingRequestLine;
+    private int parsingRequestLinePhase = 0;
+    private boolean parsingRequestLineEol = false;
+    private int parsingRequestLineStart = 0;
+    private int parsingRequestLineQPos = -1;
+    private HeaderParsePosition headerParsePos;
+    private final HeaderParseData headerData = new HeaderParseData();
+    private final HttpParser httpParser;
+
+    /**
+     * Maximum allowed size of the HTTP request line plus headers plus any
+     * leading blank lines.
+     */
+    private final int headerBufferSize;
+
+    /**
+     * Known size of the NioChannel read buffer.
+     */
+    private int socketReadBufferSize;
+
+
+    // ----------------------------------------------------------- Constructors
+
+    public Http11InputBuffer(Request request, int headerBufferSize,
+            boolean rejectIllegalHeader, HttpParser httpParser) {
+
+        this.request = request;
+        headers = request.getMimeHeaders();
+
+        this.headerBufferSize = headerBufferSize;
+        this.rejectIllegalHeader = rejectIllegalHeader;
+        this.httpParser = httpParser;
+
+        filterLibrary = new InputFilter[0];
+        activeFilters = new InputFilter[0];
+        lastActiveFilter = -1;
+
+        parsingHeader = true;
+        parsingRequestLine = true;
+        parsingRequestLinePhase = 0;
+        parsingRequestLineEol = false;
+        parsingRequestLineStart = 0;
+        parsingRequestLineQPos = -1;
+        headerParsePos = HeaderParsePosition.HEADER_START;
+        swallowInput = true;
+
+        inputStreamInputBuffer = new SocketInputBuffer();
+    }
+
+
+    // ------------------------------------------------------------- Properties
+
+    /**
+     * Add an input filter to the filter library.
+     *
+     * @throws NullPointerException if the supplied filter is null
+     */
+    void addFilter(InputFilter filter) {
+
+        if (filter == null) {
+            throw new NullPointerException(sm.getString("iib.filter.npe"));
+        }
+
+        InputFilter[] newFilterLibrary = Arrays.copyOf(filterLibrary, filterLibrary.length + 1);
+        newFilterLibrary[filterLibrary.length] = filter;
+        filterLibrary = newFilterLibrary;
+
+        activeFilters = new InputFilter[filterLibrary.length];
+    }
+
+
+    /**
+     * Get filters.
+     */
+    InputFilter[] getFilters() {
+        return filterLibrary;
+    }
+
+
+    /**
+     * Add an input filter to the filter library.
+     */
+    void addActiveFilter(InputFilter filter) {
+
+        if (lastActiveFilter == -1) {
+            filter.setBuffer(inputStreamInputBuffer);
+        } else {
+            for (int i = 0; i <= lastActiveFilter; i++) {
+                if (activeFilters[i] == filter) {
+                    return;
+                }
+            }
+            filter.setBuffer(activeFilters[lastActiveFilter]);
+        }
+
+        activeFilters[++lastActiveFilter] = filter;
+
+        filter.setRequest(request);
+    }
+
+
+    /**
+     * Set the swallow input flag.
+     */
+    void setSwallowInput(boolean swallowInput) {
+        this.swallowInput = swallowInput;
+    }
+
+
+    // ---------------------------------------------------- InputBuffer Methods
+
+    @Override
+    public int doRead(ApplicationBufferHandler handler) throws IOException {
+        if (lastActiveFilter == -1) {
+            return inputStreamInputBuffer.doRead(handler);
+        } else {
+            return activeFilters[lastActiveFilter].doRead(handler);
+        }
+    }
+
+
+    // ------------------------------------------------------- Protected Methods
+
+    /**
+     * Recycle the input buffer. This should be called when closing the
+     * connection.
+     */
+    void recycle() {
+        wrapper = null;
+        request.recycle();
+
+        for (int i = 0; i <= lastActiveFilter; i++) {
+            activeFilters[i].recycle();
+        }
+
+        byteBuffer.limit(0).position(0);
+        lastActiveFilter = -1;
+        swallowInput = true;
+
+        chr = 0;
+        prevChr = 0;
+        headerParsePos = HeaderParsePosition.HEADER_START;
+        parsingRequestLinePhase = 0;
+        parsingRequestLineEol = false;
+        parsingRequestLineStart = 0;
+        parsingRequestLineQPos = -1;
+        headerData.recycle();
+        // Recycled last because they are volatile
+        // All variables visible to this thread are guaranteed to be visible to
+        // any other thread once that thread reads the same volatile. The first
+        // action when parsing input data is to read one of these volatiles.
+        parsingRequestLine = true;
+        parsingHeader = true;
+    }
+
+
+    /**
+     * End processing of current HTTP request.
+     * Note: All bytes of the current request should have been already
+     * consumed. This method only resets all the pointers so that we are ready
+     * to parse the next HTTP request.
+     */
+    void nextRequest() {
+        request.recycle();
+
+        if (byteBuffer.position() > 0) {
+            if (byteBuffer.remaining() > 0) {
+                // Copy leftover bytes to the beginning of the buffer
+                byteBuffer.compact();
+                byteBuffer.flip();
+            } else {
+                // Reset position and limit to 0
+                byteBuffer.position(0).limit(0);
+            }
+        }
+
+        // Recycle filters
+        for (int i = 0; i <= lastActiveFilter; i++) {
+            activeFilters[i].recycle();
+        }
+
+        // Reset pointers
+        lastActiveFilter = -1;
+        parsingHeader = true;
+        swallowInput = true;
+
+        headerParsePos = HeaderParsePosition.HEADER_START;
+        parsingRequestLine = true;
+        parsingRequestLinePhase = 0;
+        parsingRequestLineEol = false;
+        parsingRequestLineStart = 0;
+        parsingRequestLineQPos = -1;
+        headerData.recycle();
+    }
+
+
+    /**
+     * Read the request line. This function is meant to be used during the
+     * HTTP request header parsing. Do NOT attempt to read the request body
+     * using it.
+     *
+     * @throws IOException If an exception occurs during the underlying socket
+     * read operations, or if the given buffer is not big enough to accommodate
+     * the whole line.
+     *
+     * @return true if data is properly fed; false if no data is available
+     * immediately and thread should be freed
+     */
+    boolean parseRequestLine(boolean keptAlive, int connectionTimeout, int keepAliveTimeout)
+            throws IOException {
+
+        // check state
+        if (!parsingRequestLine) {
+            return true;
+        }
+        //
+        // Skipping blank lines
+        //
+        if (parsingRequestLinePhase < 2) {
+            do {
+                // Read new bytes if needed
+                if (byteBuffer.position() >= byteBuffer.limit()) {
+                    if (keptAlive) {
+                        // Haven't read any request data yet so use the keep-alive
+                        // timeout.
+                        wrapper.setReadTimeout(keepAliveTimeout);
+                    }
+                    if (!fill(false)) {
+                        // A read is pending, so no longer in initial state
+                        parsingRequestLinePhase = 1;
+                        return false;
+                    }
+                    // At least one byte of the request has been received.
+                    // Switch to the socket timeout.
+                    wrapper.setReadTimeout(connectionTimeout);
+                }
+                if (!keptAlive && byteBuffer.position() == 0 && byteBuffer.limit() >= CLIENT_PREFACE_START.length) {
+                    boolean prefaceMatch = true;
+                    for (int i = 0; i < CLIENT_PREFACE_START.length && prefaceMatch; i++) {
+                        if (CLIENT_PREFACE_START[i] != byteBuffer.get(i)) {
+                            prefaceMatch = false;
+                        }
+                    }
+                    if (prefaceMatch) {
+                        // HTTP/2 preface matched
+                        parsingRequestLinePhase = -1;
+                        return false;
+                    }
+                }
+                // Set the start time once we start reading data (even if it is
+                // just skipping blank lines)
+                if (request.getStartTimeNanos() < 0) {
+                    request.setStartTimeNanos(System.nanoTime());
+                }
+                chr = byteBuffer.get();
+            } while ((chr == Constants.CR) || (chr == Constants.LF));
+            byteBuffer.position(byteBuffer.position() - 1);
+
+            parsingRequestLineStart = byteBuffer.position();
+            parsingRequestLinePhase = 2;
+        }
+        if (parsingRequestLinePhase == 2) {
+            //
+            // Reading the method name
+            // Method name is a token
+            //
+            boolean space = false;
+            while (!space) {
+                // Read new bytes if needed
+                if (byteBuffer.position() >= byteBuffer.limit()) {
+                    if (!fill(false)) {
+                        return false;
+                    }
+                }
+                // Spec says method name is a token followed by a single SP but
+                // also be tolerant of multiple SP and/or HT.
+                int pos = byteBuffer.position();
+                chr = byteBuffer.get();
+                if (chr == Constants.SP || chr == Constants.HT) {
+                    space = true;
+                    request.method().setBytes(byteBuffer.array(), parsingRequestLineStart,
+                            pos - parsingRequestLineStart);
+                } else if (!HttpParser.isToken(chr)) {
+                    // Avoid unknown protocol triggering an additional error
+                    request.protocol().setString(Constants.HTTP_11);
+                    String invalidMethodValue = parseInvalid(parsingRequestLineStart, byteBuffer);
+                    throw new IllegalArgumentException(sm.getString("iib.invalidmethod", invalidMethodValue));
+                }
+            }
+            parsingRequestLinePhase = 3;
+        }
+        if (parsingRequestLinePhase == 3) {
+            // Spec says single SP but also be tolerant of multiple SP and/or HT
+            boolean space = true;
+            while (space) {
+                // Read new bytes if needed
+                if (byteBuffer.position() >= byteBuffer.limit()) {
+                    if (!fill(false)) {
+                        return false;
+                    }
+                }
+                chr = byteBuffer.get();
+                if (!(chr == Constants.SP || chr == Constants.HT)) {
+                    space = false;
+                    byteBuffer.position(byteBuffer.position() - 1);
+                }
+            }
+            parsingRequestLineStart = byteBuffer.position();
+            parsingRequestLinePhase = 4;
+        }
+        if (parsingRequestLinePhase == 4) {
+            // Mark the current buffer position
+
+            int end = 0;
+            //
+            // Reading the URI
+            //
+            boolean space = false;
+            while (!space) {
+                // Read new bytes if needed
+                if (byteBuffer.position() >= byteBuffer.limit()) {
+                    if (!fill(false)) {
+                        return false;
+                    }
+                }
+                int pos = byteBuffer.position();
+                prevChr = chr;
+                chr = byteBuffer.get();
+                if (prevChr == Constants.CR && chr != Constants.LF) {
+                    // CR not followed by LF so not an HTTP/0.9 request and
+                    // therefore invalid. Trigger error handling.
+                    // Avoid unknown protocol triggering an additional error
+                    request.protocol().setString(Constants.HTTP_11);
+                    String invalidRequestTarget = parseInvalid(parsingRequestLineStart, byteBuffer);
+                    throw new IllegalArgumentException(sm.getString("iib.invalidRequestTarget", invalidRequestTarget));
+                }
+                if (chr == Constants.SP || chr == Constants.HT) {
+                    space = true;
+                    end = pos;
+                } else if (chr == Constants.CR) {
+                    // HTTP/0.9 style request. CR is optional. LF is not.
+                } else if (chr == Constants.LF) {
+                    // HTTP/0.9 style request
+                    // Stop this processing loop
+                    space = true;
+                    // Set blank protocol (indicates HTTP/0.9)
+                    request.protocol().setString("");
+                    // Skip the protocol processing
+                    parsingRequestLinePhase = 7;
+                    if (prevChr == Constants.CR) {
+                        end = pos - 1;
+                    } else {
+                        end = pos;
+                    }
+                } else if (chr == Constants.QUESTION && parsingRequestLineQPos == -1) {
+                    parsingRequestLineQPos = pos;
+                } else if (parsingRequestLineQPos != -1 && !httpParser.isQueryRelaxed(chr)) {
+                    // Avoid unknown protocol triggering an additional error
+                    request.protocol().setString(Constants.HTTP_11);
+                    // %nn decoding will be checked at the point of decoding
+                    String invalidRequestTarget = parseInvalid(parsingRequestLineStart, byteBuffer);
+                    throw new IllegalArgumentException(sm.getString("iib.invalidRequestTarget", invalidRequestTarget));
+                } else if (httpParser.isNotRequestTargetRelaxed(chr)) {
+                    // Avoid unknown protocol triggering an additional error
+                    request.protocol().setString(Constants.HTTP_11);
+                    // This is a general check that aims to catch problems early
+                    // Detailed checking of each part of the request target will
+                    // happen in Http11Processor#prepareRequest()
+                    String invalidRequestTarget = parseInvalid(parsingRequestLineStart, byteBuffer);
+                    throw new IllegalArgumentException(sm.getString("iib.invalidRequestTarget", invalidRequestTarget));
+                }
+            }
+            if (parsingRequestLineQPos >= 0) {
+                request.queryString().setBytes(byteBuffer.array(), parsingRequestLineQPos + 1,
+                        end - parsingRequestLineQPos - 1);
+                request.requestURI().setBytes(byteBuffer.array(), parsingRequestLineStart,
+                        parsingRequestLineQPos - parsingRequestLineStart);
+            } else {
+                request.requestURI().setBytes(byteBuffer.array(), parsingRequestLineStart,
+                        end - parsingRequestLineStart);
+            }
+            // HTTP/0.9 processing jumps to stage 7.
+            // Don't want to overwrite that here.
+            if (parsingRequestLinePhase == 4) {
+                parsingRequestLinePhase = 5;
+            }
+        }
+        if (parsingRequestLinePhase == 5) {
+            // Spec says single SP but also be tolerant of multiple and/or HT
+            boolean space = true;
+            while (space) {
+                // Read new bytes if needed
+                if (byteBuffer.position() >= byteBuffer.limit()) {
+                    if (!fill(false)) {
+                        return false;
+                    }
+                }
+                byte chr = byteBuffer.get();
+                if (!(chr == Constants.SP || chr == Constants.HT)) {
+                    space = false;
+                    byteBuffer.position(byteBuffer.position() - 1);
+                }
+            }
+            parsingRequestLineStart = byteBuffer.position();
+            parsingRequestLinePhase = 6;
+
+            // Mark the current buffer position
+            end = 0;
+        }
+        if (parsingRequestLinePhase == 6) {
+            //
+            // Reading the protocol
+            // Protocol is always "HTTP/" DIGIT "." DIGIT
+            //
+            while (!parsingRequestLineEol) {
+                // Read new bytes if needed
+                if (byteBuffer.position() >= byteBuffer.limit()) {
+                    if (!fill(false)) {
+                        return false;
+                    }
+                }
+
+                int pos = byteBuffer.position();
+                prevChr = chr;
+                chr = byteBuffer.get();
+                if (chr == Constants.CR) {
+                    // Possible end of request line. Need LF next else invalid.
+                } else if (prevChr == Constants.CR && chr == Constants.LF) {
+                    // CRLF is the standard line terminator
+                    end = pos - 1;
+                    parsingRequestLineEol = true;
+                } else if (chr == Constants.LF) {
+                    // LF is an optional line terminator
+                    end = pos;
+                    parsingRequestLineEol = true;
+                } else if (prevChr == Constants.CR || !HttpParser.isHttpProtocol(chr)) {
+                    String invalidProtocol = parseInvalid(parsingRequestLineStart, byteBuffer);
+                    throw new IllegalArgumentException(sm.getString("iib.invalidHttpProtocol", invalidProtocol));
+                }
+            }
+
+            if ((end - parsingRequestLineStart) > 0) {
+                request.protocol().setBytes(byteBuffer.array(), parsingRequestLineStart,
+                        end - parsingRequestLineStart);
+                parsingRequestLinePhase = 7;
+            }
+            // If no protocol is found, the ISE below will be triggered.
+        }
+        if (parsingRequestLinePhase == 7) {
+            // Parsing is complete. Return and clean-up.
+            parsingRequestLine = false;
+            parsingRequestLinePhase = 0;
+            parsingRequestLineEol = false;
+            parsingRequestLineStart = 0;
+            return true;
+        }
+        throw new IllegalStateException(sm.getString("iib.invalidPhase", Integer.valueOf(parsingRequestLinePhase)));
+    }
+
+
+    /**
+     * Parse the HTTP headers.
+     */
+    boolean parseHeaders() throws IOException {
+        if (!parsingHeader) {
+            throw new IllegalStateException(sm.getString("iib.parseheaders.ise.error"));
+        }
+
+        HeaderParseStatus status = HeaderParseStatus.HAVE_MORE_HEADERS;
+
+        do {
+            status = parseHeader();
+            // Checking that
+            // (1) Headers plus request line size does not exceed its limit
+            // (2) There are enough bytes to avoid expanding the buffer when
+            // reading body
+            // Technically, (2) is technical limitation, (1) is logical
+            // limitation to enforce the meaning of headerBufferSize
+            // From the way how buf is allocated and how blank lines are being
+            // read, it should be enough to check (1) only.
+            if (byteBuffer.position() > headerBufferSize || byteBuffer.capacity() - byteBuffer.position() < socketReadBufferSize) {
+                throw new IllegalArgumentException(sm.getString("iib.requestheadertoolarge.error"));
+            }
+        } while (status == HeaderParseStatus.HAVE_MORE_HEADERS);
+        if (status == HeaderParseStatus.DONE) {
+            parsingHeader = false;
+            end = byteBuffer.position();
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+
+    int getParsingRequestLinePhase() {
+        return parsingRequestLinePhase;
+    }
+
+
+    private String parseInvalid(int startPos, ByteBuffer buffer) {
+        // Look for the next space
+        byte b = 0;
+        while (buffer.hasRemaining() && b != 0x20) {
+            b = buffer.get();
+        }
+        String result = HeaderUtil.toPrintableString(buffer.array(), buffer.arrayOffset() + startPos, buffer.position() - startPos);
+        if (b != 0x20) {
+            // Ran out of buffer rather than found a space
+            result = result + "...";
+        }
+        return result;
+    }
+
+
+    /**
+     * End request (consumes leftover bytes).
+     *
+     * @throws IOException an underlying I/O error occurred
+     */
+    void endRequest() throws IOException {
+
+        if (swallowInput && (lastActiveFilter != -1)) {
+            int extraBytes = (int) activeFilters[lastActiveFilter].end();
+            byteBuffer.position(byteBuffer.position() - extraBytes);
+        }
+    }
+
+
+    @Override
+    public int available() {
+        return available(false);
+    }
+
+
+    /**
+     * Available bytes in the buffers for the current request.
+     *
+     * Note that when requests are pipelined, the data in byteBuffer may relate
+     * to the next request rather than this one.
+     */
+    int available(boolean read) {
+        int available;
+
+        if (lastActiveFilter == -1) {
+            available = inputStreamInputBuffer.available();
+        } else {
+            available = activeFilters[lastActiveFilter].available();
+        }
+
+        // Only try a non-blocking read if:
+        // - there is no data in the filters
+        // - the caller requested a read
+        // - there is no data in byteBuffer
+        // - the socket wrapper indicates a read is allowed
+        //
+        // Notes: 1. When pipelined requests are being used available may be
+        //        zero even when byteBuffer has data. This is because the data
+        //        in byteBuffer is for the next request. We don't want to
+        //        attempt a read in this case.
+        //        2. wrapper.hasDataToRead() is present to handle the NIO2 case
+        try {
+            if (available == 0 && read && !byteBuffer.hasRemaining() && wrapper.hasDataToRead()) {
+                fill(false);
+                available = byteBuffer.remaining();
+            }
+        } catch (IOException ioe) {
+            if (log.isDebugEnabled()) {
+                log.debug(sm.getString("iib.available.readFail"), ioe);
+            }
+            // Not ideal. This will indicate that data is available which should
+            // trigger a read which in turn will trigger another IOException and
+            // that one can be thrown.
+            available = 1;
+        }
+        return available;
+    }
+
+
+    /**
+     * Has all of the request body been read? There are subtle differences
+     * between this and available() &gt; 0 primarily because of having to handle
+     * faking non-blocking reads with the blocking IO connector.
+     */
+    boolean isFinished() {
+        // The active filters have the definitive information on whether or not
+        // the current request body has been read. Note that byteBuffer may
+        // contain pipelined data so is not a good indicator.
+        if (lastActiveFilter >= 0) {
+            return activeFilters[lastActiveFilter].isFinished();
+        } else {
+            // No filters. Assume request is not finished. EOF will signal end of
+            // request.
+            return false;
+        }
+    }
+
+    ByteBuffer getLeftover() {
+        int available = byteBuffer.remaining();
+        if (available > 0) {
+            return ByteBuffer.wrap(byteBuffer.array(), byteBuffer.position(), available);
+        } else {
+            return null;
+        }
+    }
+
+
+    boolean isChunking() {
+        for (int i = 0; i < lastActiveFilter; i++) {
+            if (activeFilters[i] == filterLibrary[Constants.CHUNKED_FILTER]) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+
+    void init(SocketWrapperBase<?> socketWrapper) {
+
+        wrapper = socketWrapper;
+        wrapper.setAppReadBufHandler(this);
+
+        int bufLength = headerBufferSize +
+                wrapper.getSocketBufferHandler().getReadBuffer().capacity();
+        if (byteBuffer == null || byteBuffer.capacity() < bufLength) {
+            byteBuffer = ByteBuffer.allocate(bufLength);
+            byteBuffer.position(0).limit(0);
+        }
+    }
+
+
+
+    // --------------------------------------------------------- Private Methods
+
+    /**
+     * Attempts to read some data into the input buffer.
+     *
+     * @return <code>true</code> if more data was added to the input buffer
+     *         otherwise <code>false</code>
+     */
+    private boolean fill(boolean block) throws IOException {
+
+        if (log.isDebugEnabled()) {
+            log.debug("Before fill(): parsingHeader: [" + parsingHeader +
+                    "], parsingRequestLine: [" + parsingRequestLine +
+                    "], parsingRequestLinePhase: [" + parsingRequestLinePhase +
+                    "], parsingRequestLineStart: [" + parsingRequestLineStart +
+                    "], byteBuffer.position(): [" + byteBuffer.position() +
+                    "], byteBuffer.limit(): [" + byteBuffer.limit() +
+                    "], end: [" + end + "]");
+        }
+
+        if (parsingHeader) {
+            if (byteBuffer.limit() >= headerBufferSize) {
+                if (parsingRequestLine) {
+                    // Avoid unknown protocol triggering an additional error
+                    request.protocol().setString(Constants.HTTP_11);
+                }
+                throw new IllegalArgumentException(sm.getString("iib.requestheadertoolarge.error"));
+            }
+        } else {
+            byteBuffer.limit(end).position(end);
+        }
+
+        int nRead = -1;
+        int mark = byteBuffer.position();
+        try {
+            if (byteBuffer.position() < byteBuffer.limit()) {
+                byteBuffer.position(byteBuffer.limit());
+            }
+            byteBuffer.limit(byteBuffer.capacity());
+            SocketWrapperBase<?> socketWrapper = this.wrapper;
+            if (socketWrapper != null) {
+                nRead = socketWrapper.read(block, byteBuffer);
+            } else {
+                throw new CloseNowException(sm.getString("iib.eof.error"));
+            }
+        } finally {
+            // Ensure that the buffer limit and position are returned to a
+            // consistent "ready for read" state if an error occurs during in
+            // the above code block.
+            // Some error conditions can result in the position being reset to
+            // zero which also invalidates the mark.
+            // https://bz.apache.org/bugzilla/show_bug.cgi?id=65677
+            if (byteBuffer.position() >= mark) {
+                // // Position and mark are consistent. Assume a read (possibly
+                // of zero bytes) has occurred.
+                byteBuffer.limit(byteBuffer.position());
+                byteBuffer.position(mark);
+            } else {
+                // Position and mark are inconsistent. Set position and limit to
+                // zero so effectively no data is reported as read.
+                byteBuffer.position(0);
+                byteBuffer.limit(0);
+            }
+        }
+
+        if (log.isDebugEnabled()) {
+            log.debug("Received ["
+                    + new String(byteBuffer.array(), byteBuffer.position(), byteBuffer.remaining(), StandardCharsets.ISO_8859_1) + "]");
+        }
+
+        if (nRead > 0) {
+            return true;
+        } else if (nRead == -1) {
+            throw new EOFException(sm.getString("iib.eof.error"));
+        } else {
+            return false;
+        }
+
+    }
+
+
+    /**
+     * Parse an HTTP header.
+     *
+     * @return One of {@link HeaderParseStatus#NEED_MORE_DATA},
+     * {@link HeaderParseStatus#HAVE_MORE_HEADERS} or
+     * {@link HeaderParseStatus#DONE}.
+     */
+    private HeaderParseStatus parseHeader() throws IOException {
+
+        while (headerParsePos == HeaderParsePosition.HEADER_START) {
+
+            // Read new bytes if needed
+            if (byteBuffer.position() >= byteBuffer.limit()) {
+                if (!fill(false)) {
+                    return HeaderParseStatus.NEED_MORE_DATA;
+                }
+            }
+
+            prevChr = chr;
+            chr = byteBuffer.get();
+
+            if (chr == Constants.CR && prevChr != Constants.CR) {
+                // Possible start of CRLF - process the next byte.
+            } else if (chr == Constants.LF) {
+                // CRLF or LF is an acceptable line terminator
+                return HeaderParseStatus.DONE;
+            } else {
+                if (prevChr == Constants.CR) {
+                    // Must have read two bytes (first was CR, second was not LF)
+                    byteBuffer.position(byteBuffer.position() - 2);
+                } else {
+                    // Must have only read one byte
+                    byteBuffer.position(byteBuffer.position() - 1);
+                }
+                break;
+            }
+        }
+
+        if (headerParsePos == HeaderParsePosition.HEADER_START) {
+            // Mark the current buffer position
+            headerData.start = byteBuffer.position();
+            headerData.lineStart = headerData.start;
+            headerParsePos = HeaderParsePosition.HEADER_NAME;
+        }
+
+        //
+        // Reading the header name
+        // Header name is always US-ASCII
+        //
+
+        while (headerParsePos == HeaderParsePosition.HEADER_NAME) {
+
+            // Read new bytes if needed
+            if (byteBuffer.position() >= byteBuffer.limit()) {
+                if (!fill(false)) { // parse header
+                    return HeaderParseStatus.NEED_MORE_DATA;
+                }
+            }
+
+            int pos = byteBuffer.position();
+            chr = byteBuffer.get();
+            if (chr == Constants.COLON) {
+                headerParsePos = HeaderParsePosition.HEADER_VALUE_START;
+                headerData.headerValue = headers.addValue(byteBuffer.array(), headerData.start,
+                        pos - headerData.start);
+                pos = byteBuffer.position();
+                // Mark the current buffer position
+                headerData.start = pos;
+                headerData.realPos = pos;
+                headerData.lastSignificantChar = pos;
+                break;
+            } else if (!HttpParser.isToken(chr)) {
+                // Non-token characters are illegal in header names
+                // Parsing continues so the error can be reported in context
+                headerData.lastSignificantChar = pos;
+                byteBuffer.position(byteBuffer.position() - 1);
+                // skipLine() will handle the error
+                return skipLine(false);
+            }
+
+            // chr is next byte of header name. Convert to lowercase.
+            if ((chr >= Constants.A) && (chr <= Constants.Z)) {
+                byteBuffer.put(pos, (byte) (chr - Constants.LC_OFFSET));
+            }
+        }
+
+        // Skip the line and ignore the header
+        if (headerParsePos == HeaderParsePosition.HEADER_SKIPLINE) {
+            return skipLine(false);
+        }
+
+        //
+        // Reading the header value (which can be spanned over multiple lines)
+        //
+
+        while (headerParsePos == HeaderParsePosition.HEADER_VALUE_START ||
+               headerParsePos == HeaderParsePosition.HEADER_VALUE ||
+               headerParsePos == HeaderParsePosition.HEADER_MULTI_LINE) {
+
+            if (headerParsePos == HeaderParsePosition.HEADER_VALUE_START) {
+                // Skipping spaces
+                while (true) {
+                    // Read new bytes if needed
+                    if (byteBuffer.position() >= byteBuffer.limit()) {
+                        if (!fill(false)) {// parse header
+                            // HEADER_VALUE_START
+                            return HeaderParseStatus.NEED_MORE_DATA;
+                        }
+                    }
+
+                    chr = byteBuffer.get();
+                    if (!(chr == Constants.SP || chr == Constants.HT)) {
+                        headerParsePos = HeaderParsePosition.HEADER_VALUE;
+                        byteBuffer.position(byteBuffer.position() - 1);
+                        // Avoids prevChr = chr at start of header value
+                        // parsing which causes problems when chr is CR
+                        // (in the case of an empty header value)
+                        chr = 0;
+                        break;
+                    }
+                }
+            }
+            if (headerParsePos == HeaderParsePosition.HEADER_VALUE) {
+
+                // Reading bytes until the end of the line
+                boolean eol = false;
+                while (!eol) {
+
+                    // Read new bytes if needed
+                    if (byteBuffer.position() >= byteBuffer.limit()) {
+                        if (!fill(false)) {// parse header
+                            // HEADER_VALUE
+                            return HeaderParseStatus.NEED_MORE_DATA;
+                        }
+                    }
+
+                    prevChr = chr;
+                    chr = byteBuffer.get();
+                    if (chr == Constants.CR && prevChr != Constants.CR) {
+                        // CR is only permitted at the start of a CRLF sequence.
+                        // Possible start of CRLF - process the next byte.
+                    } else if (chr == Constants.LF) {
+                        // CRLF or LF is an acceptable line terminator
+                        eol = true;
+                    } else if (prevChr == Constants.CR) {
+                        // Invalid value - also need to delete header
+                        return skipLine(true);
+                    } else if (chr != Constants.HT && HttpParser.isControl(chr)) {
+                        // Invalid value - also need to delete header
+                        return skipLine(true);
+                    } else if (chr == Constants.SP || chr == Constants.HT) {
+                        byteBuffer.put(headerData.realPos, chr);
+                        headerData.realPos++;
+                    } else {
+                        byteBuffer.put(headerData.realPos, chr);
+                        headerData.realPos++;
+                        headerData.lastSignificantChar = headerData.realPos;
+                    }
+                }
+
+                // Ignore whitespaces at the end of the line
+                headerData.realPos = headerData.lastSignificantChar;
+
+                // Checking the first character of the new line. If the character
+                // is a LWS, then it's a multiline header
+                headerParsePos = HeaderParsePosition.HEADER_MULTI_LINE;
+            }
+            // Read new bytes if needed
+            if (byteBuffer.position() >= byteBuffer.limit()) {
+                if (!fill(false)) {// parse header
+                    // HEADER_MULTI_LINE
+                    return HeaderParseStatus.NEED_MORE_DATA;
+                }
+            }
+
+            byte peek = byteBuffer.get(byteBuffer.position());
+            if (headerParsePos == HeaderParsePosition.HEADER_MULTI_LINE) {
+                if ((peek != Constants.SP) && (peek != Constants.HT)) {
+                    headerParsePos = HeaderParsePosition.HEADER_START;
+                    break;
+                } else {
+                    // Copying one extra space in the buffer (since there must
+                    // be at least one space inserted between the lines)
+                    byteBuffer.put(headerData.realPos, peek);
+                    headerData.realPos++;
+                    headerParsePos = HeaderParsePosition.HEADER_VALUE_START;
+                }
+            }
+        }
+        // Set the header value
+        headerData.headerValue.setBytes(byteBuffer.array(), headerData.start,
+                headerData.lastSignificantChar - headerData.start);
+        headerData.recycle();
+        return HeaderParseStatus.HAVE_MORE_HEADERS;
+    }
+
+
+    private HeaderParseStatus skipLine(boolean deleteHeader) throws IOException {
+        boolean rejectThisHeader = rejectIllegalHeader;
+        // Check if rejectIllegalHeader is disabled and needs to be overridden
+        // for this header. The header name is required to determine if this
+        // override is required. The header name is only available once the
+        // header has been created. If the header has been created then
+        // deleteHeader will be true.
+        if (!rejectThisHeader && deleteHeader) {
+            if (headers.getName(headers.size() - 1).equalsIgnoreCase("content-length")) {
+                // Malformed content-length headers must always be rejected
+                // RFC 9112, section 6.3, bullet 5.
+                rejectThisHeader = true;
+            } else {
+                // Only need to delete the header if the request isn't going to
+                // be rejected (it will be the most recent one)
+                headers.removeHeader(headers.size() - 1);
+            }
+        }
+
+        // Parse the rest of the invalid header so we can construct a useful
+        // exception and/or debug message.
+        headerParsePos = HeaderParsePosition.HEADER_SKIPLINE;
+        boolean eol = false;
+
+        // Reading bytes until the end of the line
+        while (!eol) {
+
+            // Read new bytes if needed
+            if (byteBuffer.position() >= byteBuffer.limit()) {
+                if (!fill(false)) {
+                    return HeaderParseStatus.NEED_MORE_DATA;
+                }
+            }
+
+            int pos = byteBuffer.position();
+            prevChr = chr;
+            chr = byteBuffer.get();
+            if (chr == Constants.CR) {
+                // Skip
+            } else if (chr == Constants.LF) {
+                // CRLF or LF is an acceptable line terminator
+                eol = true;
+            } else {
+                headerData.lastSignificantChar = pos;
+            }
+        }
+        if (rejectThisHeader || log.isDebugEnabled()) {
+            String message = sm.getString("iib.invalidheader",
+                    HeaderUtil.toPrintableString(byteBuffer.array(), headerData.lineStart,
+                            headerData.lastSignificantChar - headerData.lineStart + 1));
+            if (rejectThisHeader) {
+                throw new IllegalArgumentException(message);
+            }
+            log.debug(message);
+        }
+
+        headerParsePos = HeaderParsePosition.HEADER_START;
+        return HeaderParseStatus.HAVE_MORE_HEADERS;
+    }
+
+
+    // ----------------------------------------------------------- Inner classes
+
+    private enum HeaderParseStatus {
+        DONE, HAVE_MORE_HEADERS, NEED_MORE_DATA
+    }
+
+
+    private enum HeaderParsePosition {
+        /**
+         * Start of a new header. A CRLF here means that there are no more
+         * headers. Any other character starts a header name.
+         */
+        HEADER_START,
+        /**
+         * Reading a header name. All characters of header are HTTP_TOKEN_CHAR.
+         * Header name is followed by ':'. No whitespace is allowed.<br>
+         * Any non-HTTP_TOKEN_CHAR (this includes any whitespace) encountered
+         * before ':' will result in the whole line being ignored.
+         */
+        HEADER_NAME,
+        /**
+         * Skipping whitespace before text of header value starts, either on the
+         * first line of header value (just after ':') or on subsequent lines
+         * when it is known that subsequent line starts with SP or HT.
+         */
+        HEADER_VALUE_START,
+        /**
+         * Reading the header value. We are inside the value. Either on the
+         * first line or on any subsequent line. We come into this state from
+         * HEADER_VALUE_START after the first non-SP/non-HT byte is encountered
+         * on the line.
+         */
+        HEADER_VALUE,
+        /**
+         * Before reading a new line of a header. Once the next byte is peeked,
+         * the state changes without advancing our position. The state becomes
+         * either HEADER_VALUE_START (if that first byte is SP or HT), or
+         * HEADER_START (otherwise).
+         */
+        HEADER_MULTI_LINE,
+        /**
+         * Reading all bytes until the next CRLF. The line is being ignored.
+         */
+        HEADER_SKIPLINE
+    }
+
+
+    private static class HeaderParseData {
+        /**
+         * The first character of the header line.
+         */
+        int lineStart = 0;
+        /**
+         * When parsing header name: first character of the header.<br>
+         * When skipping broken header line: first character of the header.<br>
+         * When parsing header value: first character after ':'.
+         */
+        int start = 0;
+        /**
+         * When parsing header name: not used (stays as 0).<br>
+         * When skipping broken header line: not used (stays as 0).<br>
+         * When parsing header value: starts as the first character after ':'.
+         * Then is increased as far as more bytes of the header are harvested.
+         * Bytes from buf[pos] are copied to buf[realPos]. Thus the string from
+         * [start] to [realPos-1] is the prepared value of the header, with
+         * whitespaces removed as needed.<br>
+         */
+        int realPos = 0;
+        /**
+         * When parsing header name: not used (stays as 0).<br>
+         * When skipping broken header line: last non-CR/non-LF character.<br>
+         * When parsing header value: position after the last not-LWS character.<br>
+         */
+        int lastSignificantChar = 0;
+        /**
+         * MB that will store the value of the header. It is null while parsing
+         * header name and is created after the name has been parsed.
+         */
+        MessageBytes headerValue = null;
+        public void recycle() {
+            lineStart = 0;
+            start = 0;
+            realPos = 0;
+            lastSignificantChar = 0;
+            headerValue = null;
+        }
+    }
+
+
+    // ------------------------------------- InputStreamInputBuffer Inner Class
+
+    /**
+     * This class is an input buffer which will read its data from an input
+     * stream.
+     */
+    private class SocketInputBuffer implements InputBuffer {
+
+        @Override
+        public int doRead(ApplicationBufferHandler handler) throws IOException {
+
+            if (byteBuffer.position() >= byteBuffer.limit()) {
+                // The application is reading the HTTP request body
+                boolean block = (request.getReadListener() == null);
+                if (!fill(block)) {
+                    if (block) {
+                        return -1;
+                    } else {
+                        return 0;
+                    }
+                }
+            }
+
+            int length = byteBuffer.remaining();
+            handler.setByteBuffer(byteBuffer.duplicate());
+            byteBuffer.position(byteBuffer.limit());
+
+            return length;
+        }
+
+        @Override
+        public int available() {
+            return byteBuffer.remaining();
+        }
+    }
+
+
+    @Override
+    public void setByteBuffer(ByteBuffer buffer) {
+        byteBuffer = buffer;
+    }
+
+
+    @Override
+    public ByteBuffer getByteBuffer() {
+        return byteBuffer;
+    }
+
+
+    @Override
+    public void expand(int size) {
+        if (byteBuffer.capacity() >= size) {
+            byteBuffer.limit(size);
+        }
+        ByteBuffer temp = ByteBuffer.allocate(size);
+        temp.put(byteBuffer);
+        byteBuffer = temp;
+        byteBuffer.mark();
+        temp = null;
+    }
+}
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/filters/ChunkedInputFilter.java b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
new file mode 100644
index 0000000000..586d070f4d
--- /dev/null
+++ b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
@@ -0,0 +1,640 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.coyote.http11.filters;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.coyote.InputBuffer;
+import org.apache.coyote.Request;
+import org.apache.coyote.http11.Constants;
+import org.apache.coyote.http11.InputFilter;
+import org.apache.tomcat.util.buf.ByteChunk;
+import org.apache.tomcat.util.buf.HexUtils;
+import org.apache.tomcat.util.net.ApplicationBufferHandler;
+import org.apache.tomcat.util.res.StringManager;
+
+/**
+ * Chunked input filter. Parses chunked data according to
+ * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1">http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1</a><br>
+ *
+ * @author Remy Maucherat
+ */
+public class ChunkedInputFilter implements InputFilter, ApplicationBufferHandler {
+
+    private static final StringManager sm = StringManager.getManager(
+            ChunkedInputFilter.class.getPackage().getName());
+
+
+    // -------------------------------------------------------------- Constants
+
+    protected static final String ENCODING_NAME = "chunked";
+    protected static final ByteChunk ENCODING = new ByteChunk();
+
+
+    // ----------------------------------------------------- Static Initializer
+
+    static {
+        ENCODING.setBytes(ENCODING_NAME.getBytes(StandardCharsets.ISO_8859_1),
+                0, ENCODING_NAME.length());
+    }
+
+
+    // ----------------------------------------------------- Instance Variables
+
+    /**
+     * Next buffer in the pipeline.
+     */
+    protected InputBuffer buffer;
+
+
+    /**
+     * Number of bytes remaining in the current chunk.
+     */
+    protected int remaining = 0;
+
+
+    /**
+     * Byte chunk used to read bytes.
+     */
+    protected ByteBuffer readChunk;
+
+
+    /**
+     * Flag set to true when the end chunk has been read.
+     */
+    protected boolean endChunk = false;
+
+
+    /**
+     * Byte chunk used to store trailing headers.
+     */
+    protected final ByteChunk trailingHeaders = new ByteChunk();
+
+
+    /**
+     * Flag set to true if the next call to doRead() must parse a CRLF pair
+     * before doing anything else.
+     */
+    protected boolean needCRLFParse = false;
+
+
+    /**
+     * Request being parsed.
+     */
+    private Request request;
+
+
+    /**
+     * Limit for extension size.
+     */
+    private final long maxExtensionSize;
+
+
+    /**
+     * Limit for trailer size.
+     */
+    private final int maxTrailerSize;
+
+
+    /**
+     * Size of extensions processed for this request.
+     */
+    private long extensionSize;
+
+
+    private final int maxSwallowSize;
+
+
+    /**
+     * Flag that indicates if an error has occurred.
+     */
+    private boolean error;
+
+
+    private final Set<String> allowedTrailerHeaders;
+
+    // ----------------------------------------------------------- Constructors
+
+    public ChunkedInputFilter(int maxTrailerSize, Set<String> allowedTrailerHeaders,
+            int maxExtensionSize, int maxSwallowSize) {
+        this.trailingHeaders.setLimit(maxTrailerSize);
+        this.allowedTrailerHeaders = allowedTrailerHeaders;
+        this.maxExtensionSize = maxExtensionSize;
+        this.maxTrailerSize = maxTrailerSize;
+        this.maxSwallowSize = maxSwallowSize;
+    }
+
+
+    // ---------------------------------------------------- InputBuffer Methods
+
+    @Override
+    public int doRead(ApplicationBufferHandler handler) throws IOException {
+        if (endChunk) {
+            return -1;
+        }
+
+        checkError();
+
+        if(needCRLFParse) {
+            needCRLFParse = false;
+            parseCRLF(false);
+        }
+
+        if (remaining <= 0) {
+            if (!parseChunkHeader()) {
+                throwIOException(sm.getString("chunkedInputFilter.invalidHeader"));
+            }
+            if (endChunk) {
+                parseEndChunk();
+                return -1;
+            }
+        }
+
+        int result = 0;
+
+        if (readChunk == null || readChunk.position() >= readChunk.limit()) {
+            if (readBytes() < 0) {
+                throwIOException(sm.getString("chunkedInputFilter.eos"));
+            }
+        }
+
+        if (remaining > readChunk.remaining()) {
+            result = readChunk.remaining();
+            remaining = remaining - result;
+            if (readChunk != handler.getByteBuffer()) {
+                handler.setByteBuffer(readChunk.duplicate());
+            }
+            readChunk.position(readChunk.limit());
+        } else {
+            result = remaining;
+            if (readChunk != handler.getByteBuffer()) {
+                handler.setByteBuffer(readChunk.duplicate());
+                handler.getByteBuffer().limit(readChunk.position() + remaining);
+            }
+            readChunk.position(readChunk.position() + remaining);
+            remaining = 0;
+            //we need a CRLF
+            if ((readChunk.position() + 1) >= readChunk.limit()) {
+                //if we call parseCRLF we overrun the buffer here
+                //so we defer it to the next call BZ 11117
+                needCRLFParse = true;
+            } else {
+                parseCRLF(false); //parse the CRLF immediately
+            }
+        }
+
+        return result;
+    }
+
+
+    // ---------------------------------------------------- InputFilter Methods
+
+    /**
+     * Read the content length from the request.
+     */
+    @Override
+    public void setRequest(Request request) {
+        this.request = request;
+    }
+
+
+    /**
+     * End the current request.
+     */
+    @Override
+    public long end() throws IOException {
+        long swallowed = 0;
+        int read = 0;
+        // Consume extra bytes : parse the stream until the end chunk is found
+        while ((read = doRead(this)) >= 0) {
+            swallowed += read;
+            if (maxSwallowSize > -1 && swallowed > maxSwallowSize) {
+                throwIOException(sm.getString("inputFilter.maxSwallow"));
+            }
+        }
+
+        // Return the number of extra bytes which were consumed
+        return readChunk.remaining();
+    }
+
+
+    /**
+     * Amount of bytes still available in a buffer.
+     */
+    @Override
+    public int available() {
+        int available = 0;
+        if (readChunk != null) {
+            available = readChunk.remaining();
+        }
+        if (available == 0) {
+            // No data buffered here. Try the next filter in the chain.
+            return buffer.available();
+        } else {
+            return available;
+        }
+    }
+
+
+    /**
+     * Set the next buffer in the filter pipeline.
+     */
+    @Override
+    public void setBuffer(InputBuffer buffer) {
+        this.buffer = buffer;
+    }
+
+
+    /**
+     * Make the filter ready to process the next request.
+     */
+    @Override
+    public void recycle() {
+        remaining = 0;
+        if (readChunk != null) {
+            readChunk.position(0).limit(0);
+        }
+        endChunk = false;
+        needCRLFParse = false;
+        trailingHeaders.recycle();
+        trailingHeaders.setLimit(maxTrailerSize);
+        extensionSize = 0;
+        error = false;
+    }
+
+
+    /**
+     * Return the name of the associated encoding; Here, the value is
+     * "identity".
+     */
+    @Override
+    public ByteChunk getEncodingName() {
+        return ENCODING;
+    }
+
+
+    @Override
+    public boolean isFinished() {
+        return endChunk;
+    }
+
+
+    // ------------------------------------------------------ Protected Methods
+
+    /**
+     * Read bytes from the previous buffer.
+     * @return The byte count which has been read
+     * @throws IOException Read error
+     */
+    protected int readBytes() throws IOException {
+        return buffer.doRead(this);
+    }
+
+
+    /**
+     * Parse the header of a chunk.
+     * A chunk header can look like one of the following:<br>
+     * A10CRLF<br>
+     * F23;chunk-extension to be ignoredCRLF
+     *
+     * <p>
+     * The letters before CRLF or ';' (whatever comes first) must be valid hex
+     * digits. We should not parse F23IAMGONNAMESSTHISUP34CRLF as a valid
+     * header according to the spec.
+     * @return <code>true</code> if the chunk header has been
+     *  successfully parsed
+     * @throws IOException Read error
+     */
+    protected boolean parseChunkHeader() throws IOException {
+
+        int result = 0;
+        boolean eol = false;
+        int readDigit = 0;
+        boolean extension = false;
+
+        while (!eol) {
+
+            if (readChunk == null || readChunk.position() >= readChunk.limit()) {
+                if (readBytes() <= 0) {
+                    return false;
+                }
+            }
+
+            byte chr = readChunk.get(readChunk.position());
+            if (chr == Constants.CR || chr == Constants.LF) {
+                parseCRLF(false);
+                eol = true;
+            } else if (chr == Constants.SEMI_COLON && !extension) {
+                // First semi-colon marks the start of the extension. Further
+                // semi-colons may appear to separate multiple chunk-extensions.
+                // These need to be processed as part of parsing the extensions.
+                extension = true;
+                extensionSize++;
+            } else if (!extension) {
+                //don't read data after the trailer
+                int charValue = HexUtils.getDec(chr);
+                if (charValue != -1 && readDigit < 8) {
+                    readDigit++;
+                    result = (result << 4) | charValue;
+                } else {
+                    //we shouldn't allow invalid, non hex characters
+                    //in the chunked header
+                    return false;
+                }
+            } else {
+                // Extension 'parsing'
+                // Note that the chunk-extension is neither parsed nor
+                // validated. Currently it is simply ignored.
+                extensionSize++;
+                if (maxExtensionSize > -1 && extensionSize > maxExtensionSize) {
+                    throwIOException(sm.getString("chunkedInputFilter.maxExtension"));
+                }
+            }
+
+            // Parsing the CRLF increments pos
+            if (!eol) {
+                readChunk.position(readChunk.position() + 1);
+            }
+        }
+
+        if (readDigit == 0 || result < 0) {
+            return false;
+        }
+
+        if (result == 0) {
+            endChunk = true;
+        }
+
+        remaining = result;
+        return true;
+    }
+
+
+    /**
+     * Parse CRLF at end of chunk.
+     *
+     * @param   tolerant    Should tolerant parsing (LF and CRLF) be used? This
+     *                      is recommended (RFC2616, section 19.3) for message
+     *                      headers.
+     * @throws IOException An error occurred parsing CRLF
+     */
+    protected void parseCRLF(boolean tolerant) throws IOException {
+
+        boolean eol = false;
+        boolean crfound = false;
+
+        while (!eol) {
+            if (readChunk == null || readChunk.position() >= readChunk.limit()) {
+                if (readBytes() <= 0) {
+                    throwIOException(sm.getString("chunkedInputFilter.invalidCrlfNoData"));
+                }
+            }
+
+            byte chr = readChunk.get(readChunk.position());
+            if (chr == Constants.CR) {
+                if (crfound) {
+                    throwIOException(sm.getString("chunkedInputFilter.invalidCrlfCRCR"));
+                }
+                crfound = true;
+            } else if (chr == Constants.LF) {
+                if (!tolerant && !crfound) {
+                    throwIOException(sm.getString("chunkedInputFilter.invalidCrlfNoCR"));
+                }
+                eol = true;
+            } else {
+                throwIOException(sm.getString("chunkedInputFilter.invalidCrlf"));
+            }
+
+            readChunk.position(readChunk.position() + 1);
+        }
+    }
+
+
+    /**
+     * Parse end chunk data.
+     * @throws IOException Error propagation
+     */
+    protected void parseEndChunk() throws IOException {
+        // Handle optional trailer headers
+        while (parseHeader()) {
+            // Loop until we run out of headers
+        }
+    }
+
+
+    private boolean parseHeader() throws IOException {
+
+        Map<String,String> headers = request.getTrailerFields();
+
+        byte chr = 0;
+
+        // Read new bytes if needed
+        if (readChunk == null || readChunk.position() >= readChunk.limit()) {
+            if (readBytes() <0) {
+               throwEOFException(sm.getString("chunkedInputFilter.eosTrailer"));
+            }
+        }
+
+        // readBytes() above will set readChunk unless it returns a value < 0
+        chr = readChunk.get(readChunk.position());
+
+        // CRLF terminates the request
+        if (chr == Constants.CR || chr == Constants.LF) {
+            parseCRLF(false);
+            return false;
+        }
+
+        // Mark the current buffer position
+        int startPos = trailingHeaders.getEnd();
+
+        //
+        // Reading the header name
+        // Header name is always US-ASCII
+        //
+
+        boolean colon = false;
+        while (!colon) {
+
+            // Read new bytes if needed
+            if (readChunk == null || readChunk.position() >= readChunk.limit()) {
+                if (readBytes() <0) {
+                    throwEOFException(sm.getString("chunkedInputFilter.eosTrailer"));
+                }
+            }
+
+            // readBytes() above will set readChunk unless it returns a value < 0
+            chr = readChunk.get(readChunk.position());
+            if ((chr >= Constants.A) && (chr <= Constants.Z)) {
+                chr = (byte) (chr - Constants.LC_OFFSET);
+            }
+
+            if (chr == Constants.COLON) {
+                colon = true;
+            } else {
+                trailingHeaders.append(chr);
+            }
+
+            readChunk.position(readChunk.position() + 1);
+
+        }
+        int colonPos = trailingHeaders.getEnd();
+
+        //
+        // Reading the header value (which can be spanned over multiple lines)
+        //
+
+        boolean eol = false;
+        boolean validLine = true;
+        int lastSignificantChar = 0;
+
+        while (validLine) {
+
+            boolean space = true;
+
+            // Skipping spaces
+            while (space) {
+
+                // Read new bytes if needed
+                if (readChunk == null || readChunk.position() >= readChunk.limit()) {
+                    if (readBytes() <0) {
+                        throwEOFException(sm.getString("chunkedInputFilter.eosTrailer"));
+                    }
+                }
+
+                chr = readChunk.get(readChunk.position());
+                if ((chr == Constants.SP) || (chr == Constants.HT)) {
+                    readChunk.position(readChunk.position() + 1);
+                    // If we swallow whitespace, make sure it counts towards the
+                    // limit placed on trailing header size
+                    int newlimit = trailingHeaders.getLimit() -1;
+                    if (trailingHeaders.getEnd() > newlimit) {
+                        throwIOException(sm.getString("chunkedInputFilter.maxTrailer"));
+                    }
+                    trailingHeaders.setLimit(newlimit);
+                } else {
+                    space = false;
+                }
+
+            }
+
+            // Reading bytes until the end of the line
+            while (!eol) {
+
+                // Read new bytes if needed
+                if (readChunk == null || readChunk.position() >= readChunk.limit()) {
+                    if (readBytes() <0) {
+                        throwEOFException(sm.getString("chunkedInputFilter.eosTrailer"));
+                    }
+                }
+
+                chr = readChunk.get(readChunk.position());
+                if (chr == Constants.CR || chr == Constants.LF) {
+                    parseCRLF(true);
+                    eol = true;
+                } else if (chr == Constants.SP) {
+                    trailingHeaders.append(chr);
+                } else {
+                    trailingHeaders.append(chr);
+                    lastSignificantChar = trailingHeaders.getEnd();
+                }
+
+                if (!eol) {
+                    readChunk.position(readChunk.position() + 1);
+                }
+            }
+
+            // Checking the first character of the new line. If the character
+            // is a LWS, then it's a multiline header
+
+            // Read new bytes if needed
+            if (readChunk == null || readChunk.position() >= readChunk.limit()) {
+                if (readBytes() <0) {
+                    throwEOFException(sm.getString("chunkedInputFilter.eosTrailer"));
+                }
+            }
+
+            chr = readChunk.get(readChunk.position());
+            if ((chr != Constants.SP) && (chr != Constants.HT)) {
+                validLine = false;
+            } else {
+                eol = false;
+                // Copying one extra space in the buffer (since there must
+                // be at least one space inserted between the lines)
+                trailingHeaders.append(chr);
+            }
+
+        }
+
+        String headerName = new String(trailingHeaders.getBytes(), startPos,
+                colonPos - startPos, StandardCharsets.ISO_8859_1);
+
+        headerName = headerName.toLowerCase(Locale.ENGLISH);
+
+        if (allowedTrailerHeaders.contains(headerName)) {
+
+            String value = new String(trailingHeaders.getBytes(), colonPos,
+                    lastSignificantChar - colonPos, StandardCharsets.ISO_8859_1);
+
+            headers.put(headerName, value);
+        }
+
+        return true;
+    }
+
+
+    private void throwIOException(String msg) throws IOException {
+        error = true;
+        throw new IOException(msg);
+    }
+
+
+    private void throwEOFException(String msg) throws IOException {
+        error = true;
+        throw new EOFException(msg);
+    }
+
+
+    private void checkError() throws IOException {
+        if (error) {
+            throw new IOException(sm.getString("chunkedInputFilter.error"));
+        }
+    }
+
+
+    @Override
+    public void setByteBuffer(ByteBuffer buffer) {
+        readChunk = buffer;
+    }
+
+
+    @Override
+    public ByteBuffer getByteBuffer() {
+        return readChunk;
+    }
+
+
+    @Override
+    public void expand(int size) {
+        // no-op
+    }
+}
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/filters/LocalStrings.properties b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/filters/LocalStrings.properties
new file mode 100644
index 0000000000..c0dc9d1b10
--- /dev/null
+++ b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/filters/LocalStrings.properties
@@ -0,0 +1,27 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+chunkedInputFilter.eos=Unexpected end of stream while reading request body
+chunkedInputFilter.eosTrailer=Unexpected end of stream while reading trailer headers
+chunkedInputFilter.error=No data available due to previous error
+chunkedInputFilter.invalidCrlf=Invalid end of line sequence (character other than CR or LF found)
+chunkedInputFilter.invalidCrlfCRCR=Invalid end of line sequence (CRCR)
+chunkedInputFilter.invalidCrlfNoCR=Invalid end of line sequence (No CR before LF)
+chunkedInputFilter.invalidCrlfNoData=Invalid end of line sequence (no data available to read)
+chunkedInputFilter.invalidHeader=Invalid chunk header
+chunkedInputFilter.maxExtension=maxExtensionSize exceeded
+chunkedInputFilter.maxTrailer=maxTrailerSize exceeded
+
+inputFilter.maxSwallow=maxSwallowSize exceeded


[tomee] 02/06: TOMEE-4255 - Add patched classes from https://github.com/apache/tomcat/commit/76bb4bfbfeae827dce896f650655bbf6e251ed49#diff-9105b119c42abec1b9a22cd5d6fc2c0b4edc63175a12858b8b383fb7554ab57f for CVE-2023-44487.

Posted by rz...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rzo1 pushed a commit to branch tomee-9.x
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 87136d0eac5cf06a75eb94325ffa328455b4860c
Author: Richard Zowalla <rz...@apache.org>
AuthorDate: Wed Oct 11 09:02:02 2023 +0200

    TOMEE-4255 - Add patched classes from https://github.com/apache/tomcat/commit/76bb4bfbfeae827dce896f650655bbf6e251ed49#diff-9105b119c42abec1b9a22cd5d6fc2c0b4edc63175a12858b8b383fb7554ab57f for CVE-2023-44487.
---
 .../org/apache/coyote/http2/Http2AsyncParser.java  | 51 ++++++++++++----------
 .../org/apache/coyote/http2/Http2Protocol.java     | 18 ++++++++
 .../apache/coyote/http2/Http2UpgradeHandler.java   |  8 +++-
 3 files changed, 52 insertions(+), 25 deletions(-)

diff --git a/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2AsyncParser.java b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2AsyncParser.java
index d01497051d..6e6065fcf6 100644
--- a/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2AsyncParser.java
+++ b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2AsyncParser.java
@@ -278,36 +278,39 @@ class Http2AsyncParser extends Http2Parser {
                                 readUnknownFrame(streamId, frameTypeId, flags, payloadSize, payload);
                             }
                         }
-                        // See if there is a new 9 byte header and continue parsing if possible
-                        if (payload.remaining() >= 9) {
-                            int position = payload.position();
-                            payloadSize = ByteUtil.getThreeBytes(payload, position);
-                            frameTypeId = ByteUtil.getOneByte(payload, position + 3);
-                            frameType = FrameType.valueOf(frameTypeId);
-                            flags = ByteUtil.getOneByte(payload, position + 4);
-                            streamId = ByteUtil.get31Bits(payload, position + 5);
-                            streamException = false;
-                            if (payload.remaining() - 9 >= payloadSize) {
-                                continueParsing = true;
-                                // Now go over frame header
-                                payload.position(payload.position() + 9);
-                                try {
-                                    validateFrame(null, frameType, streamId, flags, payloadSize);
-                                } catch (StreamException e) {
-                                    error = e;
-                                    streamException = true;
-                                } catch (Http2Exception e) {
-                                    error = e;
-                                    continueParsing = false;
+                        if (!upgradeHandler.isOverheadLimitExceeded()) {
+                            // See if there is a new 9 byte header and continue parsing if possible
+                            if (payload.remaining() >= 9) {
+                                int position = payload.position();
+                                payloadSize = ByteUtil.getThreeBytes(payload, position);
+                                frameTypeId = ByteUtil.getOneByte(payload, position + 3);
+                                frameType = FrameType.valueOf(frameTypeId);
+                                flags = ByteUtil.getOneByte(payload, position + 4);
+                                streamId = ByteUtil.get31Bits(payload, position + 5);
+                                streamException = false;
+                                if (payload.remaining() - 9 >= payloadSize) {
+                                    continueParsing = true;
+                                    // Now go over frame header
+                                    payload.position(payload.position() + 9);
+                                    try {
+                                        validateFrame(null, frameType, streamId, flags, payloadSize);
+                                    } catch (StreamException e) {
+                                        error = e;
+                                        streamException = true;
+                                    } catch (Http2Exception e) {
+                                        error = e;
+                                        continueParsing = false;
+                                    }
                                 }
                             }
                         }
                     } while (continueParsing);
                 } catch (RuntimeException | IOException | Http2Exception e) {
                     error = e;
-                }
-                if (payload.hasRemaining()) {
-                    socketWrapper.unRead(payload);
+                } finally {
+                    if (payload.hasRemaining()) {
+                        socketWrapper.unRead(payload);
+                    }
                 }
             }
             if (state == CompletionState.DONE) {
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2Protocol.java b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2Protocol.java
index 46b49d926c..6ff1670388 100644
--- a/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2Protocol.java
+++ b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2Protocol.java
@@ -55,7 +55,10 @@ public class Http2Protocol implements UpgradeProtocol {
     // a single connection
     static final int DEFAULT_MAX_CONCURRENT_STREAM_EXECUTION = 20;
 
+    // Default factor used when adjusting overhead count for overhead frames
     static final int DEFAULT_OVERHEAD_COUNT_FACTOR = 10;
+    // Default factor used when adjusting overhead count for reset frames
+    static final int DEFAULT_OVERHEAD_RESET_FACTOR = 50;
     // Not currently configurable. This makes the practical limit for
     // overheadCountFactor to be ~20. The exact limit will vary with traffic
     // patterns.
@@ -86,6 +89,7 @@ public class Http2Protocol implements UpgradeProtocol {
     private int maxHeaderCount = Constants.DEFAULT_MAX_HEADER_COUNT;
     private int maxTrailerCount = Constants.DEFAULT_MAX_TRAILER_COUNT;
     private int overheadCountFactor = DEFAULT_OVERHEAD_COUNT_FACTOR;
+    private int overheadResetFactor = DEFAULT_OVERHEAD_RESET_FACTOR;
     private int overheadContinuationThreshold = DEFAULT_OVERHEAD_CONTINUATION_THRESHOLD;
     private int overheadDataThreshold = DEFAULT_OVERHEAD_DATA_THRESHOLD;
     private int overheadWindowUpdateThreshold = DEFAULT_OVERHEAD_WINDOW_UPDATE_THRESHOLD;
@@ -292,6 +296,20 @@ public class Http2Protocol implements UpgradeProtocol {
     }
 
 
+    public int getOverheadResetFactor() {
+        return overheadResetFactor;
+    }
+
+
+    public void setOverheadResetFactor(int overheadResetFactor) {
+        if (overheadResetFactor < 0) {
+            this.overheadResetFactor = 0;
+        } else {
+            this.overheadResetFactor = overheadResetFactor;
+        }
+    }
+
+
     public int getOverheadContinuationThreshold() {
         return overheadContinuationThreshold;
     }
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2UpgradeHandler.java b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2UpgradeHandler.java
index 549594354d..aeed5e6f8d 100644
--- a/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2UpgradeHandler.java
+++ b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http2/Http2UpgradeHandler.java
@@ -381,7 +381,7 @@ class Http2UpgradeHandler extends AbstractStream implements InternalHttpUpgradeH
                                 stream.close(se);
                             }
                         } finally {
-                            if (overheadCount.get() > 0) {
+                            if (isOverheadLimitExceeded()) {
                                 throw new ConnectionException(
                                         sm.getString("upgradeHandler.tooMuchOverhead", connectionId),
                                         Http2Error.ENHANCE_YOUR_CALM);
@@ -1495,6 +1495,11 @@ class Http2UpgradeHandler extends AbstractStream implements InternalHttpUpgradeH
     }
 
 
+    boolean isOverheadLimitExceeded() {
+        return overheadCount.get() > 0;
+    }
+
+
     // ----------------------------------------------- Http2Parser.Input methods
 
     @Override
@@ -1768,6 +1773,7 @@ class Http2UpgradeHandler extends AbstractStream implements InternalHttpUpgradeH
             log.debug(sm.getString("upgradeHandler.reset.receive", getConnectionId(), Integer.toString(streamId),
                     Long.toString(errorCode)));
         }
+        increaseOverheadCount(FrameType.RST, getProtocol().getOverheadResetFactor());
         AbstractNonZeroStream abstractNonZeroStream = getAbstractNonZeroStream(streamId, true);
         abstractNonZeroStream.checkState(FrameType.RST);
         if (abstractNonZeroStream instanceof Stream) {


[tomee] 04/06: TOMEE-4256 - Add patched classes from https://github.com/apache/tomcat/commit/8ecff306507be8e4fd3adee1ae5de1ea6661a8f4 for CVE-2023-45648

Posted by rz...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rzo1 pushed a commit to branch tomee-9.x
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit e0b4d659c90f44d68f1bb1fb0cac72282f8b51fd
Author: Richard Zowalla <rz...@apache.org>
AuthorDate: Wed Oct 11 09:07:06 2023 +0200

    TOMEE-4256 - Add patched classes from https://github.com/apache/tomcat/commit/8ecff306507be8e4fd3adee1ae5de1ea6661a8f4 for CVE-2023-45648
---
 .../java/org/apache/coyote/http11/Http11InputBuffer.java  |  2 +-
 .../apache/coyote/http11/filters/ChunkedInputFilter.java  | 15 ++++++++++++++-
 .../apache/coyote/http11/filters/LocalStrings.properties  |  2 ++
 3 files changed, 17 insertions(+), 2 deletions(-)

diff --git a/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/Http11InputBuffer.java b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/Http11InputBuffer.java
index ddd7e2d1e2..385fbfefb0 100644
--- a/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/Http11InputBuffer.java
+++ b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/Http11InputBuffer.java
@@ -989,7 +989,7 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler
                     } else if (prevChr == Constants.CR) {
                         // Invalid value - also need to delete header
                         return skipLine(true);
-                    } else if (chr != Constants.HT && HttpParser.isControl(chr)) {
+                    } else if (HttpParser.isControl(chr) && chr != Constants.HT) {
                         // Invalid value - also need to delete header
                         return skipLine(true);
                     } else if (chr == Constants.SP || chr == Constants.HT) {
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/filters/ChunkedInputFilter.java b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
index 586d070f4d..e2fdb0ae2e 100644
--- a/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
+++ b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
@@ -30,6 +30,7 @@ import org.apache.coyote.http11.Constants;
 import org.apache.coyote.http11.InputFilter;
 import org.apache.tomcat.util.buf.ByteChunk;
 import org.apache.tomcat.util.buf.HexUtils;
+import org.apache.tomcat.util.http.parser.HttpParser;
 import org.apache.tomcat.util.net.ApplicationBufferHandler;
 import org.apache.tomcat.util.res.StringManager;
 
@@ -444,6 +445,13 @@ public class ChunkedInputFilter implements InputFilter, ApplicationBufferHandler
 
     private boolean parseHeader() throws IOException {
 
+        /*
+         * Implementation note: Any changes to this method probably need to be echoed in
+         * Http11InputBuffer.parseHeader(). Why not use a common implementation? In short, this code uses blocking
+         * reads whereas Http11InputBuffer using non-blocking reads. The code is just different enough that a common
+         * implementation wasn't viewed as practical.
+         */
+
         Map<String,String> headers = request.getTrailerFields();
 
         byte chr = 0;
@@ -490,6 +498,9 @@ public class ChunkedInputFilter implements InputFilter, ApplicationBufferHandler
 
             if (chr == Constants.COLON) {
                 colon = true;
+            } else if (!HttpParser.isToken(chr)) {
+                // Non-token characters are illegal in header names
+                throw new IOException(sm.getString("chunkedInputFilter.invalidTrailerHeaderName"));
             } else {
                 trailingHeaders.append(chr);
             }
@@ -551,7 +562,9 @@ public class ChunkedInputFilter implements InputFilter, ApplicationBufferHandler
                 if (chr == Constants.CR || chr == Constants.LF) {
                     parseCRLF(true);
                     eol = true;
-                } else if (chr == Constants.SP) {
+                } else if (HttpParser.isControl(chr) && chr != Constants.HT) {
+                    throw new IOException(sm.getString("chunkedInputFilter.invalidTrailerHeaderValue"));
+                } else if (chr == Constants.SP || chr == Constants.HT) {
                     trailingHeaders.append(chr);
                 } else {
                     trailingHeaders.append(chr);
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/filters/LocalStrings.properties b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/filters/LocalStrings.properties
index c0dc9d1b10..aa1b19d839 100644
--- a/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/filters/LocalStrings.properties
+++ b/tomee/apache-tomee/src/patch/java/org/apache/coyote/http11/filters/LocalStrings.properties
@@ -21,6 +21,8 @@ chunkedInputFilter.invalidCrlfCRCR=Invalid end of line sequence (CRCR)
 chunkedInputFilter.invalidCrlfNoCR=Invalid end of line sequence (No CR before LF)
 chunkedInputFilter.invalidCrlfNoData=Invalid end of line sequence (no data available to read)
 chunkedInputFilter.invalidHeader=Invalid chunk header
+chunkedInputFilter.invalidTrailerHeaderName=Invalid trailer header name (non-token character in name)
+chunkedInputFilter.invalidTrailerHeaderValue=Invalid trailer header value (control character in value)
 chunkedInputFilter.maxExtension=maxExtensionSize exceeded
 chunkedInputFilter.maxTrailer=maxTrailerSize exceeded