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 2024/03/27 09:21:57 UTC
(tomee) 01/02: Drop Tomcat 10.0.x Patching and upgrade to Tomcat 10.1.x
This is an automated email from the ASF dual-hosted git repository.
rzo1 pushed a commit to branch experimental/tomee-9.x-with-tomcat-10.1x
in repository https://gitbox.apache.org/repos/asf/tomee.git
commit aa77d77e7d957b5bf2d134c684a1afcafa75fb97
Author: Richard Zowalla <rz...@apache.org>
AuthorDate: Wed Mar 27 10:15:21 2024 +0100
Drop Tomcat 10.0.x Patching and upgrade to Tomcat 10.1.x
---
pom.xml | 2 +-
tomee/apache-tomee/pom.xml | 68 -
.../patch/java/org/apache/catalina/Globals.java | 298 --
.../catalina/authenticator/FormAuthenticator.java | 739 ----
.../authenticator/jaspic/CallbackHandlerImpl.java | 163 -
.../catalina/connector/ClientAbortException.java | 73 -
.../org/apache/catalina/connector/InputBuffer.java | 681 ----
.../catalina/connector/LocalStrings.properties | 96 -
.../org/apache/catalina/connector/Request.java | 3604 --------------------
.../catalina/core/ApplicationDispatcher.java | 1036 ------
.../catalina/core/ApplicationHttpRequest.java | 1001 ------
.../apache/catalina/core/LocalStrings.properties | 313 --
.../apache/catalina/core/StandardHostValve.java | 406 ---
.../apache/catalina/core/StandardWrapperValve.java | 369 --
.../apache/catalina/filters/RemoteIpFilter.java | 1334 --------
.../apache/catalina/servlets/DefaultServlet.java | 3054 -----------------
.../java/org/apache/catalina/util/ServerInfo.java | 148 -
.../org/apache/coyote/BadRequestException.java | 68 -
.../java/org/apache/coyote/ajp/AjpProcessor.java | 1339 --------
.../org/apache/coyote/ajp/LocalStrings.properties | 35 -
.../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 --
.../java/org/apache/coyote/http2/Http2Parser.java | 840 -----
.../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 -
.../org/apache/tomcat/util/http/Parameters.java | 526 ---
.../util/http/fileupload/FileUploadBase.java | 586 ----
.../impl/FileCountLimitExceededException.java | 50 -
.../apache/tomcat/util/log/SystemLogHandler.java | 278 --
.../org/apache/tomcat/websocket/Constants.java | 185 -
.../org/apache/tomcat/websocket/WsSession.java | 1067 ------
.../tomcat/websocket/WsWebSocketContainer.java | 1166 -------
.../tomcat/websocket/server/WsServerContainer.java | 597 ----
.../apache/xbean/finder/archive/JarArchive.java | 268 --
.../tomee/catalina/LazyStopStandardRoot.java | 15 +
40 files changed, 16 insertions(+), 25668 deletions(-)
diff --git a/pom.xml b/pom.xml
index 6480a5e337..5dddd1e4cd 100644
--- a/pom.xml
+++ b/pom.xml
@@ -202,7 +202,7 @@
<version.geronimo-mail_2.1_spec>1.0.0-M1</version.geronimo-mail_2.1_spec>
<!-- Jakarta EE Impl. -->
- <tomcat.version>10.0.27</tomcat.version>
+ <tomcat.version>10.1.19</tomcat.version>
<!-- com.sun -->
<version.impl.saaj>2.0.1</version.impl.saaj>
<!-- org.apache -->
diff --git a/tomee/apache-tomee/pom.xml b/tomee/apache-tomee/pom.xml
index e9016be1bd..a66213e1ca 100644
--- a/tomee/apache-tomee/pom.xml
+++ b/tomee/apache-tomee/pom.xml
@@ -146,17 +146,6 @@
<scope>runtime</scope>
</dependency>
-
-
-
- <!-- needed to compile in intellij for tomcat patches -->
- <dependency>
- <groupId>org.apache.tomcat</groupId>
- <artifactId>tomcat-catalina</artifactId>
- <version>${tomcat.version}</version>
- <scope>provided</scope>
- </dependency>
-
<!-- needed for BOM generation -->
<dependency>
<groupId>org.projectlombok</groupId>
@@ -572,37 +561,6 @@
</execution>
</executions>
</plugin>
- <plugin>
- <groupId>org.apache.tomee.patch</groupId>
- <artifactId>tomee-patch-plugin</artifactId>
- <configuration>
- <select>apache-tomee-(plus|plume|webprofile|microprofile).*\.zip</select>
- <skipTransform>true</skipTransform>
- <createTarGz>true</createTarGz>
- <skips>
- <jars>
- <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>
- <add>
- <resources>
- <tomcat-coyote.jar>.*BadRequestException.*</tomcat-coyote.jar>
- </resources>
- </add>
- </configuration>
- <executions>
- <execution>
- <goals>
- <goal>run</goal>
- </goals>
- <phase>package</phase>
- </execution>
- </executions>
- </plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
@@ -812,32 +770,6 @@
</execution>
</executions>
</plugin>
- <plugin>
- <groupId>org.apache.tomee.patch</groupId>
- <artifactId>tomee-patch-plugin</artifactId>
- <configuration>
- <select>apache-tomee-(plus|plume|webprofile|microprofile).*\.zip</select>
- <skipTransform>true</skipTransform>
- <createTarGz>true</createTarGz>
- <skips>
- <jars>
- <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>
- <executions>
- <execution>
- <goals>
- <goal>run</goal>
- </goals>
- <phase>package</phase>
- </execution>
- </executions>
- </plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/catalina/Globals.java b/tomee/apache-tomee/src/patch/java/org/apache/catalina/Globals.java
deleted file mode 100644
index c56a177d38..0000000000
--- a/tomee/apache-tomee/src/patch/java/org/apache/catalina/Globals.java
+++ /dev/null
@@ -1,298 +0,0 @@
-/*
- * 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;
-
-/**
- * Global constants that are applicable to multiple packages within Catalina.
- *
- * @author Craig R. McClanahan
- */
-public final class Globals {
-
- // ------------------------------------------------- Request attribute names
-
- public static final String ASYNC_SUPPORTED_ATTR = "org.apache.catalina.ASYNC_SUPPORTED";
-
-
- public static final String GSS_CREDENTIAL_ATTR = "org.apache.catalina.realm.GSS_CREDENTIAL";
-
-
- /**
- * Request dispatcher state.
- */
- public static final String DISPATCHER_TYPE_ATTR = "org.apache.catalina.core.DISPATCHER_TYPE";
-
-
- /**
- * Request dispatcher path.
- */
- public static final String DISPATCHER_REQUEST_PATH_ATTR = "org.apache.catalina.core.DISPATCHER_REQUEST_PATH";
-
-
- /**
- * The request attribute under which we store the servlet name on a
- * named dispatcher request.
- */
- public static final String NAMED_DISPATCHER_ATTR = "org.apache.catalina.NAMED";
-
-
- /**
- * The request attribute used to expose the current connection ID associated
- * with the request, if any. Used with multiplexing protocols such as
- * HTTTP/2.
- */
- public static final String CONNECTION_ID = "org.apache.coyote.connectionID";
-
-
- /**
- * The request attribute used to expose the current stream ID associated
- * with the request, if any. Used with multiplexing protocols such as
- * HTTTP/2.
- */
- public static final String STREAM_ID = "org.apache.coyote.streamID";
-
-
- /**
- * The request attribute that is set to {@code Boolean.TRUE} if some request
- * parameters have been ignored during request parameters parsing. It can
- * happen, for example, if there is a limit on the total count of parseable
- * parameters, or if parameter cannot be decoded, or any other error
- * happened during parameter parsing.
- */
- public static final String PARAMETER_PARSE_FAILED_ATTR = "org.apache.catalina.parameter_parse_failed";
-
-
- /**
- * The reason that the parameter parsing failed.
- */
- public static final String PARAMETER_PARSE_FAILED_REASON_ATTR = "org.apache.catalina.parameter_parse_failed_reason";
-
-
- /**
- * The request attribute set by the RemoteIpFilter, RemoteIpValve (and may
- * be set by other similar components) that identifies for the connector the
- * remote IP address claimed to be associated with this request when a
- * request is received via one or more proxies. It is typically provided via
- * the X-Forwarded-For HTTP header.
- *
- * Duplicated here for neater code in the catalina packages.
- */
- public static final String REMOTE_ADDR_ATTRIBUTE = org.apache.coyote.Constants.REMOTE_ADDR_ATTRIBUTE;
-
-
- /**
- * The request attribute that is set to the value of {@code Boolean.TRUE}
- * by the RemoteIpFilter, RemoteIpValve (and other similar components) that identifies
- * a request which been forwarded via one or more proxies.
- */
- public static final String REQUEST_FORWARDED_ATTRIBUTE = "org.apache.tomcat.request.forwarded";
-
-
- /**
- * The request attribute that is set to the value of {@code Boolean.TRUE}
- * if connector processing this request supports use of sendfile.
- *
- * Duplicated here for neater code in the catalina packages.
- */
- public static final String SENDFILE_SUPPORTED_ATTR = org.apache.coyote.Constants.SENDFILE_SUPPORTED_ATTR;
-
-
- /**
- * The request attribute that is set to the value of {@code Boolean.TRUE}
- * if {@link org.apache.catalina.filters.RemoteIpFilter} determines
- * that this request was submitted via a secure channel.
- */
- public static final String REMOTE_IP_FILTER_SECURE = "org.apache.catalina.filters.RemoteIpFilter.secure";
-
- /**
- * The request attribute that can be used by a servlet to pass
- * to the connector the name of the file that is to be served
- * by sendfile. The value should be {@code java.lang.String}
- * that is {@code File.getCanonicalPath()} of the file to be served.
- *
- * Duplicated here for neater code in the catalina packages.
- */
- public static final String SENDFILE_FILENAME_ATTR = org.apache.coyote.Constants.SENDFILE_FILENAME_ATTR;
-
-
- /**
- * The request attribute that can be used by a servlet to pass
- * to the connector the start offset of the part of a file
- * that is to be served by sendfile. The value should be
- * {@code java.lang.Long}. To serve complete file
- * the value should be {@code Long.valueOf(0)}.
- *
- * Duplicated here for neater code in the catalina packages.
- */
- public static final String SENDFILE_FILE_START_ATTR = org.apache.coyote.Constants.SENDFILE_FILE_START_ATTR;
-
-
- /**
- * The request attribute that can be used by a servlet to pass
- * to the connector the end offset (not including) of the part
- * of a file that is to be served by sendfile. The value should be
- * {@code java.lang.Long}. To serve complete file
- * the value should be equal to the length of the file.
- *
- * Duplicated here for neater code in the catalina packages.
- */
- public static final String SENDFILE_FILE_END_ATTR = org.apache.coyote.Constants.SENDFILE_FILE_END_ATTR;
-
-
- /**
- * The request attribute under which we store the array of X509Certificate
- * objects representing the certificate chain presented by our client,
- * if any.
- */
- public static final String CERTIFICATES_ATTR = "jakarta.servlet.request.X509Certificate";
-
-
- /**
- * The request attribute under which we store the name of the cipher suite
- * being used on an SSL connection (as an object of type
- * java.lang.String).
- */
- public static final String CIPHER_SUITE_ATTR = "jakarta.servlet.request.cipher_suite";
-
-
- /**
- * The request attribute under which we store the key size being used for
- * this SSL connection (as an object of type java.lang.Integer).
- */
- public static final String KEY_SIZE_ATTR = "jakarta.servlet.request.key_size";
-
-
- /**
- * The request attribute under which we store the session id being used
- * for this SSL connection (as an object of type java.lang.String).
- */
- public static final String SSL_SESSION_ID_ATTR = "jakarta.servlet.request.ssl_session_id";
-
-
- /**
- * The request attribute key for the session manager.
- * This one is a Tomcat extension to the Servlet spec.
- */
- public static final String SSL_SESSION_MGR_ATTR = "jakarta.servlet.request.ssl_session_mgr";
-
-
- // ------------------------------------------------- Session attribute names
-
- /**
- * The subject under which the AccessControlContext is running.
- */
- public static final String SUBJECT_ATTR = "javax.security.auth.subject";
-
-
- // ------------------------------------------ ServletContext attribute names
-
- /**
- * The servlet context attribute under which we store the alternate
- * deployment descriptor for this web application
- */
- public static final String ALT_DD_ATTR = "org.apache.catalina.deploy.alt_dd";
-
-
- /**
- * The servlet context attribute under which we store the class path
- * for our application class loader (as an object of type String),
- * delimited with the appropriate path delimiter for this platform.
- */
- public static final String CLASS_PATH_ATTR = "org.apache.catalina.jsp_classpath";
-
-
- /**
- * Name of the ServletContext attribute under which we store the context
- * Realm's CredentialHandler (if both the Realm and the CredentialHandler
- * exist).
- */
- public static final String CREDENTIAL_HANDLER = "org.apache.catalina.CredentialHandler";
-
-
- /**
- * The WebResourceRoot which is associated with the context. This can be
- * used to manipulate static files.
- */
- public static final String RESOURCES_ATTR = "org.apache.catalina.resources";
-
-
- /**
- * Name of the ServletContext attribute under which we store the web
- * application version string (the text that appears after ## when parallel
- * deployment is used).
- */
- public static final String WEBAPP_VERSION = "org.apache.catalina.webappVersion";
-
-
- // --------------------------- ServletContext initialisation parameter names
-
- /**
- * Name of the ServletContext init-param that determines if the JSP engine
- * should validate *.tld files when parsing them.
- * <p>
- * This must be kept in sync with org.apache.jasper.Constants
- */
- public static final String JASPER_XML_VALIDATION_TLD_INIT_PARAM = "org.apache.jasper.XML_VALIDATE_TLD";
-
-
- /**
- * Name of the ServletContext init-param that determines if the JSP engine
- * will block external entities from being used in *.tld, *.jspx, *.tagx and
- * tagplugin.xml files.
- * <p>
- * This must be kept in sync with org.apache.jasper.Constants
- */
- public static final String JASPER_XML_BLOCK_EXTERNAL_INIT_PARAM = "org.apache.jasper.XML_BLOCK_EXTERNAL";
-
-
- // --------------------------------------------------- System property names
-
- /**
- * Name of the system property containing
- * the tomcat product installation path
- */
- public static final String CATALINA_HOME_PROP = org.apache.catalina.startup.Constants.CATALINA_HOME_PROP;
-
-
- /**
- * Name of the system property containing
- * the tomcat instance installation path
- */
- public static final String CATALINA_BASE_PROP = org.apache.catalina.startup.Constants.CATALINA_BASE_PROP;
-
-
- // -------------------------------------------------------- Global constants
-
- /**
- * The flag which controls strict servlet specification compliance. Setting
- * this flag to {@code true} will change the defaults for other settings.
- */
- public static final boolean STRICT_SERVLET_COMPLIANCE =
- Boolean.parseBoolean(System.getProperty("org.apache.catalina.STRICT_SERVLET_COMPLIANCE", "false"));
-
-
- /**
- * Has security been turned on?
- */
- public static final boolean IS_SECURITY_ENABLED = (System.getSecurityManager() != null);
-
-
- /**
- * Default domain for MBeans if none can be determined
- */
- public static final String DEFAULT_MBEAN_DOMAIN = "Catalina";
-}
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/catalina/authenticator/FormAuthenticator.java b/tomee/apache-tomee/src/patch/java/org/apache/catalina/authenticator/FormAuthenticator.java
deleted file mode 100644
index 0e95e2c08d..0000000000
--- a/tomee/apache-tomee/src/patch/java/org/apache/catalina/authenticator/FormAuthenticator.java
+++ /dev/null
@@ -1,739 +0,0 @@
-/*
- * 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.authenticator;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.Principal;
-import java.util.Enumeration;
-import java.util.Iterator;
-import java.util.Locale;
-
-import jakarta.servlet.RequestDispatcher;
-import jakarta.servlet.http.Cookie;
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
-
-import org.apache.catalina.Realm;
-import org.apache.catalina.Session;
-import org.apache.catalina.connector.Request;
-import org.apache.catalina.connector.Response;
-import org.apache.coyote.ActionCode;
-import org.apache.coyote.ContinueResponseTiming;
-import org.apache.juli.logging.Log;
-import org.apache.juli.logging.LogFactory;
-import org.apache.tomcat.util.ExceptionUtils;
-import org.apache.tomcat.util.buf.ByteChunk;
-import org.apache.tomcat.util.buf.MessageBytes;
-import org.apache.tomcat.util.descriptor.web.LoginConfig;
-import org.apache.tomcat.util.http.MimeHeaders;
-
-/**
- * An <b>Authenticator</b> and <b>Valve</b> implementation of FORM BASED
- * Authentication, as described in the Servlet API Specification.
- *
- * @author Craig R. McClanahan
- * @author Remy Maucherat
- */
-public class FormAuthenticator
- extends AuthenticatorBase {
-
- private final Log log = LogFactory.getLog(FormAuthenticator.class); // must not be static
-
-
- // ----------------------------------------------------- Instance Variables
-
- /**
- * Character encoding to use to read the username and password parameters
- * from the request. If not set, the encoding of the request body will be
- * used.
- */
- protected String characterEncoding = null;
-
- /**
- * Landing page to use if a user tries to access the login page directly or
- * if the session times out during login. If not set, error responses will
- * be sent instead.
- */
- protected String landingPage = null;
-
-
- // ------------------------------------------------------------- Properties
-
- /**
- * Return the character encoding to use to read the user name and password.
- *
- * @return The name of the character encoding
- */
- public String getCharacterEncoding() {
- return characterEncoding;
- }
-
-
- /**
- * Set the character encoding to be used to read the user name and password.
- *
- * @param encoding The name of the encoding to use
- */
- public void setCharacterEncoding(String encoding) {
- characterEncoding = encoding;
- }
-
-
- /**
- * Return the landing page to use when FORM auth is mis-used.
- *
- * @return The path to the landing page relative to the web application root
- */
- public String getLandingPage() {
- return landingPage;
- }
-
-
- /**
- * Set the landing page to use when the FORM auth is mis-used.
- *
- * @param landingPage The path to the landing page relative to the web
- * application root
- */
- public void setLandingPage(String landingPage) {
- this.landingPage = landingPage;
- }
-
-
- // ------------------------------------------------------ Protected Methods
-
-
- /**
- * Authenticate the user making this request, based on the specified
- * login configuration. Return <code>true</code> if any specified
- * constraint has been satisfied, or <code>false</code> if we have
- * created a response challenge already.
- *
- * @param request Request we are processing
- * @param response Response we are creating
- *
- * @exception IOException if an input/output error occurs
- */
- @Override
- protected boolean doAuthenticate(Request request, HttpServletResponse response)
- throws IOException {
-
- // References to objects we will need later
- Session session = null;
- Principal principal = null;
-
- // Have we authenticated this user before but have caching disabled?
- if (!cache) {
- session = request.getSessionInternal(true);
- if (log.isDebugEnabled()) {
- log.debug("Checking for reauthenticate in session " + session);
- }
- String username = (String) session.getNote(Constants.SESS_USERNAME_NOTE);
- String password = (String) session.getNote(Constants.SESS_PASSWORD_NOTE);
- if (username != null && password != null) {
- if (log.isDebugEnabled()) {
- log.debug("Reauthenticating username '" + username + "'");
- }
- principal = context.getRealm().authenticate(username, password);
- if (principal != null) {
- register(request, response, principal, HttpServletRequest.FORM_AUTH, username, password);
- if (!matchRequest(request)) {
- return true;
- }
- }
- if (log.isDebugEnabled()) {
- log.debug("Reauthentication failed, proceed normally");
- }
- }
- }
-
- // Is this the re-submit of the original request URI after successful
- // authentication? If so, forward the *original* request instead.
- if (matchRequest(request)) {
- session = request.getSessionInternal(true);
- if (log.isDebugEnabled()) {
- log.debug("Restore request from session '" + session.getIdInternal() + "'");
- }
- if (restoreRequest(request, session)) {
- if (log.isDebugEnabled()) {
- log.debug("Proceed to restored request");
- }
- return true;
- } else {
- if (log.isDebugEnabled()) {
- log.debug("Restore of original request failed");
- }
- response.sendError(HttpServletResponse.SC_BAD_REQUEST);
- return false;
- }
- }
-
- // This check has to be after the previous check for a matching request
- // because that matching request may also include a cached Principal.
- if (checkForCachedAuthentication(request, response, true)) {
- return true;
- }
-
- // Acquire references to objects we will need to evaluate
- String contextPath = request.getContextPath();
- String requestURI = request.getDecodedRequestURI();
-
- // Is this the action request from the login page?
- boolean loginAction = requestURI.startsWith(contextPath) && requestURI.endsWith(Constants.FORM_ACTION);
-
- LoginConfig config = context.getLoginConfig();
-
- // No -- Save this request and redirect to the form login page
- if (!loginAction) {
- // If this request was to the root of the context without a trailing
- // '/', need to redirect to add it else the submit of the login form
- // may not go to the correct web application
- if (request.getServletPath().length() == 0 && request.getPathInfo() == null) {
- StringBuilder location = new StringBuilder(requestURI);
- location.append('/');
- if (request.getQueryString() != null) {
- location.append('?');
- location.append(request.getQueryString());
- }
- response.sendRedirect(response.encodeRedirectURL(location.toString()));
- return false;
- }
-
- session = request.getSessionInternal(true);
- if (log.isDebugEnabled()) {
- log.debug("Save request in session '" + session.getIdInternal() + "'");
- }
- try {
- saveRequest(request, session);
- } catch (IOException ioe) {
- log.debug("Request body too big to save during authentication");
- response.sendError(HttpServletResponse.SC_FORBIDDEN, sm.getString("authenticator.requestBodyTooBig"));
- return false;
- }
- forwardToLoginPage(request, response, config);
- return false;
- }
-
- // Yes -- Acknowledge the request, validate the specified credentials
- // and redirect to the error page if they are not correct
- request.getResponse().sendAcknowledgement(ContinueResponseTiming.ALWAYS);
- Realm realm = context.getRealm();
- if (characterEncoding != null) {
- request.setCharacterEncoding(characterEncoding);
- }
- String username = request.getParameter(Constants.FORM_USERNAME);
- String password = request.getParameter(Constants.FORM_PASSWORD);
- if (log.isDebugEnabled()) {
- log.debug("Authenticating username '" + username + "'");
- }
- principal = realm.authenticate(username, password);
- if (principal == null) {
- forwardToErrorPage(request, response, config);
- return false;
- }
-
- if (log.isDebugEnabled()) {
- log.debug("Authentication of '" + username + "' was successful");
- }
-
- if (session == null) {
- session = request.getSessionInternal(false);
- }
- if (session != null && getChangeSessionIdOnAuthentication()) {
- // Does session id match?
- String expectedSessionId = (String) session.getNote(Constants.SESSION_ID_NOTE);
- if (expectedSessionId == null || !expectedSessionId.equals(request.getRequestedSessionId())) {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("formAuthenticator.sessionIdMismatch", session.getId(), expectedSessionId));
- }
- session.expire();
- session = null;
- }
- }
- if (session == null) {
- if (containerLog.isDebugEnabled()) {
- containerLog.debug("User took so long to log on the session expired");
- }
- if (landingPage == null) {
- response.sendError(
- HttpServletResponse.SC_REQUEST_TIMEOUT, sm.getString("authenticator.sessionExpired"));
- } else {
- // Make the authenticator think the user originally requested
- // the landing page
- String uri = request.getContextPath() + landingPage;
- SavedRequest saved = new SavedRequest();
- saved.setMethod("GET");
- saved.setRequestURI(uri);
- saved.setDecodedRequestURI(uri);
- request.getSessionInternal(true).setNote(Constants.FORM_REQUEST_NOTE, saved);
- response.sendRedirect(response.encodeRedirectURL(uri));
- }
- return false;
- }
-
- register(request, response, principal, HttpServletRequest.FORM_AUTH, username, password);
-
- // Redirect the user to the original request URI (which will cause
- // the original request to be restored)
- requestURI = savedRequestURL(session);
- if (log.isDebugEnabled()) {
- log.debug("Redirecting to original '" + requestURI + "'");
- }
- if (requestURI == null) {
- if (landingPage == null) {
- response.sendError(HttpServletResponse.SC_BAD_REQUEST, sm.getString("authenticator.formlogin"));
- } else {
- // Make the authenticator think the user originally requested
- // the landing page
- String uri = request.getContextPath() + landingPage;
- SavedRequest saved = new SavedRequest();
- saved.setMethod("GET");
- saved.setRequestURI(uri);
- saved.setDecodedRequestURI(uri);
- session.setNote(Constants.FORM_REQUEST_NOTE, saved);
- response.sendRedirect(response.encodeRedirectURL(uri));
- }
- } else {
- // Until the Servlet API allows specifying the type of redirect to
- // use.
- Response internalResponse = request.getResponse();
- String location = response.encodeRedirectURL(requestURI);
- if ("HTTP/1.1".equals(request.getProtocol())) {
- internalResponse.sendRedirect(location, HttpServletResponse.SC_SEE_OTHER);
- } else {
- internalResponse.sendRedirect(location, HttpServletResponse.SC_FOUND);
- }
- }
- return false;
- }
-
-
- @Override
- protected boolean isContinuationRequired(Request request) {
- // Special handling for form-based logins to deal with the case
- // where the login form (and therefore the "j_security_check" URI
- // to which it submits) might be outside the secured area
- String contextPath = this.context.getPath();
- String decodedRequestURI = request.getDecodedRequestURI();
- if (decodedRequestURI.startsWith(contextPath) &&
- decodedRequestURI.endsWith(Constants.FORM_ACTION)) {
- return true;
- }
-
- // Special handling for form-based logins to deal with the case where
- // a resource is protected for some HTTP methods but not protected for
- // GET which is used after authentication when redirecting to the
- // protected resource.
- // TODO: This is similar to the FormAuthenticator.matchRequest() logic
- // Is there a way to remove the duplication?
- Session session = request.getSessionInternal(false);
- if (session != null) {
- SavedRequest savedRequest = (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
- if (savedRequest != null &&
- decodedRequestURI.equals(savedRequest.getDecodedRequestURI())) {
- return true;
- }
- }
-
- return false;
- }
-
-
- @Override
- protected String getAuthMethod() {
- return HttpServletRequest.FORM_AUTH;
- }
-
-
- @Override
- protected void register(Request request, HttpServletResponse response,
- Principal principal, String authType, String username,
- String password, boolean alwaysUseSession, boolean cache) {
-
- super.register(request, response, principal, authType, username, password, alwaysUseSession, cache);
-
- // If caching an authenticated Principal is turned off,
- // store username and password as session notes to use them for re-authentication.
- if (!cache) {
- Session session = request.getSessionInternal(false);
- if (session != null) {
- if (username != null) {
- session.setNote(Constants.SESS_USERNAME_NOTE, username);
- } else {
- session.removeNote(Constants.SESS_USERNAME_NOTE);
- }
- if (password != null) {
- session.setNote(Constants.SESS_PASSWORD_NOTE, password);
- } else {
- session.removeNote(Constants.SESS_PASSWORD_NOTE);
- }
- }
- }
- }
-
-
- /**
- * Called to forward to the login page
- *
- * @param request Request we are processing
- * @param response Response we are populating
- * @param config Login configuration describing how authentication
- * should be performed
- * @throws IOException If the forward to the login page fails and the call
- * to {@link HttpServletResponse#sendError(int, String)}
- * throws an {@link IOException}
- */
- protected void forwardToLoginPage(Request request,
- HttpServletResponse response, LoginConfig config)
- throws IOException {
-
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("formAuthenticator.forwardLogin",
- request.getRequestURI(), request.getMethod(),
- config.getLoginPage(), context.getName()));
- }
-
- String loginPage = config.getLoginPage();
- if (loginPage == null || loginPage.length() == 0) {
- String msg = sm.getString("formAuthenticator.noLoginPage",
- context.getName());
- log.warn(msg);
- response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
- msg);
- return;
- }
-
- if (getChangeSessionIdOnAuthentication()) {
- Session session = request.getSessionInternal(false);
- if (session != null) {
- String oldSessionId = session.getId();
- String newSessionId = changeSessionID(request, session);
- session.setNote(Constants.SESSION_ID_NOTE, newSessionId);
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("formAuthenticator.changeSessionIdLogin", oldSessionId, newSessionId));
- }
- }
- }
-
- // Always use GET for the login page, regardless of the method used
- String oldMethod = request.getMethod();
- request.getCoyoteRequest().method().setString("GET");
-
- RequestDispatcher disp =
- context.getServletContext().getRequestDispatcher(loginPage);
- try {
- if (context.fireRequestInitEvent(request.getRequest())) {
- disp.forward(request.getRequest(), response);
- context.fireRequestDestroyEvent(request.getRequest());
- }
- } catch (Throwable t) {
- ExceptionUtils.handleThrowable(t);
- String msg = sm.getString("formAuthenticator.forwardLoginFail");
- log.warn(msg, t);
- request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t);
- response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
- msg);
- } finally {
- // Restore original method so that it is written into access log
- request.getCoyoteRequest().method().setString(oldMethod);
- }
- }
-
-
- /**
- * Called to forward to the error page
- *
- * @param request Request we are processing
- * @param response Response we are populating
- * @param config Login configuration describing how authentication
- * should be performed
- * @throws IOException If the forward to the error page fails and the call
- * to {@link HttpServletResponse#sendError(int, String)}
- * throws an {@link IOException}
- */
- protected void forwardToErrorPage(Request request,
- HttpServletResponse response, LoginConfig config)
- throws IOException {
-
- String errorPage = config.getErrorPage();
- if (errorPage == null || errorPage.length() == 0) {
- String msg = sm.getString("formAuthenticator.noErrorPage",
- context.getName());
- log.warn(msg);
- response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
- msg);
- return;
- }
-
- RequestDispatcher disp =
- context.getServletContext().getRequestDispatcher(config.getErrorPage());
- try {
- if (context.fireRequestInitEvent(request.getRequest())) {
- disp.forward(request.getRequest(), response);
- context.fireRequestDestroyEvent(request.getRequest());
- }
- } catch (Throwable t) {
- ExceptionUtils.handleThrowable(t);
- String msg = sm.getString("formAuthenticator.forwardErrorFail");
- log.warn(msg, t);
- request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t);
- response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
- msg);
- }
- }
-
-
- /**
- * Does this request match the saved one (so that it must be the redirect
- * we signaled after successful authentication?
- *
- * @param request The request to be verified
- * @return <code>true</code> if the requests matched the saved one
- */
- protected boolean matchRequest(Request request) {
- // Has a session been created?
- Session session = request.getSessionInternal(false);
- if (session == null) {
- return false;
- }
-
- // Is there a saved request?
- SavedRequest sreq = (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
- if (sreq == null) {
- return false;
- }
-
- // Is there a saved principal?
- if (cache && session.getPrincipal() == null || !cache && request.getPrincipal() == null) {
- return false;
- }
-
- // Does session id match?
- if (getChangeSessionIdOnAuthentication()) {
- String expectedSessionId = (String) session.getNote(Constants.SESSION_ID_NOTE);
- if (expectedSessionId == null || !expectedSessionId.equals(request.getRequestedSessionId())) {
- return false;
- }
- }
-
- // Does the request URI match?
- String decodedRequestURI = request.getDecodedRequestURI();
- if (decodedRequestURI == null) {
- return false;
- }
- return decodedRequestURI.equals(sreq.getDecodedRequestURI());
- }
-
-
- /**
- * Restore the original request from information stored in our session.
- * If the original request is no longer present (because the session
- * timed out), return <code>false</code>; otherwise, return
- * <code>true</code>.
- *
- * @param request The request to be restored
- * @param session The session containing the saved information
- * @return <code>true</code> if the request was successfully restored
- * @throws IOException if an IO error occurred during the process
- */
- protected boolean restoreRequest(Request request, Session session)
- throws IOException {
-
- // Retrieve and remove the SavedRequest object from our session
- SavedRequest saved = (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
- session.removeNote(Constants.FORM_REQUEST_NOTE);
- session.removeNote(Constants.SESSION_ID_NOTE);
- if (saved == null) {
- return false;
- }
-
- // Swallow any request body since we will be replacing it
- // Need to do this before headers are restored as AJP connector uses
- // content length header to determine how much data needs to be read for
- // request body
- byte[] buffer = new byte[4096];
- InputStream is = request.createInputStream();
- while (is.read(buffer) >= 0) {
- // Ignore request body
- }
-
- // Modify our current request to reflect the original one
- request.clearCookies();
- Iterator<Cookie> cookies = saved.getCookies();
- while (cookies.hasNext()) {
- request.addCookie(cookies.next());
- }
-
- String method = saved.getMethod();
- MimeHeaders rmh = request.getCoyoteRequest().getMimeHeaders();
- rmh.recycle();
- boolean cacheable = "GET".equalsIgnoreCase(method) ||
- "HEAD".equalsIgnoreCase(method);
- Iterator<String> names = saved.getHeaderNames();
- while (names.hasNext()) {
- String name = names.next();
- // The browser isn't expecting this conditional response now.
- // Assuming that it can quietly recover from an unexpected 412.
- // BZ 43687
- if(!("If-Modified-Since".equalsIgnoreCase(name) ||
- (cacheable && "If-None-Match".equalsIgnoreCase(name)))) {
- Iterator<String> values = saved.getHeaderValues(name);
- while (values.hasNext()) {
- rmh.addValue(name).setString(values.next());
- }
- }
- }
-
- request.clearLocales();
- Iterator<Locale> locales = saved.getLocales();
- while (locales.hasNext()) {
- request.addLocale(locales.next());
- }
-
- request.getCoyoteRequest().getParameters().recycle();
-
- ByteChunk body = saved.getBody();
-
- if (body != null) {
- request.getCoyoteRequest().action
- (ActionCode.REQ_SET_BODY_REPLAY, body);
-
- // Set content type
- MessageBytes contentType = MessageBytes.newInstance();
-
- // If no content type specified, use default for POST
- String savedContentType = saved.getContentType();
- if (savedContentType == null && "POST".equalsIgnoreCase(method)) {
- savedContentType = "application/x-www-form-urlencoded";
- }
-
- contentType.setString(savedContentType);
- request.getCoyoteRequest().setContentType(contentType);
- }
-
- request.getCoyoteRequest().method().setString(method);
- // The method, URI, queryString and protocol are normally stored as
- // bytes in the HttpInputBuffer and converted lazily to String. At this
- // point, the method has already been set as String in the line above
- // but the URI, queryString and protocol are still in byte form in the
- // HttpInputBuffer. Processing the saved request body will overwrite
- // these bytes. Configuring the HttpInputBuffer to retain these bytes as
- // it would in a normal request would require some invasive API changes.
- // Therefore force the conversion to String now so the correct values
- // are presented if the application requests them.
- request.getRequestURI();
- request.getQueryString();
- request.getProtocol();
-
- return true;
- }
-
-
- /**
- * Save the original request information into our session.
- *
- * @param request The request to be saved
- * @param session The session to contain the saved information
- * @throws IOException if an IO error occurred during the process
- */
- protected void saveRequest(Request request, Session session)
- throws IOException {
-
- // Create and populate a SavedRequest object for this request
- SavedRequest saved = new SavedRequest();
- Cookie cookies[] = request.getCookies();
- if (cookies != null) {
- for (Cookie cookie : cookies) {
- saved.addCookie(cookie);
- }
- }
- Enumeration<String> names = request.getHeaderNames();
- while (names.hasMoreElements()) {
- String name = names.nextElement();
- Enumeration<String> values = request.getHeaders(name);
- while (values.hasMoreElements()) {
- String value = values.nextElement();
- saved.addHeader(name, value);
- }
- }
- Enumeration<Locale> locales = request.getLocales();
- while (locales.hasMoreElements()) {
- Locale locale = locales.nextElement();
- saved.addLocale(locale);
- }
-
- // May need to acknowledge a 100-continue expectation
- request.getResponse().sendAcknowledgement(ContinueResponseTiming.ALWAYS);
-
- int maxSavePostSize = request.getConnector().getMaxSavePostSize();
- if (maxSavePostSize != 0) {
- ByteChunk body = new ByteChunk();
- body.setLimit(maxSavePostSize);
-
- byte[] buffer = new byte[4096];
- int bytesRead;
- InputStream is = request.getInputStream();
-
- while ( (bytesRead = is.read(buffer) ) >= 0) {
- body.append(buffer, 0, bytesRead);
- }
-
- // Only save the request body if there is something to save
- if (body.getLength() > 0) {
- saved.setContentType(request.getContentType());
- saved.setBody(body);
- }
- }
-
- saved.setMethod(request.getMethod());
- saved.setQueryString(request.getQueryString());
- saved.setRequestURI(request.getRequestURI());
- saved.setDecodedRequestURI(request.getDecodedRequestURI());
-
- // Stash the SavedRequest in our session for later use
- session.setNote(Constants.FORM_REQUEST_NOTE, saved);
- }
-
-
- /**
- * Return the request URI (with the corresponding query string, if any)
- * from the saved request so that we can redirect to it.
- *
- * @param session Our current session
- * @return the original request URL
- */
- protected String savedRequestURL(Session session) {
- SavedRequest saved =
- (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
- if (saved == null) {
- return null;
- }
- StringBuilder sb = new StringBuilder(saved.getRequestURI());
- if (saved.getQueryString() != null) {
- sb.append('?');
- sb.append(saved.getQueryString());
- }
-
- // Avoid protocol relative redirects
- while (sb.length() > 1 && sb.charAt(1) == '/') {
- sb.deleteCharAt(0);
- }
-
- return sb.toString();
- }
-}
\ No newline at end of file
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/catalina/authenticator/jaspic/CallbackHandlerImpl.java b/tomee/apache-tomee/src/patch/java/org/apache/catalina/authenticator/jaspic/CallbackHandlerImpl.java
deleted file mode 100644
index 75555a5ff7..0000000000
--- a/tomee/apache-tomee/src/patch/java/org/apache/catalina/authenticator/jaspic/CallbackHandlerImpl.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * 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.authenticator.jaspic;
-
-import org.apache.catalina.Contained;
-import org.apache.catalina.Container;
-import org.apache.catalina.realm.GenericPrincipal;
-import org.apache.juli.logging.Log;
-import org.apache.juli.logging.LogFactory;
-import org.apache.tomcat.util.res.StringManager;
-
-import javax.security.auth.Subject;
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.UnsupportedCallbackException;
-
-import jakarta.security.auth.message.callback.CallerPrincipalCallback;
-import jakarta.security.auth.message.callback.GroupPrincipalCallback;
-import jakarta.security.auth.message.callback.PasswordValidationCallback;
-
-import java.io.IOException;
-import java.security.Principal;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * This is a clone of Tomcat default callback handler but with a better handling of the Generic Principals when more than
- * one callback is used.
- * <p>
- * For instance https://github.com/apache/tomcat/blob/master/java/org/apache/catalina/authenticator/jaspic/CallbackHandlerImpl.java#L96
- * keeps adding new Generic Principals even for the same name whereas the authenticator base
- * https://github.com/apache/tomcat/blob/master/java/org/apache/catalina/authenticator/AuthenticatorBase.java#L956
- * randomly picks the first one. So it results in random failures
- * <p>
- * See https://github.com/eclipse-ee4j/jakartaee-tck/issues/575
- */
-public class CallbackHandlerImpl implements CallbackHandler, Contained {
-
- private static final StringManager sm = StringManager.getManager(org.apache.catalina.authenticator.jaspic.CallbackHandlerImpl.class);
- private final Log log = LogFactory.getLog(org.apache.catalina.authenticator.jaspic.CallbackHandlerImpl.class); // must not be static
-
- private Container container;
-
-
- @Override
- public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
-
- String name = null;
- Principal principal = null;
- Subject subject = null;
- String[] groups = null;
-
- if (callbacks != null) {
- // Need to combine data from multiple callbacks so use this to hold
- // the data
- // Process the callbacks
- for (Callback callback : callbacks) {
- if (callback instanceof CallerPrincipalCallback) {
- CallerPrincipalCallback cpc = (CallerPrincipalCallback) callback;
- name = cpc.getName();
- principal = cpc.getPrincipal();
- subject = cpc.getSubject();
- } else if (callback instanceof GroupPrincipalCallback) {
- GroupPrincipalCallback gpc = (GroupPrincipalCallback) callback;
- groups = gpc.getGroups();
- } else if (callback instanceof PasswordValidationCallback) {
- if (container == null) {
- log.warn(sm.getString("callbackHandlerImpl.containerMissing", callback.getClass().getName()));
- } else if (container.getRealm() == null) {
- log.warn(sm.getString("callbackHandlerImpl.realmMissing",
- callback.getClass().getName(), container.getName()));
- } else {
- PasswordValidationCallback pvc = (PasswordValidationCallback) callback;
- principal = container.getRealm().authenticate(pvc.getUsername(),
- String.valueOf(pvc.getPassword()));
- pvc.setResult(principal != null);
- subject = pvc.getSubject();
- }
- } else {
- log.error(sm.getString("callbackHandlerImpl.jaspicCallbackMissing",
- callback.getClass().getName()));
- }
- }
-
- // Create the GenericPrincipal
- Principal gp = getPrincipal(principal, name, groups);
- if (subject != null && gp != null) {
-
- // merge if needed
- String mergeName = gp.getName();
- List<String> mergeRoles = new ArrayList<>(Arrays.asList(((GenericPrincipal) gp).getRoles()));
- Principal mergePrincipal = ((GenericPrincipal) gp).getUserPrincipal();
-
- for (Object oPrincipal : subject.getPrivateCredentials()) {
- if (!(oPrincipal instanceof GenericPrincipal)) {
- continue;
- }
- final GenericPrincipal privateCredential = (GenericPrincipal) oPrincipal;
- if (mergeName != null && mergeName.equals(privateCredential.getName())) {
- mergeRoles.addAll(Arrays.asList(privateCredential.getRoles()));
- subject.getPrivateCredentials().remove(oPrincipal);
- }
- }
-
- subject.getPrivateCredentials().add(new GenericPrincipal(mergeName, null, mergeRoles, mergePrincipal));
-
- // may come from CallerPrincipalCallback and we need to being to get it from the Subject
- if (principal != null) {
- subject.getPrincipals().add(principal);
- }
- }
- }
- }
-
- private Principal getPrincipal(Principal principal, String name, String[] groups) {
- // If the Principal is cached in the session JASPIC may simply return it
- if (principal instanceof GenericPrincipal) {
- return principal;
- }
- if (name == null && principal != null) {
- name = principal.getName();
- }
- if (name == null) {
- return null;
- }
- List<String> roles;
- if (groups == null || groups.length == 0) {
- roles = Collections.emptyList();
- } else {
- roles = Arrays.asList(groups);
- }
-
- return new GenericPrincipal(name, null, roles, principal);
- }
-
- // Contained interface methods
- @Override
- public Container getContainer() {
- return this.container;
- }
-
-
- @Override
- public void setContainer(Container container) {
- this.container = container;
- }
-}
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/ClientAbortException.java b/tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/ClientAbortException.java
deleted file mode 100644
index 30812b8644..0000000000
--- a/tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/ClientAbortException.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * 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.connector;
-
-import java.io.IOException;
-import org.apache.coyote.BadRequestException;
-
-/**
- * Extend IOException to identify it as being caused by an abort of a request by
- * a remote client.
- *
- * @author Glenn L. Nielsen
- */
-public final class ClientAbortException extends BadRequestException {
-
- private static final long serialVersionUID = 1L;
-
-
- //------------------------------------------------------------ Constructors
-
- /**
- * Construct a new ClientAbortException with no other information.
- */
- public ClientAbortException() {
- super();
- }
-
-
- /**
- * Construct a new ClientAbortException for the specified message.
- *
- * @param message Message describing this exception
- */
- public ClientAbortException(String message) {
- super(message);
- }
-
-
- /**
- * Construct a new ClientAbortException for the specified throwable.
- *
- * @param throwable Throwable that caused this exception
- */
- public ClientAbortException(Throwable throwable) {
- super(throwable);
- }
-
-
- /**
- * Construct a new ClientAbortException for the specified message
- * and throwable.
- *
- * @param message Message describing this exception
- * @param throwable Throwable that caused this exception
- */
- public ClientAbortException(String message, Throwable throwable) {
- super(message, throwable);
- }
-}
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/InputBuffer.java b/tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/InputBuffer.java
deleted file mode 100644
index eef9d933d5..0000000000
--- a/tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/InputBuffer.java
+++ /dev/null
@@ -1,681 +0,0 @@
-/*
- * 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.connector;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.nio.Buffer;
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.Charset;
-import java.security.AccessController;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import jakarta.servlet.ReadListener;
-import jakarta.servlet.RequestDispatcher;
-
-import org.apache.catalina.security.SecurityUtil;
-import org.apache.coyote.ActionCode;
-import org.apache.coyote.BadRequestException;
-import org.apache.coyote.Request;
-import org.apache.juli.logging.Log;
-import org.apache.juli.logging.LogFactory;
-import org.apache.tomcat.util.buf.B2CConverter;
-import org.apache.tomcat.util.buf.ByteChunk;
-import org.apache.tomcat.util.collections.SynchronizedStack;
-import org.apache.tomcat.util.net.ApplicationBufferHandler;
-import org.apache.tomcat.util.res.StringManager;
-
-/**
- * The buffer used by Tomcat request. This is a derivative of the Tomcat 3.3
- * OutputBuffer, adapted to handle input instead of output. This allows
- * complete recycling of the facade objects (the ServletInputStream and the
- * BufferedReader).
- *
- * @author Remy Maucherat
- */
-public class InputBuffer extends Reader
- implements ByteChunk.ByteInputChannel, ApplicationBufferHandler {
-
- /**
- * The string manager for this package.
- */
- protected static final StringManager sm = StringManager.getManager(InputBuffer.class);
-
- private static final Log log = LogFactory.getLog(InputBuffer.class);
-
- public static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
-
- // The buffer can be used for byte[] and char[] reading
- // ( this is needed to support ServletInputStream and BufferedReader )
- public final int INITIAL_STATE = 0;
- public final int CHAR_STATE = 1;
- public final int BYTE_STATE = 2;
-
-
- /**
- * Encoder cache.
- */
- private static final Map<Charset, SynchronizedStack<B2CConverter>> encoders = new ConcurrentHashMap<>();
-
- // ----------------------------------------------------- Instance Variables
-
- /**
- * The byte buffer.
- */
- private ByteBuffer bb;
-
-
- /**
- * The char buffer.
- */
- private CharBuffer cb;
-
-
- /**
- * State of the output buffer.
- */
- private int state = 0;
-
-
- /**
- * Flag which indicates if the input buffer is closed.
- */
- private boolean closed = false;
-
-
- /**
- * Current byte to char converter.
- */
- protected B2CConverter conv;
-
-
- /**
- * Associated Coyote request.
- */
- private Request coyoteRequest;
-
-
- /**
- * Buffer position.
- */
- private int markPos = -1;
-
-
- /**
- * Char buffer limit.
- */
- private int readLimit;
-
-
- /**
- * Buffer size.
- */
- private final int size;
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Default constructor. Allocate the buffer with the default buffer size.
- */
- public InputBuffer() {
-
- this(DEFAULT_BUFFER_SIZE);
-
- }
-
-
- /**
- * Alternate constructor which allows specifying the initial buffer size.
- *
- * @param size Buffer size to use
- */
- public InputBuffer(int size) {
-
- this.size = size;
- bb = ByteBuffer.allocate(size);
- clear(bb);
- cb = CharBuffer.allocate(size);
- clear(cb);
- readLimit = size;
-
- }
-
-
- // ------------------------------------------------------------- Properties
-
-
- /**
- * Associated Coyote request.
- *
- * @param coyoteRequest Associated Coyote request
- */
- public void setRequest(Request coyoteRequest) {
- this.coyoteRequest = coyoteRequest;
- }
-
-
- // --------------------------------------------------------- Public Methods
-
- /**
- * Recycle the output buffer.
- */
- public void recycle() {
-
- state = INITIAL_STATE;
-
- // If usage of mark made the buffer too big, reallocate it
- if (cb.capacity() > size) {
- cb = CharBuffer.allocate(size);
- clear(cb);
- } else {
- clear(cb);
- }
- readLimit = size;
- markPos = -1;
- clear(bb);
- closed = false;
-
- if (conv != null) {
- conv.recycle();
- encoders.get(conv.getCharset()).push(conv);
- conv = null;
- }
- }
-
-
- /**
- * Close the input buffer.
- *
- * @throws IOException An underlying IOException occurred
- */
- @Override
- public void close() throws IOException {
- closed = true;
- }
-
-
- public int available() {
- int available = availableInThisBuffer();
- if (available == 0) {
- coyoteRequest.action(ActionCode.AVAILABLE,
- Boolean.valueOf(coyoteRequest.getReadListener() != null));
- available = (coyoteRequest.getAvailable() > 0) ? 1 : 0;
- }
- return available;
- }
-
-
- private int availableInThisBuffer() {
- int available = 0;
- if (state == BYTE_STATE) {
- available = bb.remaining();
- } else if (state == CHAR_STATE) {
- available = cb.remaining();
- }
- return available;
- }
-
-
- public void setReadListener(ReadListener listener) {
- coyoteRequest.setReadListener(listener);
- }
-
-
- public boolean isFinished() {
- int available = 0;
- if (state == BYTE_STATE) {
- available = bb.remaining();
- } else if (state == CHAR_STATE) {
- available = cb.remaining();
- }
- if (available > 0) {
- return false;
- } else {
- return coyoteRequest.isFinished();
- }
- }
-
-
- public boolean isReady() {
- if (coyoteRequest.getReadListener() == null) {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("inputBuffer.requiresNonBlocking"));
- }
- return false;
- }
- if (isFinished()) {
- // If this is a non-container thread, need to trigger a read
- // which will eventually lead to a call to onAllDataRead() via a
- // container thread.
- if (!coyoteRequest.isRequestThread()) {
- coyoteRequest.action(ActionCode.DISPATCH_READ, null);
- coyoteRequest.action(ActionCode.DISPATCH_EXECUTE, null);
- }
- return false;
- }
- // Checking for available data at the network level and registering for
- // read can be done sequentially for HTTP/1.x and AJP as there is only
- // ever a single thread processing the socket at any one time. However,
- // for HTTP/2 there is one thread processing the connection and separate
- // threads for each stream. For HTTP/2 the two operations have to be
- // performed atomically else it is possible for the connection thread to
- // read more data in to the buffer after the stream thread checks for
- // available network data but before it registers for read.
- if (availableInThisBuffer() > 0) {
- return true;
- }
-
- return coyoteRequest.isReady();
- }
-
-
- boolean isBlocking() {
- return coyoteRequest.getReadListener() == null;
- }
-
-
- // ------------------------------------------------- Bytes Handling Methods
-
- /**
- * Reads new bytes in the byte chunk.
- *
- * @throws IOException An underlying IOException occurred
- */
- @Override
- public int realReadBytes() throws IOException {
- if (closed) {
- return -1;
- }
- if (coyoteRequest == null) {
- return -1;
- }
-
- if (state == INITIAL_STATE) {
- state = BYTE_STATE;
- }
-
- try {
- return coyoteRequest.doRead(this);
- } catch (BadRequestException bre) {
- // Set flag used by asynchronous processing to detect errors on non-container threads
- coyoteRequest.setErrorException(bre);
- // In synchronous processing, this exception may be swallowed by the application so set error flags here.
- coyoteRequest.setAttribute(RequestDispatcher.ERROR_EXCEPTION, bre);
- coyoteRequest.getResponse().setStatus(400);
- coyoteRequest.getResponse().setError();
- // Make the exception visible to the application
- throw bre;
- } catch (IOException ioe) {
- // Set flag used by asynchronous processing to detect errors on non-container threads
- coyoteRequest.setErrorException(ioe);
- // In synchronous processing, this exception may be swallowed by the application so set error flags here.
- coyoteRequest.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe);
- coyoteRequest.getResponse().setStatus(400);
- coyoteRequest.getResponse().setError();
- // Any other IOException on a read is almost always due to the remote client aborting the request.
- // Make the exception visible to the application
- throw new ClientAbortException(ioe);
- }
- }
-
-
- public int readByte() throws IOException {
- throwIfClosed();
-
- if (checkByteBufferEof()) {
- return -1;
- }
- return bb.get() & 0xFF;
- }
-
-
- public int read(byte[] b, int off, int len) throws IOException {
- throwIfClosed();
-
- if (checkByteBufferEof()) {
- return -1;
- }
- int n = Math.min(len, bb.remaining());
- bb.get(b, off, n);
- return n;
- }
-
-
- /**
- * Transfers bytes from the buffer to the specified ByteBuffer. After the
- * operation the position of the ByteBuffer will be returned to the one
- * before the operation, the limit will be the position incremented by
- * the number of the transferred bytes.
- *
- * @param to the ByteBuffer into which bytes are to be written.
- * @return an integer specifying the actual number of bytes read, or -1 if
- * the end of the stream is reached
- * @throws IOException if an input or output exception has occurred
- */
- public int read(ByteBuffer to) throws IOException {
- throwIfClosed();
-
- if (checkByteBufferEof()) {
- return -1;
- }
- int n = Math.min(to.remaining(), bb.remaining());
- int orgLimit = bb.limit();
- bb.limit(bb.position() + n);
- to.put(bb);
- bb.limit(orgLimit);
- to.limit(to.position()).position(to.position() - n);
- return n;
- }
-
-
- // ------------------------------------------------- Chars Handling Methods
-
- public int realReadChars() throws IOException {
- checkConverter();
-
- boolean eof = false;
-
- if (bb.remaining() <= 0) {
- int nRead = realReadBytes();
- if (nRead < 0) {
- eof = true;
- }
- }
-
- if (markPos == -1) {
- clear(cb);
- } else {
- // Make sure there's enough space in the worst case
- makeSpace(bb.remaining());
- if ((cb.capacity() - cb.limit()) == 0 && bb.remaining() != 0) {
- // We went over the limit
- clear(cb);
- markPos = -1;
- }
- }
-
- state = CHAR_STATE;
- conv.convert(bb, cb, this, eof);
-
- if (cb.remaining() == 0 && eof) {
- return -1;
- } else {
- return cb.remaining();
- }
- }
-
-
- @Override
- public int read() throws IOException {
- throwIfClosed();
-
- if (checkCharBufferEof()) {
- return -1;
- }
- return cb.get();
- }
-
-
- @Override
- public int read(char[] cbuf) throws IOException {
- throwIfClosed();
- return read(cbuf, 0, cbuf.length);
- }
-
-
- @Override
- public int read(char[] cbuf, int off, int len) throws IOException {
- throwIfClosed();
-
- if (checkCharBufferEof()) {
- return -1;
- }
- int n = Math.min(len, cb.remaining());
- cb.get(cbuf, off, n);
- return n;
- }
-
-
- @Override
- public long skip(long n) throws IOException {
- throwIfClosed();
-
- if (n < 0) {
- throw new IllegalArgumentException();
- }
-
- long nRead = 0;
- while (nRead < n) {
- if (cb.remaining() >= n) {
- cb.position(cb.position() + (int) n);
- nRead = n;
- } else {
- nRead += cb.remaining();
- cb.position(cb.limit());
- int nb = realReadChars();
- if (nb < 0) {
- break;
- }
- }
- }
- return nRead;
- }
-
-
- @Override
- public boolean ready() throws IOException {
- throwIfClosed();
- if (state == INITIAL_STATE) {
- state = CHAR_STATE;
- }
- return (available() > 0);
- }
-
-
- @Override
- public boolean markSupported() {
- return true;
- }
-
-
- @Override
- public void mark(int readAheadLimit) throws IOException {
-
- throwIfClosed();
-
- if (cb.remaining() <= 0) {
- clear(cb);
- } else {
- if ((cb.capacity() > (2 * size)) && (cb.remaining()) < (cb.position())) {
- cb.compact();
- cb.flip();
- }
- }
- readLimit = cb.position() + readAheadLimit + size;
- markPos = cb.position();
- }
-
-
- @Override
- public void reset() throws IOException {
-
- throwIfClosed();
-
- if (state == CHAR_STATE) {
- if (markPos < 0) {
- clear(cb);
- markPos = -1;
- IOException ioe = new IOException();
- coyoteRequest.setErrorException(ioe);
- throw ioe;
- } else {
- cb.position(markPos);
- }
- } else {
- clear(bb);
- }
- }
-
-
- private void throwIfClosed() throws IOException {
- if (closed) {
- IOException ioe = new IOException(sm.getString("inputBuffer.streamClosed"));
- coyoteRequest.setErrorException(ioe);
- throw ioe;
- }
- }
-
- public void checkConverter() throws IOException {
- if (conv != null) {
- return;
- }
-
- Charset charset = null;
- if (coyoteRequest != null) {
- charset = coyoteRequest.getCharset();
- }
-
- if (charset == null) {
- charset = org.apache.coyote.Constants.DEFAULT_BODY_CHARSET;
- }
-
- SynchronizedStack<B2CConverter> stack = encoders.get(charset);
- if (stack == null) {
- stack = new SynchronizedStack<>();
- encoders.putIfAbsent(charset, stack);
- stack = encoders.get(charset);
- }
- conv = stack.pop();
-
- if (conv == null) {
- conv = createConverter(charset);
- }
- }
-
-
- private static B2CConverter createConverter(Charset charset) throws IOException {
- if (SecurityUtil.isPackageProtectionEnabled()) {
- try {
- return AccessController.doPrivileged(new PrivilegedCreateConverter(charset));
- } catch (PrivilegedActionException ex) {
- Exception e = ex.getException();
- if (e instanceof IOException) {
- throw (IOException) e;
- } else {
- throw new IOException(e);
- }
- }
- } else {
- return new B2CConverter(charset);
- }
-
- }
-
-
- @Override
- public void setByteBuffer(ByteBuffer buffer) {
- bb = buffer;
- }
-
-
- @Override
- public ByteBuffer getByteBuffer() {
- return bb;
- }
-
-
- @Override
- public void expand(int size) {
- // no-op
- }
-
-
- private boolean checkByteBufferEof() throws IOException {
- if (bb.remaining() == 0) {
- int n = realReadBytes();
- if (n < 0) {
- return true;
- }
- }
- return false;
- }
-
- private boolean checkCharBufferEof() throws IOException {
- if (cb.remaining() == 0) {
- int n = realReadChars();
- if (n < 0) {
- return true;
- }
- }
- return false;
- }
-
- private void clear(Buffer buffer) {
- buffer.rewind().limit(0);
- }
-
- private void makeSpace(int count) {
- int desiredSize = cb.limit() + count;
- if(desiredSize > readLimit) {
- desiredSize = readLimit;
- }
-
- if(desiredSize <= cb.capacity()) {
- return;
- }
-
- int newSize = 2 * cb.capacity();
- if(desiredSize >= newSize) {
- newSize= 2 * cb.capacity() + count;
- }
-
- if (newSize > readLimit) {
- newSize = readLimit;
- }
-
- CharBuffer tmp = CharBuffer.allocate(newSize);
- int oldPosition = cb.position();
- cb.position(0);
- tmp.put(cb);
- tmp.flip();
- tmp.position(oldPosition);
- cb = tmp;
- tmp = null;
- }
-
-
- private static class PrivilegedCreateConverter
- implements PrivilegedExceptionAction<B2CConverter> {
-
- private final Charset charset;
-
- public PrivilegedCreateConverter(Charset charset) {
- this.charset = charset;
- }
-
- @Override
- public B2CConverter run() throws IOException {
- return new B2CConverter(charset);
- }
- }
-}
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
deleted file mode 100644
index b0b9bba438..0000000000
--- a/tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/LocalStrings.properties
+++ /dev/null
@@ -1,96 +0,0 @@
-# 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.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
-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/connector/Request.java b/tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/Request.java
deleted file mode 100644
index 3d4faf26dc..0000000000
--- a/tomee/apache-tomee/src/patch/java/org/apache/catalina/connector/Request.java
+++ /dev/null
@@ -1,3604 +0,0 @@
-/*
- * 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.connector;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.StringReader;
-import java.io.UnsupportedEncodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.StandardCharsets;
-import java.security.Principal;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicReference;
-
-import javax.naming.NamingException;
-import javax.security.auth.Subject;
-
-import jakarta.servlet.AsyncContext;
-import jakarta.servlet.DispatcherType;
-import jakarta.servlet.FilterChain;
-import jakarta.servlet.MultipartConfigElement;
-import jakarta.servlet.RequestDispatcher;
-import jakarta.servlet.ServletContext;
-import jakarta.servlet.ServletException;
-import jakarta.servlet.ServletInputStream;
-import jakarta.servlet.ServletRequest;
-import jakarta.servlet.ServletRequestAttributeEvent;
-import jakarta.servlet.ServletRequestAttributeListener;
-import jakarta.servlet.ServletResponse;
-import jakarta.servlet.SessionTrackingMode;
-import jakarta.servlet.http.Cookie;
-import jakarta.servlet.http.HttpServletMapping;
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletRequestWrapper;
-import jakarta.servlet.http.HttpServletResponse;
-import jakarta.servlet.http.HttpSession;
-import jakarta.servlet.http.HttpUpgradeHandler;
-import jakarta.servlet.http.Part;
-import jakarta.servlet.http.PushBuilder;
-
-import org.apache.catalina.Container;
-import org.apache.catalina.Context;
-import org.apache.catalina.Globals;
-import org.apache.catalina.Host;
-import org.apache.catalina.Manager;
-import org.apache.catalina.Realm;
-import org.apache.catalina.Session;
-import org.apache.catalina.TomcatPrincipal;
-import org.apache.catalina.Wrapper;
-import org.apache.catalina.core.ApplicationFilterChain;
-import org.apache.catalina.core.ApplicationMapping;
-import org.apache.catalina.core.ApplicationPart;
-import org.apache.catalina.core.ApplicationPushBuilder;
-import org.apache.catalina.core.ApplicationSessionCookieConfig;
-import org.apache.catalina.core.AsyncContextImpl;
-import org.apache.catalina.mapper.MappingData;
-import org.apache.catalina.util.ParameterMap;
-import org.apache.catalina.util.RequestUtil;
-import org.apache.catalina.util.TLSUtil;
-import org.apache.catalina.util.URLEncoder;
-import org.apache.coyote.ActionCode;
-import org.apache.coyote.UpgradeToken;
-import org.apache.coyote.http11.upgrade.InternalHttpUpgradeHandler;
-import org.apache.juli.logging.Log;
-import org.apache.juli.logging.LogFactory;
-import org.apache.tomcat.InstanceManager;
-import org.apache.tomcat.util.ExceptionUtils;
-import org.apache.tomcat.util.buf.B2CConverter;
-import org.apache.tomcat.util.buf.ByteChunk;
-import org.apache.tomcat.util.buf.EncodedSolidusHandling;
-import org.apache.tomcat.util.buf.MessageBytes;
-import org.apache.tomcat.util.buf.StringUtils;
-import org.apache.tomcat.util.buf.UDecoder;
-import org.apache.tomcat.util.http.CookieProcessor;
-import org.apache.tomcat.util.http.FastHttpDateFormat;
-import org.apache.tomcat.util.http.Parameters;
-import org.apache.tomcat.util.http.Parameters.FailReason;
-import org.apache.tomcat.util.http.ServerCookie;
-import org.apache.tomcat.util.http.ServerCookies;
-import org.apache.tomcat.util.http.fileupload.FileItem;
-import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
-import org.apache.tomcat.util.http.fileupload.impl.InvalidContentTypeException;
-import org.apache.tomcat.util.http.fileupload.impl.SizeException;
-import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
-import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;
-import org.apache.tomcat.util.http.parser.AcceptLanguage;
-import org.apache.tomcat.util.http.parser.Upgrade;
-import org.apache.tomcat.util.net.SSLSupport;
-import org.apache.tomcat.util.res.StringManager;
-import org.ietf.jgss.GSSCredential;
-import org.ietf.jgss.GSSException;
-
-/**
- * Wrapper object for the Coyote request.
- *
- * @author Remy Maucherat
- * @author Craig R. McClanahan
- */
-public class Request implements HttpServletRequest {
-
- private static final String HTTP_UPGRADE_HEADER_NAME = "upgrade";
-
- private static final Log log = LogFactory.getLog(Request.class);
-
- /**
- * Create a new Request object associated with the given Connector.
- *
- * @param connector The Connector with which this Request object will always
- * be associated. In normal usage this must be non-null. In
- * some test scenarios, it may be possible to use a null
- * Connector without triggering an NPE.
- */
- public Request(Connector connector) {
- this.connector = connector;
- }
-
-
- // ------------------------------------------------------------- Properties
-
-
- /**
- * Coyote request.
- */
- protected org.apache.coyote.Request coyoteRequest;
-
- /**
- * Set the Coyote request.
- *
- * @param coyoteRequest The Coyote request
- */
- public void setCoyoteRequest(org.apache.coyote.Request coyoteRequest) {
- this.coyoteRequest = coyoteRequest;
- inputBuffer.setRequest(coyoteRequest);
- }
-
- /**
- * Get the Coyote request.
- *
- * @return the Coyote request object
- */
- public org.apache.coyote.Request getCoyoteRequest() {
- return this.coyoteRequest;
- }
-
-
- // ----------------------------------------------------- Variables
-
- /**
- * The string manager for this package.
- */
- protected static final StringManager sm = StringManager.getManager(Request.class);
-
-
- /**
- * The set of cookies associated with this Request.
- */
- protected Cookie[] cookies = null;
-
-
- /**
- * The default Locale if none are specified.
- */
- protected static final Locale defaultLocale = Locale.getDefault();
-
-
- /**
- * The attributes associated with this Request, keyed by attribute name.
- */
- private final Map<String, Object> attributes = new ConcurrentHashMap<>();
-
-
- /**
- * Flag that indicates if SSL attributes have been parsed to improve
- * performance for applications (usually frameworks) that make multiple
- * calls to {@link Request#getAttributeNames()}.
- */
- protected boolean sslAttributesParsed = false;
-
-
- /**
- * The preferred Locales associated with this Request.
- */
- protected final ArrayList<Locale> locales = new ArrayList<>();
-
-
- /**
- * Internal notes associated with this request by Catalina components
- * and event listeners.
- */
- private final transient HashMap<String, Object> notes = new HashMap<>();
-
-
- /**
- * Authentication type.
- */
- protected String authType = null;
-
-
- /**
- * The current dispatcher type.
- */
- protected DispatcherType internalDispatcherType = null;
-
-
- /**
- * The associated input buffer.
- */
- protected final InputBuffer inputBuffer = new InputBuffer();
-
-
- /**
- * ServletInputStream.
- */
- protected CoyoteInputStream inputStream =
- new CoyoteInputStream(inputBuffer);
-
-
- /**
- * Reader.
- */
- protected CoyoteReader reader = new CoyoteReader(inputBuffer);
-
-
- /**
- * Using stream flag.
- */
- protected boolean usingInputStream = false;
-
-
- /**
- * Using reader flag.
- */
- protected boolean usingReader = false;
-
-
- /**
- * User principal.
- */
- protected Principal userPrincipal = null;
-
-
- /**
- * Request parameters parsed flag.
- */
- protected boolean parametersParsed = false;
-
-
- /**
- * Cookie headers parsed flag. Indicates that the cookie headers have been
- * parsed into ServerCookies.
- */
- protected boolean cookiesParsed = false;
-
-
- /**
- * Cookie parsed flag. Indicates that the ServerCookies have been converted
- * into user facing Cookie objects.
- */
- protected boolean cookiesConverted = false;
-
-
- /**
- * Secure flag.
- */
- protected boolean secure = false;
-
-
- /**
- * The Subject associated with the current AccessControlContext
- */
- protected transient Subject subject = null;
-
-
- /**
- * Post data buffer.
- */
- protected static final int CACHED_POST_LEN = 8192;
- protected byte[] postData = null;
-
-
- /**
- * Hash map used in the getParametersMap method.
- */
- protected ParameterMap<String, String[]> parameterMap = new ParameterMap<>();
-
-
- /**
- * The parts, if any, uploaded with this request.
- */
- protected Collection<Part> parts = null;
-
-
- /**
- * The exception thrown, if any when parsing the parts.
- */
- protected Exception partsParseException = null;
-
-
- /**
- * The currently active session for this request.
- */
- protected Session session = null;
-
-
- /**
- * The current request dispatcher path.
- */
- protected Object requestDispatcherPath = null;
-
-
- /**
- * Was the requested session ID received in a cookie?
- */
- protected boolean requestedSessionCookie = false;
-
-
- /**
- * The requested session ID (if any) for this request.
- */
- protected String requestedSessionId = null;
-
-
- /**
- * Was the requested session ID received in a URL?
- */
- protected boolean requestedSessionURL = false;
-
-
- /**
- * Was the requested session ID obtained from the SSL session?
- */
- protected boolean requestedSessionSSL = false;
-
-
- /**
- * Parse locales.
- */
- protected boolean localesParsed = false;
-
-
- /**
- * Local port
- */
- protected int localPort = -1;
-
- /**
- * Remote address.
- */
- protected String remoteAddr = null;
-
-
- /**
- * Connection peer address.
- */
- protected String peerAddr = null;
-
-
- /**
- * Remote host.
- */
- protected String remoteHost = null;
-
-
- /**
- * Remote port
- */
- protected int remotePort = -1;
-
- /**
- * Local address
- */
- protected String localAddr = null;
-
-
- /**
- * Local address
- */
- protected String localName = null;
-
- /**
- * AsyncContext
- */
- private volatile AsyncContextImpl asyncContext = null;
-
- protected Boolean asyncSupported = null;
-
- private HttpServletRequest applicationRequest = null;
-
-
- // --------------------------------------------------------- Public Methods
-
- protected void addPathParameter(String name, String value) {
- coyoteRequest.addPathParameter(name, value);
- }
-
- protected String getPathParameter(String name) {
- return coyoteRequest.getPathParameter(name);
- }
-
- public void setAsyncSupported(boolean asyncSupported) {
- this.asyncSupported = Boolean.valueOf(asyncSupported);
- }
-
- /**
- * Release all object references, and initialize instance variables, in
- * preparation for reuse of this object.
- */
- public void recycle() {
-
- internalDispatcherType = null;
- requestDispatcherPath = null;
-
- authType = null;
- inputBuffer.recycle();
- usingInputStream = false;
- usingReader = false;
- userPrincipal = null;
- subject = null;
- parametersParsed = false;
- if (parts != null) {
- for (Part part: parts) {
- try {
- part.delete();
- } catch (Throwable t) {
- ExceptionUtils.handleThrowable(t);
- log.warn(sm.getString("coyoteRequest.deletePartFailed", part.getName()), t);
- }
- }
- parts = null;
- }
- partsParseException = null;
- locales.clear();
- localesParsed = false;
- secure = false;
- remoteAddr = null;
- peerAddr = null;
- remoteHost = null;
- remotePort = -1;
- localPort = -1;
- localAddr = null;
- localName = null;
-
- attributes.clear();
- sslAttributesParsed = false;
- notes.clear();
-
- recycleSessionInfo();
- recycleCookieInfo(false);
-
- if (getDiscardFacades()) {
- parameterMap = new ParameterMap<>();
- } else {
- parameterMap.setLocked(false);
- parameterMap.clear();
- }
-
- mappingData.recycle();
- applicationMapping.recycle();
-
- applicationRequest = null;
- if (getDiscardFacades()) {
- if (facade != null) {
- facade.clear();
- facade = null;
- }
- if (inputStream != null) {
- inputStream.clear();
- inputStream = null;
- }
- if (reader != null) {
- reader.clear();
- reader = null;
- }
- }
-
- asyncSupported = null;
- if (asyncContext!=null) {
- asyncContext.recycle();
- asyncContext = null;
- }
- }
-
-
- protected void recycleSessionInfo() {
- if (session != null) {
- try {
- session.endAccess();
- } catch (Throwable t) {
- ExceptionUtils.handleThrowable(t);
- log.warn(sm.getString("coyoteRequest.sessionEndAccessFail"), t);
- }
- }
- session = null;
- requestedSessionCookie = false;
- requestedSessionId = null;
- requestedSessionURL = false;
- requestedSessionSSL = false;
- }
-
-
- protected void recycleCookieInfo(boolean recycleCoyote) {
- cookiesParsed = false;
- cookiesConverted = false;
- cookies = null;
- if (recycleCoyote) {
- getCoyoteRequest().getCookies().recycle();
- }
- }
-
-
- // -------------------------------------------------------- Request Methods
-
- /**
- * Associated Catalina connector.
- */
- protected final Connector connector;
-
- /**
- * @return the Connector through which this Request was received.
- */
- public Connector getConnector() {
- return this.connector;
- }
-
-
- /**
- * Return the Context within which this Request is being processed.
- * <p>
- * This is available as soon as the appropriate Context is identified.
- * Note that availability of a Context allows <code>getContextPath()</code>
- * to return a value, and thus enables parsing of the request URI.
- *
- * @return the Context mapped with the request
- */
- public Context getContext() {
- return mappingData.context;
- }
-
-
- /**
- * Get the recycling strategy of the facade objects.
- * @return the value of the flag as set on the connector, or
- * <code>true</code> if no connector is associated with this request
- */
- public boolean getDiscardFacades() {
- return (connector == null) ? true : connector.getDiscardFacades();
- }
-
-
- /**
- * Filter chain associated with the request.
- */
- protected FilterChain filterChain = null;
-
- /**
- * Get filter chain associated with the request.
- *
- * @return the associated filter chain
- */
- public FilterChain getFilterChain() {
- return this.filterChain;
- }
-
- /**
- * Set filter chain associated with the request.
- *
- * @param filterChain new filter chain
- */
- public void setFilterChain(FilterChain filterChain) {
- this.filterChain = filterChain;
- }
-
-
- /**
- * @return the Host within which this Request is being processed.
- */
- public Host getHost() {
- return mappingData.host;
- }
-
-
- /**
- * Mapping data.
- */
- protected final MappingData mappingData = new MappingData();
- private final ApplicationMapping applicationMapping = new ApplicationMapping(mappingData);
-
- /**
- * @return mapping data.
- */
- public MappingData getMappingData() {
- return mappingData;
- }
-
-
- /**
- * The facade associated with this request.
- */
- protected RequestFacade facade = null;
-
-
- /**
- * @return the <code>ServletRequest</code> for which this object
- * is the facade. This method must be implemented by a subclass.
- */
- public HttpServletRequest getRequest() {
- if (facade == null) {
- facade = new RequestFacade(this);
- }
- if (applicationRequest == null) {
- applicationRequest = facade;
- }
- return applicationRequest;
- }
-
-
- /**
- * Set a wrapped HttpServletRequest to pass to the application. Components
- * wishing to wrap the request should obtain the request via
- * {@link #getRequest()}, wrap it and then call this method with the
- * wrapped request.
- *
- * @param applicationRequest The wrapped request to pass to the application
- */
- public void setRequest(HttpServletRequest applicationRequest) {
- // Check the wrapper wraps this request
- ServletRequest r = applicationRequest;
- while (r instanceof HttpServletRequestWrapper) {
- r = ((HttpServletRequestWrapper) r).getRequest();
- }
- if (r != facade) {
- throw new IllegalArgumentException(sm.getString("request.illegalWrap"));
- }
- this.applicationRequest = applicationRequest;
- }
-
-
- /**
- * The response with which this request is associated.
- */
- protected org.apache.catalina.connector.Response response = null;
-
- /**
- * @return the Response with which this Request is associated.
- */
- public org.apache.catalina.connector.Response getResponse() {
- return this.response;
- }
-
- /**
- * Set the Response with which this Request is associated.
- *
- * @param response The new associated response
- */
- public void setResponse(org.apache.catalina.connector.Response response) {
- this.response = response;
- }
-
- /**
- * @return the input stream associated with this Request.
- */
- public InputStream getStream() {
- if (inputStream == null) {
- inputStream = new CoyoteInputStream(inputBuffer);
- }
- return inputStream;
- }
-
- /**
- * URI byte to char converter.
- */
- protected B2CConverter URIConverter = null;
-
- /**
- * @return the URI converter.
- */
- protected B2CConverter getURIConverter() {
- return URIConverter;
- }
-
- /**
- * Set the URI converter.
- *
- * @param URIConverter the new URI converter
- */
- protected void setURIConverter(B2CConverter URIConverter) {
- this.URIConverter = URIConverter;
- }
-
-
- /**
- * @return the Wrapper within which this Request is being processed.
- */
- public Wrapper getWrapper() {
- return mappingData.wrapper;
- }
-
-
- // ------------------------------------------------- Request Public Methods
-
- /**
- * Create and return a ServletInputStream to read the content
- * associated with this Request.
- *
- * @return the created input stream
- * @exception IOException if an input/output error occurs
- */
- public ServletInputStream createInputStream()
- throws IOException {
- if (inputStream == null) {
- inputStream = new CoyoteInputStream(inputBuffer);
- }
- return inputStream;
- }
-
-
- /**
- * Perform whatever actions are required to flush and close the input
- * stream or reader, in a single operation.
- *
- * @exception IOException if an input/output error occurs
- */
- public void finishRequest() throws IOException {
- if (response.getStatus() == HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE) {
- checkSwallowInput();
- }
- }
-
-
- /**
- * @return the object bound with the specified name to the internal notes
- * for this request, or <code>null</code> if no such binding exists.
- *
- * @param name Name of the note to be returned
- */
- public Object getNote(String name) {
- return notes.get(name);
- }
-
-
- /**
- * Remove any object bound to the specified name in the internal notes
- * for this request.
- *
- * @param name Name of the note to be removed
- */
- public void removeNote(String name) {
- notes.remove(name);
- }
-
-
- /**
- * Set the port number of the server to process this request.
- *
- * @param port The server port
- */
- public void setLocalPort(int port) {
- localPort = port;
- }
-
- /**
- * Bind an object to a specified name in the internal notes associated
- * with this request, replacing any existing binding for this name.
- *
- * @param name Name to which the object should be bound
- * @param value Object to be bound to the specified name
- */
- public void setNote(String name, Object value) {
- notes.put(name, value);
- }
-
-
- /**
- * Set the IP address of the remote client associated with this Request.
- *
- * @param remoteAddr The remote IP address
- */
- public void setRemoteAddr(String remoteAddr) {
- this.remoteAddr = remoteAddr;
- }
-
-
- /**
- * Set the fully qualified name of the remote client associated with this
- * Request.
- *
- * @param remoteHost The remote host name
- */
- public void setRemoteHost(String remoteHost) {
- this.remoteHost = remoteHost;
- }
-
-
- /**
- * Set the value to be returned by <code>isSecure()</code>
- * for this Request.
- *
- * @param secure The new isSecure value
- */
- public void setSecure(boolean secure) {
- this.secure = secure;
- }
-
-
- /**
- * Set the port number of the server to process this request.
- *
- * @param port The server port
- */
- public void setServerPort(int port) {
- coyoteRequest.setServerPort(port);
- }
-
-
- // ------------------------------------------------- ServletRequest Methods
-
- /**
- * @return the specified request attribute if it exists; otherwise, return
- * <code>null</code>.
- *
- * @param name Name of the request attribute to return
- */
- @Override
- public Object getAttribute(String name) {
- // Special attributes
- SpecialAttributeAdapter adapter = specialAttributes.get(name);
- if (adapter != null) {
- return adapter.get(this, name);
- }
-
- Object attr = attributes.get(name);
-
- if (attr != null) {
- return attr;
- }
-
- attr = coyoteRequest.getAttribute(name);
- if (attr != null) {
- return attr;
- }
- if (!sslAttributesParsed && TLSUtil.isTLSRequestAttribute(name)) {
- coyoteRequest.action(ActionCode.REQ_SSL_ATTRIBUTE, coyoteRequest);
- attr = coyoteRequest.getAttribute(Globals.CERTIFICATES_ATTR);
- if (attr != null) {
- attributes.put(Globals.CERTIFICATES_ATTR, attr);
- }
- attr = coyoteRequest.getAttribute(Globals.CIPHER_SUITE_ATTR);
- if (attr != null) {
- attributes.put(Globals.CIPHER_SUITE_ATTR, attr);
- }
- attr = coyoteRequest.getAttribute(Globals.KEY_SIZE_ATTR);
- if (attr != null) {
- attributes.put(Globals.KEY_SIZE_ATTR, attr);
- }
- attr = coyoteRequest.getAttribute(Globals.SSL_SESSION_ID_ATTR);
- if (attr != null) {
- attributes.put(Globals.SSL_SESSION_ID_ATTR, attr);
- }
- attr = coyoteRequest.getAttribute(Globals.SSL_SESSION_MGR_ATTR);
- if (attr != null) {
- attributes.put(Globals.SSL_SESSION_MGR_ATTR, attr);
- }
- attr = coyoteRequest.getAttribute(SSLSupport.PROTOCOL_VERSION_KEY);
- if (attr != null) {
- attributes.put(SSLSupport.PROTOCOL_VERSION_KEY, attr);
- }
- attr = coyoteRequest.getAttribute(SSLSupport.REQUESTED_PROTOCOL_VERSIONS_KEY);
- if (attr != null) {
- attributes.put(SSLSupport.REQUESTED_PROTOCOL_VERSIONS_KEY, attr);
- }
- attr = coyoteRequest.getAttribute(SSLSupport.REQUESTED_CIPHERS_KEY);
- if (attr != null) {
- attributes.put(SSLSupport.REQUESTED_CIPHERS_KEY, attr);
- }
- attr = attributes.get(name);
- sslAttributesParsed = true;
- }
- return attr;
- }
-
-
- @Override
- public long getContentLengthLong() {
- return coyoteRequest.getContentLengthLong();
- }
-
-
- /**
- * Return the names of all request attributes for this Request, or an
- * empty <code>Enumeration</code> if there are none. Note that the attribute
- * names returned will only be those for the attributes set via
- * {@link #setAttribute(String, Object)}. Tomcat internal attributes will
- * not be included although they are accessible via
- * {@link #getAttribute(String)}. The Tomcat internal attributes include:
- * <ul>
- * <li>{@link Globals#DISPATCHER_TYPE_ATTR}</li>
- * <li>{@link Globals#DISPATCHER_REQUEST_PATH_ATTR}</li>
- * <li>{@link Globals#ASYNC_SUPPORTED_ATTR}</li>
- * <li>{@link Globals#CERTIFICATES_ATTR} (SSL connections only)</li>
- * <li>{@link Globals#CIPHER_SUITE_ATTR} (SSL connections only)</li>
- * <li>{@link Globals#KEY_SIZE_ATTR} (SSL connections only)</li>
- * <li>{@link Globals#SSL_SESSION_ID_ATTR} (SSL connections only)</li>
- * <li>{@link Globals#SSL_SESSION_MGR_ATTR} (SSL connections only)</li>
- * <li>{@link Globals#PARAMETER_PARSE_FAILED_ATTR}</li>
- * </ul>
- * The underlying connector may also expose request attributes. These all
- * have names starting with "org.apache.tomcat" and include:
- * <ul>
- * <li>{@link Globals#SENDFILE_SUPPORTED_ATTR}</li>
- * </ul>
- * Connector implementations may return some, all or none of these
- * attributes and may also support additional attributes.
- *
- * @return the attribute names enumeration
- */
- @Override
- public Enumeration<String> getAttributeNames() {
- if (isSecure() && !sslAttributesParsed) {
- getAttribute(Globals.CERTIFICATES_ATTR);
- }
- // Take a copy to prevent ConcurrentModificationExceptions if used to
- // remove attributes
- Set<String> names = new HashSet<>(attributes.keySet());
- return Collections.enumeration(names);
- }
-
-
- /**
- * @return the character encoding for this Request.
- */
- @Override
- public String getCharacterEncoding() {
- String characterEncoding = coyoteRequest.getCharacterEncoding();
- if (characterEncoding != null) {
- return characterEncoding;
- }
-
- Context context = getContext();
- if (context != null) {
- return context.getRequestCharacterEncoding();
- }
-
- return null;
- }
-
-
- private Charset getCharset() {
- Charset charset = null;
- try {
- charset = coyoteRequest.getCharset();
- } catch (UnsupportedEncodingException e) {
- // Ignore
- }
- if (charset != null) {
- return charset;
- }
-
- Context context = getContext();
- if (context != null) {
- String encoding = context.getRequestCharacterEncoding();
- if (encoding != null) {
- try {
- return B2CConverter.getCharset(encoding);
- } catch (UnsupportedEncodingException e) {
- // Ignore
- }
- }
- }
-
- return org.apache.coyote.Constants.DEFAULT_BODY_CHARSET;
- }
-
-
- /**
- * @return the content length for this Request.
- */
- @Override
- public int getContentLength() {
- return coyoteRequest.getContentLength();
- }
-
-
- /**
- * @return the content type for this Request.
- */
- @Override
- public String getContentType() {
- return coyoteRequest.getContentType();
- }
-
-
- /**
- * Set the content type for this Request.
- *
- * @param contentType The content type
- */
- public void setContentType(String contentType) {
- coyoteRequest.setContentType(contentType);
- }
-
-
- /**
- * @return the servlet input stream for this Request. The default
- * implementation returns a servlet input stream created by
- * <code>createInputStream()</code>.
- *
- * @exception IllegalStateException if <code>getReader()</code> has
- * already been called for this request
- * @exception IOException if an input/output error occurs
- */
- @Override
- public ServletInputStream getInputStream() throws IOException {
-
- if (usingReader) {
- throw new IllegalStateException(sm.getString("coyoteRequest.getInputStream.ise"));
- }
-
- usingInputStream = true;
- if (inputStream == null) {
- inputStream = new CoyoteInputStream(inputBuffer);
- }
- return inputStream;
-
- }
-
-
- /**
- * @return the preferred Locale that the client will accept content in,
- * based on the value for the first <code>Accept-Language</code> header
- * that was encountered. If the request did not specify a preferred
- * language, the server's default Locale is returned.
- */
- @Override
- public Locale getLocale() {
-
- if (!localesParsed) {
- parseLocales();
- }
-
- if (locales.size() > 0) {
- return locales.get(0);
- }
-
- return defaultLocale;
- }
-
-
- /**
- * @return the set of preferred Locales that the client will accept
- * content in, based on the values for any <code>Accept-Language</code>
- * headers that were encountered. If the request did not specify a
- * preferred language, the server's default Locale is returned.
- */
- @Override
- public Enumeration<Locale> getLocales() {
-
- if (!localesParsed) {
- parseLocales();
- }
-
- if (locales.size() > 0) {
- return Collections.enumeration(locales);
- }
- ArrayList<Locale> results = new ArrayList<>();
- results.add(defaultLocale);
- return Collections.enumeration(results);
-
- }
-
-
- /**
- * @return the value of the specified request parameter, if any; otherwise,
- * return <code>null</code>. If there is more than one value defined,
- * return only the first one.
- *
- * @param name Name of the desired request parameter
- */
- @Override
- public String getParameter(String name) {
-
- if (!parametersParsed) {
- parseParameters();
- }
-
- return coyoteRequest.getParameters().getParameter(name);
-
- }
-
-
-
- /**
- * Returns a <code>Map</code> of the parameters of this request.
- * Request parameters are extra information sent with the request.
- * For HTTP servlets, parameters are contained in the query string
- * or posted form data.
- *
- * @return A <code>Map</code> containing parameter names as keys
- * and parameter values as map values.
- */
- @Override
- public Map<String, String[]> getParameterMap() {
-
- if (parameterMap.isLocked()) {
- return parameterMap;
- }
-
- Enumeration<String> enumeration = getParameterNames();
- while (enumeration.hasMoreElements()) {
- String name = enumeration.nextElement();
- String[] values = getParameterValues(name);
- parameterMap.put(name, values);
- }
-
- parameterMap.setLocked(true);
-
- return parameterMap;
-
- }
-
-
- /**
- * @return the names of all defined request parameters for this request.
- */
- @Override
- public Enumeration<String> getParameterNames() {
-
- if (!parametersParsed) {
- parseParameters();
- }
-
- return coyoteRequest.getParameters().getParameterNames();
-
- }
-
-
- /**
- * @return the defined values for the specified request parameter, if any;
- * otherwise, return <code>null</code>.
- *
- * @param name Name of the desired request parameter
- */
- @Override
- public String[] getParameterValues(String name) {
-
- if (!parametersParsed) {
- parseParameters();
- }
-
- return coyoteRequest.getParameters().getParameterValues(name);
-
- }
-
-
- /**
- * @return the protocol and version used to make this Request.
- */
- @Override
- public String getProtocol() {
- return coyoteRequest.protocol().toString();
- }
-
-
- /**
- * Read the Reader wrapping the input stream for this Request. The
- * default implementation wraps a <code>BufferedReader</code> around the
- * servlet input stream returned by <code>createInputStream()</code>.
- *
- * @return a buffered reader for the request
- * @exception IllegalStateException if <code>getInputStream()</code>
- * has already been called for this request
- * @exception IOException if an input/output error occurs
- */
- @Override
- public BufferedReader getReader() throws IOException {
-
- if (usingInputStream) {
- throw new IllegalStateException(sm.getString("coyoteRequest.getReader.ise"));
- }
-
- // InputBuffer has no easily accessible reference chain to the Context
- // to check for a default request character encoding at the Context.
- // Therefore, if a Context default should be used, it is set explicitly
- // here. Need to do this before setting usingReader.
- if (coyoteRequest.getCharacterEncoding() == null) {
- // Nothing currently set explicitly.
- // Check the content
- Context context = getContext();
- if (context != null) {
- String enc = context.getRequestCharacterEncoding();
- if (enc != null) {
- // Explicitly set the context default so it is visible to
- // InputBuffer when creating the Reader.
- setCharacterEncoding(enc);
- }
- }
- }
-
- usingReader = true;
-
- inputBuffer.checkConverter();
- if (reader == null) {
- reader = new CoyoteReader(inputBuffer);
- }
- return reader;
- }
-
-
- /**
- * @return the real path of the specified virtual path.
- *
- * @param path Path to be translated
- *
- * @deprecated As of version 2.1 of the Java Servlet API, use
- * <code>ServletContext.getRealPath()</code>.
- */
- @Override
- @Deprecated
- public String getRealPath(String path) {
-
- Context context = getContext();
- if (context == null) {
- return null;
- }
- ServletContext servletContext = context.getServletContext();
- if (servletContext == null) {
- return null;
- }
-
- try {
- return servletContext.getRealPath(path);
- } catch (IllegalArgumentException e) {
- return null;
- }
- }
-
-
- /**
- * @return the remote IP address making this Request.
- */
- @Override
- public String getRemoteAddr() {
- if (remoteAddr == null) {
- coyoteRequest.action(ActionCode.REQ_HOST_ADDR_ATTRIBUTE, coyoteRequest);
- remoteAddr = coyoteRequest.remoteAddr().toString();
- }
- return remoteAddr;
- }
-
-
- /**
- * @return the connection peer IP address making this Request.
- */
- public String getPeerAddr() {
- if (peerAddr == null) {
- coyoteRequest.action(ActionCode.REQ_PEER_ADDR_ATTRIBUTE, coyoteRequest);
- peerAddr = coyoteRequest.peerAddr().toString();
- }
- return peerAddr;
- }
-
-
- /**
- * @return the remote host name making this Request.
- */
- @Override
- public String getRemoteHost() {
- if (remoteHost == null) {
- if (!connector.getEnableLookups()) {
- remoteHost = getRemoteAddr();
- } else {
- coyoteRequest.action(ActionCode.REQ_HOST_ATTRIBUTE, coyoteRequest);
- remoteHost = coyoteRequest.remoteHost().toString();
- }
- }
- return remoteHost;
- }
-
- /**
- * @return the Internet Protocol (IP) source port of the client
- * or last proxy that sent the request.
- */
- @Override
- public int getRemotePort(){
- if (remotePort == -1) {
- coyoteRequest.action(ActionCode.REQ_REMOTEPORT_ATTRIBUTE, coyoteRequest);
- remotePort = coyoteRequest.getRemotePort();
- }
- return remotePort;
- }
-
- /**
- * @return the host name of the Internet Protocol (IP) interface on
- * which the request was received.
- */
- @Override
- public String getLocalName(){
- if (localName == null) {
- coyoteRequest.action(ActionCode.REQ_LOCAL_NAME_ATTRIBUTE, coyoteRequest);
- localName = coyoteRequest.localName().toString();
- }
- return localName;
- }
-
- /**
- * @return the Internet Protocol (IP) address of the interface on
- * which the request was received.
- */
- @Override
- public String getLocalAddr(){
- if (localAddr == null) {
- coyoteRequest.action(ActionCode.REQ_LOCAL_ADDR_ATTRIBUTE, coyoteRequest);
- localAddr = coyoteRequest.localAddr().toString();
- }
- return localAddr;
- }
-
-
- /**
- * @return the Internet Protocol (IP) port number of the interface
- * on which the request was received.
- */
- @Override
- public int getLocalPort(){
- if (localPort == -1){
- coyoteRequest.action(ActionCode.REQ_LOCALPORT_ATTRIBUTE, coyoteRequest);
- localPort = coyoteRequest.getLocalPort();
- }
- return localPort;
- }
-
- /**
- * @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) {
-
- Context context = getContext();
- if (context == null) {
- return null;
- }
-
- if (path == null) {
- return null;
- }
-
- int fragmentPos = path.indexOf('#');
- if (fragmentPos > -1) {
- log.warn(sm.getString("request.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);
- }
-
- /*
- * Relative to what, exactly?
- *
- * From the Servlet 4.0 Javadoc:
- * - The pathname specified may be relative, although it cannot extend
- * outside the current servlet context.
- * - If it is relative, it must be relative against the current servlet
- *
- * From Section 9.1 of the spec:
- * - The servlet container uses information in the request object to
- * transform the given relative path against the current servlet to a
- * complete path.
- *
- * It is undefined whether the requestURI is used or whether servletPath
- * and pathInfo are used. Given that the RequestURI includes the
- * contextPath (and extracting that is messy) , using the servletPath and
- * pathInfo looks to be the more reasonable choice.
- */
-
- // 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);
- }
-
-
- /**
- * @return the scheme used to make this Request.
- */
- @Override
- public String getScheme() {
- return coyoteRequest.scheme().toString();
- }
-
-
- /**
- * @return the server name responding to this Request.
- */
- @Override
- public String getServerName() {
- return coyoteRequest.serverName().toString();
- }
-
-
- /**
- * @return the server port responding to this Request.
- */
- @Override
- public int getServerPort() {
- return coyoteRequest.getServerPort();
- }
-
-
- /**
- * @return <code>true</code> if this request was received on a secure connection.
- */
- @Override
- public boolean isSecure() {
- return secure;
- }
-
-
- /**
- * Remove the specified request attribute if it exists.
- *
- * @param name Name of the request attribute to remove
- */
- @Override
- public void removeAttribute(String name) {
- // Remove the specified attribute
- // Pass special attributes to the native layer
- if (name.startsWith("org.apache.tomcat.")) {
- coyoteRequest.getAttributes().remove(name);
- }
-
- boolean found = attributes.containsKey(name);
- if (found) {
- Object value = attributes.get(name);
- attributes.remove(name);
-
- // Notify interested application event listeners
- notifyAttributeRemoved(name, value);
- }
- }
-
-
- /**
- * Set the specified request attribute to the specified value.
- *
- * @param name Name of the request attribute to set
- * @param value The associated value
- */
- @Override
- public void setAttribute(String name, Object value) {
-
- // Name cannot be null
- if (name == null) {
- throw new IllegalArgumentException(sm.getString("coyoteRequest.setAttribute.namenull"));
- }
-
- // Null value is the same as removeAttribute()
- if (value == null) {
- removeAttribute(name);
- return;
- }
-
- // Special attributes
- SpecialAttributeAdapter adapter = specialAttributes.get(name);
- if (adapter != null) {
- adapter.set(this, name, value);
- return;
- }
-
- // Add or replace the specified attribute
- // Do the security check before any updates are made
- if (Globals.IS_SECURITY_ENABLED &&
- name.equals(Globals.SENDFILE_FILENAME_ATTR)) {
- // Use the canonical file name to avoid any possible symlink and
- // relative path issues
- String canonicalPath;
- try {
- canonicalPath = new File(value.toString()).getCanonicalPath();
- } catch (IOException e) {
- throw new SecurityException(sm.getString(
- "coyoteRequest.sendfileNotCanonical", value), e);
- }
- // Sendfile is performed in Tomcat's security context so need to
- // check if the web app is permitted to access the file while still
- // in the web app's security context
- System.getSecurityManager().checkRead(canonicalPath);
- // Update the value so the canonical path is used
- value = canonicalPath;
- }
-
- Object oldValue = attributes.put(name, value);
-
- // Pass special attributes to the native layer
- if (name.startsWith("org.apache.tomcat.")) {
- coyoteRequest.setAttribute(name, value);
- }
-
- // Notify interested application event listeners
- notifyAttributeAssigned(name, value, oldValue);
- }
-
-
- /**
- * Notify interested listeners that attribute has been assigned a value.
- *
- * @param name Attribute name
- * @param value New attribute value
- * @param oldValue Old attribute value
- */
- private void notifyAttributeAssigned(String name, Object value,
- Object oldValue) {
- Context context = getContext();
- if (context == null) {
- return;
- }
- Object listeners[] = context.getApplicationEventListeners();
- if ((listeners == null) || (listeners.length == 0)) {
- return;
- }
- boolean replaced = (oldValue != null);
- ServletRequestAttributeEvent event = null;
- if (replaced) {
- event = new ServletRequestAttributeEvent(
- context.getServletContext(), getRequest(), name, oldValue);
- } else {
- event = new ServletRequestAttributeEvent(
- context.getServletContext(), getRequest(), name, value);
- }
-
- for (Object o : listeners) {
- if (!(o instanceof ServletRequestAttributeListener)) {
- continue;
- }
- ServletRequestAttributeListener listener = (ServletRequestAttributeListener) o;
- try {
- if (replaced) {
- listener.attributeReplaced(event);
- } else {
- listener.attributeAdded(event);
- }
- } catch (Throwable t) {
- ExceptionUtils.handleThrowable(t);
- // Error valve will pick this exception up and display it to user
- attributes.put(RequestDispatcher.ERROR_EXCEPTION, t);
- context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t);
- }
- }
- }
-
-
- /**
- * Notify interested listeners that attribute has been removed.
- *
- * @param name Attribute name
- * @param value Attribute value
- */
- private void notifyAttributeRemoved(String name, Object value) {
- Context context = getContext();
- Object listeners[] = context.getApplicationEventListeners();
- if ((listeners == null) || (listeners.length == 0)) {
- return;
- }
- ServletRequestAttributeEvent event =
- new ServletRequestAttributeEvent(context.getServletContext(),
- getRequest(), name, value);
- for (Object o : listeners) {
- if (!(o instanceof ServletRequestAttributeListener)) {
- continue;
- }
- ServletRequestAttributeListener listener = (ServletRequestAttributeListener) o;
- try {
- listener.attributeRemoved(event);
- } catch (Throwable t) {
- ExceptionUtils.handleThrowable(t);
- // Error valve will pick this exception up and display it to user
- attributes.put(RequestDispatcher.ERROR_EXCEPTION, t);
- context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t);
- }
- }
- }
-
-
- /**
- * Overrides the name of the character encoding used in the body of
- * this request. This method must be called prior to reading request
- * parameters or reading input using <code>getReader()</code>.
- *
- * @param enc The character encoding to be used
- *
- * @exception UnsupportedEncodingException if the specified encoding
- * is not supported
- *
- * @since Servlet 2.3
- */
- @Override
- public void setCharacterEncoding(String enc) throws UnsupportedEncodingException {
-
- if (usingReader) {
- return;
- }
-
- // Confirm that the encoding name is valid
- Charset charset = B2CConverter.getCharset(enc);
-
- // Save the validated encoding
- coyoteRequest.setCharset(charset);
- }
-
-
- @Override
- public ServletContext getServletContext() {
- return getContext().getServletContext();
- }
-
- @Override
- public AsyncContext startAsync() {
- return startAsync(getRequest(),response.getResponse());
- }
-
- @Override
- public AsyncContext startAsync(ServletRequest request,
- ServletResponse response) {
- if (!isAsyncSupported()) {
- IllegalStateException ise =
- new IllegalStateException(sm.getString("request.asyncNotSupported"));
- log.warn(sm.getString("coyoteRequest.noAsync",
- StringUtils.join(getNonAsyncClassNames())), ise);
- throw ise;
- }
-
- if (asyncContext == null) {
- asyncContext = new AsyncContextImpl(this);
- }
-
- asyncContext.setStarted(getContext(), request, response,
- request==getRequest() && response==getResponse().getResponse());
- asyncContext.setTimeout(getConnector().getAsyncTimeout());
-
- return asyncContext;
- }
-
-
- private Set<String> getNonAsyncClassNames() {
- Set<String> result = new HashSet<>();
-
- Wrapper wrapper = getWrapper();
- if (!wrapper.isAsyncSupported()) {
- result.add(wrapper.getServletClass());
- }
-
- FilterChain filterChain = getFilterChain();
- if (filterChain instanceof ApplicationFilterChain) {
- ((ApplicationFilterChain) filterChain).findNonAsyncFilters(result);
- } else {
- result.add(sm.getString("coyoteRequest.filterAsyncSupportUnknown"));
- }
-
- Container c = wrapper;
- while (c != null) {
- c.getPipeline().findNonAsyncValves(result);
- c = c.getParent();
- }
-
- return result;
- }
-
- @Override
- public boolean isAsyncStarted() {
- if (asyncContext == null) {
- return false;
- }
-
- return asyncContext.isStarted();
- }
-
- public boolean isAsyncDispatching() {
- if (asyncContext == null) {
- return false;
- }
-
- AtomicBoolean result = new AtomicBoolean(false);
- coyoteRequest.action(ActionCode.ASYNC_IS_DISPATCHING, result);
- return result.get();
- }
-
- public boolean isAsyncCompleting() {
- if (asyncContext == null) {
- return false;
- }
-
- AtomicBoolean result = new AtomicBoolean(false);
- coyoteRequest.action(ActionCode.ASYNC_IS_COMPLETING, result);
- return result.get();
- }
-
- public boolean isAsync() {
- if (asyncContext == null) {
- return false;
- }
-
- AtomicBoolean result = new AtomicBoolean(false);
- coyoteRequest.action(ActionCode.ASYNC_IS_ASYNC, result);
- return result.get();
- }
-
- @Override
- public boolean isAsyncSupported() {
- if (this.asyncSupported == null) {
- return true;
- }
-
- return asyncSupported.booleanValue();
- }
-
- @Override
- public AsyncContext getAsyncContext() {
- if (!isAsyncStarted()) {
- throw new IllegalStateException(sm.getString("request.notAsync"));
- }
- return asyncContext;
- }
-
- public AsyncContextImpl getAsyncContextInternal() {
- return asyncContext;
- }
-
- @Override
- public DispatcherType getDispatcherType() {
- if (internalDispatcherType == null) {
- return DispatcherType.REQUEST;
- }
-
- return this.internalDispatcherType;
- }
-
- // ---------------------------------------------------- HttpRequest Methods
-
- /**
- * Add a Cookie to the set of Cookies associated with this Request.
- *
- * @param cookie The new cookie
- */
- public void addCookie(Cookie cookie) {
-
- if (!cookiesConverted) {
- convertCookies();
- }
-
- int size = 0;
- if (cookies != null) {
- size = cookies.length;
- }
-
- Cookie[] newCookies = new Cookie[size + 1];
- if (cookies != null) {
- System.arraycopy(cookies, 0, newCookies, 0, size);
- }
- newCookies[size] = cookie;
-
- cookies = newCookies;
-
- }
-
-
- /**
- * Add a Locale to the set of preferred Locales for this Request. The
- * first added Locale will be the first one returned by getLocales().
- *
- * @param locale The new preferred Locale
- */
- public void addLocale(Locale locale) {
- locales.add(locale);
- }
-
-
- /**
- * Clear the collection of Cookies associated with this Request.
- */
- public void clearCookies() {
- cookiesParsed = true;
- cookiesConverted = true;
- cookies = null;
- }
-
-
- /**
- * Clear the collection of Locales associated with this Request.
- */
- public void clearLocales() {
- locales.clear();
- }
-
-
- /**
- * Set the authentication type used for this request, if any; otherwise
- * set the type to <code>null</code>. Typical values are "BASIC",
- * "DIGEST", or "SSL".
- *
- * @param type The authentication type used
- */
- public void setAuthType(String type) {
- this.authType = type;
- }
-
-
- /**
- * Set the path information for this Request. This will normally be called
- * when the associated Context is mapping the Request to a particular
- * Wrapper.
- *
- * @param path The path information
- */
- public void setPathInfo(String path) {
- mappingData.pathInfo.setString(path);
- }
-
-
- /**
- * Set a flag indicating whether or not the requested session ID for this
- * request came in through a cookie. This is normally called by the
- * HTTP Connector, when it parses the request headers.
- *
- * @param flag The new flag
- */
- public void setRequestedSessionCookie(boolean flag) {
-
- this.requestedSessionCookie = flag;
-
- }
-
-
- /**
- * Set the requested session ID for this request. This is normally called
- * by the HTTP Connector, when it parses the request headers.
- *
- * @param id The new session id
- */
- public void setRequestedSessionId(String id) {
-
- this.requestedSessionId = id;
-
- }
-
-
- /**
- * Set a flag indicating whether or not the requested session ID for this
- * request came in through a URL. This is normally called by the
- * HTTP Connector, when it parses the request headers.
- *
- * @param flag The new flag
- */
- public void setRequestedSessionURL(boolean flag) {
-
- this.requestedSessionURL = flag;
-
- }
-
-
- /**
- * Set a flag indicating whether or not the requested session ID for this
- * request came in through SSL. This is normally called by the
- * HTTP Connector, when it parses the request headers.
- *
- * @param flag The new flag
- */
- public void setRequestedSessionSSL(boolean flag) {
-
- this.requestedSessionSSL = flag;
-
- }
-
-
- /**
- * Get the decoded request URI.
- *
- * @return the URL decoded request URI
- */
- public String getDecodedRequestURI() {
- return coyoteRequest.decodedURI().toString();
- }
-
-
- /**
- * Get the decoded request URI.
- *
- * @return the URL decoded request URI
- */
- public MessageBytes getDecodedRequestURIMB() {
- return coyoteRequest.decodedURI();
- }
-
-
- /**
- * Set the Principal who has been authenticated for this Request. This
- * value is also used to calculate the value to be returned by the
- * <code>getRemoteUser()</code> method.
- *
- * @param principal The user Principal
- */
- public void setUserPrincipal(final Principal principal) {
- if (Globals.IS_SECURITY_ENABLED && principal != null) {
- if (subject == null) {
- final HttpSession session = getSession(false);
- if (session == null) {
- // Cache the subject in the request
- subject = newSubject(principal);
- } else {
- // Cache the subject in the request and the session
- subject = (Subject) session.getAttribute(Globals.SUBJECT_ATTR);
- if (subject == null) {
- subject = newSubject(principal);
- session.setAttribute(Globals.SUBJECT_ATTR, subject);
- } else {
- subject.getPrincipals().add(principal);
- }
- }
- } else {
- subject.getPrincipals().add(principal);
- }
- }
- userPrincipal = principal;
- }
-
-
- private Subject newSubject(final Principal principal) {
- final Subject result = new Subject();
- result.getPrincipals().add(principal);
- return result;
- }
-
-
- // --------------------------------------------- HttpServletRequest Methods
-
- @Override
- public boolean isTrailerFieldsReady() {
- return coyoteRequest.isTrailerFieldsReady();
- }
-
-
- @Override
- public Map<String, String> getTrailerFields() {
- if (!isTrailerFieldsReady()) {
- throw new IllegalStateException(sm.getString("coyoteRequest.trailersNotReady"));
- }
- Map<String, String> result = new HashMap<>(coyoteRequest.getTrailerFields());
- return result;
- }
-
-
- @Override
- public PushBuilder newPushBuilder() {
- return newPushBuilder(this);
- }
-
-
- public PushBuilder newPushBuilder(HttpServletRequest request) {
- AtomicBoolean result = new AtomicBoolean();
- coyoteRequest.action(ActionCode.IS_PUSH_SUPPORTED, result);
- if (result.get()) {
- return new ApplicationPushBuilder(this, request);
- } else {
- return null;
- }
- }
-
-
- @SuppressWarnings("unchecked")
- @Override
- public <T extends HttpUpgradeHandler> T upgrade(
- Class<T> httpUpgradeHandlerClass) throws java.io.IOException, ServletException {
- T handler;
- InstanceManager instanceManager = null;
- try {
- // Do not go through the instance manager for internal Tomcat classes since they don't
- // need injection
- if (InternalHttpUpgradeHandler.class.isAssignableFrom(httpUpgradeHandlerClass)) {
- handler = httpUpgradeHandlerClass.getConstructor().newInstance();
- } else {
- instanceManager = getContext().getInstanceManager();
- handler = (T) instanceManager.newInstance(httpUpgradeHandlerClass);
- }
- } catch (ReflectiveOperationException | NamingException | IllegalArgumentException |
- SecurityException e) {
- throw new ServletException(e);
- }
- UpgradeToken upgradeToken = new UpgradeToken(handler, getContext(), instanceManager,
- getUpgradeProtocolName(httpUpgradeHandlerClass));
-
- coyoteRequest.action(ActionCode.UPGRADE, upgradeToken);
-
- // Output required by RFC2616. Protocol specific headers should have
- // already been set.
- response.setStatus(HttpServletResponse.SC_SWITCHING_PROTOCOLS);
-
- return handler;
- }
-
-
- private String getUpgradeProtocolName(Class<? extends HttpUpgradeHandler> httpUpgradeHandlerClass) {
- // Ideal - the caller has already explicitly set the selected protocol
- // on the response
- String result = response.getHeader(HTTP_UPGRADE_HEADER_NAME);
-
- if (result == null) {
- // If the request's upgrade header contains a single protocol that
- // is the protocol that must have been selected
- List<Upgrade> upgradeProtocols = Upgrade.parse(getHeaders(HTTP_UPGRADE_HEADER_NAME));
- if (upgradeProtocols != null && upgradeProtocols.size() == 1) {
- result = upgradeProtocols.get(0).toString();
- }
- }
-
- if (result == null) {
- // Ugly but use the class name - it is better than nothing
- result = httpUpgradeHandlerClass.getName();
- }
- return result;
- }
-
-
- /**
- * Return the authentication type used for this Request.
- */
- @Override
- public String getAuthType() {
- return authType;
- }
-
-
- /**
- * Return the portion of the request URI used to select the Context
- * of the Request. The value returned is not decoded which also implies it
- * is not normalised.
- */
- @Override
- public String getContextPath() {
- int lastSlash = mappingData.contextSlashCount;
- // Special case handling for the root context
- if (lastSlash == 0) {
- return "";
- }
-
- String canonicalContextPath = getServletContext().getContextPath();
-
- String uri = getRequestURI();
- int pos = 0;
- if (!getContext().getAllowMultipleLeadingForwardSlashInPath()) {
- // Ensure that the returned value only starts with a single '/'.
- // This prevents the value being misinterpreted as a protocol-
- // relative URI if used with sendRedirect().
- do {
- pos++;
- } while (pos < uri.length() && uri.charAt(pos) == '/');
- pos--;
- uri = uri.substring(pos);
- }
-
- char[] uriChars = uri.toCharArray();
- // Need at least the number of slashes in the context path
- while (lastSlash > 0) {
- pos = nextSlash(uriChars, pos + 1);
- if (pos == -1) {
- break;
- }
- lastSlash--;
- }
- // Now allow for path parameters, normalization and/or encoding.
- // Essentially, keep extending the candidate path up to the next slash
- // until the decoded and normalized candidate path (with the path
- // parameters removed) is the same as the canonical path.
- String candidate;
- if (pos == -1) {
- candidate = uri;
- } else {
- candidate = uri.substring(0, pos);
- }
- candidate = removePathParameters(candidate);
- candidate = UDecoder.URLDecode(candidate, connector.getURICharset());
- candidate = org.apache.tomcat.util.http.RequestUtil.normalize(candidate);
- boolean match = canonicalContextPath.equals(candidate);
- while (!match && pos != -1) {
- pos = nextSlash(uriChars, pos + 1);
- if (pos == -1) {
- candidate = uri;
- } else {
- candidate = uri.substring(0, pos);
- }
- candidate = removePathParameters(candidate);
- candidate = UDecoder.URLDecode(candidate, connector.getURICharset());
- candidate = org.apache.tomcat.util.http.RequestUtil.normalize(candidate);
- match = canonicalContextPath.equals(candidate);
- }
- if (match) {
- if (pos == -1) {
- return uri;
- } else {
- return uri.substring(0, pos);
- }
- } else {
- // Should never happen
- throw new IllegalStateException(sm.getString(
- "coyoteRequest.getContextPath.ise", canonicalContextPath, uri));
- }
- }
-
-
- private String removePathParameters(String input) {
- int nextSemiColon = input.indexOf(';');
- // Shortcut
- if (nextSemiColon == -1) {
- return input;
- }
- StringBuilder result = new StringBuilder(input.length());
- result.append(input.substring(0, nextSemiColon));
- while (true) {
- int nextSlash = input.indexOf('/', nextSemiColon);
- if (nextSlash == -1) {
- break;
- }
- nextSemiColon = input.indexOf(';', nextSlash);
- if (nextSemiColon == -1) {
- result.append(input.substring(nextSlash));
- break;
- } else {
- result.append(input.substring(nextSlash, nextSemiColon));
- }
- }
-
- return result.toString();
- }
-
-
- private int nextSlash(char[] uri, int startPos) {
- int len = uri.length;
- int pos = startPos;
- while (pos < len) {
- if (uri[pos] == '/') {
- return pos;
- } else if (connector.getEncodedSolidusHandlingInternal() == EncodedSolidusHandling.DECODE &&
- uri[pos] == '%' && pos + 2 < len && uri[pos+1] == '2' &&
- (uri[pos + 2] == 'f' || uri[pos + 2] == 'F')) {
- return pos;
- }
- pos++;
- }
- return -1;
- }
-
-
- /**
- * Return the set of Cookies received with this Request. Triggers parsing of
- * the Cookie HTTP headers followed by conversion to Cookie objects if this
- * has not already been performed.
- *
- * @return the array of cookies
- */
- @Override
- public Cookie[] getCookies() {
- if (!cookiesConverted) {
- convertCookies();
- }
- return cookies;
- }
-
-
- /**
- * Return the server representation of the cookies associated with this
- * request. Triggers parsing of the Cookie HTTP headers (but not conversion
- * to Cookie objects) if the headers have not yet been parsed.
- *
- * @return the server cookies
- */
- public ServerCookies getServerCookies() {
- parseCookies();
- return coyoteRequest.getCookies();
- }
-
-
- /**
- * Return the value of the specified date header, if any; otherwise
- * return -1.
- *
- * @param name Name of the requested date header
- * @return the date as a long
- *
- * @exception IllegalArgumentException if the specified header value
- * cannot be converted to a date
- */
- @Override
- public long getDateHeader(String name) {
-
- String value = getHeader(name);
- if (value == null) {
- return -1L;
- }
-
- // Attempt to convert the date header in a variety of formats
- long result = FastHttpDateFormat.parseDate(value);
- if (result != (-1L)) {
- return result;
- }
- throw new IllegalArgumentException(value);
-
- }
-
-
- /**
- * Return the first value of the specified header, if any; otherwise,
- * return <code>null</code>
- *
- * @param name Name of the requested header
- * @return the header value
- */
- @Override
- public String getHeader(String name) {
- return coyoteRequest.getHeader(name);
- }
-
-
- /**
- * Return all of the values of the specified header, if any; otherwise,
- * return an empty enumeration.
- *
- * @param name Name of the requested header
- * @return the enumeration with the header values
- */
- @Override
- public Enumeration<String> getHeaders(String name) {
- return coyoteRequest.getMimeHeaders().values(name);
- }
-
-
- /**
- * @return the names of all headers received with this request.
- */
- @Override
- public Enumeration<String> getHeaderNames() {
- return coyoteRequest.getMimeHeaders().names();
- }
-
-
- /**
- * Return the value of the specified header as an integer, or -1 if there
- * is no such header for this request.
- *
- * @param name Name of the requested header
- * @return the header value as an int
- *
- * @exception IllegalArgumentException if the specified header value
- * cannot be converted to an integer
- */
- @Override
- public int getIntHeader(String name) {
-
- String value = getHeader(name);
- if (value == null) {
- return -1;
- }
-
- return Integer.parseInt(value);
- }
-
-
- @Override
- public HttpServletMapping getHttpServletMapping() {
- return applicationMapping.getHttpServletMapping();
- }
-
-
- /**
- * @return the HTTP request method used in this Request.
- */
- @Override
- public String getMethod() {
- return coyoteRequest.method().toString();
- }
-
-
- /**
- * @return the path information associated with this Request.
- */
- @Override
- public String getPathInfo() {
- return mappingData.pathInfo.toString();
- }
-
-
- /**
- * @return the extra path information for this request, translated
- * to a real path.
- */
- @Override
- public String getPathTranslated() {
-
- Context context = getContext();
- if (context == null) {
- return null;
- }
-
- if (getPathInfo() == null) {
- return null;
- }
-
- return context.getServletContext().getRealPath(getPathInfo());
- }
-
-
- /**
- * @return the query string associated with this request.
- */
- @Override
- public String getQueryString() {
- return coyoteRequest.queryString().toString();
- }
-
-
- /**
- * @return the name of the remote user that has been authenticated
- * for this Request.
- */
- @Override
- public String getRemoteUser() {
-
- if (userPrincipal == null) {
- return null;
- }
-
- return userPrincipal.getName();
- }
-
-
- /**
- * Get the request path.
- *
- * @return the request path
- */
- public MessageBytes getRequestPathMB() {
- return mappingData.requestPath;
- }
-
-
- /**
- * @return the session identifier included in this request, if any.
- */
- @Override
- public String getRequestedSessionId() {
- return requestedSessionId;
- }
-
-
- /**
- * @return the request URI for this request.
- */
- @Override
- public String getRequestURI() {
- return coyoteRequest.requestURI().toString();
- }
-
-
- @Override
- public StringBuffer getRequestURL() {
- return RequestUtil.getRequestURL(this);
- }
-
-
- /**
- * @return the portion of the request URI used to select the servlet
- * that will process this request.
- */
- @Override
- public String getServletPath() {
- return mappingData.wrapperPath.toString();
- }
-
-
- /**
- * @return the session associated with this Request, creating one
- * if necessary.
- */
- @Override
- public HttpSession getSession() {
- Session session = doGetSession(true);
- if (session == null) {
- return null;
- }
-
- return session.getSession();
- }
-
-
- /**
- * @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) {
- Session session = doGetSession(create);
- if (session == null) {
- return null;
- }
-
- return session.getSession();
- }
-
-
- /**
- * @return <code>true</code> if the session identifier included in this
- * request came from a cookie.
- */
- @Override
- public boolean isRequestedSessionIdFromCookie() {
-
- if (requestedSessionId == null) {
- return false;
- }
-
- return requestedSessionCookie;
- }
-
-
- /**
- * @return <code>true</code> if the session identifier included in this
- * request came from the request URI.
- */
- @Override
- public boolean isRequestedSessionIdFromURL() {
-
- if (requestedSessionId == null) {
- return false;
- }
-
- return requestedSessionURL;
- }
-
-
- /**
- * @return <code>true</code> if the session identifier included in this
- * request came from the request URI.
- *
- * @deprecated As of Version 2.1 of the Java Servlet API, use
- * <code>isRequestedSessionIdFromURL()</code> instead.
- */
- @Override
- @Deprecated
- public boolean isRequestedSessionIdFromUrl() {
- return isRequestedSessionIdFromURL();
- }
-
-
- /**
- * @return <code>true</code> if the session identifier included in this
- * request identifies a valid session.
- */
- @Override
- public boolean isRequestedSessionIdValid() {
-
- if (requestedSessionId == null) {
- return false;
- }
-
- Context context = getContext();
- 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) {
- // Can't find the session
- }
-
- if ((session == null) || !session.isValid()) {
- // Check for parallel deployment contexts
- if (getMappingData().contexts == null) {
- return false;
- } else {
- for (int i = (getMappingData().contexts.length); i > 0; i--) {
- Context ctxt = getMappingData().contexts[i - 1];
- try {
- if (ctxt.getManager().findSession(requestedSessionId) !=
- null) {
- return true;
- }
- } catch (IOException e) {
- // Ignore
- }
- }
- return false;
- }
- }
-
- return true;
- }
-
-
- /**
- * @return <code>true</code> if the authenticated user principal
- * possesses the specified role name.
- *
- * @param role Role name to be validated
- */
- @Override
- public boolean isUserInRole(String role) {
-
- // Have we got an authenticated principal at all?
- if (userPrincipal == null) {
- return false;
- }
-
- // Identify the Realm we will use for checking role assignments
- Context context = getContext();
- if (context == null) {
- return false;
- }
-
- // If the role is "*" then the return value must be false
- // Servlet 31, section 13.3
- if ("*".equals(role)) {
- return false;
- }
-
- // If the role is "**" then, unless the application defines a role with
- // that name, only check if the user is authenticated
- if ("**".equals(role) && !context.findSecurityRole("**")) {
- return userPrincipal != null;
- }
-
- Realm realm = context.getRealm();
- if (realm == null) {
- return false;
- }
-
- // Check for a role defined directly as a <security-role>
- return realm.hasRole(getWrapper(), userPrincipal, role);
- }
-
-
- /**
- * @return the principal that has been authenticated for this Request.
- */
- public Principal getPrincipal() {
- return userPrincipal;
- }
-
-
- /**
- * @return the principal that has been authenticated for this Request.
- */
- @Override
- public Principal getUserPrincipal() {
- if (userPrincipal instanceof TomcatPrincipal) {
- GSSCredential gssCredential =
- ((TomcatPrincipal) userPrincipal).getGssCredential();
- if (gssCredential != null) {
- int left = -1;
- try {
- // Concurrent calls to this method from an expired session
- // can trigger an ISE. If one thread calls logout() below
- // before another thread calls getRemainingLifetime() then
- // then since logout() eventually calls
- // GSSCredential.dispose(), the subsequent call to
- // GSSCredential.getRemainingLifetime() will throw an ISE.
- // Avoiding the ISE would require locking in this method to
- // protect against concurrent access to the GSSCredential.
- // That would have a small performance impact. The ISE is
- // rare so it is caught and handled rather than avoided.
- left = gssCredential.getRemainingLifetime();
- } catch (GSSException | IllegalStateException e) {
- log.warn(sm.getString("coyoteRequest.gssLifetimeFail",
- userPrincipal.getName()), e);
- }
- // zero is expired. Exception above will mean left == -1
- // Treat both as expired.
- if (left <= 0) {
- // GSS credential has expired. Need to re-authenticate.
- try {
- logout();
- } catch (ServletException e) {
- // Should never happen (no code called by logout()
- // throws a ServletException
- }
- return null;
- }
- }
- return ((TomcatPrincipal) userPrincipal).getUserPrincipal();
- }
-
- return userPrincipal;
- }
-
-
- /**
- * @return the session associated with this Request, creating one
- * if necessary.
- */
- public Session getSessionInternal() {
- return doGetSession(true);
- }
-
-
- /**
- * Change the ID of the session that this request is associated with. There
- * are several things that may trigger an ID change. These include moving
- * between nodes in a cluster and session fixation prevention during the
- * authentication process.
- *
- * @param newSessionId The session to change the session ID for
- */
- public void changeSessionId(String newSessionId) {
- // This should only ever be called if there was an old session ID but
- // double check to be sure
- if (requestedSessionId != null && requestedSessionId.length() > 0) {
- requestedSessionId = newSessionId;
- }
-
- Context context = getContext();
- if (context != null &&
- !context.getServletContext()
- .getEffectiveSessionTrackingModes()
- .contains(SessionTrackingMode.COOKIE)) {
- return;
- }
-
- if (response != null) {
- Cookie newCookie = ApplicationSessionCookieConfig.createSessionCookie(context,
- newSessionId, isSecure());
- response.addSessionCookieInternal(newCookie);
- }
- }
-
-
- @Override
- public String changeSessionId() {
-
- Session session = this.getSessionInternal(false);
- if (session == null) {
- throw new IllegalStateException(
- sm.getString("coyoteRequest.changeSessionId"));
- }
-
- Manager manager = this.getContext().getManager();
-
- String newSessionId = manager.rotateSessionId(session);
- this.changeSessionId(newSessionId);
-
- return newSessionId;
- }
-
- /**
- * @return the session associated with this Request, creating one
- * if necessary and requested.
- *
- * @param create Create a new session if one does not exist
- */
- public Session getSessionInternal(boolean create) {
- return doGetSession(create);
- }
-
-
- /**
- * @return <code>true</code> if we have parsed parameters
- */
- public boolean isParametersParsed() {
- return parametersParsed;
- }
-
-
- /**
- * @return <code>true</code> if an attempt has been made to read the request
- * body and all of the request body has been read.
- */
- public boolean isFinished() {
- return coyoteRequest.isFinished();
- }
-
-
- /**
- * Check the configuration for aborted uploads and if configured to do so,
- * disable the swallowing of any remaining input and close the connection
- * once the response has been written.
- */
- protected void checkSwallowInput() {
- Context context = getContext();
- if (context != null && !context.getSwallowAbortedUploads()) {
- coyoteRequest.action(ActionCode.DISABLE_SWALLOW_INPUT, null);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean authenticate(HttpServletResponse response)
- throws IOException, ServletException {
- if (response.isCommitted()) {
- throw new IllegalStateException(
- sm.getString("coyoteRequest.authenticate.ise"));
- }
-
- return getContext().getAuthenticator().authenticate(this, response);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void login(String username, String password)
- throws ServletException {
- if (getAuthType() != null || getRemoteUser() != null ||
- getUserPrincipal() != null) {
- throw new ServletException(
- sm.getString("coyoteRequest.alreadyAuthenticated"));
- }
-
- getContext().getAuthenticator().login(username, password, this);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void logout() throws ServletException {
- getContext().getAuthenticator().logout(this);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Collection<Part> getParts() throws IOException, IllegalStateException,
- ServletException {
-
- parseParts(true);
-
- if (partsParseException != null) {
- if (partsParseException instanceof IOException) {
- throw (IOException) partsParseException;
- } else if (partsParseException instanceof IllegalStateException) {
- throw (IllegalStateException) partsParseException;
- } else if (partsParseException instanceof ServletException) {
- throw (ServletException) partsParseException;
- }
- }
-
- return parts;
- }
-
- private void parseParts(boolean explicit) {
-
- // Return immediately if the parts have already been parsed
- if (parts != null || partsParseException != null) {
- return;
- }
-
- Context context = getContext();
- MultipartConfigElement mce = getWrapper().getMultipartConfigElement();
-
- if (mce == null) {
- if(context.getAllowCasualMultipartParsing()) {
- mce = new MultipartConfigElement(null, connector.getMaxPostSize(),
- connector.getMaxPostSize(), connector.getMaxPostSize());
- } else {
- if (explicit) {
- partsParseException = new IllegalStateException(
- sm.getString("coyoteRequest.noMultipartConfig"));
- return;
- } else {
- parts = Collections.emptyList();
- return;
- }
- }
- }
-
- int maxParameterCount = getConnector().getMaxParameterCount();
- Parameters parameters = coyoteRequest.getParameters();
- parameters.setLimit(maxParameterCount);
-
- boolean success = false;
- try {
- File location;
- String locationStr = mce.getLocation();
- if (locationStr == null || locationStr.length() == 0) {
- location = ((File) context.getServletContext().getAttribute(
- ServletContext.TEMPDIR));
- } else {
- // If relative, it is relative to TEMPDIR
- location = new File(locationStr);
- if (!location.isAbsolute()) {
- location = new File(
- (File) context.getServletContext().getAttribute(ServletContext.TEMPDIR),
- locationStr).getAbsoluteFile();
- }
- }
-
- if (!location.exists() && context.getCreateUploadTargets()) {
- log.warn(sm.getString("coyoteRequest.uploadCreate",
- location.getAbsolutePath(), getMappingData().wrapper.getName()));
- if (!location.mkdirs()) {
- log.warn(sm.getString("coyoteRequest.uploadCreateFail",
- location.getAbsolutePath()));
- }
- }
-
- if (!location.isDirectory()) {
- parameters.setParseFailedReason(FailReason.MULTIPART_CONFIG_INVALID);
- partsParseException = new IOException(
- sm.getString("coyoteRequest.uploadLocationInvalid",
- location));
- return;
- }
-
-
- // Create a new file upload handler
- DiskFileItemFactory factory = new DiskFileItemFactory();
- try {
- factory.setRepository(location.getCanonicalFile());
- } catch (IOException ioe) {
- parameters.setParseFailedReason(FailReason.IO_ERROR);
- partsParseException = ioe;
- return;
- }
- factory.setSizeThreshold(mce.getFileSizeThreshold());
-
- ServletFileUpload upload = new ServletFileUpload();
- upload.setFileItemFactory(factory);
- upload.setFileSizeMax(mce.getMaxFileSize());
- upload.setSizeMax(mce.getMaxRequestSize());
- if (maxParameterCount > -1) {
- // There is a limit. The limit for parts needs to be reduced by
- // the number of parameters we have already parsed.
- // Must be under the limit else parsing parameters would have
- // triggered an exception.
- upload.setFileCountMax(maxParameterCount - parameters.size());
- }
-
- parts = new ArrayList<>();
- try {
- List<FileItem> items =
- upload.parseRequest(new ServletRequestContext(this));
- int maxPostSize = getConnector().getMaxPostSize();
- int postSize = 0;
- Charset charset = getCharset();
- for (FileItem item : items) {
- ApplicationPart part = new ApplicationPart(item, location);
- parts.add(part);
- if (part.getSubmittedFileName() == null) {
- String name = part.getName();
- if (maxPostSize >= 0) {
- // Have to calculate equivalent size. Not completely
- // accurate but close enough.
- postSize += name.getBytes(charset).length;
- // Equals sign
- postSize++;
- // Value length
- postSize += part.getSize();
- // Value separator
- postSize++;
- if (postSize > maxPostSize) {
- parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
- throw new IllegalStateException(sm.getString(
- "coyoteRequest.maxPostSizeExceeded"));
- }
- }
- String value = null;
- try {
- value = part.getString(charset.name());
- } catch (UnsupportedEncodingException uee) {
- // Not possible
- }
- parameters.addParameter(name, value);
- }
- }
-
- success = true;
- } catch (InvalidContentTypeException e) {
- parameters.setParseFailedReason(FailReason.INVALID_CONTENT_TYPE);
- partsParseException = new ServletException(e);
- } catch (SizeException e) {
- parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
- checkSwallowInput();
- partsParseException = new IllegalStateException(e);
- } catch (IOException e) {
- parameters.setParseFailedReason(FailReason.IO_ERROR);
- partsParseException = new IOException(e);
- } catch (IllegalStateException e) {
- // addParameters() will set parseFailedReason
- checkSwallowInput();
- partsParseException = e;
- }
- } finally {
- // This might look odd but is correct. setParseFailedReason() only
- // sets the failure reason if none is currently set. This code could
- // be more efficient but it is written this way to be robust with
- // respect to changes in the remainder of the method.
- if (partsParseException != null || !success) {
- parameters.setParseFailedReason(FailReason.UNKNOWN);
- }
- }
- }
-
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Part getPart(String name) throws IOException, IllegalStateException,
- ServletException {
- for (Part part : getParts()) {
- if (name.equals(part.getName())) {
- return part;
- }
- }
- return null;
- }
-
-
- // ------------------------------------------------------ Protected Methods
-
- protected Session doGetSession(boolean create) {
-
- // There cannot be a session if no context has been assigned yet
- Context context = getContext();
- if (context == null) {
- return null;
- }
-
- // Return the current session if it exists and is valid
- if ((session != null) && !session.isValid()) {
- session = null;
- }
- if (session != null) {
- return session;
- }
-
- // Return the requested session if it exists and is valid
- Manager manager = context.getManager();
- if (manager == null) {
- return null; // Sessions are not supported
- }
- if (requestedSessionId != null) {
- try {
- session = manager.findSession(requestedSessionId);
- } catch (IOException e) {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("request.session.failed", requestedSessionId, e.getMessage()), e);
- } else {
- log.info(sm.getString("request.session.failed", requestedSessionId, e.getMessage()));
- }
- session = null;
- }
- if ((session != null) && !session.isValid()) {
- session = null;
- }
- if (session != null) {
- session.access();
- return session;
- }
- }
-
- // Create a new session if requested and the response is not committed
- if (!create) {
- return null;
- }
- boolean trackModesIncludesCookie =
- context.getServletContext().getEffectiveSessionTrackingModes().contains(SessionTrackingMode.COOKIE);
- if (trackModesIncludesCookie && response.getResponse().isCommitted()) {
- throw new IllegalStateException(sm.getString("coyoteRequest.sessionCreateCommitted"));
- }
-
- // Re-use session IDs provided by the client in very limited
- // circumstances.
- String sessionId = getRequestedSessionId();
- if (requestedSessionSSL) {
- // If the session ID has been obtained from the SSL handshake then
- // use it.
- } else if (("/".equals(context.getSessionCookiePath())
- && isRequestedSessionIdFromCookie())) {
- /* This is the common(ish) use case: using the same session ID with
- * multiple web applications on the same host. Typically this is
- * used by Portlet implementations. It only works if sessions are
- * tracked via cookies. The cookie must have a path of "/" else it
- * won't be provided for requests to all web applications.
- *
- * Any session ID provided by the client should be for a session
- * that already exists somewhere on the host. Check if the context
- * is configured for this to be confirmed.
- */
- if (context.getValidateClientProvidedNewSessionId()) {
- boolean found = false;
- for (Container container : getHost().findChildren()) {
- Manager m = ((Context) container).getManager();
- if (m != null) {
- try {
- if (m.findSession(sessionId) != null) {
- found = true;
- break;
- }
- } catch (IOException e) {
- // Ignore. Problems with this manager will be
- // handled elsewhere.
- }
- }
- }
- if (!found) {
- sessionId = null;
- }
- }
- } else {
- sessionId = null;
- }
- session = manager.createSession(sessionId);
-
- // Creating a new session cookie based on that session
- if (session != null && trackModesIncludesCookie) {
- Cookie cookie = ApplicationSessionCookieConfig.createSessionCookie(
- context, session.getIdInternal(), isSecure());
-
- response.addSessionCookieInternal(cookie);
- }
-
- if (session == null) {
- return null;
- }
-
- session.access();
- return session;
- }
-
- protected String unescape(String s) {
- if (s==null) {
- return null;
- }
- if (s.indexOf('\\') == -1) {
- return s;
- }
- StringBuilder buf = new StringBuilder();
- for (int i=0; i<s.length(); i++) {
- char c = s.charAt(i);
- if (c!='\\') {
- buf.append(c);
- } else {
- if (++i >= s.length()) {
- throw new IllegalArgumentException();//invalid escape, hence invalid cookie
- }
- c = s.charAt(i);
- buf.append(c);
- }
- }
- return buf.toString();
- }
-
- /**
- * Parse cookies. This only parses the cookies into the memory efficient
- * ServerCookies structure. It does not populate the Cookie objects.
- */
- protected void parseCookies() {
- if (cookiesParsed) {
- return;
- }
-
- cookiesParsed = true;
-
- ServerCookies serverCookies = coyoteRequest.getCookies();
- serverCookies.setLimit(connector.getMaxCookieCount());
- CookieProcessor cookieProcessor = getContext().getCookieProcessor();
- cookieProcessor.parseCookieHeader(coyoteRequest.getMimeHeaders(), serverCookies);
- }
-
- /**
- * Converts the parsed cookies (parsing the Cookie headers first if they
- * have not been parsed) into Cookie objects.
- */
- protected void convertCookies() {
- if (cookiesConverted) {
- return;
- }
-
- cookiesConverted = true;
-
- if (getContext() == null) {
- return;
- }
-
- parseCookies();
-
- ServerCookies serverCookies = coyoteRequest.getCookies();
- CookieProcessor cookieProcessor = getContext().getCookieProcessor();
-
- int count = serverCookies.getCookieCount();
- if (count <= 0) {
- return;
- }
-
- cookies = new Cookie[count];
-
- int idx=0;
- for (int i = 0; i < count; i++) {
- ServerCookie scookie = serverCookies.getCookie(i);
- try {
- // We must unescape the '\\' escape character
- Cookie cookie = new Cookie(scookie.getName().toString(),null);
- int version = scookie.getVersion();
- cookie.setVersion(version);
- scookie.getValue().getByteChunk().setCharset(cookieProcessor.getCharset());
- cookie.setValue(unescape(scookie.getValue().toString()));
- cookie.setPath(unescape(scookie.getPath().toString()));
- String domain = scookie.getDomain().toString();
- if (domain!=null) {
- cookie.setDomain(unescape(domain));//avoid NPE
- }
- String comment = scookie.getComment().toString();
- cookie.setComment(version==1?unescape(comment):null);
- cookies[idx++] = cookie;
- } catch(IllegalArgumentException e) {
- // Ignore bad cookie
- }
- }
- if( idx < count ) {
- Cookie [] ncookies = new Cookie[idx];
- System.arraycopy(cookies, 0, ncookies, 0, idx);
- cookies = ncookies;
- }
- }
-
-
- /**
- * Parse request parameters.
- */
- protected void parseParameters() {
-
- parametersParsed = true;
-
- Parameters parameters = coyoteRequest.getParameters();
- boolean success = false;
- try {
- // Set this every time in case limit has been changed via JMX
- parameters.setLimit(getConnector().getMaxParameterCount());
-
- // getCharacterEncoding() may have been overridden to search for
- // hidden form field containing request encoding
- Charset charset = getCharset();
-
- boolean useBodyEncodingForURI = connector.getUseBodyEncodingForURI();
- parameters.setCharset(charset);
- if (useBodyEncodingForURI) {
- parameters.setQueryStringCharset(charset);
- }
- // Note: If !useBodyEncodingForURI, the query string encoding is
- // that set towards the start of CoyoyeAdapter.service()
-
- parameters.handleQueryParameters();
-
- if (usingInputStream || usingReader) {
- success = true;
- return;
- }
-
- String contentType = getContentType();
- if (contentType == null) {
- contentType = "";
- }
- int semicolon = contentType.indexOf(';');
- if (semicolon >= 0) {
- contentType = contentType.substring(0, semicolon).trim();
- } else {
- contentType = contentType.trim();
- }
-
- if ("multipart/form-data".equals(contentType)) {
- parseParts(false);
- success = true;
- return;
- }
-
- if( !getConnector().isParseBodyMethod(getMethod()) ) {
- success = true;
- return;
- }
-
- if (!("application/x-www-form-urlencoded".equals(contentType))) {
- success = true;
- return;
- }
-
- int len = getContentLength();
-
- if (len > 0) {
- int maxPostSize = connector.getMaxPostSize();
- if ((maxPostSize >= 0) && (len > maxPostSize)) {
- Context context = getContext();
- if (context != null && context.getLogger().isDebugEnabled()) {
- context.getLogger().debug(
- sm.getString("coyoteRequest.postTooLarge"));
- }
- checkSwallowInput();
- parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
- return;
- }
- byte[] formData = null;
- if (len < CACHED_POST_LEN) {
- if (postData == null) {
- postData = new byte[CACHED_POST_LEN];
- }
- formData = postData;
- } else {
- formData = new byte[len];
- }
- try {
- if (readPostBody(formData, len) != len) {
- parameters.setParseFailedReason(FailReason.REQUEST_BODY_INCOMPLETE);
- return;
- }
- } catch (IOException e) {
- // Client disconnect
- Context context = getContext();
- if (context != null && context.getLogger().isDebugEnabled()) {
- context.getLogger().debug(
- sm.getString("coyoteRequest.parseParameters"), e);
- }
- parameters.setParseFailedReason(FailReason.CLIENT_DISCONNECT);
- return;
- }
- parameters.processParameters(formData, 0, len);
- } else if ("chunked".equalsIgnoreCase(
- coyoteRequest.getHeader("transfer-encoding"))) {
- byte[] formData = null;
- try {
- formData = readChunkedPostBody();
- } catch (IllegalStateException ise) {
- // chunkedPostTooLarge error
- parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
- Context context = getContext();
- if (context != null && context.getLogger().isDebugEnabled()) {
- context.getLogger().debug(
- sm.getString("coyoteRequest.parseParameters"),
- ise);
- }
- return;
- } catch (IOException e) {
- // Client disconnect
- parameters.setParseFailedReason(FailReason.CLIENT_DISCONNECT);
- Context context = getContext();
- if (context != null && context.getLogger().isDebugEnabled()) {
- context.getLogger().debug(
- sm.getString("coyoteRequest.parseParameters"), e);
- }
- return;
- }
- if (formData != null) {
- parameters.processParameters(formData, 0, formData.length);
- }
- }
- success = true;
- } finally {
- if (!success) {
- parameters.setParseFailedReason(FailReason.UNKNOWN);
- }
- }
-
- }
-
-
- /**
- * Read post body in an array.
- *
- * @param body The bytes array in which the body will be read
- * @param len The body length
- * @return the bytes count that has been read
- * @throws IOException if an IO exception occurred
- */
- protected int readPostBody(byte[] body, int len)
- throws IOException {
-
- int offset = 0;
- do {
- int inputLen = getStream().read(body, offset, len - offset);
- if (inputLen <= 0) {
- return offset;
- }
- offset += inputLen;
- } while ((len - offset) > 0);
- return len;
-
- }
-
-
- /**
- * Read chunked post body.
- *
- * @return the post body as a bytes array
- * @throws IOException if an IO exception occurred
- */
- protected byte[] readChunkedPostBody() throws IOException {
- ByteChunk body = new ByteChunk();
-
- byte[] buffer = new byte[CACHED_POST_LEN];
-
- int len = 0;
- while (len > -1) {
- len = getStream().read(buffer, 0, CACHED_POST_LEN);
- if (connector.getMaxPostSize() >= 0 &&
- (body.getLength() + len) > connector.getMaxPostSize()) {
- // Too much data
- checkSwallowInput();
- throw new IllegalStateException(
- sm.getString("coyoteRequest.chunkedPostTooLarge"));
- }
- if (len > 0) {
- body.append(buffer, 0, len);
- }
- }
- if (body.getLength() == 0) {
- return null;
- }
- if (body.getLength() < body.getBuffer().length) {
- int length = body.getLength();
- byte[] result = new byte[length];
- System.arraycopy(body.getBuffer(), 0, result, 0, length);
- return result;
- }
-
- return body.getBuffer();
- }
-
-
- /**
- * Parse request locales.
- */
- protected void parseLocales() {
-
- localesParsed = true;
-
- // Store the accumulated languages that have been requested in
- // a local collection, sorted by the quality value (so we can
- // add Locales in descending order). The values will be ArrayLists
- // containing the corresponding Locales to be added
- TreeMap<Double, ArrayList<Locale>> locales = new TreeMap<>();
-
- Enumeration<String> values = getHeaders("accept-language");
-
- while (values.hasMoreElements()) {
- String value = values.nextElement();
- parseLocalesHeader(value, locales);
- }
-
- // Process the quality values in highest->lowest order (due to
- // negating the Double value when creating the key)
- for (ArrayList<Locale> list : locales.values()) {
- for (Locale locale : list) {
- addLocale(locale);
- }
- }
- }
-
-
- /**
- * Parse accept-language header value.
- *
- * @param value the header value
- * @param locales the map that will hold the result
- */
- protected void parseLocalesHeader(String value, TreeMap<Double, ArrayList<Locale>> locales) {
-
- List<AcceptLanguage> acceptLanguages;
- try {
- acceptLanguages = AcceptLanguage.parse(new StringReader(value));
- } catch (IOException e) {
- // Mal-formed headers are ignore. Do the same in the unlikely event
- // of an IOException.
- return;
- }
-
- for (AcceptLanguage acceptLanguage : acceptLanguages) {
- // Add a new Locale to the list of Locales for this quality level
- Double key = Double.valueOf(-acceptLanguage.getQuality()); // Reverse the order
- locales.computeIfAbsent(key, k -> new ArrayList<>()).add(acceptLanguage.getLocale());
- }
- }
-
-
- // ----------------------------------------------------- Special attributes handling
-
- private static interface SpecialAttributeAdapter {
- Object get(Request request, String name);
-
- void set(Request request, String name, Object value);
-
- // None of special attributes support removal
- // void remove(Request request, String name);
- }
-
- private static final Map<String, SpecialAttributeAdapter> specialAttributes = new HashMap<>();
-
- static {
- specialAttributes.put(Globals.DISPATCHER_TYPE_ATTR,
- new SpecialAttributeAdapter() {
- @Override
- public Object get(Request request, String name) {
- return (request.internalDispatcherType == null) ? DispatcherType.REQUEST
- : request.internalDispatcherType;
- }
-
- @Override
- public void set(Request request, String name, Object value) {
- request.internalDispatcherType = (DispatcherType) value;
- }
- });
- specialAttributes.put(Globals.DISPATCHER_REQUEST_PATH_ATTR,
- new SpecialAttributeAdapter() {
- @Override
- public Object get(Request request, String name) {
- return (request.requestDispatcherPath == null) ? request
- .getRequestPathMB().toString()
- : request.requestDispatcherPath.toString();
- }
-
- @Override
- public void set(Request request, String name, Object value) {
- request.requestDispatcherPath = value;
- }
- });
- specialAttributes.put(Globals.ASYNC_SUPPORTED_ATTR,
- new SpecialAttributeAdapter() {
- @Override
- public Object get(Request request, String name) {
- return request.asyncSupported;
- }
-
- @Override
- public void set(Request request, String name, Object value) {
- Boolean oldValue = request.asyncSupported;
- request.asyncSupported = (Boolean)value;
- request.notifyAttributeAssigned(name, value, oldValue);
- }
- });
- specialAttributes.put(Globals.GSS_CREDENTIAL_ATTR,
- new SpecialAttributeAdapter() {
- @Override
- public Object get(Request request, String name) {
- if (request.userPrincipal instanceof TomcatPrincipal) {
- return ((TomcatPrincipal) request.userPrincipal)
- .getGssCredential();
- }
- return null;
- }
-
- @Override
- public void set(Request request, String name, Object value) {
- // NO-OP
- }
- });
- specialAttributes.put(Globals.PARAMETER_PARSE_FAILED_ATTR,
- new SpecialAttributeAdapter() {
- @Override
- public Object get(Request request, String name) {
- if (request.getCoyoteRequest().getParameters()
- .isParseFailed()) {
- return Boolean.TRUE;
- }
- return null;
- }
-
- @Override
- public void set(Request request, String name, Object value) {
- // NO-OP
- }
- });
- specialAttributes.put(Globals.PARAMETER_PARSE_FAILED_REASON_ATTR,
- new SpecialAttributeAdapter() {
- @Override
- public Object get(Request request, String name) {
- return request.getCoyoteRequest().getParameters().getParseFailedReason();
- }
-
- @Override
- public void set(Request request, String name, Object value) {
- // NO-OP
- }
- });
- specialAttributes.put(Globals.SENDFILE_SUPPORTED_ATTR,
- new SpecialAttributeAdapter() {
- @Override
- public Object get(Request request, String name) {
- return Boolean.valueOf(
- request.getConnector().getProtocolHandler(
- ).isSendfileSupported() && request.getCoyoteRequest().getSendfile());
- }
- @Override
- public void set(Request request, String name, Object value) {
- // NO-OP
- }
- });
- specialAttributes.put(Globals.CONNECTION_ID,
- new SpecialAttributeAdapter() {
- @Override
- public Object get(Request request, String name) {
- AtomicReference<Object> result = new AtomicReference<>();
- request.getCoyoteRequest().action(ActionCode.CONNECTION_ID, result);
- return result.get();
- }
- @Override
- public void set(Request request, String name, Object value) {
- // NO-OP
- }
- });
- specialAttributes.put(Globals.STREAM_ID,
- new SpecialAttributeAdapter() {
- @Override
- public Object get(Request request, String name) {
- AtomicReference<Object> result = new AtomicReference<>();
- request.getCoyoteRequest().action(ActionCode.STREAM_ID, result);
- return result.get();
- }
- @Override
- public void set(Request request, String name, Object value) {
- // NO-OP
- }
- });
- specialAttributes.put(Globals.REMOTE_IP_FILTER_SECURE,
- new SpecialAttributeAdapter() {
- @Override
- public Object get(Request request, String name) {
- return Boolean.valueOf(request.isSecure());
- }
-
- @Override
- public void set(Request request, String name, Object value) {
- if (value instanceof Boolean) {
- request.setSecure(((Boolean) value).booleanValue());
- }
- }
- });
- }
-}
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/ApplicationDispatcher.java b/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/ApplicationDispatcher.java
deleted file mode 100644
index f11de9f23e..0000000000
--- a/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/ApplicationDispatcher.java
+++ /dev/null
@@ -1,1036 +0,0 @@
-/*
- * 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.PrintWriter;
-import java.security.AccessController;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-
-import jakarta.servlet.AsyncContext;
-import jakarta.servlet.DispatcherType;
-import jakarta.servlet.RequestDispatcher;
-import jakarta.servlet.Servlet;
-import jakarta.servlet.ServletException;
-import jakarta.servlet.ServletOutputStream;
-import jakarta.servlet.ServletRequest;
-import jakarta.servlet.ServletRequestWrapper;
-import jakarta.servlet.ServletResponse;
-import jakarta.servlet.ServletResponseWrapper;
-import jakarta.servlet.UnavailableException;
-import jakarta.servlet.http.HttpServletMapping;
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
-
-import org.apache.catalina.AsyncDispatcher;
-import org.apache.catalina.Context;
-import org.apache.catalina.Globals;
-import org.apache.catalina.Wrapper;
-import org.apache.catalina.connector.Request;
-import org.apache.catalina.connector.RequestFacade;
-import org.apache.catalina.connector.Response;
-import org.apache.catalina.connector.ResponseFacade;
-import org.apache.coyote.BadRequestException;
-import org.apache.tomcat.util.ExceptionUtils;
-import org.apache.tomcat.util.res.StringManager;
-
-/**
- * Standard implementation of <code>RequestDispatcher</code> that allows a
- * request to be forwarded to a different resource to create the ultimate
- * response, or to include the output of another resource in the response
- * from this resource. This implementation allows application level servlets
- * to wrap the request and/or response objects that are passed on to the
- * called resource, as long as the wrapping classes extend
- * <code>jakarta.servlet.ServletRequestWrapper</code> and
- * <code>jakarta.servlet.ServletResponseWrapper</code>.
- *
- * @author Craig R. McClanahan
- */
-final class ApplicationDispatcher implements AsyncDispatcher, RequestDispatcher {
-
- protected class PrivilegedForward
- implements PrivilegedExceptionAction<Void> {
- private final ServletRequest request;
- private final ServletResponse response;
-
- PrivilegedForward(ServletRequest request, ServletResponse response) {
- this.request = request;
- this.response = response;
- }
-
- @Override
- public Void run() throws java.lang.Exception {
- doForward(request,response);
- return null;
- }
- }
-
- protected class PrivilegedInclude implements
- PrivilegedExceptionAction<Void> {
- private final ServletRequest request;
- private final ServletResponse response;
-
- PrivilegedInclude(ServletRequest request, ServletResponse response) {
- this.request = request;
- this.response = response;
- }
-
- @Override
- public Void run() throws ServletException, IOException {
- doInclude(request, response);
- return null;
- }
- }
-
- protected class PrivilegedDispatch implements
- PrivilegedExceptionAction<Void> {
- private final ServletRequest request;
- private final ServletResponse response;
-
- PrivilegedDispatch(ServletRequest request, ServletResponse response) {
- this.request = request;
- this.response = response;
- }
-
- @Override
- public Void run() throws ServletException, IOException {
- doDispatch(request, response);
- return null;
- }
- }
-
-
- /**
- * Used to pass state when the request dispatcher is used. Using instance
- * variables causes threading issues and state is too complex to pass and
- * return single ServletRequest or ServletResponse objects.
- */
- private static class State {
- State(ServletRequest request, ServletResponse response,
- boolean including) {
- this.outerRequest = request;
- this.outerResponse = response;
- this.including = including;
- }
-
- /**
- * The outermost request that will be passed on to the invoked servlet.
- */
- ServletRequest outerRequest = null;
-
-
- /**
- * The outermost response that will be passed on to the invoked servlet.
- */
- ServletResponse outerResponse = null;
-
- /**
- * The request wrapper we have created and installed (if any).
- */
- ServletRequest wrapRequest = null;
-
-
- /**
- * The response wrapper we have created and installed (if any).
- */
- ServletResponse wrapResponse = null;
-
- /**
- * Are we performing an include() instead of a forward()?
- */
- boolean including = false;
-
- /**
- * Outermost HttpServletRequest in the chain
- */
- HttpServletRequest hrequest = null;
-
- /**
- * Outermost HttpServletResponse in the chain
- */
- HttpServletResponse hresponse = null;
- }
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Construct a new instance of this class, configured according to the
- * specified parameters. If both servletPath and pathInfo are
- * <code>null</code>, it will be assumed that this RequestDispatcher
- * was acquired by name, rather than by path.
- *
- * @param wrapper The Wrapper associated with the resource that will
- * be forwarded to or included (required)
- * @param requestURI The request URI to this resource (if any)
- * @param servletPath The revised servlet path to this resource (if any)
- * @param pathInfo The revised extra path information to this resource
- * (if any)
- * @param queryString Query string parameters included with this request
- * (if any)
- * @param mapping The mapping for this resource (if any)
- * @param name Servlet name (if a named dispatcher was created)
- * else <code>null</code>
- */
- public ApplicationDispatcher
- (Wrapper wrapper, String requestURI, String servletPath,
- String pathInfo, String queryString, HttpServletMapping mapping, String name) {
-
- super();
-
- // Save all of our configuration parameters
- this.wrapper = wrapper;
- this.context = (Context) wrapper.getParent();
- this.requestURI = requestURI;
- this.servletPath = servletPath;
- this.pathInfo = pathInfo;
- this.queryString = queryString;
- this.mapping = mapping;
- this.name = name;
- }
-
-
- // ----------------------------------------------------- Instance Variables
-
- /**
- * The Context this RequestDispatcher is associated with.
- */
- private final Context context;
-
-
- /**
- * The servlet name for a named dispatcher.
- */
- private final String name;
-
-
- /**
- * The extra path information for this RequestDispatcher.
- */
- private final String pathInfo;
-
-
- /**
- * The query string parameters for this RequestDispatcher.
- */
- private final String queryString;
-
-
- /**
- * The request URI for this RequestDispatcher.
- */
- private final String requestURI;
-
-
- /**
- * The servlet path for this RequestDispatcher.
- */
- private final String servletPath;
-
-
- /**
- * The mapping for this RequestDispatcher.
- */
- private final HttpServletMapping mapping;
-
-
- /**
- * The StringManager for this package.
- */
- private static final StringManager sm = StringManager.getManager(ApplicationDispatcher.class);
-
-
- /**
- * The Wrapper associated with the resource that will be forwarded to
- * or included.
- */
- private final Wrapper wrapper;
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Forward this request and response to another resource for processing.
- * Any runtime exception, IOException, or ServletException thrown by the
- * called servlet will be propagated to the caller.
- *
- * @param request The servlet request to be forwarded
- * @param response The servlet response to be forwarded
- *
- * @exception IOException if an input/output error occurs
- * @exception ServletException if a servlet exception occurs
- */
- @Override
- public void forward(ServletRequest request, ServletResponse response)
- throws ServletException, IOException
- {
- if (Globals.IS_SECURITY_ENABLED) {
- try {
- PrivilegedForward dp = new PrivilegedForward(request,response);
- AccessController.doPrivileged(dp);
- } catch (PrivilegedActionException pe) {
- Exception e = pe.getException();
- if (e instanceof ServletException) {
- throw (ServletException) e;
- }
- throw (IOException) e;
- }
- } else {
- doForward(request,response);
- }
- }
-
- private void doForward(ServletRequest request, ServletResponse response)
- throws ServletException, IOException
- {
-
- // Reset any output that has been buffered, but keep headers/cookies
- if (response.isCommitted()) {
- throw new IllegalStateException
- (sm.getString("applicationDispatcher.forward.ise"));
- }
- try {
- response.resetBuffer();
- } catch (IllegalStateException e) {
- throw e;
- }
-
- // Set up to handle the specified request and response
- State state = new State(request, response, false);
-
- if (context.getDispatcherWrapsSameObject()) {
- // Check SRV.9.2 / RequestDispacther Javadoc
- checkSameObjects(request, response);
- }
-
- wrapResponse(state);
- // Handle an HTTP named dispatcher forward
- if ((servletPath == null) && (pathInfo == null)) {
-
- ApplicationHttpRequest wrequest =
- (ApplicationHttpRequest) wrapRequest(state);
- HttpServletRequest hrequest = state.hrequest;
- wrequest.setRequestURI(hrequest.getRequestURI());
- wrequest.setContextPath(hrequest.getContextPath());
- wrequest.setServletPath(hrequest.getServletPath());
- wrequest.setPathInfo(hrequest.getPathInfo());
- wrequest.setQueryString(hrequest.getQueryString());
-
- processRequest(request,response,state);
- }
-
- // Handle an HTTP path-based forward
- else {
-
- ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state);
- HttpServletRequest hrequest = state.hrequest;
- if (hrequest.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI) == null) {
- wrequest.setAttribute(RequestDispatcher.FORWARD_REQUEST_URI,
- hrequest.getRequestURI());
- wrequest.setAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH,
- hrequest.getContextPath());
- wrequest.setAttribute(RequestDispatcher.FORWARD_SERVLET_PATH,
- hrequest.getServletPath());
- wrequest.setAttribute(RequestDispatcher.FORWARD_PATH_INFO,
- hrequest.getPathInfo());
- wrequest.setAttribute(RequestDispatcher.FORWARD_QUERY_STRING,
- hrequest.getQueryString());
- wrequest.setAttribute(RequestDispatcher.FORWARD_MAPPING, hrequest.getHttpServletMapping());
- }
-
- wrequest.setContextPath(context.getEncodedPath());
- wrequest.setRequestURI(requestURI);
- wrequest.setServletPath(servletPath);
- wrequest.setPathInfo(pathInfo);
- if (queryString != null) {
- wrequest.setQueryString(queryString);
- wrequest.setQueryParams(queryString);
- }
- wrequest.setMapping(mapping);
-
- processRequest(request,response,state);
- }
-
- if (request.isAsyncStarted()) {
- // An async request was started during the forward, don't close the
- // response as it may be written to during the async handling
- return;
- }
-
- // This is not a real close in order to support error processing
- if (wrapper.getLogger().isDebugEnabled() ) {
- wrapper.getLogger().debug(" Disabling the response for further output");
- }
-
- if (response instanceof ResponseFacade) {
- ((ResponseFacade) response).finish();
- } else {
- // Servlet SRV.6.2.2. The Request/Response may have been wrapped
- // and may no longer be instance of RequestFacade
- if (wrapper.getLogger().isDebugEnabled()){
- wrapper.getLogger().debug( " The Response is vehiculed using a wrapper: "
- + response.getClass().getName() );
- }
-
- // Close anyway
- try {
- PrintWriter writer = response.getWriter();
- writer.close();
- } catch (IllegalStateException e) {
- try {
- ServletOutputStream stream = response.getOutputStream();
- stream.close();
- } catch (IllegalStateException | IOException f) {
- // Ignore
- }
- } catch (IOException e) {
- // Ignore
- }
- }
-
- }
-
-
- /**
- * Prepare the request based on the filter configuration.
- * @param request The servlet request we are processing
- * @param response The servlet response we are creating
- * @param state The RD state
- *
- * @exception IOException if an input/output error occurs
- * @exception ServletException if a servlet error occurs
- */
- private void processRequest(ServletRequest request,
- ServletResponse response,
- State state)
- throws IOException, ServletException {
-
- DispatcherType disInt = (DispatcherType) request.getAttribute(Globals.DISPATCHER_TYPE_ATTR);
- if (disInt != null) {
- boolean doInvoke = true;
-
- if (context.getFireRequestListenersOnForwards() &&
- !context.fireRequestInitEvent(request)) {
- doInvoke = false;
- }
-
- if (doInvoke) {
- if (disInt != DispatcherType.ERROR) {
- state.outerRequest.setAttribute(
- Globals.DISPATCHER_REQUEST_PATH_ATTR,
- getCombinedPath());
- state.outerRequest.setAttribute(
- Globals.DISPATCHER_TYPE_ATTR,
- DispatcherType.FORWARD);
- invoke(state.outerRequest, response, state);
- } else {
- invoke(state.outerRequest, response, state);
- }
-
- if (context.getFireRequestListenersOnForwards()) {
- context.fireRequestDestroyEvent(request);
- }
- }
- }
- }
-
-
- /**
- * Combine the servletPath and the pathInfo. If pathInfo is
- * <code>null</code> it is ignored. If servletPath is <code>null</code> then
- * <code>null</code> is returned.
- * @return The combined path with pathInfo appended to servletInfo
- */
- private String getCombinedPath() {
- if (servletPath == null) {
- return null;
- }
- if (pathInfo == null) {
- return servletPath;
- }
- return servletPath + pathInfo;
- }
-
-
- /**
- * Include the response from another resource in the current response.
- * Any runtime exception, IOException, or ServletException thrown by the
- * called servlet will be propagated to the caller.
- *
- * @param request The servlet request that is including this one
- * @param response The servlet response to be appended to
- *
- * @exception IOException if an input/output error occurs
- * @exception ServletException if a servlet exception occurs
- */
- @Override
- public void include(ServletRequest request, ServletResponse response)
- throws ServletException, IOException
- {
- if (Globals.IS_SECURITY_ENABLED) {
- try {
- PrivilegedInclude dp = new PrivilegedInclude(request,response);
- AccessController.doPrivileged(dp);
- } catch (PrivilegedActionException pe) {
- Exception e = pe.getException();
-
- if (e instanceof ServletException) {
- throw (ServletException) e;
- }
- throw (IOException) e;
- }
- } else {
- doInclude(request, response);
- }
- }
-
- private void doInclude(ServletRequest request, ServletResponse response)
- throws ServletException, IOException {
-
- // Set up to handle the specified request and response
- State state = new State(request, response, true);
-
- if (context.getDispatcherWrapsSameObject()) {
- // Check SRV.8.2 / SRV.14.2.5.1 compliance
- checkSameObjects(request, response);
- }
-
- // Create a wrapped response to use for this request
- wrapResponse(state);
-
- // Handle an HTTP named dispatcher include
- if (name != null) {
-
- ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state);
- wrequest.setAttribute(Globals.NAMED_DISPATCHER_ATTR, name);
- if (servletPath != null) {
- wrequest.setServletPath(servletPath);
- }
- wrequest.setAttribute(Globals.DISPATCHER_TYPE_ATTR, DispatcherType.INCLUDE);
- wrequest.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR, getCombinedPath());
- invoke(state.outerRequest, state.outerResponse, state);
- }
-
- // Handle an HTTP path based include
- else {
-
- ApplicationHttpRequest wrequest =
- (ApplicationHttpRequest) wrapRequest(state);
- String contextPath = context.getPath();
- if (requestURI != null) {
- wrequest.setAttribute(RequestDispatcher.INCLUDE_REQUEST_URI, requestURI);
- }
- if (contextPath != null) {
- wrequest.setAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH, contextPath);
- }
- if (servletPath != null) {
- wrequest.setAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH, servletPath);
- }
- if (pathInfo != null) {
- wrequest.setAttribute(RequestDispatcher.INCLUDE_PATH_INFO, pathInfo);
- }
- if (queryString != null) {
- wrequest.setAttribute(RequestDispatcher.INCLUDE_QUERY_STRING, queryString);
- wrequest.setQueryParams(queryString);
- }
- if (mapping != null) {
- wrequest.setAttribute(RequestDispatcher.INCLUDE_MAPPING, mapping);
- }
-
- wrequest.setAttribute(Globals.DISPATCHER_TYPE_ATTR,
- DispatcherType.INCLUDE);
- wrequest.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR,
- getCombinedPath());
- invoke(state.outerRequest, state.outerResponse, state);
- }
-
- }
-
-
- @Override
- public void dispatch(ServletRequest request, ServletResponse response)
- throws ServletException, IOException {
- if (Globals.IS_SECURITY_ENABLED) {
- try {
- PrivilegedDispatch dp = new PrivilegedDispatch(request,response);
- AccessController.doPrivileged(dp);
- } catch (PrivilegedActionException pe) {
- Exception e = pe.getException();
-
- if (e instanceof ServletException) {
- throw (ServletException) e;
- }
- throw (IOException) e;
- }
- } else {
- doDispatch(request, response);
- }
- }
-
- private void doDispatch(ServletRequest request, ServletResponse response)
- throws ServletException, IOException {
-
- // Set up to handle the specified request and response
- State state = new State(request, response, false);
-
- // Create a wrapped response to use for this request
- wrapResponse(state);
-
- ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state);
- HttpServletRequest hrequest = state.hrequest;
-
- wrequest.setAttribute(Globals.DISPATCHER_TYPE_ATTR, DispatcherType.ASYNC);
- wrequest.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR, getCombinedPath());
- wrequest.setAttribute(AsyncContext.ASYNC_MAPPING, hrequest.getHttpServletMapping());
-
- wrequest.setContextPath(context.getEncodedPath());
- wrequest.setRequestURI(requestURI);
- wrequest.setServletPath(servletPath);
- wrequest.setPathInfo(pathInfo);
- if (queryString != null) {
- wrequest.setQueryString(queryString);
- wrequest.setQueryParams(queryString);
- }
- wrequest.setMapping(mapping);
-
- invoke(state.outerRequest, state.outerResponse, state);
- }
-
-
- // -------------------------------------------------------- Private Methods
-
-
- /**
- * Ask the resource represented by this RequestDispatcher to process
- * the associated request, and create (or append to) the associated
- * response.
- * <p>
- * <strong>IMPLEMENTATION NOTE</strong>: This implementation assumes
- * that no filters are applied to a forwarded or included resource,
- * because they were already done for the original request.
- *
- * @param request The servlet request we are processing
- * @param response The servlet response we are creating
- *
- * @exception IOException if an input/output error occurs
- * @exception ServletException if a servlet error occurs
- */
- private void invoke(ServletRequest request, ServletResponse response,
- State state) throws IOException, ServletException {
-
- // Checking to see if the context classloader is the current context
- // classloader. If it's not, we're saving it, and setting the context
- // classloader to the Context classloader
- ClassLoader oldCCL = context.bind(false, null);
-
- // Initialize local variables we may need
- HttpServletResponse hresponse = state.hresponse;
- Servlet servlet = null;
- IOException ioException = null;
- ServletException servletException = null;
- RuntimeException runtimeException = null;
- boolean unavailable = false;
-
- // Check for the servlet being marked unavailable
- if (wrapper.isUnavailable()) {
- wrapper.getLogger().warn(
- sm.getString("applicationDispatcher.isUnavailable",
- wrapper.getName()));
- long available = wrapper.getAvailable();
- if ((available > 0L) && (available < Long.MAX_VALUE)) {
- hresponse.setDateHeader("Retry-After", available);
- }
- hresponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
- sm.getString("applicationDispatcher.isUnavailable", wrapper.getName()));
- unavailable = true;
- }
-
- // Allocate a servlet instance to process this request
- try {
- if (!unavailable) {
- servlet = wrapper.allocate();
- }
- } catch (ServletException e) {
- wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException",
- wrapper.getName()), StandardWrapper.getRootCause(e));
- servletException = e;
- } catch (Throwable e) {
- ExceptionUtils.handleThrowable(e);
- wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException",
- wrapper.getName()), e);
- servletException = new ServletException
- (sm.getString("applicationDispatcher.allocateException",
- wrapper.getName()), e);
- servlet = null;
- }
-
- // Get the FilterChain Here
- ApplicationFilterChain filterChain =
- ApplicationFilterFactory.createFilterChain(request, wrapper, servlet);
-
- // Call the service() method for the allocated servlet instance
- try {
- // for includes/forwards
- if ((servlet != null) && (filterChain != null)) {
- filterChain.doFilter(request, response);
- }
- // Servlet Service Method is called by the FilterChain
- } catch (BadRequestException e) {
- ioException = e;
- } catch (IOException e) {
- wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException",
- wrapper.getName()), e);
- ioException = e;
- } catch (UnavailableException e) {
- wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException",
- wrapper.getName()), e);
- servletException = e;
- wrapper.unavailable(e);
- } catch (ServletException e) {
- Throwable rootCause = StandardWrapper.getRootCause(e);
- if (!(rootCause instanceof BadRequestException)) {
- wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException",
- wrapper.getName()), rootCause);
- }
- servletException = e;
- } catch (RuntimeException e) {
- wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException",
- wrapper.getName()), e);
- runtimeException = e;
- }
-
- // Release the filter chain (if any) for this request
- if (filterChain != null) {
- filterChain.release();
- }
-
- // Deallocate the allocated servlet instance
- try {
- if (servlet != null) {
- wrapper.deallocate(servlet);
- }
- } catch (ServletException e) {
- wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException",
- wrapper.getName()), e);
- servletException = e;
- } catch (Throwable e) {
- ExceptionUtils.handleThrowable(e);
- wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException",
- wrapper.getName()), e);
- servletException = new ServletException
- (sm.getString("applicationDispatcher.deallocateException",
- wrapper.getName()), e);
- }
-
- // Reset the old context class loader
- context.unbind(false, oldCCL);
-
- // Unwrap request/response if needed
- // See Bugzilla 30949
- unwrapRequest(state);
- unwrapResponse(state);
- // Recycle request if necessary (also BZ 30949)
- recycleRequestWrapper(state);
-
- // Rethrow an exception if one was thrown by the invoked servlet
- if (ioException != null) {
- throw ioException;
- }
- if (servletException != null) {
- throw servletException;
- }
- if (runtimeException != null) {
- throw runtimeException;
- }
- }
-
-
- /**
- * Unwrap the request if we have wrapped it.
- */
- private void unwrapRequest(State state) {
-
- if (state.wrapRequest == null) {
- return;
- }
-
- if (state.outerRequest.isAsyncStarted()) {
- if (!state.outerRequest.getAsyncContext().hasOriginalRequestAndResponse()) {
- return;
- }
- }
-
- ServletRequest previous = null;
- ServletRequest current = state.outerRequest;
- while (current != null) {
-
- // If we run into the container request we are done
- if ((current instanceof Request) || (current instanceof RequestFacade)) {
- break;
- }
-
- // Remove the current request if it is our wrapper
- if (current == state.wrapRequest) {
- ServletRequest next =
- ((ServletRequestWrapper) current).getRequest();
- if (previous == null) {
- state.outerRequest = next;
- } else {
- ((ServletRequestWrapper) previous).setRequest(next);
- }
- break;
- }
-
- // Advance to the next request in the chain
- previous = current;
- current = ((ServletRequestWrapper) current).getRequest();
-
- }
-
- }
-
- /**
- * Unwrap the response if we have wrapped it.
- */
- private void unwrapResponse(State state) {
-
- if (state.wrapResponse == null) {
- return;
- }
-
- if (state.outerRequest.isAsyncStarted()) {
- if (!state.outerRequest.getAsyncContext().hasOriginalRequestAndResponse()) {
- return;
- }
- }
-
- ServletResponse previous = null;
- ServletResponse current = state.outerResponse;
- while (current != null) {
-
- // If we run into the container response we are done
- if ((current instanceof Response) || (current instanceof ResponseFacade)) {
- break;
- }
-
- // Remove the current response if it is our wrapper
- if (current == state.wrapResponse) {
- ServletResponse next =
- ((ServletResponseWrapper) current).getResponse();
- if (previous == null) {
- state.outerResponse = next;
- } else {
- ((ServletResponseWrapper) previous).setResponse(next);
- }
- break;
- }
-
- // Advance to the next response in the chain
- previous = current;
- current = ((ServletResponseWrapper) current).getResponse();
-
- }
-
- }
-
-
- /**
- * Create and return a request wrapper that has been inserted in the
- * appropriate spot in the request chain.
- */
- private ServletRequest wrapRequest(State state) {
-
- // Locate the request we should insert in front of
- ServletRequest previous = null;
- ServletRequest current = state.outerRequest;
- while (current != null) {
- if(state.hrequest == null && (current instanceof HttpServletRequest)) {
- state.hrequest = (HttpServletRequest)current;
- }
- if (!(current instanceof ServletRequestWrapper)) {
- break;
- }
- if (current instanceof ApplicationHttpRequest) {
- break;
- }
- if (current instanceof ApplicationRequest) {
- break;
- }
- previous = current;
- current = ((ServletRequestWrapper) current).getRequest();
- }
-
- // Instantiate a new wrapper at this point and insert it in the chain
- ServletRequest wrapper = null;
- if ((current instanceof ApplicationHttpRequest) ||
- (current instanceof Request) ||
- (current instanceof HttpServletRequest)) {
- // Compute a crossContext flag
- HttpServletRequest hcurrent = (HttpServletRequest) current;
- boolean crossContext = false;
- if ((state.outerRequest instanceof ApplicationHttpRequest) ||
- (state.outerRequest instanceof Request) ||
- (state.outerRequest instanceof HttpServletRequest)) {
- HttpServletRequest houterRequest =
- (HttpServletRequest) state.outerRequest;
- Object contextPath = houterRequest.getAttribute(
- RequestDispatcher.INCLUDE_CONTEXT_PATH);
- if (contextPath == null) {
- // Forward
- contextPath = houterRequest.getContextPath();
- }
- crossContext = !(context.getPath().equals(contextPath));
- }
- wrapper = new ApplicationHttpRequest
- (hcurrent, context, crossContext);
- } else {
- wrapper = new ApplicationRequest(current);
- }
- if (previous == null) {
- state.outerRequest = wrapper;
- } else {
- ((ServletRequestWrapper) previous).setRequest(wrapper);
- }
- state.wrapRequest = wrapper;
- return wrapper;
-
- }
-
-
- /**
- * Create and return a response wrapper that has been inserted in the
- * appropriate spot in the response chain.
- */
- private ServletResponse wrapResponse(State state) {
-
- // Locate the response we should insert in front of
- ServletResponse previous = null;
- ServletResponse current = state.outerResponse;
- while (current != null) {
- if (state.hresponse == null && (current instanceof HttpServletResponse)) {
- state.hresponse = (HttpServletResponse)current;
- if (!state.including) { // Forward only needs hresponse
- return null;
- }
- }
- if (!(current instanceof ServletResponseWrapper)) {
- break;
- }
- if (current instanceof ApplicationHttpResponse) {
- break;
- }
- if (current instanceof ApplicationResponse) {
- break;
- }
- previous = current;
- current = ((ServletResponseWrapper) current).getResponse();
- }
-
- // Instantiate a new wrapper at this point and insert it in the chain
- ServletResponse wrapper = null;
- if ((current instanceof ApplicationHttpResponse) || (current instanceof Response) ||
- (current instanceof HttpServletResponse)) {
- wrapper = new ApplicationHttpResponse((HttpServletResponse) current, state.including);
- } else {
- wrapper = new ApplicationResponse(current, state.including);
- }
- if (previous == null) {
- state.outerResponse = wrapper;
- } else {
- ((ServletResponseWrapper) previous).setResponse(wrapper);
- }
- state.wrapResponse = wrapper;
- return wrapper;
-
- }
-
- private void checkSameObjects(ServletRequest appRequest,
- ServletResponse appResponse) throws ServletException {
- ServletRequest originalRequest =
- ApplicationFilterChain.getLastServicedRequest();
- ServletResponse originalResponse =
- ApplicationFilterChain.getLastServicedResponse();
-
- // Some forwards, eg from valves will not set original values
- if (originalRequest == null || originalResponse == null) {
- return;
- }
-
- boolean same = false;
- ServletRequest dispatchedRequest = appRequest;
-
- //find the request that was passed into the service method
- while (originalRequest instanceof ServletRequestWrapper &&
- ((ServletRequestWrapper) originalRequest).getRequest()!=null ) {
- originalRequest =
- ((ServletRequestWrapper) originalRequest).getRequest();
- }
- //compare with the dispatched request
- while (!same) {
- if (originalRequest.equals(dispatchedRequest)) {
- same = true;
- }
- if (!same && dispatchedRequest instanceof ServletRequestWrapper) {
- dispatchedRequest =
- ((ServletRequestWrapper) dispatchedRequest).getRequest();
- } else {
- break;
- }
- }
- if (!same) {
- throw new ServletException(sm.getString(
- "applicationDispatcher.specViolation.request"));
- }
-
- same = false;
- ServletResponse dispatchedResponse = appResponse;
-
- //find the response that was passed into the service method
- while (originalResponse instanceof ServletResponseWrapper &&
- ((ServletResponseWrapper) originalResponse).getResponse() !=
- null ) {
- originalResponse =
- ((ServletResponseWrapper) originalResponse).getResponse();
- }
- //compare with the dispatched response
- while (!same) {
- if (originalResponse.equals(dispatchedResponse)) {
- same = true;
- }
-
- if (!same && dispatchedResponse instanceof ServletResponseWrapper) {
- dispatchedResponse =
- ((ServletResponseWrapper) dispatchedResponse).getResponse();
- } else {
- break;
- }
- }
-
- if (!same) {
- throw new ServletException(sm.getString(
- "applicationDispatcher.specViolation.response"));
- }
- }
-
- private void recycleRequestWrapper(State state) {
- if (state.wrapRequest instanceof ApplicationHttpRequest) {
- ((ApplicationHttpRequest) state.wrapRequest).recycle();
- }
- }
-}
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
deleted file mode 100644
index 0c36f12a0b..0000000000
--- a/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/ApplicationHttpRequest.java
+++ /dev/null
@@ -1,1001 +0,0 @@
-/*
- * 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.ExceptionUtils;
-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) {
- try {
- session.endAccess();
- } catch (Throwable t) {
- ExceptionUtils.handleThrowable(t);
- context.getLogger().warn(sm.getString("applicationHttpRequest.sessionEndAccessFail"), t);
- }
- }
- }
-
-
- /**
- * 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
deleted file mode 100644
index 07b47be594..0000000000
--- a/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/LocalStrings.properties
+++ /dev/null
@@ -1,313 +0,0 @@
-# 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
-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
-
-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/catalina/core/StandardHostValve.java b/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/StandardHostValve.java
deleted file mode 100644
index 6208dcd2f7..0000000000
--- a/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/StandardHostValve.java
+++ /dev/null
@@ -1,406 +0,0 @@
-/*
- * 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.util.concurrent.atomic.AtomicBoolean;
-
-import jakarta.servlet.DispatcherType;
-import jakarta.servlet.RequestDispatcher;
-import jakarta.servlet.ServletContext;
-import jakarta.servlet.ServletException;
-import jakarta.servlet.http.HttpServletResponse;
-
-import org.apache.catalina.Context;
-import org.apache.catalina.Globals;
-import org.apache.catalina.Wrapper;
-import org.apache.catalina.connector.ClientAbortException;
-import org.apache.catalina.connector.Request;
-import org.apache.catalina.connector.Response;
-import org.apache.catalina.valves.ValveBase;
-import org.apache.coyote.ActionCode;
-import org.apache.juli.logging.Log;
-import org.apache.juli.logging.LogFactory;
-import org.apache.tomcat.util.ExceptionUtils;
-import org.apache.tomcat.util.descriptor.web.ErrorPage;
-import org.apache.tomcat.util.res.StringManager;
-
-/**
- * Valve that implements the default basic behavior for the
- * <code>StandardHost</code> container implementation.
- * <p>
- * <b>USAGE CONSTRAINT</b>: This implementation is likely to be useful only
- * when processing HTTP requests.
- *
- * @author Craig R. McClanahan
- * @author Remy Maucherat
- */
-final class StandardHostValve extends ValveBase {
-
- private static final Log log = LogFactory.getLog(StandardHostValve.class);
- private static final StringManager sm = StringManager.getManager(StandardHostValve.class);
-
- // Saves a call to getClassLoader() on very request. Under high load these
- // calls took just long enough to appear as a hot spot (although a very
- // minor one) in a profiler.
- private static final ClassLoader MY_CLASSLOADER = StandardHostValve.class.getClassLoader();
-
- //------------------------------------------------------ Constructor
-
- public StandardHostValve() {
- super(true);
- }
-
-
- // --------------------------------------------------------- Public Methods
-
- /**
- * Select the appropriate child Context to process this request,
- * based on the specified request URI. If no matching Context can
- * be found, return an appropriate HTTP error.
- *
- * @param request Request to be processed
- * @param response Response to be produced
- *
- * @exception IOException if an input/output error occurred
- * @exception ServletException if a servlet error occurred
- */
- @Override
- public final void invoke(Request request, Response response)
- throws IOException, ServletException {
-
- // Select the Context to be used for this Request
- Context context = request.getContext();
- if (context == null) {
- // Don't overwrite an existing error
- if (!response.isError()) {
- response.sendError(404);
- }
- return;
- }
-
- if (request.isAsyncSupported()) {
- request.setAsyncSupported(context.getPipeline().isAsyncSupported());
- }
-
- boolean asyncAtStart = request.isAsync();
-
- try {
- context.bind(Globals.IS_SECURITY_ENABLED, MY_CLASSLOADER);
-
- if (!asyncAtStart && !context.fireRequestInitEvent(request.getRequest())) {
- // Don't fire listeners during async processing (the listener
- // fired for the request that called startAsync()).
- // If a request init listener throws an exception, the request
- // is aborted.
- return;
- }
-
- // Ask this Context to process this request. Requests that are
- // already in error must have been routed here to check for
- // application defined error pages so DO NOT forward them to the the
- // application for processing.
- try {
- if (!response.isErrorReportRequired()) {
- context.getPipeline().getFirst().invoke(request, response);
- }
- } catch (Throwable t) {
- ExceptionUtils.handleThrowable(t);
- container.getLogger().error("Exception Processing " + request.getRequestURI(), t);
- // If a new error occurred while trying to report a previous
- // error allow the original error to be reported.
- if (!response.isErrorReportRequired()) {
- request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t);
- throwable(request, response, t);
- }
- }
-
- // Now that the request/response pair is back under container
- // control lift the suspension so that the error handling can
- // complete and/or the container can flush any remaining data
- response.setSuspended(false);
-
- Throwable t = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
-
- // Protect against NPEs if the context was destroyed during a
- // long running request.
- if (!context.getState().isAvailable()) {
- return;
- }
-
- // Look for (and render if found) an application level error page
- if (response.isErrorReportRequired()) {
- // If an error has occurred that prevents further I/O, don't waste time
- // producing an error report that will never be read
- AtomicBoolean result = new AtomicBoolean(false);
- response.getCoyoteResponse().action(ActionCode.IS_IO_ALLOWED, result);
- if (result.get()) {
- if (t != null) {
- throwable(request, response, t);
- } else {
- status(request, response);
- }
- }
- }
-
- if (!request.isAsync() && !asyncAtStart) {
- context.fireRequestDestroyEvent(request.getRequest());
- }
- } finally {
- // Access a session (if present) to update last accessed time, based
- // on a strict interpretation of the specification
- if (context.getAlwaysAccessSession()) {
- request.getSession(false);
- }
-
- context.unbind(Globals.IS_SECURITY_ENABLED, MY_CLASSLOADER);
- }
- }
-
-
- // -------------------------------------------------------- Private Methods
-
- /**
- * Handle the HTTP status code (and corresponding message) generated
- * while processing the specified Request to produce the specified
- * Response. Any exceptions that occur during generation of the error
- * report are logged and swallowed.
- *
- * @param request The request being processed
- * @param response The response being generated
- */
- private void status(Request request, Response response) {
-
- int statusCode = response.getStatus();
-
- // Handle a custom error page for this status code
- Context context = request.getContext();
- if (context == null) {
- return;
- }
-
- /* Only look for error pages when isError() is set.
- * isError() is set when response.sendError() is invoked. This
- * allows custom error pages without relying on default from
- * web.xml.
- */
- if (!response.isError()) {
- return;
- }
-
- ErrorPage errorPage = context.findErrorPage(statusCode);
- if (errorPage == null) {
- // Look for a default error page
- errorPage = context.findErrorPage(0);
- }
- if (errorPage != null && response.isErrorReportRequired()) {
- response.setAppCommitted(false);
- request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE,
- Integer.valueOf(statusCode));
-
- String message = response.getMessage();
- if (message == null) {
- message = "";
- }
- request.setAttribute(RequestDispatcher.ERROR_MESSAGE, message);
- request.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR,
- errorPage.getLocation());
- request.setAttribute(Globals.DISPATCHER_TYPE_ATTR,
- DispatcherType.ERROR);
-
-
- Wrapper wrapper = request.getWrapper();
- if (wrapper != null) {
- request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME,
- wrapper.getName());
- }
- request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI,
- request.getRequestURI());
- if (custom(request, response, errorPage)) {
- response.setErrorReported();
- try {
- response.finishResponse();
- } catch (ClientAbortException e) {
- // Ignore
- } catch (IOException e) {
- container.getLogger().warn("Exception Processing " + errorPage, e);
- }
- }
- }
- }
-
-
- /**
- * Handle the specified Throwable encountered while processing
- * the specified Request to produce the specified Response. Any
- * exceptions that occur during generation of the exception report are
- * logged and swallowed.
- *
- * @param request The request being processed
- * @param response The response being generated
- * @param throwable The exception that occurred (which possibly wraps
- * a root cause exception
- */
- protected void throwable(Request request, Response response,
- Throwable throwable) {
- Context context = request.getContext();
- if (context == null) {
- return;
- }
-
- Throwable realError = throwable;
-
- if (realError instanceof ServletException) {
- realError = ((ServletException) realError).getRootCause();
- if (realError == null) {
- realError = throwable;
- }
- }
-
- // If this is an aborted request from a client just log it and return
- if (realError instanceof ClientAbortException ) {
- if (log.isDebugEnabled()) {
- log.debug
- (sm.getString("standardHost.clientAbort",
- realError.getCause().getMessage()));
- }
- return;
- }
-
- ErrorPage errorPage = context.findErrorPage(throwable);
- if ((errorPage == null) && (realError != throwable)) {
- errorPage = context.findErrorPage(realError);
- }
-
- if (errorPage != null) {
- if (response.setErrorReported()) {
- response.setAppCommitted(false);
- request.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR,
- errorPage.getLocation());
- request.setAttribute(Globals.DISPATCHER_TYPE_ATTR,
- DispatcherType.ERROR);
- request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE,
- Integer.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
- request.setAttribute(RequestDispatcher.ERROR_MESSAGE,
- throwable.getMessage());
- request.setAttribute(RequestDispatcher.ERROR_EXCEPTION,
- realError);
- Wrapper wrapper = request.getWrapper();
- if (wrapper != null) {
- request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME,
- wrapper.getName());
- }
- request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI,
- request.getRequestURI());
- request.setAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE,
- realError.getClass());
- if (custom(request, response, errorPage)) {
- try {
- response.finishResponse();
- } catch (IOException e) {
- container.getLogger().warn("Exception Processing " + errorPage, e);
- }
- }
- }
- } else {
- /*
- * A custom error-page has not been defined for the exception that was thrown during request processing.
- * Set the status to 500 if an error status has not already been set and check for custom error-page for
- * the status.
- */
- if (response.getStatus() < HttpServletResponse.SC_BAD_REQUEST) {
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
- // The response is an error
- response.setError();
-
- status(request, response);
- }
- }
-
-
- /**
- * Handle an HTTP status code or Java exception by forwarding control
- * to the location included in the specified errorPage object. It is
- * assumed that the caller has already recorded any request attributes
- * that are to be forwarded to this page. Return <code>true</code> if
- * we successfully utilized the specified error page location, or
- * <code>false</code> if the default error report should be rendered.
- *
- * @param request The request being processed
- * @param response The response being generated
- * @param errorPage The errorPage directive we are obeying
- */
- private boolean custom(Request request, Response response,
- ErrorPage errorPage) {
-
- if (container.getLogger().isDebugEnabled()) {
- container.getLogger().debug("Processing " + errorPage);
- }
-
- try {
- // Forward control to the specified location
- ServletContext servletContext =
- request.getContext().getServletContext();
- RequestDispatcher rd =
- servletContext.getRequestDispatcher(errorPage.getLocation());
-
- if (rd == null) {
- container.getLogger().error(
- sm.getString("standardHostValue.customStatusFailed", errorPage.getLocation()));
- return false;
- }
-
- if (response.isCommitted()) {
- // Response is committed - including the error page is the
- // best we can do
- rd.include(request.getRequest(), response.getResponse());
-
- // Ensure the combined incomplete response and error page is
- // written to the client
- try {
- response.flushBuffer();
- } catch (Throwable t) {
- ExceptionUtils.handleThrowable(t);
- }
-
- // Now close immediately as an additional signal to the client
- // that something went wrong
- response.getCoyoteResponse().action(ActionCode.CLOSE_NOW,
- request.getAttribute(RequestDispatcher.ERROR_EXCEPTION));
- } else {
- // Reset the response (keeping the real error code and message)
- response.resetBuffer(true);
- response.setContentLength(-1);
-
- rd.forward(request.getRequest(), response.getResponse());
-
- // If we forward, the response is suspended again
- response.setSuspended(false);
- }
-
- // Indicate that we have successfully processed this custom page
- return true;
-
- } catch (Throwable t) {
- ExceptionUtils.handleThrowable(t);
- // Report our failure to process this custom page
- container.getLogger().error("Exception Processing " + errorPage, t);
- return false;
- }
- }
-}
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/StandardWrapperValve.java b/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/StandardWrapperValve.java
deleted file mode 100644
index e8bb713f43..0000000000
--- a/tomee/apache-tomee/src/patch/java/org/apache/catalina/core/StandardWrapperValve.java
+++ /dev/null
@@ -1,369 +0,0 @@
-/*
- * 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.util.concurrent.atomic.AtomicInteger;
-
-import jakarta.servlet.DispatcherType;
-import jakarta.servlet.RequestDispatcher;
-import jakarta.servlet.Servlet;
-import jakarta.servlet.ServletException;
-import jakarta.servlet.UnavailableException;
-import jakarta.servlet.http.HttpServletResponse;
-
-import org.apache.catalina.Container;
-import org.apache.catalina.Context;
-import org.apache.catalina.Globals;
-import org.apache.catalina.LifecycleException;
-import org.apache.catalina.connector.Request;
-import org.apache.catalina.connector.Response;
-import org.apache.catalina.valves.ValveBase;
-import org.apache.coyote.BadRequestException;
-import org.apache.coyote.CloseNowException;
-import org.apache.tomcat.util.ExceptionUtils;
-import org.apache.tomcat.util.buf.MessageBytes;
-import org.apache.tomcat.util.log.SystemLogHandler;
-import org.apache.tomcat.util.res.StringManager;
-
-/**
- * Valve that implements the default basic behavior for the
- * <code>StandardWrapper</code> container implementation.
- *
- * @author Craig R. McClanahan
- */
-final class StandardWrapperValve extends ValveBase {
-
- private static final StringManager sm = StringManager.getManager(StandardWrapperValve.class);
-
-
- //------------------------------------------------------ Constructor
-
- public StandardWrapperValve() {
- super(true);
- }
-
-
- // ----------------------------------------------------- Instance Variables
-
- // Some JMX statistics. This valve is associated with a StandardWrapper.
- // We expose the StandardWrapper as JMX ( j2eeType=Servlet ). The fields
- // are here for performance.
- private volatile long processingTime;
- private volatile long maxTime;
- private volatile long minTime = Long.MAX_VALUE;
- private final AtomicInteger requestCount = new AtomicInteger(0);
- private final AtomicInteger errorCount = new AtomicInteger(0);
-
-
- // --------------------------------------------------------- Public Methods
-
- /**
- * Invoke the servlet we are managing, respecting the rules regarding
- * servlet lifecycle and SingleThreadModel support.
- *
- * @param request Request to be processed
- * @param response Response to be produced
- *
- * @exception IOException if an input/output error occurred
- * @exception ServletException if a servlet error occurred
- */
- @Override
- public final void invoke(Request request, Response response)
- throws IOException, ServletException {
-
- // Initialize local variables we may need
- boolean unavailable = false;
- Throwable throwable = null;
- // This should be a Request attribute...
- long t1=System.currentTimeMillis();
- requestCount.incrementAndGet();
- StandardWrapper wrapper = (StandardWrapper) getContainer();
- Servlet servlet = null;
- Context context = (Context) wrapper.getParent();
-
- // Check for the application being marked unavailable
- if (!context.getState().isAvailable()) {
- response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
- sm.getString("standardContext.isUnavailable"));
- unavailable = true;
- }
-
- // Check for the servlet being marked unavailable
- if (!unavailable && wrapper.isUnavailable()) {
- container.getLogger().info(sm.getString("standardWrapper.isUnavailable",
- wrapper.getName()));
- long available = wrapper.getAvailable();
- if ((available > 0L) && (available < Long.MAX_VALUE)) {
- response.setDateHeader("Retry-After", available);
- response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
- sm.getString("standardWrapper.isUnavailable",
- wrapper.getName()));
- } else if (available == Long.MAX_VALUE) {
- response.sendError(HttpServletResponse.SC_NOT_FOUND,
- sm.getString("standardWrapper.notFound",
- wrapper.getName()));
- }
- unavailable = true;
- }
-
- // Allocate a servlet instance to process this request
- try {
- if (!unavailable) {
- servlet = wrapper.allocate();
- }
- } catch (UnavailableException e) {
- container.getLogger().error(
- sm.getString("standardWrapper.allocateException",
- wrapper.getName()), e);
- long available = wrapper.getAvailable();
- if ((available > 0L) && (available < Long.MAX_VALUE)) {
- response.setDateHeader("Retry-After", available);
- response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
- sm.getString("standardWrapper.isUnavailable",
- wrapper.getName()));
- } else if (available == Long.MAX_VALUE) {
- response.sendError(HttpServletResponse.SC_NOT_FOUND,
- sm.getString("standardWrapper.notFound",
- wrapper.getName()));
- }
- } catch (ServletException e) {
- container.getLogger().error(sm.getString("standardWrapper.allocateException",
- wrapper.getName()), StandardWrapper.getRootCause(e));
- throwable = e;
- exception(request, response, e);
- } catch (Throwable e) {
- ExceptionUtils.handleThrowable(e);
- container.getLogger().error(sm.getString("standardWrapper.allocateException",
- wrapper.getName()), e);
- throwable = e;
- exception(request, response, e);
- servlet = null;
- }
-
- MessageBytes requestPathMB = request.getRequestPathMB();
- DispatcherType dispatcherType = DispatcherType.REQUEST;
- if (request.getDispatcherType()==DispatcherType.ASYNC) {
- dispatcherType = DispatcherType.ASYNC;
- }
- request.setAttribute(Globals.DISPATCHER_TYPE_ATTR,dispatcherType);
- request.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR,
- requestPathMB);
- // Create the filter chain for this request
- ApplicationFilterChain filterChain =
- ApplicationFilterFactory.createFilterChain(request, wrapper, servlet);
-
- // Call the filter chain for this request
- // NOTE: This also calls the servlet's service() method
- Container container = this.container;
- try {
- if ((servlet != null) && (filterChain != null)) {
- // Swallow output if needed
- if (context.getSwallowOutput()) {
- try {
- SystemLogHandler.startCapture();
- if (request.isAsyncDispatching()) {
- request.getAsyncContextInternal().doInternalDispatch();
- } else {
- filterChain.doFilter(request.getRequest(),
- response.getResponse());
- }
- } finally {
- String log = SystemLogHandler.stopCapture();
- if (log != null && log.length() > 0) {
- context.getLogger().info(log);
- }
- }
- } else {
- if (request.isAsyncDispatching()) {
- request.getAsyncContextInternal().doInternalDispatch();
- } else {
- filterChain.doFilter
- (request.getRequest(), response.getResponse());
- }
- }
-
- }
- } catch (BadRequestException e) {
- if (container.getLogger().isDebugEnabled()) {
- container.getLogger().debug(
- sm.getString("standardWrapper.serviceException", wrapper.getName(), context.getName()), e);
- }
- throwable = e;
- exception(request, response, e, HttpServletResponse.SC_BAD_REQUEST);
- } catch (CloseNowException e) {
- if (container.getLogger().isDebugEnabled()) {
- container.getLogger().debug(sm.getString(
- "standardWrapper.serviceException", wrapper.getName(),
- context.getName()), e);
- }
- throwable = e;
- exception(request, response, e);
- } catch (IOException e) {
- container.getLogger().error(sm.getString(
- "standardWrapper.serviceException", wrapper.getName(),
- context.getName()), e);
- throwable = e;
- exception(request, response, e);
- } catch (UnavailableException e) {
- container.getLogger().error(sm.getString(
- "standardWrapper.serviceException", wrapper.getName(),
- context.getName()), e);
- // throwable = e;
- // exception(request, response, e);
- wrapper.unavailable(e);
- long available = wrapper.getAvailable();
- if ((available > 0L) && (available < Long.MAX_VALUE)) {
- response.setDateHeader("Retry-After", available);
- response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
- sm.getString("standardWrapper.isUnavailable",
- wrapper.getName()));
- } else if (available == Long.MAX_VALUE) {
- response.sendError(HttpServletResponse.SC_NOT_FOUND,
- sm.getString("standardWrapper.notFound",
- wrapper.getName()));
- }
- // Do not save exception in 'throwable', because we
- // do not want to do exception(request, response, e) processing
- } catch (ServletException e) {
- Throwable rootCause = StandardWrapper.getRootCause(e);
- if (!(rootCause instanceof BadRequestException)) {
- container.getLogger().error(sm.getString(
- "standardWrapper.serviceExceptionRoot",
- wrapper.getName(), context.getName(), e.getMessage()),
- rootCause);
- }
- throwable = e;
- exception(request, response, e);
- } catch (Throwable e) {
- ExceptionUtils.handleThrowable(e);
- container.getLogger().error(sm.getString(
- "standardWrapper.serviceException", wrapper.getName(),
- context.getName()), e);
- throwable = e;
- exception(request, response, e);
- } finally {
- // Release the filter chain (if any) for this request
- if (filterChain != null) {
- filterChain.release();
- }
-
- // Deallocate the allocated servlet instance
- try {
- if (servlet != null) {
- wrapper.deallocate(servlet);
- }
- } catch (Throwable e) {
- ExceptionUtils.handleThrowable(e);
- container.getLogger().error(sm.getString("standardWrapper.deallocateException",
- wrapper.getName()), e);
- if (throwable == null) {
- throwable = e;
- exception(request, response, e);
- }
- }
-
- // If this servlet has been marked permanently unavailable,
- // unload it and release this instance
- try {
- if ((servlet != null) &&
- (wrapper.getAvailable() == Long.MAX_VALUE)) {
- wrapper.unload();
- }
- } catch (Throwable e) {
- ExceptionUtils.handleThrowable(e);
- container.getLogger().error(sm.getString("standardWrapper.unloadException",
- wrapper.getName()), e);
- if (throwable == null) {
- exception(request, response, e);
- }
- }
- long t2=System.currentTimeMillis();
-
- long time=t2-t1;
- processingTime += time;
- if( time > maxTime) {
- maxTime=time;
- }
- if( time < minTime) {
- minTime=time;
- }
- }
- }
-
-
- // -------------------------------------------------------- Private Methods
-
- /**
- * Handle the specified ServletException encountered while processing the specified Request to produce the specified
- * Response. Any exceptions that occur during generation of the exception report are logged and swallowed.
- *
- * @param request The request being processed
- * @param response The response being generated
- * @param exception The exception that occurred (which possibly wraps a root cause exception
- */
- private void exception(Request request, Response response, Throwable exception) {
- exception(request, response, exception, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
-
- /**
- * Handle the specified ServletException encountered while processing
- * the specified Request to produce the specified Response. Any
- * exceptions that occur during generation of the exception report are
- * logged and swallowed.
- *
- * @param request The request being processed
- * @param response The response being generated
- * @param exception The exception that occurred (which possibly wraps
- * a root cause exception
- */
- private void exception(Request request, Response response,Throwable exception, int errorCode) {
- request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, exception);
- response.setStatus(errorCode);
- response.setError();
- }
-
- public long getProcessingTime() {
- return processingTime;
- }
-
- public long getMaxTime() {
- return maxTime;
- }
-
- public long getMinTime() {
- return minTime;
- }
-
- public int getRequestCount() {
- return requestCount.get();
- }
-
- public int getErrorCount() {
- return errorCount.get();
- }
-
- public void incrementErrorCount() {
- errorCount.incrementAndGet();
- }
-
- @Override
- protected void initInternal() throws LifecycleException {
- // NOOP - Don't register this Valve in JMX
- }
-}
diff --git a/tomee/apache-tomee/src/patch/java/org/apache/catalina/filters/RemoteIpFilter.java b/tomee/apache-tomee/src/patch/java/org/apache/catalina/filters/RemoteIpFilter.java
deleted file mode 100644
index 732300a359..0000000000
--- a/tomee/apache-tomee/src/patch/java/org/apache/catalina/filters/RemoteIpFilter.java
+++ /dev/null
@@ -1,1334 +0,0 @@
-/*
- * 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.filters;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.ArrayDeque;
-import java.util.Collections;
-import java.util.Deque;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Pattern;
-
-import jakarta.servlet.FilterChain;
-import jakarta.servlet.GenericFilter;
-import jakarta.servlet.ServletException;
-import jakarta.servlet.ServletRequest;
-import jakarta.servlet.ServletRequestWrapper;
-import jakarta.servlet.ServletResponse;
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletRequestWrapper;
-import jakarta.servlet.http.HttpServletResponse;
-import jakarta.servlet.http.PushBuilder;
-
-import org.apache.catalina.AccessLog;
-import org.apache.catalina.Globals;
-import org.apache.catalina.connector.RequestFacade;
-import org.apache.catalina.util.RequestUtil;
-import org.apache.juli.logging.Log;
-import org.apache.juli.logging.LogFactory;
-import org.apache.tomcat.util.buf.StringUtils;
-import org.apache.tomcat.util.http.FastHttpDateFormat;
-import org.apache.tomcat.util.http.parser.Host;
-import org.apache.tomcat.util.res.StringManager;
-
-/**
- * <p>
- * Servlet filter to integrate "X-Forwarded-For" and "X-Forwarded-Proto" HTTP headers.
- * </p>
- * <p>
- * Most of the design of this Servlet Filter is a port of <a
- * href="https://httpd.apache.org/docs/trunk/mod/mod_remoteip.html">mod_remoteip</a>, this servlet filter replaces the apparent client remote
- * IP address and hostname for the request with the IP address list presented by a proxy or a load balancer via a request headers (e.g.
- * "X-Forwarded-For").
- * </p>
- * <p>
- * Another feature of this servlet filter is to replace the apparent scheme (http/https) and server port with the scheme presented by a
- * proxy or a load balancer via a request header (e.g. "X-Forwarded-Proto").
- * </p>
- * <p>
- * This servlet filter proceeds as follows:
- * </p>
- * <p>
- * If the incoming <code>request.getRemoteAddr()</code> matches the servlet
- * filter's list of internal or trusted proxies:
- * </p>
- * <ul>
- * <li>Loop on the comma delimited list of IPs and hostnames passed by the preceding load balancer or proxy in the given request's Http
- * header named <code>$remoteIpHeader</code> (default value <code>x-forwarded-for</code>). Values are processed in right-to-left order.</li>
- * <li>For each ip/host of the list:
- * <ul>
- * <li>if it matches the internal proxies list, the ip/host is swallowed</li>
- * <li>if it matches the trusted proxies list, the ip/host is added to the created proxies header</li>
- * <li>otherwise, the ip/host is declared to be the remote ip and looping is stopped.</li>
- * </ul>
- * </li>
- * <li>If the request http header named <code>$protocolHeader</code> (e.g. <code>x-forwarded-proto</code>) consists only of forwards that match
- * <code>protocolHeaderHttpsValue</code> configuration parameter (default <code>https</code>) then <code>request.isSecure = true</code>,
- * <code>request.scheme = https</code> and <code>request.serverPort = 443</code>. Note that 443 can be overwritten with the
- * <code>$httpsServerPort</code> configuration parameter.</li>
- * <li>Mark the request with the attribute {@link Globals#REQUEST_FORWARDED_ATTRIBUTE} and value {@code Boolean.TRUE} to indicate
- * that this request has been forwarded by one or more proxies.</li>
- * </ul>
- * <table border="1">
- * <caption>Configuration parameters</caption>
- * <tr>
- * <th>XForwardedFilter property</th>
- * <th>Description</th>
- * <th>Equivalent mod_remoteip directive</th>
- * <th>Format</th>
- * <th>Default Value</th>
- * </tr>
- * <tr>
- * <td>remoteIpHeader</td>
- * <td>Name of the Http Header read by this servlet filter that holds the list of traversed IP addresses starting from the requesting client
- * </td>
- * <td>RemoteIPHeader</td>
- * <td>Compliant http header name</td>
- * <td>x-forwarded-for</td>
- * </tr>
- * <tr>
- * <td>internalProxies</td>
- * <td>Regular expression that matches the IP addresses of internal proxies.
- * If they appear in the <code>remoteIpHeader</code> value, they will be
- * trusted and will not appear
- * in the <code>proxiesHeader</code> value</td>
- * <td>RemoteIPInternalProxy</td>
- * <td>Regular expression (in the syntax supported by
- * {@link java.util.regex.Pattern java.util.regex})</td>
- * <td>10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|
- * 169\.254\.\d{1,3}\.\d{1,3}|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|
- * 172\.1[6-9]{1}\.\d{1,3}\.\d{1,3}|172\.2[0-9]{1}\.\d{1,3}\.\d{1,3}|
- * 172\.3[0-1]{1}\.\d{1,3}\.\d{1,3}|
- * 0:0:0:0:0:0:0:1|::1
- * <br>
- * By default, 10/8, 192.168/16, 169.254/16, 127/8, 172.16/12, and 0:0:0:0:0:0:0:1 are allowed.</td>
- * </tr>
- * <tr>
- * <td>proxiesHeader</td>
- * <td>Name of the http header created by this servlet filter to hold the list of proxies that have been processed in the incoming
- * <code>remoteIpHeader</code></td>
- * <td>RemoteIPProxiesHeader</td>
- * <td>Compliant http header name</td>
- * <td>x-forwarded-by</td>
- * </tr>
- * <tr>
- * <td>trustedProxies</td>
- * <td>Regular expression that matches the IP addresses of trusted proxies.
- * If they appear in the <code>remoteIpHeader</code> value, they will be
- * trusted and will appear in the <code>proxiesHeader</code> value</td>
- * <td>RemoteIPTrustedProxy</td>
- * <td>Regular expression (in the syntax supported by
- * {@link java.util.regex.Pattern java.util.regex})</td>
- * <td> </td>
- * </tr>
- * <tr>
- * <td>protocolHeader</td>
- * <td>Name of the http header read by this servlet filter that holds the flag that this request</td>
- * <td>N/A</td>
- * <td>Compliant http header name like <code>X-Forwarded-Proto</code>, <code>X-Forwarded-Ssl</code> or <code>Front-End-Https</code></td>
- * <td><code>null</code></td>
- * </tr>
- * <tr>
- * <td>protocolHeaderHttpsValue</td>
- * <td>Value of the <code>protocolHeader</code> to indicate that it is an Https request</td>
- * <td>N/A</td>
- * <td>String like <code>https</code> or <code>ON</code></td>
- * <td><code>https</code></td>
- * </tr>
- * <tr>
- * <td>httpServerPort</td>
- * <td>Value returned by {@link ServletRequest#getServerPort()} when the <code>protocolHeader</code> indicates <code>http</code> protocol</td>
- * <td>N/A</td>
- * <td>integer</td>
- * <td>80</td>
- * </tr>
- * <tr>
- * <td>httpsServerPort</td>
- * <td>Value returned by {@link ServletRequest#getServerPort()} when the <code>protocolHeader</code> indicates <code>https</code> protocol</td>
- * <td>N/A</td>
- * <td>integer</td>
- * <td>443</td>
- * </tr>
- * <tr>
- * <td>enableLookups</td>
- * <td>Should a DNS lookup be performed to provide a host name when calling {@link ServletRequest#getRemoteHost()}</td>
- * <td>N/A</td>
- * <td>boolean</td>
- * <td>false</td>
- * </tr>
- * </table>
- * <p>
- * <strong>Regular expression vs. IP address blocks:</strong> <code>mod_remoteip</code> allows to use address blocks (e.g.
- * <code>192.168/16</code>) to configure <code>RemoteIPInternalProxy</code> and <code>RemoteIPTrustedProxy</code> ; as the JVM doesn't have a
- * library similar to <a
- * href="https://apr.apache.org/docs/apr/1.3/group__apr__network__io.html#gb74d21b8898b7c40bf7fd07ad3eb993d">apr_ipsubnet_test</a>, we rely on
- * regular expressions.
- * </p>
- * <hr>
- * <p>
- * <strong>Sample with internal proxies</strong>
- * </p>
- * <p>
- * XForwardedFilter configuration:
- * </p>
- * <code>
- * <filter>
- * <filter-name>RemoteIpFilter</filter-name>
- * <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
- * <init-param>
- * <param-name>internalProxies</param-name>
- * <param-value>192\.168\.0\.10|192\.168\.0\.11</param-value>
- * </init-param>
- * <init-param>
- * <param-name>remoteIpHeader</param-name>
- * <param-value>x-forwarded-for</param-value>
- * </init-param>
- * <init-param>
- * <param-name>remoteIpProxiesHeader</param-name>
- * <param-value>x-forwarded-by</param-value>
- * </init-param>
- * <init-param>
- * <param-name>protocolHeader</param-name>
- * <param-value>x-forwarded-proto</param-value>
- * </init-param>
- * </filter>
- *
- * <filter-mapping>
- * <filter-name>RemoteIpFilter</filter-name>
- * <url-pattern>/*</url-pattern>
- * <dispatcher>REQUEST</dispatcher>
- * </filter-mapping></code>
- * <table border="1">
- * <caption>Request Values</caption>
- * <tr>
- * <th>property</th>
- * <th>Value Before RemoteIpFilter</th>
- * <th>Value After RemoteIpFilter</th>
- * </tr>
- * <tr>
- * <td>request.remoteAddr</td>
- * <td>192.168.0.10</td>
- * <td>140.211.11.130</td>
- * </tr>
- * <tr>
- * <td>request.header['x-forwarded-for']</td>
- * <td>140.211.11.130, 192.168.0.10</td>
- * <td>null</td>
- * </tr>
- * <tr>
- * <td>request.header['x-forwarded-by']</td>
- * <td>null</td>
- * <td>null</td>
- * </tr>
- * <tr>
- * <td>request.header['x-forwarded-proto']</td>
- * <td>https</td>
- * <td>https</td>
- * </tr>
- * <tr>
- * <td>request.scheme</td>
- * <td>http</td>
- * <td>https</td>
- * </tr>
- * <tr>
- * <td>request.secure</td>
- * <td>false</td>
- * <td>true</td>
- * </tr>
- * <tr>
- * <td>request.serverPort</td>
- * <td>80</td>
- * <td>443</td>
- * </tr>
- * </table>
- * Note : <code>x-forwarded-by</code> header is null because only internal proxies as been traversed by the request.
- * <code>x-forwarded-by</code> is null because all the proxies are trusted or internal.
- * <hr>
- * <p>
- * <strong>Sample with trusted proxies</strong>
- * </p>
- * <p>
- * RemoteIpFilter configuration:
- * </p>
- * <code>
- * <filter>
- * <filter-name>RemoteIpFilter</filter-name>
- * <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
- * <init-param>
- * <param-name>internalProxies</param-name>
- * <param-value>192\.168\.0\.10|192\.168\.0\.11</param-value>
- * </init-param>
- * <init-param>
- * <param-name>remoteIpHeader</param-name>
- * <param-value>x-forwarded-for</param-value>
- * </init-param>
- * <init-param>
- * <param-name>remoteIpProxiesHeader</param-name>
- * <param-value>x-forwarded-by</param-value>
- * </init-param>
- * <init-param>
- * <param-name>trustedProxies</param-name>
- * <param-value>proxy1|proxy2</param-value>
- * </init-param>
- * </filter>
- *
- * <filter-mapping>
- * <filter-name>RemoteIpFilter</filter-name>
- * <url-pattern>/*</url-pattern>
- * <dispatcher>REQUEST</dispatcher>
- * </filter-mapping></code>
- * <table border="1">
- * <caption>Request Values</caption>
- * <tr>
- * <th>property</th>
- * <th>Value Before RemoteIpFilter</th>
- * <th>Value After RemoteIpFilter</th>
- * </tr>
- * <tr>
- * <td>request.remoteAddr</td>
- * <td>192.168.0.10</td>
- * <td>140.211.11.130</td>
- * </tr>
- * <tr>
- * <td>request.header['x-forwarded-for']</td>
- * <td>140.211.11.130, proxy1, proxy2</td>
- * <td>null</td>
- * </tr>
- * <tr>
- * <td>request.header['x-forwarded-by']</td>
- * <td>null</td>
- * <td>proxy1, proxy2</td>
- * </tr>
- * </table>
- * <p>
- * Note : <code>proxy1</code> and <code>proxy2</code> are both trusted proxies that come in <code>x-forwarded-for</code> header, they both
- * are migrated in <code>x-forwarded-by</code> header. <code>x-forwarded-by</code> is null because all the proxies are trusted or internal.
- * </p>
- * <hr>
- * <p>
- * <strong>Sample with internal and trusted proxies</strong>
- * </p>
- * <p>
- * RemoteIpFilter configuration:
- * </p>
- * <code>
- * <filter>
- * <filter-name>RemoteIpFilter</filter-name>
- * <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
- * <init-param>
- * <param-name>internalProxies</param-name>
- * <param-value>192\.168\.0\.10|192\.168\.0\.11</param-value>
- * </init-param>
- * <init-param>
- * <param-name>remoteIpHeader</param-name>
- * <param-value>x-forwarded-for</param-value>
- * </init-param>
- * <init-param>
- * <param-name>remoteIpProxiesHeader</param-name>
- * <param-value>x-forwarded-by</param-value>
- * </init-param>
- * <init-param>
- * <param-name>trustedProxies</param-name>
- * <param-value>proxy1|proxy2</param-value>
- * </init-param>
- * </filter>
- *
- * <filter-mapping>
- * <filter-name>RemoteIpFilter</filter-name>
- * <url-pattern>/*</url-pattern>
- * <dispatcher>REQUEST</dispatcher>
- * </filter-mapping></code>
- * <table border="1">
- * <caption>Request Values</caption>
- * <tr>
- * <th>property</th>
- * <th>Value Before RemoteIpFilter</th>
- * <th>Value After RemoteIpFilter</th>
- * </tr>
- * <tr>
- * <td>request.remoteAddr</td>
- * <td>192.168.0.10</td>
- * <td>140.211.11.130</td>
- * </tr>
- * <tr>
- * <td>request.header['x-forwarded-for']</td>
- * <td>140.211.11.130, proxy1, proxy2, 192.168.0.10</td>
- * <td>null</td>
- * </tr>
- * <tr>
- * <td>request.header['x-forwarded-by']</td>
- * <td>null</td>
- * <td>proxy1, proxy2</td>
- * </tr>
- * </table>
- * <p>
- * Note : <code>proxy1</code> and <code>proxy2</code> are both trusted proxies that come in <code>x-forwarded-for</code> header, they both
- * are migrated in <code>x-forwarded-by</code> header. As <code>192.168.0.10</code> is an internal proxy, it does not appear in
- * <code>x-forwarded-by</code>. <code>x-forwarded-by</code> is null because all the proxies are trusted or internal.
- * </p>
- * <hr>
- * <p>
- * <strong>Sample with an untrusted proxy</strong>
- * </p>
- * <p>
- * RemoteIpFilter configuration:
- * </p>
- * <code>
- * <filter>
- * <filter-name>RemoteIpFilter</filter-name>
- * <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
- * <init-param>
- * <param-name>internalProxies</param-name>
- * <param-value>192\.168\.0\.10|192\.168\.0\.11</param-value>
- * </init-param>
- * <init-param>
- * <param-name>remoteIpHeader</param-name>
- * <param-value>x-forwarded-for</param-value>
- * </init-param>
- * <init-param>
- * <param-name>remoteIpProxiesHeader</param-name>
- * <param-value>x-forwarded-by</param-value>
- * </init-param>
- * <init-param>
- * <param-name>trustedProxies</param-name>
- * <param-value>proxy1|proxy2</param-value>
- * </init-param>
- * </filter>
- *
- * <filter-mapping>
- * <filter-name>RemoteIpFilter</filter-name>
- * <url-pattern>/*</url-pattern>
- * <dispatcher>REQUEST</dispatcher>
- * </filter-mapping></code>
- * <table border="1">
- * <caption>Request Values</caption>
- * <tr>
- * <th>property</th>
- * <th>Value Before RemoteIpFilter</th>
- * <th>Value After RemoteIpFilter</th>
- * </tr>
- * <tr>
- * <td>request.remoteAddr</td>
- * <td>192.168.0.10</td>
- * <td>untrusted-proxy</td>
- * </tr>
- * <tr>
- * <td>request.header['x-forwarded-for']</td>
- * <td>140.211.11.130, untrusted-proxy, proxy1</td>
- * <td>140.211.11.130</td>
- * </tr>
- * <tr>
- * <td>request.header['x-forwarded-by']</td>
- * <td>null</td>
- * <td>proxy1</td>
- * </tr>
- * </table>
- * <p>
- * Note : <code>x-forwarded-by</code> holds the trusted proxy <code>proxy1</code>. <code>x-forwarded-by</code> holds
- * <code>140.211.11.130</code> because <code>untrusted-proxy</code> is not trusted and thus, we cannot trust that
- * <code>untrusted-proxy</code> is the actual remote ip. <code>request.remoteAddr</code> is <code>untrusted-proxy</code> that is an IP
- * verified by <code>proxy1</code>.
- * </p>
- * <hr>
- */
-public class RemoteIpFilter extends GenericFilter {
-
- private static final long serialVersionUID = 1L;
-
- public static class XForwardedRequest extends HttpServletRequestWrapper {
-
- protected final Map<String, List<String>> headers;
-
- protected String localName;
-
- protected int localPort;
-
- protected String remoteAddr;
-
- protected String remoteHost;
-
- protected String scheme;
-
- protected boolean secure;
-
- protected String serverName;
-
- protected int serverPort;
-
- public XForwardedRequest(HttpServletRequest request) {
- super(request);
- this.localName = request.getLocalName();
- this.localPort = request.getLocalPort();
- this.remoteAddr = request.getRemoteAddr();
- this.remoteHost = request.getRemoteHost();
- this.scheme = request.getScheme();
- this.secure = request.isSecure();
- this.serverName = request.getServerName();
- this.serverPort = request.getServerPort();
-
- headers = new HashMap<>();
- for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements();) {
- String header = headerNames.nextElement();
- headers.put(header, Collections.list(request.getHeaders(header)));
- }
- }
-
- @Override
- public long getDateHeader(String name) {
- String value = getHeader(name);
- if (value == null) {
- return -1;
- }
- long date = FastHttpDateFormat.parseDate(value);
- if (date == -1) {
- throw new IllegalArgumentException(value);
- }
- return date;
- }
-
- @Override
- public String getHeader(String name) {
- Map.Entry<String, List<String>> header = getHeaderEntry(name);
- if (header == null || header.getValue() == null || header.getValue().isEmpty()) {
- return null;
- }
- return header.getValue().get(0);
- }
-
- protected Map.Entry<String, List<String>> getHeaderEntry(String name) {
- for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
- if (entry.getKey().equalsIgnoreCase(name)) {
- return entry;
- }
- }
- return null;
- }
-
- @Override
- public Enumeration<String> getHeaderNames() {
- return Collections.enumeration(headers.keySet());
- }
-
- @Override
- public Enumeration<String> getHeaders(String name) {
- Map.Entry<String, List<String>> header = getHeaderEntry(name);
- if (header == null || header.getValue() == null) {
- return Collections.enumeration(Collections.<String>emptyList());
- }
- return Collections.enumeration(header.getValue());
- }
-
- @Override
- public int getIntHeader(String name) {
- String value = getHeader(name);
- if (value == null) {
- return -1;
- }
- return Integer.parseInt(value);
- }
-
- @Override
- public String getLocalName() {
- return localName;
- }
-
- @Override
- public int getLocalPort() {
- return localPort;
- }
-
- @Override
- public String getRemoteAddr() {
- return this.remoteAddr;
- }
-
- @Override
- public String getRemoteHost() {
- return this.remoteHost;
- }
-
- @Override
- public String getScheme() {
- return scheme;
- }
-
- @Override
- public String getServerName() {
- return serverName;
- }
-
- @Override
- public int getServerPort() {
- return serverPort;
- }
-
- public void removeHeader(String name) {
- Map.Entry<String, List<String>> header = getHeaderEntry(name);
- if (header != null) {
- headers.remove(header.getKey());
- }
- }
-
- public void setHeader(String name, String value) {
- List<String> values = Collections.singletonList(value);
- Map.Entry<String, List<String>> header = getHeaderEntry(name);
- if (header == null) {
- headers.put(name, values);
- } else {
- header.setValue(values);
- }
-
- }
-
- public void setLocalName(String localName) {
- this.localName = localName;
- }
-
- public void setLocalPort(int localPort) {
- this.localPort = localPort;
- }
-
- public void setRemoteAddr(String remoteAddr) {
- this.remoteAddr = remoteAddr;
- }
-
- public void setRemoteHost(String remoteHost) {
- this.remoteHost = remoteHost;
- }
-
- public void setScheme(String scheme) {
- this.scheme = scheme;
- }
-
- public void setSecure(boolean secure) {
- super.getRequest().setAttribute(Globals.REMOTE_IP_FILTER_SECURE, Boolean.valueOf(secure));
- }
-
- public void setServerName(String serverName) {
- this.serverName = serverName;
- }
-
- public void setServerPort(int serverPort) {
- this.serverPort = serverPort;
- }
-
- @Override
- public StringBuffer getRequestURL() {
- return RequestUtil.getRequestURL(this);
- }
-
- @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;
- }
- }
- }
-
-
- /**
- * {@link Pattern} for a comma delimited string that support whitespace characters
- */
- private static final Pattern commaSeparatedValuesPattern = Pattern.compile("\\s*,\\s*");
-
- protected static final String HTTP_SERVER_PORT_PARAMETER = "httpServerPort";
-
- protected static final String HTTPS_SERVER_PORT_PARAMETER = "httpsServerPort";
-
- protected static final String INTERNAL_PROXIES_PARAMETER = "internalProxies";
-
- // Log must be non-static as loggers are created per class-loader and this
- // Filter may be used in multiple class loaders
- private transient Log log = LogFactory.getLog(RemoteIpFilter.class);
- protected static final StringManager sm = StringManager.getManager(RemoteIpFilter.class);
-
- protected static final String PROTOCOL_HEADER_PARAMETER = "protocolHeader";
-
- protected static final String PROTOCOL_HEADER_HTTPS_VALUE_PARAMETER = "protocolHeaderHttpsValue";
-
- protected static final String HOST_HEADER_PARAMETER = "hostHeader";
-
- protected static final String PORT_HEADER_PARAMETER = "portHeader";
-
- protected static final String CHANGE_LOCAL_NAME_PARAMETER = "changeLocalName";
-
- protected static final String CHANGE_LOCAL_PORT_PARAMETER = "changeLocalPort";
-
- protected static final String PROXIES_HEADER_PARAMETER = "proxiesHeader";
-
- protected static final String REMOTE_IP_HEADER_PARAMETER = "remoteIpHeader";
-
- protected static final String TRUSTED_PROXIES_PARAMETER = "trustedProxies";
-
- protected static final String ENABLE_LOOKUPS_PARAMETER = "enableLookups";
-
- /**
- * Convert a given comma delimited list of regular expressions into an array of String
- *
- * @param commaDelimitedStrings The string to split
- * @return array of patterns (non <code>null</code>)
- */
- protected static String[] commaDelimitedListToStringArray(String commaDelimitedStrings) {
- return (commaDelimitedStrings == null || commaDelimitedStrings.length() == 0) ? new String[0] : commaSeparatedValuesPattern
- .split(commaDelimitedStrings);
- }
-
- /**
- * Convert a list of strings in a comma delimited string.
- *
- * @param stringList List of strings
- * @return concatenated string
- *
- * @deprecated Unused. Will be removed in Tomcat 11 onwards
- */
- @Deprecated
- protected static String listToCommaDelimitedString(List<String> stringList) {
- if (stringList == null) {
- return "";
- }
- StringBuilder result = new StringBuilder();
- for (Iterator<String> it = stringList.iterator(); it.hasNext();) {
- Object element = it.next();
- if (element != null) {
- result.append(element);
- if (it.hasNext()) {
- result.append(", ");
- }
- }
- }
- return result.toString();
- }
-
- /**
- * @see #setHttpServerPort(int)
- */
- private int httpServerPort = 80;
-
- /**
- * @see #setHttpsServerPort(int)
- */
- private int httpsServerPort = 443;
-
- /**
- * @see #setInternalProxies(String)
- */
- private Pattern internalProxies = Pattern.compile(
- "10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|" +
- "192\\.168\\.\\d{1,3}\\.\\d{1,3}|" +
- "169\\.254\\.\\d{1,3}\\.\\d{1,3}|" +
- "127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|" +
- "172\\.1[6-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" +
- "172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" +
- "172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3}|" +
- "0:0:0:0:0:0:0:1|::1");
-
- /**
- * @see #setProtocolHeader(String)
- */
- private String protocolHeader = "X-Forwarded-Proto";
-
- private String protocolHeaderHttpsValue = "https";
-
- private String hostHeader = null;
-
- private boolean changeLocalName = false;
-
- private String portHeader = null;
-
- private boolean changeLocalPort = false;
-
- /**
- * @see #setProxiesHeader(String)
- */
- private String proxiesHeader = "X-Forwarded-By";
-
- /**
- * @see #setRemoteIpHeader(String)
- */
- private String remoteIpHeader = "X-Forwarded-For";
-
- /**
- * @see #setRequestAttributesEnabled(boolean)
- */
- private boolean requestAttributesEnabled = true;
-
- /**
- * @see #setTrustedProxies(String)
- */
- private Pattern trustedProxies = null;
-
- private boolean enableLookups;
-
- public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
-
- boolean isInternal = internalProxies != null &&
- internalProxies.matcher(request.getRemoteAddr()).matches();
-
- if (isInternal || (trustedProxies != null &&
- trustedProxies.matcher(request.getRemoteAddr()).matches())) {
- String remoteIp = null;
- Deque<String> proxiesHeaderValue = new ArrayDeque<>();
- StringBuilder concatRemoteIpHeaderValue = new StringBuilder();
-
- for (Enumeration<String> e = request.getHeaders(remoteIpHeader); e.hasMoreElements();) {
- if (concatRemoteIpHeaderValue.length() > 0) {
- concatRemoteIpHeaderValue.append(", ");
- }
-
- concatRemoteIpHeaderValue.append(e.nextElement());
- }
-
- String[] remoteIpHeaderValue = commaDelimitedListToStringArray(concatRemoteIpHeaderValue.toString());
- int idx;
- if (!isInternal) {
- proxiesHeaderValue.addFirst(request.getRemoteAddr());
- }
- // loop on remoteIpHeaderValue to find the first trusted remote ip and to build the proxies chain
- for (idx = remoteIpHeaderValue.length - 1; idx >= 0; idx--) {
- String currentRemoteIp = remoteIpHeaderValue[idx];
- remoteIp = currentRemoteIp;
- if (internalProxies !=null && internalProxies.matcher(currentRemoteIp).matches()) {
- // do nothing, internalProxies IPs are not appended to the
- } else if (trustedProxies != null &&
- trustedProxies.matcher(currentRemoteIp).matches()) {
- proxiesHeaderValue.addFirst(currentRemoteIp);
- } else {
- idx--; // decrement idx because break statement doesn't do it
- break;
- }
- }
- // continue to loop on remoteIpHeaderValue to build the new value of the remoteIpHeader
- LinkedList<String> newRemoteIpHeaderValue = new LinkedList<>();
- for (; idx >= 0; idx--) {
- String currentRemoteIp = remoteIpHeaderValue[idx];
- newRemoteIpHeaderValue.addFirst(currentRemoteIp);
- }
-
- XForwardedRequest xRequest = new XForwardedRequest(request);
- if (remoteIp != null) {
-
- xRequest.setRemoteAddr(remoteIp);
- if (getEnableLookups()) {
- // This isn't a lazy lookup but that would be a little more
- // invasive - mainly in XForwardedRequest - and if
- // enableLookups is true is seems reasonable that the
- // hostname will be required so look it up here.
- try {
- InetAddress inetAddress = InetAddress.getByName(remoteIp);
- // We know we need a DNS look up so use getCanonicalHostName()
- xRequest.setRemoteHost(inetAddress.getCanonicalHostName());
- } catch (UnknownHostException e) {
- log.debug(sm.getString("remoteIpFilter.invalidRemoteAddress", remoteIp), e);
- xRequest.setRemoteHost(remoteIp);
- }
- } else {
- xRequest.setRemoteHost(remoteIp);
- }
-
- if (proxiesHeaderValue.size() == 0) {
- xRequest.removeHeader(proxiesHeader);
- } else {
- String commaDelimitedListOfProxies = StringUtils.join(proxiesHeaderValue);
- xRequest.setHeader(proxiesHeader, commaDelimitedListOfProxies);
- }
- if (newRemoteIpHeaderValue.size() == 0) {
- xRequest.removeHeader(remoteIpHeader);
- } else {
- String commaDelimitedRemoteIpHeaderValue = StringUtils.join(newRemoteIpHeaderValue);
- xRequest.setHeader(remoteIpHeader, commaDelimitedRemoteIpHeaderValue);
- }
- }
-
- if (protocolHeader != null) {
- String protocolHeaderValue = request.getHeader(protocolHeader);
- if (protocolHeaderValue == null) {
- // Don't modify the secure, scheme and serverPort attributes
- // of the request
- } else if (isForwardedProtoHeaderValueSecure(protocolHeaderValue)) {
- xRequest.setSecure(true);
- xRequest.setScheme("https");
- setPorts(xRequest, httpsServerPort);
- } else {
- xRequest.setSecure(false);
- xRequest.setScheme("http");
- setPorts(xRequest, httpServerPort);
- }
- }
-
- if (hostHeader != null) {
- String hostHeaderValue = request.getHeader(hostHeader);
- if (hostHeaderValue != null) {
- try {
- int portIndex = Host.parse(hostHeaderValue);
- if (portIndex > -1) {
- log.debug(sm.getString("remoteIpFilter.invalidHostWithPort", hostHeaderValue, hostHeader));
- hostHeaderValue = hostHeaderValue.substring(0, portIndex);
- }
-
- xRequest.setServerName(hostHeaderValue);
- if (isChangeLocalName()) {
- xRequest.setLocalName(hostHeaderValue);
- }
-
- } catch (IllegalArgumentException iae) {
- log.debug(sm.getString("remoteIpFilter.invalidHostHeader", hostHeaderValue, hostHeader));
- }
- }
- }
- request.setAttribute(Globals.REQUEST_FORWARDED_ATTRIBUTE, Boolean.TRUE);
-
- if (log.isDebugEnabled()) {
- log.debug("Incoming request " + request.getRequestURI() + " with originalRemoteAddr [" + request.getRemoteAddr() +
- "], originalRemoteHost=[" + request.getRemoteHost() + "], originalSecure=[" + request.isSecure() +
- "], originalScheme=[" + request.getScheme() + "], originalServerName=[" + request.getServerName() +
- "], originalServerPort=[" + request.getServerPort() +
- "] will be seen as newRemoteAddr=[" + xRequest.getRemoteAddr() +
- "], newRemoteHost=[" + xRequest.getRemoteHost() + "], newSecure=[" + xRequest.isSecure() +
- "], newScheme=[" + xRequest.getScheme() + "], newServerName=[" + xRequest.getServerName() +
- "], newServerPort=[" + xRequest.getServerPort() + "]");
- }
- if (requestAttributesEnabled) {
- request.setAttribute(AccessLog.REMOTE_ADDR_ATTRIBUTE,
- xRequest.getRemoteAddr());
- request.setAttribute(Globals.REMOTE_ADDR_ATTRIBUTE,
- xRequest.getRemoteAddr());
- request.setAttribute(AccessLog.REMOTE_HOST_ATTRIBUTE,
- xRequest.getRemoteHost());
- request.setAttribute(AccessLog.PROTOCOL_ATTRIBUTE,
- xRequest.getProtocol());
- request.setAttribute(AccessLog.SERVER_NAME_ATTRIBUTE,
- xRequest.getServerName());
- request.setAttribute(AccessLog.SERVER_PORT_ATTRIBUTE,
- Integer.valueOf(xRequest.getServerPort()));
- }
- chain.doFilter(xRequest, response);
- } else {
- if (log.isDebugEnabled()) {
- log.debug("Skip RemoteIpFilter for request " + request.getRequestURI() + " with originalRemoteAddr '"
- + request.getRemoteAddr() + "'");
- }
- chain.doFilter(request, response);
- }
-
- }
-
- /*
- * Considers the value to be secure if it exclusively holds forwards for
- * {@link #protocolHeaderHttpsValue}.
- */
- private boolean isForwardedProtoHeaderValueSecure(String protocolHeaderValue) {
- if (!protocolHeaderValue.contains(",")) {
- return protocolHeaderHttpsValue.equalsIgnoreCase(protocolHeaderValue);
- }
- String[] forwardedProtocols = commaDelimitedListToStringArray(protocolHeaderValue);
- if (forwardedProtocols.length == 0) {
- return false;
- }
- for (String forwardedProtocol : forwardedProtocols) {
- if (!protocolHeaderHttpsValue.equalsIgnoreCase(forwardedProtocol)) {
- return false;
- }
- }
- return true;
- }
-
- private void setPorts(XForwardedRequest xrequest, int defaultPort) {
- int port = defaultPort;
- if (getPortHeader() != null) {
- String portHeaderValue = xrequest.getHeader(getPortHeader());
- if (portHeaderValue != null) {
- try {
- port = Integer.parseInt(portHeaderValue);
- } catch (NumberFormatException nfe) {
- log.debug("Invalid port value [" + portHeaderValue +
- "] provided in header [" + getPortHeader() + "]");
- }
- }
- }
- xrequest.setServerPort(port);
- if (isChangeLocalPort()) {
- xrequest.setLocalPort(port);
- }
- }
-
- /**
- * Wrap the incoming <code>request</code> in a {@link XForwardedRequest} if the http header <code>x-forwarded-for</code> is not empty.
- * {@inheritDoc}
- */
- @Override
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
- if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
... 16006 lines suppressed ...